var DI=Object.create;var tp=Object.defineProperty;var FI=Object.getOwnPropertyDescriptor;var BI=Object.getOwnPropertyNames;var UI=Object.getPrototypeOf,jI=Object.prototype.hasOwnProperty;var Os=(t,e)=>{for(var r in e)tp(t,r,{get:e[r],enumerable:!0})},LE=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of BI(e))!jI.call(t,n)&&n!==r&&tp(t,n,{get:()=>e[n],enumerable:!(s=FI(e,n))||s.enumerable});return t};var vr=(t,e,r)=>(r=t!=null?DI(UI(t)):{},LE(e||!t||!t.__esModule?tp(r,"default",{value:t,enumerable:!0}):r,t)),GI=t=>LE(tp({},"__esModule",{value:!0}),t);var h3={};Os(h3,{ASTFeatureExtractor:()=>Nf,ASTForAudioClassification:()=>N_,ASTModel:()=>L_,ASTPreTrainedModel:()=>vo,AfmoeForCausalLM:()=>C_,AfmoeModel:()=>I_,AfmoePreTrainedModel:()=>yo,AlbertForMaskedLM:()=>T_,AlbertForQuestionAnswering:()=>M_,AlbertForSequenceClassification:()=>A_,AlbertModel:()=>E_,AlbertPreTrainedModel:()=>_s,AlbertTokenizer:()=>Fp,ApertusForCausalLM:()=>O_,ApertusModel:()=>S_,ApertusPreTrainedModel:()=>xo,ArceeForCausalLM:()=>z_,ArceeModel:()=>P_,ArceePreTrainedModel:()=>bo,AudioClassificationPipeline:()=>Xi,AutoConfig:()=>Rt,AutoFeatureExtractor:()=>je,AutoImageProcessor:()=>Ae,AutoModel:()=>_r,AutoModelForAudioClassification:()=>Ru,AutoModelForAudioFrameClassification:()=>kv,AutoModelForAudioTextToText:()=>Sv,AutoModelForCTC:()=>$u,AutoModelForCausalLM:()=>Ou,AutoModelForDepthEstimation:()=>Bu,AutoModelForDocumentQuestionAnswering:()=>Du,AutoModelForImageClassification:()=>zu,AutoModelForImageFeatureExtraction:()=>Uu,AutoModelForImageMatting:()=>Ev,AutoModelForImageSegmentation:()=>Ri,AutoModelForImageTextToText:()=>Tv,AutoModelForImageToImage:()=>Fu,AutoModelForMaskGeneration:()=>bv,AutoModelForMaskedLM:()=>Iu,AutoModelForNormalEstimation:()=>Av,AutoModelForObjectDetection:()=>Lu,AutoModelForPoseEstimation:()=>Mv,AutoModelForQuestionAnswering:()=>Cu,AutoModelForSemanticSegmentation:()=>Di,AutoModelForSeq2SeqLM:()=>Mn,AutoModelForSequenceClassification:()=>$i,AutoModelForSpeechSeq2Seq:()=>Mu,AutoModelForTextToSpectrogram:()=>Tu,AutoModelForTextToWaveform:()=>Su,AutoModelForTokenClassification:()=>Au,AutoModelForUniversalSegmentation:()=>Fi,AutoModelForVision2Seq:()=>Pu,AutoModelForXVector:()=>vv,AutoModelForZeroShotObjectDetection:()=>Nu,AutoProcessor:()=>lc,AutoTokenizer:()=>se,AutomaticSpeechRecognitionPipeline:()=>Yi,BackgroundRemovalPipeline:()=>el,BartForConditionalGeneration:()=>R_,BartForSequenceClassification:()=>D_,BartModel:()=>$_,BartPretrainedModel:()=>nn,BartTokenizer:()=>Bp,BaseStreamer:()=>rb,BeitFeatureExtractor:()=>ed,BeitForImageClassification:()=>B_,BeitModel:()=>F_,BeitPreTrainedModel:()=>ko,BertForMaskedLM:()=>j_,BertForQuestionAnswering:()=>W_,BertForSequenceClassification:()=>G_,BertForTokenClassification:()=>q_,BertModel:()=>U_,BertPreTrainedModel:()=>Mr,BertTokenizer:()=>Up,BitImageProcessor:()=>td,BlenderbotForConditionalGeneration:()=>H_,BlenderbotModel:()=>V_,BlenderbotPreTrainedModel:()=>Eo,BlenderbotSmallForConditionalGeneration:()=>K_,BlenderbotSmallModel:()=>X_,BlenderbotSmallPreTrainedModel:()=>Ao,BlenderbotSmallTokenizer:()=>jp,BlenderbotTokenizer:()=>Gp,BloomForCausalLM:()=>Q_,BloomModel:()=>Y_,BloomPreTrainedModel:()=>Mo,BloomTokenizer:()=>qp,CHMv2ForDepthEstimation:()=>nm,CHMv2ImageProcessor:()=>sd,CHMv2PreTrainedModel:()=>Sc,CLIPFeatureExtractor:()=>nd,CLIPImageProcessor:()=>Wl,CLIPModel:()=>am,CLIPPreTrainedModel:()=>rr,CLIPSegForImageSegmentation:()=>pm,CLIPSegModel:()=>um,CLIPSegPreTrainedModel:()=>Co,CLIPTextModel:()=>im,CLIPTextModelWithProjection:()=>Io,CLIPTokenizer:()=>Vp,CLIPVisionModel:()=>lm,CLIPVisionModelWithProjection:()=>cm,CamembertForMaskedLM:()=>Z_,CamembertForQuestionAnswering:()=>rm,CamembertForSequenceClassification:()=>em,CamembertForTokenClassification:()=>tm,CamembertModel:()=>J_,CamembertPreTrainedModel:()=>Tr,CamembertTokenizer:()=>Wp,ChatterboxFeatureExtractor:()=>$f,ChatterboxModel:()=>To,ChatterboxPreTrainedModel:()=>Mc,ChatterboxProcessor:()=>Xf,ChineseCLIPFeatureExtractor:()=>rd,ChineseCLIPModel:()=>sm,ChineseCLIPPreTrainedModel:()=>Tc,ClapAudioModelWithProjection:()=>Oo,ClapFeatureExtractor:()=>Rf,ClapModel:()=>om,ClapPreTrainedModel:()=>on,ClapTextModelWithProjection:()=>So,ClassifierFreeGuidanceLogitsProcessor:()=>wc,CodeGenForCausalLM:()=>dm,CodeGenModel:()=>fm,CodeGenPreTrainedModel:()=>Po,CodeGenTokenizer:()=>Xp,CodeLlamaTokenizer:()=>Hp,Cohere2ForCausalLM:()=>gm,Cohere2Model:()=>hm,Cohere2PreTrainedModel:()=>Lo,CohereAsrFeatureExtractor:()=>Df,CohereAsrForConditionalGeneration:()=>xm,CohereAsrModel:()=>wm,CohereAsrPreTrainedModel:()=>No,CohereAsrProcessor:()=>Kf,CohereAsrTokenizer:()=>Yp,CohereForCausalLM:()=>mm,CohereModel:()=>_m,CoherePreTrainedModel:()=>zo,CohereTokenizer:()=>Kp,ConvBertForMaskedLM:()=>bm,ConvBertForQuestionAnswering:()=>Em,ConvBertForSequenceClassification:()=>vm,ConvBertForTokenClassification:()=>km,ConvBertModel:()=>ym,ConvBertPreTrainedModel:()=>Sr,ConvBertTokenizer:()=>Qp,ConvNextFeatureExtractor:()=>od,ConvNextForImageClassification:()=>Mm,ConvNextImageProcessor:()=>Vl,ConvNextModel:()=>Am,ConvNextPreTrainedModel:()=>$o,ConvNextV2ForImageClassification:()=>Sm,ConvNextV2Model:()=>Tm,ConvNextV2PreTrainedModel:()=>Ro,DFineForObjectDetection:()=>Pm,DFineModel:()=>Cm,DFinePreTrainedModel:()=>Fo,DINOv3ConvNextModel:()=>nh,DINOv3ConvNextPreTrainedModel:()=>Nc,DINOv3ViTImageProcessor:()=>ld,DINOv3ViTModel:()=>oh,DINOv3ViTPreTrainedModel:()=>$c,DPTFeatureExtractor:()=>ud,DPTForDepthEstimation:()=>dh,DPTImageProcessor:()=>Kl,DPTModel:()=>fh,DPTPreTrainedModel:()=>Vo,DacDecoderModel:()=>Uo,DacDecoderOutput:()=>Ic,DacEncoderModel:()=>Bo,DacEncoderOutput:()=>Oc,DacFeatureExtractor:()=>Jn,DacModel:()=>zm,DacPreTrainedModel:()=>an,DebertaForMaskedLM:()=>Nm,DebertaForQuestionAnswering:()=>Dm,DebertaForSequenceClassification:()=>$m,DebertaForTokenClassification:()=>Rm,DebertaModel:()=>Lm,DebertaPreTrainedModel:()=>Or,DebertaTokenizer:()=>Zp,DebertaV2ForMaskedLM:()=>jm,DebertaV2ForQuestionAnswering:()=>Wm,DebertaV2ForSequenceClassification:()=>Gm,DebertaV2ForTokenClassification:()=>qm,DebertaV2Model:()=>Um,DebertaV2PreTrainedModel:()=>Ir,DebertaV2Tokenizer:()=>Jp,DecisionTransformerModel:()=>Vm,DecisionTransformerPreTrainedModel:()=>Cc,DeepseekV3ForCausalLM:()=>Bm,DeepseekV3Model:()=>Fm,DeepseekV3PreTrainedModel:()=>jo,DeiTFeatureExtractor:()=>ad,DeiTForImageClassification:()=>Xm,DeiTImageProcessor:()=>Hl,DeiTModel:()=>Hm,DeiTPreTrainedModel:()=>Go,DepthAnythingForDepthEstimation:()=>Km,DepthAnythingPreTrainedModel:()=>Pc,DepthEstimationPipeline:()=>al,DepthProForDepthEstimation:()=>Ym,DepthProPreTrainedModel:()=>zc,DetrFeatureExtractor:()=>id,DetrForObjectDetection:()=>Jm,DetrForSegmentation:()=>Zm,DetrImageProcessor:()=>Xl,DetrModel:()=>Qm,DetrObjectDetectionOutput:()=>cn,DetrPreTrainedModel:()=>ln,DetrSegmentationOutput:()=>Lc,Dinov2ForImageClassification:()=>th,Dinov2Model:()=>eh,Dinov2PreTrainedModel:()=>qo,Dinov2WithRegistersForImageClassification:()=>sh,Dinov2WithRegistersModel:()=>rh,Dinov2WithRegistersPreTrainedModel:()=>Wo,DistilBertForMaskedLM:()=>uh,DistilBertForQuestionAnswering:()=>ch,DistilBertForSequenceClassification:()=>ih,DistilBertForTokenClassification:()=>lh,DistilBertModel:()=>ah,DistilBertPreTrainedModel:()=>Cr,DistilBertTokenizer:()=>ef,DocumentQuestionAnsweringPipeline:()=>nl,DonutFeatureExtractor:()=>cd,DonutImageProcessor:()=>Hs,DonutSwinModel:()=>ph,DonutSwinPreTrainedModel:()=>Rc,DynamicCache:()=>tn,EdgeTamModel:()=>Ey,EfficientNetForImageClassification:()=>mh,EfficientNetImageProcessor:()=>pd,EfficientNetModel:()=>_h,EfficientNetPreTrainedModel:()=>Ho,ElectraForMaskedLM:()=>gh,ElectraForQuestionAnswering:()=>yh,ElectraForSequenceClassification:()=>wh,ElectraForTokenClassification:()=>xh,ElectraModel:()=>hh,ElectraPreTrainedModel:()=>Pr,ElectraTokenizer:()=>tf,EncodecFeatureExtractor:()=>Yn,EosTokenCriteria:()=>bc,Ernie4_5ForCausalLM:()=>vh,Ernie4_5Model:()=>bh,Ernie4_5PretrainedModel:()=>Xo,EsmForMaskedLM:()=>Eh,EsmForSequenceClassification:()=>Ah,EsmForTokenClassification:()=>Mh,EsmModel:()=>kh,EsmPreTrainedModel:()=>ms,EsmTokenizer:()=>rf,EuroBertForMaskedLM:()=>Sh,EuroBertForSequenceClassification:()=>Oh,EuroBertForTokenClassification:()=>Ih,EuroBertModel:()=>Th,EuroBertPreTrainedModel:()=>hs,ExaoneForCausalLM:()=>Ph,ExaoneModel:()=>Ch,ExaonePreTrainedModel:()=>Ko,FalconForCausalLM:()=>Lh,FalconH1ForCausalLM:()=>$h,FalconH1Model:()=>Nh,FalconH1PreTrainedModel:()=>Qo,FalconModel:()=>zh,FalconPreTrainedModel:()=>Yo,FalconTokenizer:()=>sf,FastViTForImageClassification:()=>Dh,FastViTModel:()=>Rh,FastViTPreTrainedModel:()=>Jo,FeatureExtractionPipeline:()=>il,FeatureExtractor:()=>Ee,FillMaskPipeline:()=>Gi,Florence2ForConditionalGeneration:()=>Fh,Florence2PreTrainedModel:()=>Dc,Florence2Processor:()=>jd,ForcedBOSTokenLogitsProcessor:()=>cc,ForcedEOSTokenLogitsProcessor:()=>uc,GLPNFeatureExtractor:()=>_d,GLPNForDepthEstimation:()=>rg,GLPNModel:()=>tg,GLPNPreTrainedModel:()=>oa,GPT2LMHeadModel:()=>fg,GPT2Model:()=>pg,GPT2PreTrainedModel:()=>ua,GPT2Tokenizer:()=>af,GPTBigCodeForCausalLM:()=>ng,GPTBigCodeModel:()=>sg,GPTBigCodePreTrainedModel:()=>aa,GPTJForCausalLM:()=>_g,GPTJModel:()=>dg,GPTJPreTrainedModel:()=>pa,GPTNeoForCausalLM:()=>ag,GPTNeoModel:()=>og,GPTNeoPreTrainedModel:()=>ia,GPTNeoXForCausalLM:()=>lg,GPTNeoXModel:()=>ig,GPTNeoXPreTrainedModel:()=>la,GPTNeoXTokenizer:()=>of,Gemma2ForCausalLM:()=>Gh,Gemma2Model:()=>jh,Gemma2PreTrainedModel:()=>ea,Gemma3ForCausalLM:()=>Hh,Gemma3ForConditionalGeneration:()=>Uc,Gemma3ImageProcessor:()=>fd,Gemma3Model:()=>Vh,Gemma3PreTrainedModel:()=>Bc,Gemma3Processor:()=>Gd,Gemma3nAudioFeatureExtractor:()=>Zn,Gemma3nForCausalLM:()=>Xh,Gemma3nForConditionalGeneration:()=>zr,Gemma3nPreTrainedModel:()=>jc,Gemma3nProcessor:()=>qd,Gemma4AudioFeatureExtractor:()=>eo,Gemma4ForCausalLM:()=>Kh,Gemma4ForConditionalGeneration:()=>un,Gemma4ImageProcessor:()=>so,Gemma4Processor:()=>Wd,GemmaForCausalLM:()=>Uh,GemmaModel:()=>Bh,GemmaPreTrainedModel:()=>Zo,GemmaTokenizer:()=>nf,Glm46VImageProcessor:()=>dd,Glm46VProcessor:()=>Vd,GlmForCausalLM:()=>Qh,GlmModel:()=>Yh,GlmMoeDsaForCausalLM:()=>Zh,GlmMoeDsaModel:()=>Jh,GlmMoeDsaPreTrainedModel:()=>ra,GlmOcrForConditionalGeneration:()=>eg,GlmPreTrainedModel:()=>ta,GptOssForCausalLM:()=>ug,GptOssModel:()=>cg,GptOssPreTrainedModel:()=>ca,GraniteForCausalLM:()=>hg,GraniteModel:()=>mg,GraniteMoeHybridForCausalLM:()=>wg,GraniteMoeHybridModel:()=>gg,GraniteMoeHybridPreTrainedModel:()=>da,GranitePreTrainedModel:()=>fa,GraniteSpeechFeatureExtractor:()=>Ff,GraniteSpeechForConditionalGeneration:()=>xg,GraniteSpeechProcessor:()=>Hd,GroundingDinoForObjectDetection:()=>yg,GroundingDinoImageProcessor:()=>md,GroundingDinoPreTrainedModel:()=>Wc,GroundingDinoProcessor:()=>Xd,GroupViTModel:()=>bg,GroupViTPreTrainedModel:()=>Vc,HeliumForCausalLM:()=>kg,HeliumModel:()=>vg,HeliumPreTrainedModel:()=>_a,HerbertTokenizer:()=>lf,HieraForImageClassification:()=>Ag,HieraModel:()=>Eg,HieraPreTrainedModel:()=>ma,HubertForCTC:()=>Pg,HubertForSequenceClassification:()=>zg,HubertModel:()=>Cg,HubertPreTrainedModel:()=>Ig,HunYuanDenseV1ForCausalLM:()=>Ng,HunYuanDenseV1Model:()=>Lg,HunYuanDenseV1PreTrainedModel:()=>ha,IJepaForImageClassification:()=>Rg,IJepaModel:()=>$g,IJepaPreTrainedModel:()=>wa,Idefics3ForConditionalGeneration:()=>ga,Idefics3ImageProcessor:()=>Yl,Idefics3Processor:()=>ac,ImageClassificationPipeline:()=>Zi,ImageFeatureExtractionPipeline:()=>ll,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,ImageSegmentationPipeline:()=>As,ImageToImagePipeline:()=>ol,ImageToTextPipeline:()=>Ji,InterruptableStoppingCriteria:()=>lv,JAISLMHeadModel:()=>Fg,JAISModel:()=>Dg,JAISPreTrainedModel:()=>xa,JinaCLIPImageProcessor:()=>gd,JinaCLIPModel:()=>Bg,JinaCLIPPreTrainedModel:()=>fn,JinaCLIPProcessor:()=>Yd,JinaCLIPTextModel:()=>ya,JinaCLIPVisionModel:()=>Ug,Lfm2ForCausalLM:()=>Gg,Lfm2Model:()=>jg,Lfm2MoeForCausalLM:()=>Vg,Lfm2MoeModel:()=>Wg,Lfm2MoePreTrainedModel:()=>va,Lfm2PreTrainedModel:()=>ba,Lfm2VlForConditionalGeneration:()=>Hg,Lfm2VlImageProcessor:()=>wd,Lfm2VlProcessor:()=>Qd,LightOnOcrForConditionalGeneration:()=>qg,LiteWhisperForConditionalGeneration:()=>F0,Llama4ForCausalLM:()=>Yg,Llama4PreTrainedModel:()=>Hc,LlamaForCausalLM:()=>Kg,LlamaModel:()=>Xg,LlamaPreTrainedModel:()=>ka,LlamaTokenizer:()=>cf,LlavaForConditionalGeneration:()=>bt,LlavaOnevisionForConditionalGeneration:()=>bt,LlavaOnevisionImageProcessor:()=>xd,LlavaPreTrainedModel:()=>Fc,LlavaProcessor:()=>Jd,LlavaQwen2ForCausalLM:()=>Wh,LogLevel:()=>St,LogitsProcessor:()=>It,LogitsProcessorList:()=>ds,LogitsWarper:()=>fo,LongT5ForConditionalGeneration:()=>Jg,LongT5Model:()=>Qg,LongT5PreTrainedModel:()=>Ea,M2M100ForConditionalGeneration:()=>ew,M2M100Model:()=>Zg,M2M100PreTrainedModel:()=>Aa,M2M100Tokenizer:()=>uf,MBart50Tokenizer:()=>ff,MBartForCausalLM:()=>lw,MBartForConditionalGeneration:()=>aw,MBartForSequenceClassification:()=>iw,MBartModel:()=>ow,MBartPreTrainedModel:()=>xs,MBartTokenizer:()=>Xn,MPNetForMaskedLM:()=>Xw,MPNetForQuestionAnswering:()=>Qw,MPNetForSequenceClassification:()=>Kw,MPNetForTokenClassification:()=>Yw,MPNetModel:()=>Hw,MPNetPreTrainedModel:()=>Lr,MPNetTokenizer:()=>mf,MT5ForConditionalGeneration:()=>tx,MT5Model:()=>ex,MT5PreTrainedModel:()=>Da,MarianMTModel:()=>rw,MarianModel:()=>tw,MarianPreTrainedModel:()=>Ma,MarianTokenizer:()=>pf,Mask2FormerImageProcessor:()=>bd,MaskFormerFeatureExtractor:()=>yd,MaskFormerForInstanceSegmentation:()=>nw,MaskFormerImageProcessor:()=>Xs,MaskFormerModel:()=>sw,MaskFormerPreTrainedModel:()=>Ta,MaxLengthCriteria:()=>yc,Metric3DForDepthEstimation:()=>cw,Metric3DPreTrainedModel:()=>Xc,Metric3Dv2ForDepthEstimation:()=>uw,Metric3Dv2PreTrainedModel:()=>Kc,MgpstrForSceneTextRecognition:()=>pw,MgpstrModelOutput:()=>Yc,MgpstrPreTrainedModel:()=>Qc,MgpstrProcessor:()=>Zd,MgpstrTokenizer:()=>df,MimiDecoderModel:()=>Oa,MimiDecoderOutput:()=>Zc,MimiEncoderModel:()=>Sa,MimiEncoderOutput:()=>Jc,MimiModel:()=>fw,MimiPreTrainedModel:()=>dn,MinLengthLogitsProcessor:()=>mc,MinNewTokensLengthLogitsProcessor:()=>hc,Mistral4ForCausalLM:()=>hw,Mistral4Model:()=>mw,Mistral4PreTrainedModel:()=>Ca,MistralForCausalLM:()=>_w,MistralModel:()=>dw,MistralPreTrainedModel:()=>Ia,MobileBertForMaskedLM:()=>ww,MobileBertForQuestionAnswering:()=>yw,MobileBertForSequenceClassification:()=>xw,MobileBertModel:()=>gw,MobileBertPreTrainedModel:()=>ys,MobileBertTokenizer:()=>_f,MobileLLMForCausalLM:()=>vw,MobileLLMModel:()=>bw,MobileLLMPreTrainedModel:()=>Pa,MobileNetV1FeatureExtractor:()=>vd,MobileNetV1ForImageClassification:()=>Ew,MobileNetV1ForSemanticSegmentation:()=>Aw,MobileNetV1ImageProcessor:()=>Ql,MobileNetV1Model:()=>kw,MobileNetV1PreTrainedModel:()=>_n,MobileNetV2FeatureExtractor:()=>kd,MobileNetV2ForImageClassification:()=>Tw,MobileNetV2ForSemanticSegmentation:()=>Sw,MobileNetV2ImageProcessor:()=>Jl,MobileNetV2Model:()=>Mw,MobileNetV2PreTrainedModel:()=>mn,MobileNetV3FeatureExtractor:()=>Ed,MobileNetV3ForImageClassification:()=>Iw,MobileNetV3ForSemanticSegmentation:()=>Cw,MobileNetV3ImageProcessor:()=>Zl,MobileNetV3Model:()=>Ow,MobileNetV3PreTrainedModel:()=>hn,MobileNetV4FeatureExtractor:()=>Ad,MobileNetV4ForImageClassification:()=>zw,MobileNetV4ForSemanticSegmentation:()=>Lw,MobileNetV4ImageProcessor:()=>ec,MobileNetV4Model:()=>Pw,MobileNetV4PreTrainedModel:()=>gn,MobileViTFeatureExtractor:()=>Md,MobileViTForImageClassification:()=>$w,MobileViTImageProcessor:()=>tc,MobileViTModel:()=>Nw,MobileViTPreTrainedModel:()=>za,MobileViTV2ForImageClassification:()=>Dw,MobileViTV2Model:()=>Rw,MobileViTV2PreTrainedModel:()=>La,ModelRegistry:()=>ob,ModernBertDecoderForCausalLM:()=>qw,ModernBertDecoderModel:()=>Gw,ModernBertDecoderPreTrainedModel:()=>Na,ModernBertForMaskedLM:()=>Bw,ModernBertForSequenceClassification:()=>Uw,ModernBertForTokenClassification:()=>jw,ModernBertModel:()=>Fw,ModernBertPreTrainedModel:()=>bs,Moondream1ForConditionalGeneration:()=>qh,MoonshineFeatureExtractor:()=>Bf,MoonshineForConditionalGeneration:()=>Vw,MoonshineModel:()=>Ww,MoonshinePreTrainedModel:()=>$a,MoonshineProcessor:()=>e_,MptForCausalLM:()=>Zw,MptModel:()=>Jw,MptPreTrainedModel:()=>Ra,MultiModalityCausalLM:()=>rx,MultiModalityPreTrainedModel:()=>eu,MusicgenForCausalLM:()=>nx,MusicgenForConditionalGeneration:()=>Ba,MusicgenModel:()=>sx,MusicgenPreTrainedModel:()=>Fa,NanoChatForCausalLM:()=>ax,NanoChatModel:()=>ox,NanoChatPreTrainedModel:()=>Ua,NemotronHForCausalLM:()=>lx,NemotronHModel:()=>ix,NemotronHPreTrainedModel:()=>ja,NeoBertForMaskedLM:()=>ux,NeoBertForQuestionAnswering:()=>dx,NeoBertForSequenceClassification:()=>px,NeoBertForTokenClassification:()=>fx,NeoBertModel:()=>cx,NeoBertPreTrainedModel:()=>Nr,NllbTokenizer:()=>hf,NoBadWordsLogitsProcessor:()=>gc,NoRepeatNGramLogitsProcessor:()=>dc,NomicBertModel:()=>_x,NomicBertPreTrainedModel:()=>tu,NougatImageProcessor:()=>Td,NougatTokenizer:()=>gf,OPTForCausalLM:()=>Sx,OPTModel:()=>Tx,OPTPreTrainedModel:()=>Ka,ObjectDetectionPipeline:()=>rl,Olmo2ForCausalLM:()=>wx,Olmo2Model:()=>gx,Olmo2PreTrainedModel:()=>qa,Olmo3ForCausalLM:()=>yx,Olmo3Model:()=>xx,Olmo3PreTrainedModel:()=>Wa,OlmoForCausalLM:()=>hx,OlmoHybridForCausalLM:()=>vx,OlmoHybridModel:()=>bx,OlmoHybridPreTrainedModel:()=>Va,OlmoModel:()=>mx,OlmoPreTrainedModel:()=>Ga,OpenAIPrivacyFilterForTokenClassification:()=>Ex,OpenAIPrivacyFilterModel:()=>kx,OpenAIPrivacyFilterPreTrainedModel:()=>Ha,OpenELMForCausalLM:()=>Mx,OpenELMModel:()=>Ax,OpenELMPreTrainedModel:()=>Xa,OwlViTFeatureExtractor:()=>Sd,OwlViTForObjectDetection:()=>Px,OwlViTImageProcessor:()=>Ks,OwlViTModel:()=>Cx,OwlViTPreTrainedModel:()=>Qa,OwlViTProcessor:()=>t_,Owlv2ForObjectDetection:()=>Ix,Owlv2ImageProcessor:()=>Od,Owlv2Model:()=>Ox,Owlv2PreTrainedModel:()=>Ya,PaliGemmaForConditionalGeneration:()=>zx,PaliGemmaProcessor:()=>r_,ParakeetFeatureExtractor:()=>Qn,ParakeetForCTC:()=>Lx,ParakeetPreTrainedModel:()=>ru,PatchTSMixerForPrediction:()=>$x,PatchTSMixerModel:()=>Nx,PatchTSMixerPreTrainedModel:()=>Ja,PatchTSTForPrediction:()=>Dx,PatchTSTModel:()=>Rx,PatchTSTPreTrainedModel:()=>Za,Phi3ForCausalLM:()=>jx,Phi3Model:()=>Ux,Phi3PreTrainedModel:()=>ti,Phi3VForCausalLM:()=>ri,Phi3VImageProcessor:()=>Id,Phi3VPreTrainedModel:()=>su,Phi3VProcessor:()=>s_,PhiForCausalLM:()=>Bx,PhiModel:()=>Fx,PhiPreTrainedModel:()=>ei,PixtralImageProcessor:()=>Cd,PixtralProcessor:()=>n_,PreTrainedModel:()=>y,PreTrainedTokenizer:()=>W,PretrainedConfig:()=>Ys,Processor:()=>re,PvtForImageClassification:()=>qx,PvtImageProcessor:()=>Pd,PvtModel:()=>Gx,PvtPreTrainedModel:()=>si,PyAnnoteFeatureExtractor:()=>to,PyAnnoteForAudioFrameClassification:()=>Vx,PyAnnoteModel:()=>Wx,PyAnnotePreTrainedModel:()=>ni,PyAnnoteProcessor:()=>o_,QuestionAnsweringPipeline:()=>ji,Qwen2ForCausalLM:()=>Xx,Qwen2Model:()=>Hx,Qwen2MoeForCausalLM:()=>Yx,Qwen2MoeModel:()=>Kx,Qwen2MoePreTrainedModel:()=>ai,Qwen2PreTrainedModel:()=>oi,Qwen2Tokenizer:()=>wf,Qwen2VLForCausalLM:()=>sa,Qwen2VLForConditionalGeneration:()=>pn,Qwen2VLImageProcessor:()=>no,Qwen2VLPreTrainedModel:()=>Gc,Qwen2VLProcessor:()=>fs,Qwen2_5_VLForCausalLM:()=>na,Qwen2_5_VLForConditionalGeneration:()=>gs,Qwen2_5_VLProcessor:()=>co,Qwen3ForCausalLM:()=>Jx,Qwen3Model:()=>Qx,Qwen3MoeForCausalLM:()=>ey,Qwen3MoeModel:()=>Zx,Qwen3MoePreTrainedModel:()=>li,Qwen3NextForCausalLM:()=>ry,Qwen3NextModel:()=>ty,Qwen3NextPreTrainedModel:()=>ci,Qwen3PreTrainedModel:()=>ii,Qwen3VLForCausalLM:()=>ui,Qwen3VLForConditionalGeneration:()=>vs,Qwen3VLMoeForCausalLM:()=>ny,Qwen3VLMoeForConditionalGeneration:()=>sy,Qwen3VLProcessor:()=>a_,Qwen3_5ForCausalLM:()=>pi,Qwen3_5ForConditionalGeneration:()=>wn,Qwen3_5MoeForCausalLM:()=>ay,Qwen3_5MoeForConditionalGeneration:()=>oy,RFDetrForObjectDetection:()=>uy,RFDetrModel:()=>cy,RFDetrObjectDetectionOutput:()=>nu,RFDetrPreTrainedModel:()=>di,RTDetrForObjectDetection:()=>Im,RTDetrImageProcessor:()=>zd,RTDetrModel:()=>Om,RTDetrObjectDetectionOutput:()=>sr,RTDetrPreTrainedModel:()=>Do,RTDetrV2ForObjectDetection:()=>vy,RTDetrV2Model:()=>by,RTDetrV2ObjectDetectionOutput:()=>ou,RTDetrV2PreTrainedModel:()=>_i,RawAudio:()=>Kn,RawImage:()=>Je,RawVideo:()=>Gu,RawVideoFrame:()=>ul,RepetitionPenaltyLogitsProcessor:()=>_c,ResNetForImageClassification:()=>ly,ResNetModel:()=>iy,ResNetPreTrainedModel:()=>fi,RoFormerForMaskedLM:()=>gy,RoFormerForQuestionAnswering:()=>yy,RoFormerForSequenceClassification:()=>wy,RoFormerForTokenClassification:()=>xy,RoFormerModel:()=>hy,RoFormerPreTrainedModel:()=>Rr,RoFormerTokenizer:()=>yf,RobertaForMaskedLM:()=>fy,RobertaForQuestionAnswering:()=>my,RobertaForSequenceClassification:()=>dy,RobertaForTokenClassification:()=>_y,RobertaModel:()=>py,RobertaPreTrainedModel:()=>$r,RobertaTokenizer:()=>xf,Sam2ImageProcessor:()=>ao,Sam2ImageSegmentationOutput:()=>lu,Sam2Model:()=>mi,Sam2PreTrainedModel:()=>cu,Sam2Processor:()=>ic,Sam2VideoProcessor:()=>i_,Sam3ImageProcessor:()=>ao,Sam3TrackerModel:()=>Ay,SamImageProcessor:()=>ao,SamImageSegmentationOutput:()=>au,SamModel:()=>ky,SamPreTrainedModel:()=>iu,SamProcessor:()=>uo,SapiensFeatureExtractor:()=>Ld,SapiensForDepthEstimation:()=>Ty,SapiensForNormalEstimation:()=>Sy,SapiensForSemanticSegmentation:()=>My,SapiensImageProcessor:()=>rc,SapiensPreTrainedModel:()=>xn,SeamlessM4TFeatureExtractor:()=>Uf,SegformerFeatureExtractor:()=>Nd,SegformerForImageClassification:()=>Iy,SegformerForSemanticSegmentation:()=>Cy,SegformerImageProcessor:()=>sc,SegformerModel:()=>Oy,SegformerPreTrainedModel:()=>yn,SiglipImageProcessor:()=>$d,SiglipModel:()=>Py,SiglipPreTrainedModel:()=>hi,SiglipTextModel:()=>gi,SiglipTokenizer:()=>bf,SiglipVisionModel:()=>zy,SmolLM3ForCausalLM:()=>Ny,SmolLM3Model:()=>Ly,SmolLM3PreTrainedModel:()=>wi,SmolVLMForConditionalGeneration:()=>$y,SmolVLMImageProcessor:()=>Yl,SmolVLMProcessor:()=>ac,SnacDecoderModel:()=>yi,SnacEncoderModel:()=>xi,SnacFeatureExtractor:()=>jf,SnacModel:()=>Ry,SnacPreTrainedModel:()=>bn,SolarOpenForCausalLM:()=>Fy,SolarOpenModel:()=>Dy,SolarOpenPreTrainedModel:()=>bi,SpeechT5FeatureExtractor:()=>Gf,SpeechT5ForSpeechToText:()=>Uy,SpeechT5ForTextToSpeech:()=>jy,SpeechT5HifiGan:()=>Gy,SpeechT5Model:()=>By,SpeechT5PreTrainedModel:()=>vn,SpeechT5Processor:()=>l_,SpeechT5Tokenizer:()=>vf,SqueezeBertForMaskedLM:()=>Wy,SqueezeBertForQuestionAnswering:()=>Hy,SqueezeBertForSequenceClassification:()=>Vy,SqueezeBertModel:()=>qy,SqueezeBertPreTrainedModel:()=>ks,SqueezeBertTokenizer:()=>kf,StableLmForCausalLM:()=>Ky,StableLmModel:()=>Xy,StableLmPreTrainedModel:()=>vi,Starcoder2ForCausalLM:()=>Qy,Starcoder2Model:()=>Yy,Starcoder2PreTrainedModel:()=>ki,StoppingCriteria:()=>Ar,StoppingCriteriaList:()=>Zs,StyleTextToSpeech2Model:()=>Jy,StyleTextToSpeech2PreTrainedModel:()=>uu,SummarizationPipeline:()=>qi,SupertonicForConditionalGeneration:()=>Ei,SupertonicPreTrainedModel:()=>pu,SuppressTokensAtBeginLogitsProcessor:()=>Js,SuppressTokensLogitsProcessor:()=>pc,Swin2SRForImageSuperResolution:()=>s0,Swin2SRImageProcessor:()=>Rd,Swin2SRModel:()=>r0,Swin2SRPreTrainedModel:()=>Ai,SwinForImageClassification:()=>e0,SwinForSemanticSegmentation:()=>t0,SwinModel:()=>Zy,SwinPreTrainedModel:()=>kn,T5ForConditionalGeneration:()=>o0,T5Model:()=>n0,T5PreTrainedModel:()=>Mi,T5Tokenizer:()=>Ef,TableTransformerForObjectDetection:()=>i0,TableTransformerModel:()=>a0,TableTransformerObjectDetectionOutput:()=>fu,TableTransformerPreTrainedModel:()=>Ti,TemperatureLogitsWarper:()=>xc,Tensor:()=>N,Text2TextGenerationPipeline:()=>mr,TextClassificationPipeline:()=>Bi,TextGenerationPipeline:()=>Vi,TextStreamer:()=>sb,TextToAudioPipeline:()=>Qi,TokenClassificationPipeline:()=>Ui,TokenizersBackend:()=>W,TopKLogitsWarper:()=>iv,TopPLogitsWarper:()=>av,TrOCRForCausalLM:()=>l0,TrOCRPreTrainedModel:()=>du,TranslationPipeline:()=>Wi,UltravoxModel:()=>ws,UltravoxPreTrainedModel:()=>qc,UltravoxProcessor:()=>c_,UniSpeechForCTC:()=>u0,UniSpeechForSequenceClassification:()=>p0,UniSpeechModel:()=>c0,UniSpeechPreTrainedModel:()=>En,UniSpeechSatForAudioFrameClassification:()=>m0,UniSpeechSatForCTC:()=>d0,UniSpeechSatForSequenceClassification:()=>_0,UniSpeechSatModel:()=>f0,UniSpeechSatPreTrainedModel:()=>Es,VLChatProcessor:()=>Kd,VLMImageProcessor:()=>hd,VaultGemmaForCausalLM:()=>g0,VaultGemmaModel:()=>h0,VaultGemmaPreTrainedModel:()=>Si,ViTFeatureExtractor:()=>Dd,ViTForImageClassification:()=>y0,ViTImageProcessor:()=>nc,ViTMAEModel:()=>b0,ViTMAEPreTrainedModel:()=>_u,ViTMSNForImageClassification:()=>k0,ViTMSNModel:()=>v0,ViTMSNPreTrainedModel:()=>Ii,ViTModel:()=>x0,ViTPreTrainedModel:()=>Oi,VisionEncoderDecoderModel:()=>w0,VitMatteForImageMatting:()=>E0,VitMatteImageProcessor:()=>Fd,VitMattePreTrainedModel:()=>mu,VitPoseForPoseEstimation:()=>A0,VitPoseImageProcessor:()=>Bd,VitPosePreTrainedModel:()=>hu,VitsModel:()=>M0,VitsModelOutput:()=>gu,VitsPreTrainedModel:()=>wu,VitsTokenizer:()=>Af,VoxtralForConditionalGeneration:()=>T0,VoxtralProcessor:()=>p_,VoxtralRealtimeFeatureExtractor:()=>Vf,VoxtralRealtimeForConditionalGeneration:()=>Ci,VoxtralRealtimePreTrainedModel:()=>xu,VoxtralRealtimeProcessor:()=>d_,Wav2Vec2BertForCTC:()=>O0,Wav2Vec2BertForSequenceClassification:()=>I0,Wav2Vec2BertModel:()=>S0,Wav2Vec2BertPreTrainedModel:()=>An,Wav2Vec2CTCTokenizer:()=>Mf,Wav2Vec2FeatureExtractor:()=>qf,Wav2Vec2ForAudioFrameClassification:()=>Og,Wav2Vec2ForCTC:()=>Tg,Wav2Vec2ForSequenceClassification:()=>Sg,Wav2Vec2Model:()=>Mg,Wav2Vec2PreTrainedModel:()=>Wt,Wav2Vec2Processor:()=>__,Wav2Vec2ProcessorWithLM:()=>m_,WavLMForAudioFrameClassification:()=>N0,WavLMForCTC:()=>P0,WavLMForSequenceClassification:()=>z0,WavLMForXVector:()=>L0,WavLMModel:()=>C0,WavLMPreTrainedModel:()=>Dr,WeSpeakerFeatureExtractor:()=>Wf,WeSpeakerResNetModel:()=>$0,WeSpeakerResNetPreTrainedModel:()=>bu,WhisperFeatureExtractor:()=>Hf,WhisperForConditionalGeneration:()=>vu,WhisperModel:()=>D0,WhisperPreTrainedModel:()=>Pi,WhisperProcessor:()=>h_,WhisperTextStreamer:()=>Ov,WhisperTimeStampLogitsProcessor:()=>fc,WhisperTokenizer:()=>Tf,XLMForQuestionAnswering:()=>q0,XLMForSequenceClassification:()=>j0,XLMForTokenClassification:()=>G0,XLMModel:()=>B0,XLMPreTrainedModel:()=>Fr,XLMRobertaForMaskedLM:()=>V0,XLMRobertaForQuestionAnswering:()=>K0,XLMRobertaForSequenceClassification:()=>H0,XLMRobertaForTokenClassification:()=>X0,XLMRobertaModel:()=>W0,XLMRobertaPreTrainedModel:()=>Br,XLMRobertaTokenizer:()=>Sf,XLMTokenizer:()=>Of,XLMWithLMHeadModel:()=>U0,XVectorOutput:()=>yu,YolosFeatureExtractor:()=>Ud,YolosForObjectDetection:()=>Q0,YolosImageProcessor:()=>oc,YolosModel:()=>Y0,YolosObjectDetectionOutput:()=>ku,YolosPreTrainedModel:()=>zi,YoutuForCausalLM:()=>Z0,YoutuModel:()=>J0,YoutuPreTrainedModel:()=>Li,ZeroShotAudioClassificationPipeline:()=>Ki,ZeroShotClassificationPipeline:()=>Hi,ZeroShotImageClassificationPipeline:()=>tl,ZeroShotObjectDetectionPipeline:()=>sl,cat:()=>ye,cos_sim:()=>zA,dot:()=>Kb,env:()=>_e,full:()=>Ke,full_like:()=>Wn,interpolate:()=>Np,interpolate_4d:()=>yt,layer_norm:()=>JL,load_audio:()=>Z1,load_image:()=>CM,load_video:()=>ST,log_softmax:()=>hp,matmul:()=>q1,mean:()=>Fl,mean_pooling:()=>W1,ones:()=>Ze,ones_like:()=>Bl,permute:()=>xM,pipeline:()=>d3,quantize_embeddings:()=>X1,rand:()=>ZL,randn:()=>H1,random:()=>Kr,read_audio:()=>Lf,rfft:()=>QL,slice:()=>Dl,softmax:()=>Pe,stack:()=>_t,std_mean:()=>$p,topk:()=>Gt,zeros:()=>Rp,zeros_like:()=>Dp});module.exports=GI(h3);var RE=vr(require("fs"),1),Is=vr(require("path"),1),DE=vr(require("url"),1),sC={},qI="4.2.0",zb=typeof self<"u",Ln=!jE(RE.default),FE=!jE(Is.default),rp=zb&&"caches"in self,WI=typeof globalThis.Deno<"u",w3=typeof globalThis.Bun<"u",np=WI&&rp&&!Ln,BE=typeof process<"u",UE=BE&&process?.release?.name==="node"&&!np,Lb=typeof window<"u"&&typeof window.document<"u",Nb=zb&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),VI=Lb||Nb||np,HI=UE||typeof navigator<"u"&&"gpu"in navigator,XI=typeof navigator<"u"&&"ml"in navigator,KI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",YI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",QI=typeof ServiceWorkerGlobalScope<"u"&&zb&&self instanceof ServiceWorkerGlobalScope,JI=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},ZI=JI(),ie=Object.freeze({IS_BROWSER_ENV:Lb,IS_WEBWORKER_ENV:Nb,IS_WEB_ENV:VI,IS_SERVICE_WORKER_ENV:QI,IS_DENO_WEB_RUNTIME:np,IS_WEB_CACHE_AVAILABLE:rp,IS_WEBGPU_AVAILABLE:HI,IS_WEBNN_AVAILABLE:XI,IS_SAFARI:ZI,IS_PROCESS_AVAILABLE:BE,IS_NODE_ENV:UE,IS_FS_AVAILABLE:Ln,IS_PATH_AVAILABLE:FE,IS_CRYPTO_AVAILABLE:KI,IS_CHROME_AVAILABLE:YI}),$b=Ln&&FE,sp="./";if($b){let t=Object(sC).url;t?sp=Is.default.dirname(Is.default.dirname(DE.default.fileURLToPath(t))):typeof __dirname<"u"&&(sp=Is.default.dirname(__dirname))}var eC=$b?Is.default.join(sp,"/.cache/"):null,NE="/models/",tC=$b?Is.default.join(sp,NE):NE,rC=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,St=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),$E=St.WARNING,_e={version:qI,backends:{onnx:{}},get logLevel(){return $E},set logLevel(t){$E=t,_e.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Lb||Nb||np),localModelPath:tC,useFS:Ln,useBrowserCache:rp,useFSCache:Ln,cacheDir:eC,useCustomCache:!1,customCache:null,useWasmCache:rp||Ln,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:rC};function jE(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function lr(t,e){t&&t(e)}var Cs=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function GE(t){return Number.isInteger(t)||typeof t=="bigint"}function Rb(t){return t==null||t===-1}function Db(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function wt(...t){return Array.prototype.concat.apply([],t)}function qE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function Nn(t,e){return Math.abs((t+e)%(2*e)-e)}function Ve(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function WE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){_e.logLevel<=St.ERROR&&console.error(...t)},warn(...t){_e.logLevel<=St.WARNING&&console.warn(...t)},info(...t){_e.logLevel<=St.INFO&&console.log(...t)},debug(...t){_e.logLevel<=St.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var nC=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),iC=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),lC=iC(ZE),HE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",cC=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${HE}])]+`,` ?[^\\s${HE}]+`]]),op="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Bb=t=>t.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"),ap=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of cC)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=uC(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},uC=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pC=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,dC=t=>Number.isInteger(t)||typeof t=="bigint",_C=t=>{let e=0;for(let r of t)++e;return e},mC=t=>eA(t.toLowerCase()),Xt=(...t)=>Array.prototype.concat.apply([],t),Ub=t=>new Map(Object.entries(t)),hC=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),XE=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},gC=t=>t.match(/\S+/g)||[],wC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},gl=wC,xC=class extends gl{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},kr=xC,yC=class extends kr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},kC=vC,EC=class extends kr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>tA(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},AC=EC,MC=class extends kr{normalize(t){let e=ap(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},TC=MC,SC=class extends kr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},ip=SC,OC=class extends ip{constructor(){super(...arguments),this.form="NFC"}},IC=OC,CC=class extends ip{constructor(){super(...arguments),this.form="NFD"}},PC=CC,zC=class extends ip{constructor(){super(...arguments),this.form="NFKC"}},LC=zC,NC=class extends ip{constructor(){super(...arguments),this.form="NFKD"}},$C=NC,RC=class extends kr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},DC=RC,FC=class extends kr{normalize(t){return eA(t)}},BC=FC,UC=class extends kr{normalize(t){return t.toLowerCase()}},jC=UC,GC=class extends kr{normalize(t){return t=this.config.prepend+t,t}},qC=GC;function WC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new bC(t);case"Precompiled":return new kC(t);case"Sequence":return new AC(t);case"Replace":return new TC(t);case"NFC":return new IC(t);case"NFD":return new PC(t);case"NFKC":return new LC(t);case"NFKD":return new $C(t);case"Strip":return new DC(t);case"StripAccents":return new BC(t);case"Lowercase":return new jC(t);case"Prepend":return new qC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var tA=WC,VC=class extends gl{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Kt=VC,HC=class extends Kt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=ZE,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},XC=HC,KC=class extends Kt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},YC=KC,QC=class extends Kt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},JC=QC,ZC=class extends Kt{constructor(t){super(),this.config=t,this.pattern=ap(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):hC(t,this.pattern)}},eP=ZC,tP=class extends Kt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${op}]+|[${op}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},rP=tP,sP=class extends Kt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},nP=sP,oP=class extends Kt{constructor(){super(),this.pattern=new RegExp(`[^\\s${op}]+|[${op}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},aP=oP,iP=class extends Kt{constructor(t){super(),this.config=t,this.pattern=ap(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},lP=iP,cP=class extends Kt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>rA(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},uP=cP,pP=class extends Kt{pre_tokenize_text(t){return gC(t)}},fP=pP,dP=class extends Kt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;rthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},KE=gP,YE=class sA{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new sA(!1,new Map)}},wP=class{constructor(){this.root=YE.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=YE.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let s of t){if(r+=s,e=e.children.get(s),e===void 0)return;e.is_leaf&&(yield r)}}},xP=wP,Fb=class nA{constructor(e,r,s,n,o){this.token_id=e,this.node_id=r,this.pos=s,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new nA(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},yP=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new Fb(this.bos_token_id??0,0,0,0,0),n=new Fb(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new Fb(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+a.score;(l===null||p>i)&&(l=c.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},bP=yP;function vP(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=vP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new xP,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;sr>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},TP=MP,SP=class extends lp{constructor(t){super(t),this.tokens_to_ids=Ub(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.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 TP(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new AP((i,l)=>i.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},JE=SP,OP=class extends lp{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Ub(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},IP=OP;function CP(t,e){switch(t.type){case"WordPiece":return new KE(t);case"Unigram":return new QE(t,e.eos_token);case"BPE":return new JE(t);default:if(t.vocab)return Array.isArray(t.vocab)?new QE(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new JE(t):new KE(t):new IP(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var PP=CP,zP=class extends gl{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},wl=zP,LP=class extends wl{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Xt(n,t),o=Xt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Xt(n,e),o=Xt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},NP=LP,$P=class extends wl{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},RP=$P,DP=class extends wl{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Xt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Xt(t,n,e,o),s=Xt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},FP=DP,BP=class extends wl{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Xt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Xt(t,n,e,o),s=Xt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},UP=BP,jP=class extends wl{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>oA(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},GP=jP;function qP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new NP(t);case"ByteLevel":return new RP(t);case"BertProcessing":return new FP(t);case"RobertaProcessing":return new UP(t);case"Sequence":return new GP(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var oA=qP,WP=class extends gl{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Ft=WP,VP=class extends Ft{constructor(t){super(t),this.byte_decoder=lC,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},HP=VP,XP=class extends Ft{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=Bb(e)),e})}},KP=XP,YP=class extends Ft{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;re.replaceAll(this.suffix,r===t.length-1?"":" "))}},ZP=JP,ez=class extends Ft{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(s=Bb(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},tz=ez,rz=class extends Ft{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>aA(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},sz=rz,nz=class extends Ft{decode_chain(t){let e=ap(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},oz=nz,az=class extends Ft{decode_chain(t){return[t.join("")]}},iz=az,lz=class extends Ft{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},pz=uz;function fz(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new HP(t);case"WordPiece":return new KP(t);case"Metaspace":return new QP(t);case"BPEDecoder":return new ZP(t);case"CTC":return new tz(t);case"Sequence":return new sz(t);case"Replace":return new oz(t);case"Fuse":return new iz(t);case"Strip":return new cz(t);case"ByteFallback":return new pz(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var aA=fz,dz=class{constructor(t,e){let r=XE(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=XE(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=tA(this.tokenizer.normalizer),this.pre_tokenizer=rA(this.tokenizer.pre_tokenizer),this.model=PP(this.tokenizer.model,this.config),this.post_processor=oA(this.tokenizer.post_processor),this.decoder=aA(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new aC(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new VE(n),this.splitter_normalized=new VE(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!dC(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=Bb(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=mC(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Xt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],mz=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function hz(t,e={}){return t.endsWith(` `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function gz(t,e={}){let r=[],s=hz(t,e),n=0,o=0,a=c=>{let p="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],_=mz.get(f);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);p+=_;continue}if(p+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return p},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new Bt(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let _="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");_+=s[n++]}let m=_.endsWith("-");m&&(_=_.slice(0,-1)),f&&i(),r.push(new Bt(_,D.Comment)),n+=2,m&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Bt("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Bt("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(cA),s.slice(n,n+3)==="-%}"){r.push(new Bt("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Bt("}}",D.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let _=a(xl);r.push(new Bt(`${p}${_}`,_.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,_]of _z){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Bt(f,_)),_===D.OpenExpression?o=0:_===D.OpenCurlyBracket?++o:_===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(_=>_!==p);r.push(new Bt(f,D.StringLiteral)),++n;continue}if(xl(p)){let f=a(xl);if(s[n]==="."&&xl(s[n+1])){++n;let _=a(xl);f=`${f}.${_}`}r.push(new Bt(f,D.NumericLiteral));continue}if(lA(p)){let f=a(lA);r.push(new Bt(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Qt=class{type="Statement"},wz=class extends Qt{constructor(t){super(),this.body=t}type="Program"},xz=class extends Qt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},yz=class extends Qt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},bz=class extends Qt{type="Break"},vz=class extends Qt{type="Continue"},kz=class extends Qt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},Ez=class extends Qt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},Az=class extends Qt{constructor(t){super(),this.value=t}type="Comment"},Pt=class extends Qt{type="Expression"},Mz=class extends Pt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},uA=class extends Pt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},$n=class extends Pt{constructor(t){super(),this.value=t}type="Identifier"},Rn=class extends Pt{constructor(t){super(),this.value=t}type="Literal"},Tz=class extends Rn{type="IntegerLiteral"},Sz=class extends Rn{type="FloatLiteral"},pA=class extends Rn{type="StringLiteral"},Oz=class extends Rn{type="ArrayLiteral"},fA=class extends Rn{type="TupleLiteral"},Iz=class extends Rn{type="ObjectLiteral"},yl=class extends Pt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},Cz=class extends Pt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},Pz=class extends Qt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},zz=class extends Pt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},Lz=class extends Pt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},Nz=class extends Pt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},$z=class extends Pt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},Rz=class extends Pt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},Dz=class extends Pt{constructor(t){super(),this.argument=t}type="SpreadExpression"},Fz=class extends Qt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},Bz=class extends Pt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function Uz(t){let e=new wz([]),r=0;function s(z,$){let B=t[r++];if(!B||B.type!==z)throw new Error(`Parser Error: ${$}. ${B.type} !== ${z}.`);return B}function n(z){if(!l(z))throw new SyntaxError(`Expected ${z}`);++r}function o(){switch(t[r].type){case D.Comment:return new Az(t[r++].value);case D.Text:return c();case D.OpenStatement:return p();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...z){return r+z.length<=t.length&&z.every(($,B)=>$===t[r+B].type)}function i(...z){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&z.includes(t[r+1]?.value)}function l(...z){return r+z.length<=t.length&&z.every(($,B)=>t[r+B].type==="Identifier"&&$===t[r+B].value)}function c(){return new pA(s(D.Text,"Expected text token").value)}function p(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let z=t[r].value,$;switch(z){case"set":++r,$=_();break;case"if":++r,$=m(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,$=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,$=k(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let B=null;a(D.OpenParen)&&(B=U());let Q=Y();if(Q.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let le=U();s(D.CloseStatement,"Expected closing statement token");let Ge=[];for(;!i("endcall");)Ge.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let ce=new uA(Q,le);$=new Fz(ce,B,Ge);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),$=new bz;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),$=new vz;break;case"filter":{++r;let B=Y();B instanceof $n&&a(D.OpenParen)&&(B=j(B)),s(D.CloseStatement,"Expected closing statement token");let Q=[];for(;!i("endfilter");)Q.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),$=new Pz(B,Q);break}default:throw new SyntaxError(`Unknown statement type: ${z}`)}return $}function f(){s(D.OpenExpression,"Expected opening expression token");let z=A();return s(D.CloseExpression,"Expected closing expression token"),z}function _(){let z=x(),$=null,B=[];if(a(D.Equals))++r,$=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)B.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new kz(z,$,B)}function m(){let z=A();s(D.CloseStatement,"Expected closing statement token");let $=[],B=[];for(;!i("elif","else","endif");)$.push(o());if(i("elif")){++r,++r;let Q=m();B.push(Q)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)B.push(o());return new xz(z,$,B)}function w(){let z=Y();if(z.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let $=U();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endmacro");)B.push(o());return new Ez(z,$,B)}function x(z=!1){let $=z?Y:A,B=[$()],Q=a(D.Comma);for(;Q&&(++r,B.push($()),!!a(D.Comma)););return Q?new fA(B):B[0]}function k(){let z=x(!0);if(!(z instanceof $n||z instanceof fA))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${z.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let $=A();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endfor","else");)B.push(o());let Q=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)Q.push(o());return new yz(z,$,B,Q)}function A(){return E()}function E(){let z=S();if(l("if")){++r;let $=S();if(l("else")){++r;let B=E();return new Bz($,z,B)}else return new zz(z,$)}return z}function S(){let z=T();for(;l("or");){let $=t[r];++r;let B=T();z=new yl($,z,B)}return z}function T(){let z=I();for(;l("and");){let $=t[r];++r;let B=I();z=new yl($,z,B)}return z}function I(){let z;for(;l("not");){let $=t[r];++r;let B=I();z=new Nz($,B)}return z??O()}function O(){let z=b();for(;;){let $;if(l("not","in"))$=new Bt("not in",D.Identifier),r+=2;else if(l("in"))$=t[r++];else if(a(D.ComparisonBinaryOperator))$=t[r++];else break;let B=b();z=new yl($,z,B)}return z}function b(){let z=R();for(;a(D.AdditiveBinaryOperator);){let $=t[r];++r;let B=R();z=new yl($,z,B)}return z}function F(){let z=J(Y());return a(D.OpenParen)?j(z):z}function j(z){let $=new uA(z,U());return $=J($),a(D.OpenParen)&&($=j($)),$}function U(){s(D.OpenParen,"Expected opening parenthesis for arguments list");let z=X();return s(D.CloseParen,"Expected closing parenthesis for arguments list"),z}function X(){let z=[];for(;!a(D.CloseParen);){let $;if(t[r].type===D.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let B=A();$=new Dz(B)}else if($=A(),a(D.Equals)){if(++r,!($ instanceof $n))throw new SyntaxError("Expected identifier for keyword argument");let B=A();$=new Rz($,B)}z.push($),a(D.Comma)&&++r}return z}function K(){let z=[],$=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(z.push(void 0),++r,$=!0):(z.push(A()),a(D.Colon)&&(++r,$=!0));if(z.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($){if(z.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new $z(...z)}return z[0]}function J(z){for(;a(D.Dot)||a(D.OpenSquareBracket);){let $=t[r];++r;let B,Q=$.type===D.OpenSquareBracket;if(Q)B=K(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(B=Y(),B.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");z=new Mz(z,B,Q)}return z}function R(){let z=C();for(;a(D.MultiplicativeBinaryOperator);){let $=t[r++],B=C();z=new yl($,z,B)}return z}function C(){let z=ne();for(;l("is");){++r;let $=l("not");$&&++r;let B=Y();if(!(B instanceof $n))throw new SyntaxError("Expected identifier for the test");z=new Lz(z,$,B)}return z}function ne(){let z=F();for(;a(D.Pipe);){++r;let $=Y();if(!($ instanceof $n))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&($=j($)),z=new Cz(z,$)}return z}function Y(){let z=t[r++];switch(z.type){case D.NumericLiteral:{let $=z.value;return $.includes(".")?new Sz(Number($)):new Tz(Number($))}case D.StringLiteral:{let $=z.value;for(;a(D.StringLiteral);)$+=t[r++].value;return new pA($)}case D.Identifier:return new $n(z.value);case D.OpenParen:{let $=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),$}case D.OpenSquareBracket:{let $=[];for(;!a(D.CloseSquareBracket);)$.push(A()),a(D.Comma)&&++r;return++r,new Oz($)}case D.OpenCurlyBracket:{let $=new Map;for(;!a(D.CloseCurlyBracket);){let B=A();s(D.Colon,"Expected colon between key and value in object literal");let Q=A();$.set(B,Q),a(D.Comma)&&++r}return++r,new Iz($)}default:throw new SyntaxError(`Unexpected token: ${z.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function dA(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*ae.toUpperCase())}function qz(t){return Wz(new Date,t)}function Wz(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function Vz(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hz(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(Vz(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var _A=class extends Error{},mA=class extends Error{},cr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new de(!!this.value)}toString(){return String(this.value)}},he=class extends cr{type="IntegerValue"},et=class extends cr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},te=class extends cr{type="StringValue";builtins=new Map([["upper",new Xe(()=>new te(this.value.toUpperCase()))],["lower",new Xe(()=>new te(this.value.toLowerCase()))],["strip",new Xe(()=>new te(this.value.trim()))],["title",new Xe(()=>new te(Gz(this.value)))],["capitalize",new Xe(()=>new te(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new Xe(()=>new te(this.value.trimEnd()))],["lstrip",new Xe(()=>new te(this.value.trimStart()))],["startswith",new Xe(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.startsWith(e.value));if(e instanceof be){for(let r of e.value){if(!(r instanceof te))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Xe(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.endsWith(e.value));if(e instanceof be){for(let r of e.value){if(!(r instanceof te))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Xe(t=>{let e=t[0]??new Ye;if(!(e instanceof te||e instanceof Ye))throw new Error("sep argument must be a string or null");let r=t[1]??new he(-1);if(!(r instanceof he))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Ye){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new be(s.map(n=>new te(n)))})],["replace",new Xe(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof te&&r instanceof te))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Ye:s=t[2]:s=new Ye,!(s instanceof he||s instanceof Ye))throw new Error("replace() count argument must be a number or null");return new te(Hz(this.value,e.value,r.value,s.value))})]])},de=class extends cr{type="BooleanValue"},Xz=/[\x7f-\uffff]/g;function hA(t){return t.replace(Xz,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function zs(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=hA(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",f=` `+p.repeat(r),_=f+p;if(t.type==="ArrayValue"){let m=t.value.map(w=>zs(w,e,r+1,s));return n?`[${_}${m.join(`${l}${_}`)}${f}]`:`[${m.join(l)}]`}else{let m=Array.from(t.value.entries());i&&(m=m.sort(([x],[k])=>x.localeCompare(k)));let w=m.map(([x,k])=>{let A=JSON.stringify(x);o&&(A=hA(A));let E=`${A}${c}${zs(k,e,r+1,s)}`;return n?`${_}${E}`:E});return n?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var ft=class extends cr{type="ObjectValue";__bool__(){return new de(this.value.size>0)}builtins=new Map([["get",new Xe(([t,e])=>{if(!(t instanceof te))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Ye})],["items",new Xe(()=>this.items())],["keys",new Xe(()=>this.keys())],["values",new Xe(()=>this.values())],["dictsort",new Xe(t=>{let e=new Map,r=t.filter(i=>i instanceof bl?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new de(!1);if(!(s instanceof de))throw new Error("case_sensitive must be a boolean");let n=r.at(1)??e.get("by")??new te("key");if(!(n instanceof te))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");let o=r.at(2)??e.get("reverse")??new de(!1);if(!(o instanceof de))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new be([new te(i),l])).sort((i,l)=>{let c=n.value==="key"?0:1,p=i.value[c],f=l.value[c],_=jb(p,f,s.value);return o.value?-_:_});return new be(a)})]]);items(){return new be(Array.from(this.value.entries()).map(([t,e])=>new be([new te(t),e])))}keys(){return new be(Array.from(this.value.keys()).map(t=>new te(t)))}values(){return new be(Array.from(this.value.values()))}toString(){return zs(this,{},0,!1)}},bl=class extends ft{type="KeywordArgumentsValue"},be=class extends cr{type="ArrayValue";builtins=new Map([["length",new he(this.value.length)]]);__bool__(){return new de(this.value.length>0)}toString(){return zs(this,{},0,!1)}},gA=class extends be{type="TupleValue"},Xe=class extends cr{type="FunctionValue"},Ye=class extends cr{type="NullValue"},He=class extends cr{type="UndefinedValue"},Ps=class{constructor(t){this.parent=t}variables=new Map([["namespace",new Xe(t=>{if(t.length===0)return new ft(new Map);if(t.length!==1||!(t[0]instanceof ft))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]);tests=new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof Xe],["odd",t=>{if(!(t instanceof he))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof he))throw new Error(`cannot even on ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["none",t=>t.type==="NullValue"],["string",t=>t.type==="StringValue"],["number",t=>t instanceof he||t instanceof et],["integer",t=>t instanceof he],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t instanceof ft],["sequence",t=>t instanceof be||t instanceof ft||t instanceof te],["lower",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]]);set(t,e){return this.declareVariable(t,cp(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new He}catch{return new He}}};function Kz(t){t.set("false",!1),t.set("true",!0),t.set("none",null),t.set("raise_exception",e=>{throw new Error(e)}),t.set("range",jz),t.set("strftime_now",qz),t.set("True",!0),t.set("False",!1),t.set("None",null)}function wA(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof ft)s=s.value.get(n)??new He;else if(s instanceof be){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&oo instanceof he||o instanceof et||o instanceof de,n=o=>o instanceof de?o.value?1:0:o.value;if(s(t)&&s(e)){let o=n(t),a=n(e);return oa?1:0}if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);if(t.type==="StringValue"){let o=t.value,a=e.value;return r||(o=o.toLowerCase(),a=a.toLowerCase()),oa?1:0}else throw new Error(`Cannot compare type: ${t.type}`)}var Yz=class{global;constructor(t){this.global=t??new Ps}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){let r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}let s=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new de(r.value==s.value);case"!=":return new de(r.value!=s.value)}if(r instanceof He||s instanceof He){if(s instanceof He&&["in","not in"].includes(t.operator.value))return new de(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof Ye||s instanceof Ye)throw new Error("Cannot perform operation on null values");if(t.operator.value==="~")return new te(r.value.toString()+s.value.toString());if((r instanceof he||r instanceof et)&&(s instanceof he||s instanceof et)){let n=r.value,o=s.value;switch(t.operator.value){case"+":case"-":case"*":{let a=t.operator.value==="+"?n+o:t.operator.value==="-"?n-o:n*o;return r instanceof et||s instanceof et?new et(a):new he(a)}case"/":return new et(n/o);case"%":{let a=n%o;return r instanceof et||s instanceof et?new et(a):new he(a)}case"<":return new de(n":return new de(n>o);case">=":return new de(n>=o);case"<=":return new de(n<=o)}}else if(r instanceof be&&s instanceof be){if(t.operator.value==="+")return new be(r.value.concat(s.value))}else if(s instanceof be){let n=s.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new de(n);case"not in":return new de(!n)}}}if((r instanceof te||s instanceof te)&&t.operator.value==="+")return new te(r.value.toString()+s.value.toString());if(r instanceof te&&s instanceof te)switch(t.operator.value){case"in":return new de(s.value.includes(r.value));case"not in":return new de(!s.value.includes(r.value))}if(r instanceof te&&s instanceof ft)switch(t.operator.value){case"in":return new de(s.value.has(r.value));case"not in":return new de(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(t,e){let r=[],s=new Map;for(let n of t)if(n.type==="SpreadExpression"){let o=n,a=this.evaluate(o.argument,e);if(!(a instanceof be))throw new Error(`Cannot unpack non-iterable type: ${a.type}`);for(let i of a.value)r.push(i)}else if(n.type==="KeywordArgumentExpression"){let o=n;s.set(o.key.value,this.evaluate(o.value,e))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,e))}return[r,s]}applyFilter(t,e,r){if(e.type==="Identifier"){let s=e;if(s.value==="safe")return t;if(s.value==="tojson")return new te(zs(t,{}));if(t instanceof be)switch(s.value){case"list":return t;case"first":return t.value[0];case"last":return t.value[t.value.length-1];case"length":return new he(t.value.length);case"reverse":return new be(t.value.slice().reverse());case"sort":return new be(t.value.slice().sort((n,o)=>jb(n,o,!1)));case"join":return new te(t.value.map(n=>n.value).join(""));case"string":return new te(zs(t,{},0,!1));case"unique":{let n=new Set,o=[];for(let a of t.value)n.has(a.value)||(n.add(a.value),o.push(a));return new be(o)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(t instanceof te)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=t.builtins.get(s.value);if(n instanceof Xe)return n.value([],r);if(n instanceof he)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new te(t.value.trim());case"indent":return new te(t.value.split(` `).map((n,o)=>o===0||n.length===0?n:" "+n).join(` `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new he(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new et(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof he||t instanceof et)switch(s.value){case"abs":return t instanceof he?new he(Math.abs(t.value)):new et(Math.abs(t.value));case"int":return new he(Math.floor(t.value));case"float":return new et(t.value);case"string":return new te(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof ft)switch(s.value){case"items":return new be(Array.from(t.value.entries()).map(([n,o])=>new be([new te(n),o])));case"length":return new he(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof Xe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof de)switch(s.value){case"bool":return new de(t.value);case"int":return new he(t.value?1:0);case"float":return new et(t.value?1:0);case"string":return new te(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new Ye;if(!(a instanceof he||a instanceof Ye))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new de(!1);if(!(i instanceof de))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new de(!1);if(!(l instanceof de))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Ye,p=null;if(c instanceof be||c instanceof gA){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,_]=c.value;if(!(f instanceof te)||!(_ instanceof te))throw new Error("separators must be a tuple of two strings");p=[f.value,_.value]}else if(!(c instanceof Ye))throw new Error("If set, separators must be a tuple of two strings");return new te(zs(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:p}))}else if(n==="join"){let o;if(t instanceof te)o=Array.from(t.value);else if(t instanceof be)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new te("");if(!(l instanceof te))throw new Error("separator must be a string");return new te(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new he(0):new et(0));if(t instanceof te){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new he(l):new et(l)}else{if(t instanceof he||t instanceof et)return t;if(t instanceof de)return n==="int"?new he(t.value?1:0):new et(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new te(""),l=o[1]??a.get("boolean")??new de(!1);if(!(l instanceof de))throw new Error("`default` filter flag must be a boolean");return t instanceof He||l.value&&!t.__bool__().value?i:t}if(t instanceof be){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new de(!1);if(!(i instanceof de))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new de(!1);if(!(l instanceof de))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Ye;if(!(c instanceof te||c instanceof he||c instanceof Ye))throw new Error("attribute must be a string, integer, or null");let p=f=>{if(c instanceof Ye)return f;let _=c instanceof he?String(c.value):c.value;return wA(f,_)};return new be(t.value.slice().sort((f,_)=>{let m=p(f),w=p(_),x=jb(m,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ft)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let p=t.value.filter(f=>{let _=f.value.get(a.value),m=_?c(_,l):!1;return o?m:!m});return new be(p)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof te))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof ft))throw new Error("items in map must be an object");let p=wA(c,a.value);return p instanceof He?i??new He:p});return new be(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof te){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new he(4);if(!(i instanceof he))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new de(!1),c=o.at(2)??a.get("blank")??new de(!1),p=t.value.split(` `),f=" ".repeat(i.value),_=p.map((m,w)=>!l.value&&w===0||!c.value&&m.length===0?m:f+m);return new te(_.join(` `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof Xe))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new bl(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ft){let o=t.builtins.get(n);if(o&&o instanceof Xe){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new bl(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new de(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new He}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new de(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new te(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new bl(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof be||t instanceof te))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof he||s instanceof He))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof He))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof he||o instanceof He))throw new Error("Slice step must be numeric or undefined");return t instanceof be?new be(dA(t.value,s.value,n.value,o.value)):new te(dA(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new te(t.property.value);let n;if(r instanceof ft){if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof be||r instanceof te)if(s instanceof he)n=r.value.at(s.value),r instanceof te&&(n=new te(r.value.at(s.value)));else if(s instanceof te)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof cr?n:new He}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof be))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;om.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let m=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(m.value.length!==w.value.length)throw new Error(`Too ${m.value.length>w.value.length?"few":"many"} items to unpack`);_=x=>{for(let k=0;k0?o[c-1]:new He],["nextitem",c{let n=new Ps(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a{let c=new Ps(l);if(t.callerArgs)for(let p=0;pthis.evaluate(r,e)));case"TupleLiteral":return new gA(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof te))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new ft(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Ye;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function cp(t){switch(typeof t){case"number":return Number.isInteger(t)?new he(t):new et(t);case"string":return new te(t);case"boolean":return new de(t);case"undefined":return new He;case"object":return t===null?new Ye:Array.isArray(t)?new be(t.map(cp)):new ft(new Map(Object.entries(t).map(([e,r])=>[e,cp(r)])));case"function":return new Xe((e,r)=>{let s=t(...e.map(n=>n.value))??null;return cp(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var at=` `,Qz="{%- ",Jz=" -%}";function Zz(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function eL(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Yt(t.body,0,r).replace(/\n$/,"")}function xt(...t){return Qz+t.join(" ")+Jz}function Yt(t,e,r){return t.map(s=>tL(s,e,r)).join(at)}function tL(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Yt(t.body,e,r);case"If":return rL(t,e,r);case"For":return sL(t,e,r);case"Set":return nL(t,e,r);case"Macro":return oL(t,e,r);case"Break":return s+xt("break");case"Continue":return s+xt("continue");case"CallStatement":return aL(t,e,r);case"FilterStatement":return iL(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function rL(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+xt("if",ke(n[0].test))+at+Yt(n[0].body,e+1,r);for(let i=1;i0&&(a+=at+s+xt("else")+at+Yt(o.alternate,e+1,r)),a+=at+s+xt("endif"),a}function sL(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+xt("for",ke(t.loopvar),"in",n)+at+Yt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=at+s+xt("else")+at+Yt(t.defaultBlock,e+1,r)),o+=at+s+xt("endfor"),o}function nL(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+xt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+at+Yt(t.body,e+1,r)+at+s+xt("endset")}function oL(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+xt("macro",`${t.name.value}(${n})`)+at+Yt(t.body,e+1,r)+at+s+xt("endmacro")}function aL(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+xt(`call${n}`,o)+at;return a+=Yt(t.body,e+1,r)+at,a+=s+xt("endcall"),a}function iL(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+xt("filter",n)+at;return o+=Yt(t.body,e+1,r)+at,o+=s+xt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=Zz(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var xA=class{parsed;constructor(t){let e=gz(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Uz(e)}render(t){let e=new Ps;if(Kz(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new Yz(e).run(this.parsed).value}format(t){return eL(this.parsed,t?.indent||" ")}};var Ls=vr(require("fs"),1),lL={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"},Hr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Ls.default.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Ls.default.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=Ls.default.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",lL[e]??"application/octet-stream")}clone(){let e=new t(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 Ls.default.promises.readFile(this.filePath)).buffer}async blob(){let e=await Ls.default.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Ls.default.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Dn=vr(require("fs"),1),vl=vr(require("path"),1);var Xr=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[yA(this._random_fn,r)]}};function yA(t,e){let r=0;for(let n=0;nyA(Kr.random,t);var cL=new Xr,Fn=class{constructor(e){this.path=e}async match(e){let r=vl.default.join(this.path,e),s=new Hr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=vl.default.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=cL._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await Dn.default.promises.mkdir(vl.default.dirname(n),{recursive:!0});let f=Dn.default.createWriteStream(i),_=r.body.getReader();for(;;){let{done:m,value:w}=await _.read();if(m)break;await new Promise((k,A)=>{f.write(w,E=>{if(E){A(E);return}k()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,total:c})}await new Promise((m,w)=>{f.close(x=>x?w(x):m())}),await Dn.default.promises.rename(i,n)}catch(l){try{await Dn.default.promises.unlink(i)}catch{}throw l}}async delete(e){let r=vl.default.join(this.path,e);try{return await Dn.default.promises.unlink(r),!0}catch{return!1}}};var vA={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"},up=100,kA=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;var Gb={};function kl(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Yr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function EA(t){return!(!kA.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function AA(t,e,r){if(!r)return null;let s=vA[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function MA(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:p}=await i.read();if(c)return;let f=a+p.length;if(f>n){n=f;let m=new Uint8Array(n);m.set(o),o=m}o.set(p,a),a=f;let _=a/n*100;return e({progress:_,loaded:a,total:n}),l()}return await l(),o}function qb(t){return Yr(t,["blob:"])}function Wb(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof Gb<"u"&&Gb.url)e=Gb.url;else return t;return new URL(t,e).href}var SA="SHA-256",uL="experimental_transformers-hash-cache",TA=t=>({algorithm:SA,value:t}),El=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(uL),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([TA(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([TA(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(SA,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Jt(t=null){let e=null;if(_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");e=_e.customCache}if(!e&&_e.experimental_useCrossOriginStorage&&El.isAvailable()&&(e=new El),!e&&_e.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(_e.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&_e.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Fn(t??_e.cacheDir)}return e}async function OA(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var pp=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var pL=100,Vb=new pp(pL);function fp(t,e){let r=Vb.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Vb.delete(t),Promise.reject(n)));return Vb.put(t,s),s}async function fL(t){if(!Yr(t,["http:","https:"]))return null;let e=Hb(t);return e.set("Range","bytes=0-0"),_e.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ot(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return fp(s,()=>dL(t,e,r))}async function dL(t,e,r){let s=await Jt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=Jr(t,e,r,s),l=await Zr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(_e.allowLocalModels&&!Yr(n,["http:","https:"]))try{let p=await Qr(n);if(typeof p!="string"&&p.status!==404){let f=p.headers.get("content-length"),_=p.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(_e.allowRemoteModels&&!r.local_files_only&&i)try{let c=await fL(o);if(c&&c.status>=200&&c.status<300){let p,f=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let m=_.match(/bytes \d+-\d+\/(\d+)/);m&&(p=parseInt(m[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let _=c.headers.get("content-length");p=_?parseInt(_,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Qr(t){return _e.useFS&&!Yr(t,["http:","https:","blob:"])?new Hr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):_e.fetch(t,{headers:Hb(t)})}function Hb(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=_e.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Yr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function Jr(t,e,r={},s=null){let n=r.revision??"main",o=kl(t,e),a=EA(t),i=a?kl(_e.localModelPath,o):o,l=kl(_e.remoteHost,_e.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof Fn?n==="main"?o:kl(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Zr(t,e,r){if(t)return await OA(t,e,r)}async function _L(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>lr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function mL(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=Jr(t,e,s,o),f,_=!1,m;m=await Zr(o,i,c);let w=m!==void 0;if(w)f=c;else{if(_e.allowLocalModels)if(Yr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!_e.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{m=await Qr(i),f=i}catch(E){ee.warn(`Unable to load from local path "${i}": "${E}"`)}if(m===void 0||typeof m!="string"&&m.status===404){if(s.local_files_only||!_e.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(m=await Qr(l),m.status!==200)return AA(m.status,l,r);f=c}_=o&&typeof Response<"u"&&m instanceof Response&&m.status===200}lr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let A;if(typeof m!="string")if(!s.progress_callback)A=new Uint8Array(await m.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))A=new Uint8Array(await m.arrayBuffer()),lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let E,S=m.headers.get("content-length");if(S)E=parseInt(S,10);else try{let T=await Ot(t,e,s);T.size&&(E=T.size)}catch{}A=await MA(m,T=>{lr(s.progress_callback,{status:"progress",name:t,file:e,...T})},E)}x=A}if(_&&f&&typeof m!="string"&&await _L(t,e,o,f,m,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof m!="string"){let A=parseInt(m.headers.get("content-length"),10)||0;lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(lr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(m instanceof Hr)return m.filePath;let k=await o?.match(f);if(k instanceof Hr)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}var dp=new Map;async function Al(t,e,r=!0,s={},n=!1){if(!_e.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!_e.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}lr(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=dp.get(o);if(!a){let i=await Jt(s?.cache_dir);a=mL(t,e,r,s,n,i).then(l=>(dp.delete(o),l),l=>{throw dp.delete(o),l}),dp.set(o,a)}return await a}async function Ml(t,e,r=!0,s={}){let n=await Al(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function nt(t,e,r=!0,s={}){let n=await Ml(t,e,r,s);return n===null?{}:JSON.parse(n)}function CA(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),f=r*s,_=n*o;for(let m=0;m=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function Pe(t){let e=ze(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function hp(t){let e=ze(t)[0],r=0;for(let o=0;oo-e-s)}function Kb(t,e){let r=0;for(let s=0;se+r*r,0))}function Tl(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function LA(t){return t>0&&(t&t-1)===0}var _p=class{constructor(e){if(this.size=e|0,this.size<=1||!LA(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>1,w=m>>>1,x=w>>>1;for(l=0;l>>1;for(let m=2;m<_;m+=2)e[n-m]=e[m],e[n-m+1]=-e[m+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+o],f=e[n+i],_=e[n+l],m=c+f,w=c-f,x=p+_,k=a*(p-_);r[s]=m+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=m-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},Xb=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=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);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p>1;++p){let f=(p+1-e)**2/2,_=Math.sqrt(l**2+c**2)**f,m=f*Math.atan2(c,l),w=2*p;o[w]=_*Math.cos(m),o[w+1]=_*Math.sin(m),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new _p(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f>1,w=r[m];n[f]=w*c[f],n[_]=w*c[_]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function Ns(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function $A(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function RA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let p=1;p0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var DA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,_=l&1023;if(f===31)c=p|2139095040|_<<13;else if(f===0)if(_===0)c=p;else{let m=113;for(;(_&1024)===0;)_<<=1,--m;_&=-1025,c=p|m<<23|_<<13}else c=p|f+112<<23|_<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;oE1,TRACE:()=>Ap,TRACE_EVENT_BEGIN:()=>ns,TRACE_EVENT_END:()=>os,TRACE_FUNC_BEGIN:()=>Us,TRACE_FUNC_END:()=>js,Tensor:()=>er,default:()=>qL,env:()=>Qe,registerBackend:()=>Bs});var Zt={};var v1=Object.defineProperty,hL=Object.getOwnPropertyDescriptor,gL=Object.getOwnPropertyNames,wL=Object.prototype.hasOwnProperty,xL=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ve=(t,e)=>()=>(t&&(e=t(t=0)),e),Nl=(t,e)=>{for(var r in e)v1(t,r,{get:e[r],enumerable:!0})},yL=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of gL(e))!wL.call(t,n)&&n!==r&&v1(t,n,{get:()=>e[n],enumerable:!(s=hL(e,n))||s.enumerable});return t},Ep=t=>yL(v1({},"__esModule",{value:!0}),t),Sl,es,Bs,FA,f2,d2=ve(()=>{"use strict";Sl=new Map,es=[],Bs=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Sl.get(t);if(s===void 0)Sl.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=es.indexOf(t);n!==-1&&es.splice(n,1);for(let o=0;o{let e=Sl.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},f2=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?es:r,n,o=[],a=new Set;for(let l of s){let c=await FA(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),bL=ve(()=>{"use strict";d2()}),_2,vL=ve(()=>{"use strict";_2="1.24.0-dev.20251116-b39e144322"}),Yb,dt,m2=ve(()=>{"use strict";vL(),Yb="warning",dt={wasm:{},webgl:{},webgpu:{},versions:{common:_2},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Yb=t}},get logLevel(){return Yb}},Object.defineProperty(dt,"logLevel",{enumerable:!0})}),Qe,kL=ve(()=>{"use strict";m2(),Qe=dt}),h2,g2,EL=ve(()=>{"use strict";h2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,_=p,m=p*2,w=-1;a==="RGBA"?(f=0,_=p,m=p*2,w=p*3):a==="RGB"?(f=0,_=p,m=p*2):a==="RBG"&&(f=0,m=p,_=p*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,m=0,w=1,x=2,k=3,A=0,E=f,S=f*2,T=-1;i==="RGBA"?(A=0,E=f,S=f*2,T=f*3):i==="RGB"?(A=0,E=f,S=f*2):i==="RBG"&&(A=0,S=f,E=f*2),s=r.createImageData(n,o);for(let I=0;I{"use strict";k1(),gp=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,_=0,m=1,w=2,x=3,k=0,A=c,E=c*2,S=-1;i==="RGB"&&(f=3,_=0,m=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,E=c,A=c*2):l==="BGR"&&(E=0,A=c,k=c*2);for(let T=0;T{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(_=e.resizedHeight,m=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=m}else i.tensorFormat="RGBA",i.height=_,i.width=m;f.drawImage(t,0,0),a=f.getImageData(0,0,m,_).data}else throw new Error("Can not access image data")}else if(s){let p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let _=l();_.width=f,_.height=p;let m=c(_);if(m!=null)m.putImageData(t,0,0),a=m.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;return f.drawImage(t,0,0,m,_),a=f.getImageData(0,0,m,_).data,i.height=_,i.width=m,gp(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let _=l(),m=c(_);if(!t||!m)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{_.width=w.width,_.height=w.height,m.drawImage(w,0,0,_.width,_.height);let x=m.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,p(gp(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return gp(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},x2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Nt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},y2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},b2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},v2=(t,e,r)=>new Nt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Ds,zl,Qb,k2,ML=ve(()=>{"use strict";Ds=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),zl=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Qb=!1,k2=()=>{if(!Qb){Qb=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Ds.set("int64",BigInt64Array),zl.set(BigInt64Array,"int64")),e&&(Ds.set("uint64",BigUint64Array),zl.set(BigUint64Array,"uint64")),s?(Ds.set("float16",r),zl.set(r,"float16")):Ds.set("float16",Uint16Array)}}}),E2,A2,TL=ve(()=>{"use strict";k1(),E2=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Nt(t.type,t.data,e);case"cpu-pinned":return new Nt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Nt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Nt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Nt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Nt,k1=ve(()=>{"use strict";EL(),AL(),ML(),TL(),Nt=class{constructor(t,e,r){k2();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=Ds.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=Ds.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=zl.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=E2(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return w2(t,e)}static fromTexture(t,e){return x2(t,e)}static fromGpuBuffer(t,e){return y2(t,e)}static fromMLTensor(t,e){return b2(t,e)}static fromPinnedBuffer(t,e,r){return v2(t,e,r)}toDataURL(t){return h2(this,t)}toImageData(t){return g2(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return A2(this,t)}}}),er,M2=ve(()=>{"use strict";k1(),er=Nt}),Ap,Jb,Us,js,ns,os,T2=ve(()=>{"use strict";m2(),Ap=(t,e)=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Jb=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Jb("BEGIN",t)},js=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||Jb("END",t)},ns=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.time(`ORT::${t}`)},os=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeEnd(`ORT::${t}`)}}),S2,SL=ve(()=>{"use strict";d2(),M2(),T2(),S2=class O2{constructor(e){this.handler=e}async run(e,r,s){Us(),ns("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof er||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let _=r[f];(_===null||_ instanceof er)&&(c=!0,a=!1,n[f]=_)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof er?l[c]=p:l[c]=new er(p.type,p.data,p.dims)}return os("InferenceSession.run"),js(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Us(),ns("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,f=0,_=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(_=e.byteLength-f,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||f+_>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,f,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await f2(a),c=await i.createInferenceSessionHandler(o,l);return os("InferenceSession.create"),js(),new O2(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),E1,OL=ve(()=>{"use strict";SL(),E1=S2}),IL=ve(()=>{"use strict"}),CL=ve(()=>{"use strict"}),PL=ve(()=>{"use strict"}),zL=ve(()=>{"use strict"}),I2={};Nl(I2,{InferenceSession:()=>E1,TRACE:()=>Ap,TRACE_EVENT_BEGIN:()=>ns,TRACE_EVENT_END:()=>os,TRACE_FUNC_BEGIN:()=>Us,TRACE_FUNC_END:()=>js,Tensor:()=>er,env:()=>Qe,registerBackend:()=>Bs});var Gs=ve(()=>{"use strict";bL(),kL(),OL(),M2(),IL(),CL(),T2(),PL(),zL()}),A1=ve(()=>{"use strict"}),C2={};Nl(C2,{default:()=>P2});var Zb,e1,P2,LL=ve(()=>{"use strict";H2(),qs(),M1(),Zb="ort-wasm-proxy-worker",e1=globalThis.self?.name===Zb,e1&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":T1(r.wasm).then(()=>{P1(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;z1(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Sp(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;L1(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":N1(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;$1(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},D1([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":R1(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),P2=e1?null:t=>new Worker(t??zt,{type:"module",name:Zb})}),z2={};Nl(z2,{default:()=>L2});async function BA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let u=d=>(...h)=>{let g=ar;return h=d(...h),ar!=g?new Promise((v,M)=>{mb={resolve:v,reject:M}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=Zt.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(O(u))return new Promise((h,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):g(v.status)},v.onerror=g,v.send(null)});var d=await fetch(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,_,m,w,x,k,A=console.log.bind(console),E=console.error.bind(console),S=A,T=E,I=!1,O=u=>u.startsWith("file://");function b(){Wr.buffer!=U.buffer&&le()}if(n){let u=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let v=[];self.onmessage=M=>v.push(M),k=()=>{postMessage({Oc:"loaded"});for(let M of v)u(M);self.onmessage=u};for(let M of h.ce)e[M]&&!e[M].proxy||(e[M]=(...P)=>{postMessage({Oc:"callHandler",be:M,args:P})},M=="print"&&(S=e[M]),M=="printErr"&&(T=e[M]));Wr=h.ie,le(),_=h.je,qe(),ep()}else if(g==="run"){(function(v){var M=(b(),C)[v+52>>>2>>>0];v=(b(),C)[v+56>>>2>>>0],Wk(M,M-v),pe(M)})(h.Nc),Tb(h.Nc,0,0,1,0,0),Pv(),fb(h.Nc),j||(Tk(),j=!0);try{DT(h.ge,h.Wc)}catch(v){if(v!="unwind")throw v}}else h.target!=="setimmediate"&&(g==="checkMailbox"?j&&Vu():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(v){throw Bk(),v}};var F=u,j=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var U,X,K,J,R,C,ne,Y,z,$,B,Q=!1;function le(){var u=Wr.buffer;e.HEAP8=U=new Int8Array(u),K=new Int16Array(u),e.HEAPU8=X=new Uint8Array(u),J=new Uint16Array(u),e.HEAP32=R=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),ne=new Float32Array(u),Y=new Float64Array(u),z=new BigInt64Array(u),$=new BigUint64Array(u)}function Ge(){Q=!0,n?k():br._b()}function ce(u){throw T(u="Aborted("+u+")"),I=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function Et(){return{a:{f:FT,J:BT,k:UT,p:jT,l:GT,sa:qT,b:WT,ca:VT,Ja:Dv,q:HT,da:jv,Za:Gv,Fa:qv,Ha:Wv,_a:Vv,Xa:Hv,Qa:Xv,Wa:Kv,oa:Yv,Ga:Qv,Xb:Jv,Ya:Zv,Yb:ek,db:XT,Da:YT,Sb:QT,Qb:ZT,Ca:tS,M:rS,I:sS,Rb:nS,ja:pS,Tb:fS,Ta:dS,Vb:mS,Ka:hS,Ob:gS,ka:wS,Sa:fb,ab:xS,U:kS,n:SS,c:ub,rb:OS,w:IS,L:CS,z:PS,j:zS,o:lk,sb:LS,G:NS,T:$S,h:RS,u:DS,m:FS,i:BS,Na:US,Oa:jS,Pa:GS,La:fk,Ma:dk,Pb:_k,eb:WS,cb:XS,Y:KS,qb:YS,la:QS,bb:VS,fb:JS,$a:ZS,Wb:eO,N:qS,gb:tO,X:rO,Ub:sO,nb:fO,C:dO,ra:_O,qa:mO,pb:hO,W:gO,v:wO,mb:xO,lb:yO,kb:bO,ob:vO,jb:kO,ib:EO,hb:AO,Ua:yk,Va:bk,Ia:Sn,V:vk,na:kk,Ra:Ek,ma:Ak,Cb:NI,xa:OI,Db:LI,ya:SI,F:gI,e:nI,s:rI,x:tI,B:_I,Fb:AI,ba:EI,D:iI,za:MI,$:II,ga:kI,Gb:vI,Hb:bI,Ba:wI,Aa:yI,Ib:xI,wa:zI,aa:TI,d:sI,A:aI,r:oI,Bb:$I,t:cI,y:mI,H:lI,E:uI,K:hI,R:CI,ia:dI,_:PI,Jb:fI,Kb:pI,g:TO,a:Wr,Nb:Tn,Eb:SO,ha:OO,O:IO,pa:CO,Lb:PO,ta:zO,Q:LO,yb:NO,zb:$O,ua:RO,ea:DO,P:FO,Ea:BO,va:UO,Z:jO,wb:GO,Zb:qO,S:WO,Ab:VO,tb:HO,ub:KO,vb:YO,fa:QO,xb:JO,Mb:ZO}}}async function qe(){function u(g,v){var M=br=g.exports;g={};for(let[P,L]of Object.entries(M))typeof L=="function"?(M=yS(L),g[P]=M):g[P]=L;return br=g,br=(function(){var P=br,L=Z=>Ie=>Z(Ie)>>>0,G=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=L(P.$b),P.Cc=G(P.Cc),P.Ec=L(P.Ec),P.rd=(Z=>(Ie,$e)=>Z(Ie,$e)>>>0)(P.rd),P.wd=L(P.wd),P.xd=G(P.xd),P.Bd=L(P.Bd),P})(),Iv.push(br.id),Mk=(g=br).$b,Tk=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,bb=e._OrtGetWebGpuDevice=g.Bc,Ju=g.Cc,Ht=e._free=g.Dc,zn=e._malloc=g.Ec,Sk=e._wgpuBufferRelease=g.Fc,Ok=e._wgpuCreateInstance=g.Gc,Ik=g.Hc,Ck=g.Ic,Pk=g.Jc,zk=g.Kc,Lk=g.Lc,Nk=g.Pc,$k=g.Zc,Rk=g._c,Dk=g.$c,vb=g.bd,kb=g.cd,Eb=g.dd,Ab=g.ed,ml=g.fd,Mb=g.gd,Fk=g.hd,Tb=g.kd,Bk=g.ld,Uk=g.md,jk=g.nd,Sb=g.od,Gk=g.pd,qk=g.qd,Ob=g.rd,xe=g.sd,hl=g.td,Wk=g.ud,pe=g.vd,Zu=g.wd,fe=g.xd,Vk=g.yd,Ib=g.zd,Hk=g.Ad,Xk=g.Bd,Kk=g.Cd,Cb=g.Dd,Yk=g.Ed,Qk=g.Fd,Jk=g.Gd,Zk=g.Hd,eE=g.Id,tE=g.Jd,rE=g.Kd,sE=g.Ld,nE=g.Md,oE=g.Nd,aE=g.Od,iE=g.Pd,lE=g.Qd,cE=g.Rd,uE=g.Td,pE=g.Ud,fE=g.Vd,dE=g.Wd,_E=g.Yd,mE=g.Zd,hE=g._d,gE=g.$d,wE=g.ae,xE=g.oe,yE=g.pe,bE=g.qe,vE=g.re,kE=g.se,EE=g.te,AE=g.ue,ME=g.ve,TE=g.we,SE=g.xe,OE=g.ye,IE=g.Ye,CE=g.Ze,PE=g._e,zE=g.$e,_=v,br}var d,h=Et();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(v,M)=>{g(u(v,M))})}):n?u(new WebAssembly.Instance(_,Et()),_):(B??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",Zt.url).href,d=await(async function(g){var v=B;if(!f&&!O(v))try{var M=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(M,g)}catch(P){T(`wasm streaming compile failed: ${P}`),T("falling back to ArrayBuffer instantiation")}return(async function(P,L){try{var G=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==B&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(G,L)}catch(Z){T(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(v,g)})(h),u(d.instance,d.module))}class ct{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var At=u=>{u.terminate(),u.onmessage=()=>{}},Fe=[],Se=0,rt=null,nr=u=>{qr.length==0&&(Lv(),zv(qr[0]));var d=qr.pop();if(!d)return 6;fl.push(d),Ms[u.Nc]=d,d.Nc=u.Nc;var h={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return d.postMessage(h,u.Yc),0},Oe=0,Be=(u,d,...h)=>{var g,v=16*h.length,M=fe(),P=Zu(v),L=P>>>3;for(g of h)typeof g=="bigint"?((b(),z)[L++>>>0]=1n,(b(),z)[L++>>>0]=g):((b(),z)[L++>>>0]=0n,(b(),Y)[L++>>>0]=g);return u=Uk(u,0,v,P,d),pe(M),u};function Tn(u){if(n)return Be(0,1,u);if(m=u,!(0{if(m=u,n)throw pl(u),"unwind";Tn(u)},qr=[],fl=[],Iv=[],Ms={},Cv=u=>{var d=u.Nc;delete Ms[d],qr.push(u),fl.splice(fl.indexOf(u),1),u.Nc=0,jk(d)};function Pv(){Iv.forEach(u=>u())}var zv=u=>new Promise(d=>{u.onmessage=v=>{var M=v.data;if(v=M.Oc,M.Vc&&M.Vc!=Ju()){var P=Ms[M.Vc];P?P.postMessage(M,M.Yc):T(`Internal error! Worker sent a message "${v}" to target pthread ${M.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?Vu():v==="spawnThread"?nr(M):v==="cleanupThread"?Mt(()=>{Cv(Ms[M.he])}):v==="loaded"?(u.loaded=!0,d(u)):M.target==="setimmediate"?u.postMessage(M):v==="uncaughtException"?u.onerror(M.error):v==="callHandler"?e[M.be](...M.args):v&&T(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw T(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);u.postMessage({Oc:"load",ce:g,ie:Wr,je:_})});function Lv(){var u=new Worker((()=>{let d=URL;return Zt.url>"file:"&&Zt.url<"file;"?new d("ort.webgpu.bundle.min.mjs",Zt.url):new URL(Zt.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});qr.push(u)}var Wr,DT=(u,d)=>{Oe=0,u=Cb(u,d),0-9007199254740992>u||9007199254740992>>=0);return(b(),U)[d.Qc+12>>>0]==0&&(Nv(d,!0),Wu--),$v(d,!1),qu.push(d),Xk(u)}var On=0,BT=()=>{xe(0,0);var u=qu.pop();Vk(u.Xc),On=0};function Nv(u,d){d=d?1:0,(b(),U)[u.Qc+12>>>0]=d}function $v(u,d){d=d?1:0,(b(),U)[u.Qc+13>>>0]=d}class ab{constructor(d){this.Xc=d,this.Qc=d-24}}var ib=u=>{var d=On;if(!d)return hl(0),0;var h=new ab(d);(b(),C)[h.Qc+16>>>2>>>0]=d;var g=(b(),C)[h.Qc+4>>>2>>>0];if(!g)return hl(0),d;for(var v of u){if(v===0||v===g)break;if(Hk(v,g,h.Qc+16))return hl(v),d}return hl(g),d};function UT(){return ib([])}function jT(u){return ib([u>>>0])}function GT(u,d,h,g){return ib([u>>>0,d>>>0,h>>>0,g>>>0])}var qT=()=>{var u=qu.pop();u||ce("no exception to throw");var d=u.Xc;throw(b(),U)[u.Qc+13>>>0]==0&&(qu.push(u),$v(u,!0),Nv(u,!1),Wu++),Ib(d),On=d};function WT(u,d,h){var g=new ab(u>>>=0);throw d>>>=0,h>>>=0,(b(),C)[g.Qc+16>>>2>>>0]=0,(b(),C)[g.Qc+4>>>2>>>0]=d,(b(),C)[g.Qc+8>>>2>>>0]=h,Ib(u),Wu++,On=u}var VT=()=>Wu;function Rv(u,d,h,g){return n?Be(2,1,u,d,h,g):Dv(u,d,h,g)}function Dv(u,d,h,g){if(u>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?Rv(u,d,h,g):(u={fe:h,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):nr(u))}function HT(u){throw On||=u>>>0,On}var Fv=globalThis.TextDecoder&&new TextDecoder,Bv=(u,d,h,g)=>{if(h=d+h,g)return h;for(;u[d]&&!(d>=h);)++d;return d},Uv=(u,d=0,h,g)=>{if(16<(h=Bv(u,d>>>=0,h,g))-d&&u.buffer&&Fv)return Fv.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,h):u.slice(d,h));for(g="";d(v=(240&v)==224?(15&v)<<12|M<<6|P:(7&v)<<18|M<<12|P<<6|63&u[d++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},In=(u,d,h)=>(u>>>=0)?Uv((b(),X),u,d,h):"";function jv(u,d,h){return n?Be(3,1,u,d,h):0}function Gv(u,d){if(n)return Be(4,1,u,d)}function qv(u,d){if(n)return Be(5,1,u,d)}function Wv(u,d,h){if(n)return Be(6,1,u,d,h)}function Vv(u,d,h){return n?Be(7,1,u,d,h):0}function Hv(u,d){if(n)return Be(8,1,u,d)}function Xv(u,d,h){if(n)return Be(9,1,u,d,h)}function Kv(u,d,h,g){if(n)return Be(10,1,u,d,h,g)}function Yv(u,d,h,g){if(n)return Be(11,1,u,d,h,g)}function Qv(u,d,h,g){if(n)return Be(12,1,u,d,h,g)}function Jv(u){if(n)return Be(13,1,u)}function Zv(u,d){if(n)return Be(14,1,u,d)}function ek(u,d,h){if(n)return Be(15,1,u,d,h)}var XT=()=>ce(""),or=u=>{u>>>=0;for(var d="";;){var h=(b(),X)[u++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},lb={},cb={},KT={},Cn=class extends Error{constructor(u){super(u),this.name="BindingError"}};function hr(u,d,h={}){return(function(g,v,M={}){var P=v.name;if(!g)throw new Cn(`type "${P}" must have a positive integer typeid pointer`);if(cb.hasOwnProperty(g)){if(M.de)return;throw new Cn(`Cannot register type '${P}' twice`)}cb[g]=v,delete KT[g],lb.hasOwnProperty(g)&&(v=lb[g],delete lb[g],v.forEach(L=>L()))})(u,d,h)}var tk=(u,d,h)=>{switch(d){case 1:return h?g=>(b(),U)[g>>>0]:g=>(b(),X)[g>>>0];case 2:return h?g=>(b(),K)[g>>>1>>>0]:g=>(b(),J)[g>>>1>>>0];case 4:return h?g=>(b(),R)[g>>>2>>>0]:g=>(b(),C)[g>>>2>>>0];case 8:return h?g=>(b(),z)[g>>>3>>>0]:g=>(b(),$)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function YT(u,d,h,g,v){u>>>=0,h>>>=0,d=or(d>>>0);let M=P=>P;if(g=g===0n){let P=8*h;M=L=>BigInt.asUintN(P,L),v=M(v)}hr(u,{name:d,Mc:M,Sc:(P,L)=>(typeof L=="number"&&(L=BigInt(L)),L),Rc:tk(d,h,!g),Tc:null})}function QT(u,d,h,g){hr(u>>>=0,{name:d=or(d>>>0),Mc:function(v){return!!v},Sc:function(v,M){return M?h:g},Rc:function(v){return this.Mc((b(),X)[v>>>0])},Tc:null})}var rk=[],Ts=[0,1,,1,null,1,!0,1,!1,1];function ub(u){9<(u>>>=0)&&--Ts[u+1]==0&&(Ts[u]=void 0,rk.push(u))}var Dt=u=>{if(!u)throw new Cn(`Cannot use deleted val. handle = ${u}`);return Ts[u]},Vt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=rk.pop()||Ts.length;return Ts[d]=u,Ts[d+1]=1,d}};function pb(u){return this.Mc((b(),C)[u>>>2>>>0])}var JT={name:"emscripten::val",Mc:u=>{var d=Dt(u);return ub(u),d},Sc:(u,d)=>Vt(d),Rc:pb,Tc:null};function ZT(u){return hr(u>>>0,JT)}var eS=(u,d)=>{switch(d){case 4:return function(h){return this.Mc((b(),ne)[h>>>2>>>0])};case 8:return function(h){return this.Mc((b(),Y)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function tS(u,d,h){h>>>=0,hr(u>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:eS(d,h),Tc:null})}function rS(u,d,h,g,v){u>>>=0,h>>>=0,d=or(d>>>0);let M=L=>L;if(g===0){var P=32-8*h;M=L=>L<

>>P,v=M(v)}hr(u,{name:d,Mc:M,Sc:(L,G)=>G,Rc:tk(d,h,g!==0),Tc:null})}function sS(u,d,h){function g(M){var P=(b(),C)[M>>>2>>>0];return M=(b(),C)[M+4>>>2>>>0],new v((b(),U).buffer,M,P)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];hr(u>>>=0,{name:h=or(h>>>0),Mc:g,Rc:g},{de:!0})}var gr=(u,d,h)=>{var g=(b(),X);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,M++}}g[d>>>0]=0,u=d-v}else u=0;return u},wr=u=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function nS(u,d){hr(u>>>=0,{name:d=or(d>>>0),Mc(h){var g=(b(),C)[h>>>2>>>0];return g=In(h+4,g,!0),Ht(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Cn("Cannot pass non-string to std::string");var M=v?wr(g):g.length,P=zn(4+M+1),L=P+4;return(b(),C)[P>>>2>>>0]=M,v?gr(g,L,M+1):(b(),X).set(g,L>>>0),h!==null&&h.push(Ht,P),P},Rc:pb,Tc(h){Ht(h)}})}var sk=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,oS=(u,d,h)=>{if(u>>>=1,16<(d=Bv((b(),J),u,d/2,h))-u&&sk)return sk.decode((b(),J).slice(u,d));for(h="";u>>0];h+=String.fromCharCode(g)}return h},aS=(u,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*u.length?h/2:u.length;for(var v=0;v>>1>>>0]=M,d+=2}return(b(),K)[d>>>1>>>0]=0,d-g},iS=u=>2*u.length,lS=(u,d,h)=>{var g="";u>>>=2;for(var v=0;!(v>=d/4);v++){var M=(b(),C)[u+v>>>0];if(!M&&!h)break;g+=String.fromCodePoint(M)}return g},cS=(u,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var v=0;v>>2>>>0]=M,(d+=4)+4>h)break}return(b(),R)[d>>>2>>>0]=0,d-g},uS=u=>{for(var d=0,h=0;h>>=0,d>>>=0,h=or(h>>>=0),d===2)var g=oS,v=aS,M=iS;else g=lS,v=cS,M=uS;hr(u,{name:h,Mc:P=>{var L=(b(),C)[P>>>2>>>0];return L=g(P+4,L*d,!0),Ht(P),L},Sc:(P,L)=>{if(typeof L!="string")throw new Cn(`Cannot pass non-string to C++ string type ${h}`);var G=M(L),Z=zn(4+G+d);return(b(),C)[Z>>>2>>>0]=G/d,v(L,Z+4,G+d),P!==null&&P.push(Ht,Z),Z},Rc:pb,Tc(P){Ht(P)}})}function fS(u,d){hr(u>>>=0,{ee:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function dS(u){Tb(u>>>0,!s,1,!r,131072,!1),Pv()}var Mt=u=>{if(!I)try{if(u(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function fb(u){u>>>=0,_S||(Atomics.waitAsync((b(),R),u>>>2,u).value.then(Vu),u+=128,Atomics.store((b(),R),u>>>2,1))}var Vu=()=>Mt(()=>{var u=Ju();u&&(fb(u),qk())});function mS(u,d){(u>>>=0)==d>>>0?setTimeout(Vu):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=Ms[u])&&u.postMessage({Oc:"checkMailbox"})}var db=[];function hS(u,d,h,g,v){for(d>>>=0,v>>>=0,db.length=0,h=v>>>3,g=v+g>>>3;h>>0]?(b(),z)[h++>>>0]:(b(),Y)[h++>>>0],db.push(M)}return(d?Pb[d]:eI[u])(...db)}var gS=()=>{Oe=0};function wS(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):Cv(Ms[u])}function xS(u){}var Hu=u=>{try{u()}catch(d){ce(d)}};function yS(u){var d=(...h)=>{Xu.push(u);try{return u(...h)}finally{I||(Xu.pop(),ar&&Vr===1&&Xu.length===0&&(Vr=0,Oe+=1,Hu(CE),typeof Fibers<"u"&&Fibers.Be()))}};return ak.set(u,d),d}var Vr=0,ar=null,nk=0,Xu=[],_b=new Map,ok=new Map,ak=new Map,bS=0,mb=null,vS=[],ik=u=>(function(d){if(!I){if(Vr===0){var h=!1,g=!1;d((v=0)=>{if(!I&&(nk=v,h=!0,g)){Vr=2,Hu(()=>PE(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var M=(function(){var G=(b(),R)[ar+8>>>2>>>0];return G=ok.get(G),G=ak.get(G),--Oe,G()})()}catch(G){M=G,v=!0}var P=!1;if(!ar){var L=mb;L&&(mb=null,(v?L.reject:L.resolve)(M),P=!0)}if(v&&!P)throw M}}),g=!0,h||(Vr=1,ar=(function(){var v=zn(65548),M=v+12;if((b(),C)[v>>>2>>>0]=M,(b(),C)[v+4>>>2>>>0]=M+65536,M=Xu[0],!_b.has(M)){var P=bS++;_b.set(M,P),ok.set(P,M)}return M=_b.get(M),(b(),R)[v+8>>>2>>>0]=M,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Hu(()=>IE(ar)))}else Vr===2?(Vr=0,Hu(zE),Ht(ar),ar=null,vS.forEach(Mt)):ce(`invalid state: ${Vr}`);return nk}})(d=>{u().then(d)});function kS(u){return u>>>=0,ik(async()=>{var d=await Dt(u);return Vt(d)})}var hb=[],ES=u=>{var d=hb.length;return hb.push(u),d},AS=(u,d)=>{for(var h=Array(u),g=0;g>>2>>>0],P=cb[M];if(P===void 0)throw u=`parameter ${g}`,M=Mk(M),d=or(M),Ht(M),new Cn(`${u} has unknown type ${d}`);h[v]=P}return h},MS=(u,d,h)=>{var g=[];return u=u(g,h),g.length&&((b(),C)[d>>>2>>>0]=Vt(g)),u},TS={},Ku=u=>{var d=TS[u];return d===void 0?or(u):d};function SS(u,d,h){var[g,...v]=AS(u,d>>>0);d=g.Sc.bind(g);var M=v.map(G=>G.Rc.bind(G));u--;var P={toValue:Dt};switch(u=M.map((G,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=G,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var L="toValue(handle)";break;case 2:L="new (toValue(handle))";break;case 3:L="";break;case 1:P.getStringOrSymbol=Ku,L="toValue(handle)[getStringOrSymbol(methodName)]"}return L+=`(${u})`,g.ee||(P.toReturnWire=d,P.emval_returnValue=MS,L=`return emval_returnValue(toReturnWire, destructorsRef, ${L})`),L=`return function (handle, methodName, destructorsRef, args) { ${L} }`,h=new Function(Object.keys(P),L)(...Object.values(P)),L=`methodCaller<(${v.map(G=>G.name)}) => ${g.name}>`,ES(Object.defineProperty(h,"name",{value:L}))}function OS(u,d){return d>>>=0,(u=Dt(u>>>0))==Dt(d)}function IS(u){return(u>>>=0)?(u=Ku(u),Vt(globalThis[u])):Vt(globalThis)}function CS(u){return u=Ku(u>>>0),Vt(e[u])}function PS(u,d){return d>>>=0,u=Dt(u>>>0),d=Dt(d),Vt(u[d])}function zS(u){9<(u>>>=0)&&(Ts[u+1]+=1)}function lk(u,d,h,g,v){return hb[u>>>0](d>>>0,h>>>0,g>>>0,v>>>0)}function LS(u,d,h,g,v){return lk(u>>>0,d>>>0,h>>>0,g>>>0,v>>>0)}function NS(){return Vt([])}function $S(u){u=Dt(u>>>0);for(var d=Array(u.length),h=0;h>>0))}function DS(){return Vt({})}function FS(u){for(var d=Dt(u>>>=0);d.length;){var h=d.pop();d.pop()(h)}ub(u)}function BS(u,d,h){d>>>=0,h>>>=0,u=Dt(u>>>0),d=Dt(d),h=Dt(h),u[d]=h}function US(u,d){u=ht(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getUTCSeconds(),(b(),R)[d+4>>>2>>>0]=u.getUTCMinutes(),(b(),R)[d+8>>>2>>>0]=u.getUTCHours(),(b(),R)[d+12>>>2>>>0]=u.getUTCDate(),(b(),R)[d+16>>>2>>>0]=u.getUTCMonth(),(b(),R)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(b(),R)[d+28>>>2>>>0]=u}var ck=u=>u%4==0&&(u%100!=0||u%400==0),uk=[0,31,60,91,121,152,182,213,244,274,305,335],pk=[0,31,59,90,120,151,181,212,243,273,304,334];function jS(u,d){u=ht(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getSeconds(),(b(),R)[d+4>>>2>>>0]=u.getMinutes(),(b(),R)[d+8>>>2>>>0]=u.getHours(),(b(),R)[d+12>>>2>>>0]=u.getDate(),(b(),R)[d+16>>>2>>>0]=u.getMonth(),(b(),R)[d+20>>>2>>>0]=u.getFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getDay();var h=(ck(u.getFullYear())?uk:pk)[u.getMonth()]+u.getDate()-1|0;(b(),R)[d+28>>>2>>>0]=h,(b(),R)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),h=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(h!=g&&u.getTimezoneOffset()==Math.min(g,h)),(b(),R)[d+32>>>2>>>0]=u}function GS(u){u>>>=0;var d=new Date((b(),R)[u+20>>>2>>>0]+1900,(b(),R)[u+16>>>2>>>0],(b(),R)[u+12>>>2>>>0],(b(),R)[u+8>>>2>>>0],(b(),R)[u+4>>>2>>>0],(b(),R)[u>>>2>>>0],0),h=(b(),R)[u+32>>>2>>>0],g=d.getTimezoneOffset(),v=new Date(d.getFullYear(),6,1).getTimezoneOffset(),M=new Date(d.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(M,v);return 0>h?(b(),R)[u+32>>>2>>>0]=+(v!=M&&P==g):0>>2>>>0]=d.getDay(),h=(ck(d.getFullYear())?uk:pk)[d.getMonth()]+d.getDate()-1|0,(b(),R)[u+28>>>2>>>0]=h,(b(),R)[u>>>2>>>0]=d.getSeconds(),(b(),R)[u+4>>>2>>>0]=d.getMinutes(),(b(),R)[u+8>>>2>>>0]=d.getHours(),(b(),R)[u+12>>>2>>>0]=d.getDate(),(b(),R)[u+16>>>2>>>0]=d.getMonth(),(b(),R)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function fk(u,d,h,g,v,M,P){return n?Be(16,1,u,d,h,g,v,M,P):-52}function dk(u,d,h,g,v,M){if(n)return Be(17,1,u,d,h,g,v,M)}var dl={},qS=()=>performance.timeOrigin+performance.now();function _k(u,d){if(n)return Be(18,1,u,d);if(dl[u]&&(clearTimeout(dl[u].id),delete dl[u]),!d)return 0;var h=setTimeout(()=>{delete dl[u],Mt(()=>Gk(u,performance.timeOrigin+performance.now()))},d);return dl[u]={id:h,Ae:d},0}function WS(u,d,h,g){u>>>=0,d>>>=0,h>>>=0,g>>>=0;var v=new Date().getFullYear(),M=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var P=Math.max(M,v);(b(),C)[u>>>2>>>0]=60*P,(b(),R)[d>>>2>>>0]=+(M!=v),u=(d=L=>{var G=Math.abs(L);return`UTC${0<=L?"-":"+"}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`})(M),d=d(v),vDate.now(),HS=1;function XS(u,d,h){if(h>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!HS)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(b(),z)[h>>>3>>>0]=BigInt(u),0}var gb=[],mk=(u,d)=>{gb.length=0;for(var h;h=(b(),X)[u++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,gb.push(h==112?(b(),C)[d>>>2>>>0]:h==106?(b(),z)[d>>>3>>>0]:h==105?(b(),R)[d>>>2>>>0]:(b(),Y)[d>>>3>>>0]),d+=g?8:4}return gb};function KS(u,d,h){return u>>>=0,d=mk(d>>>0,h>>>0),Pb[u](...d)}function YS(u,d,h){return u>>>=0,d=mk(d>>>0,h>>>0),Pb[u](...d)}var QS=()=>{};function JS(u,d){return T(In(u>>>0,d>>>0))}var ZS=()=>{throw Oe+=1,"unwind"};function eO(){return 4294901760}var tO=()=>1,rO=()=>navigator.hardwareConcurrency;function sO(u){u>>>=0;var d=(b(),X).length;if(u<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Wr.buffer.byteLength+65535)/65536|0;try{Wr.grow(g),le();var v=1;break e}catch{}v=void 0}if(v)return!0}return!1}var ir=u=>{var d=wr(u)+1,h=Zu(d);return gr(u,h,d),h},wb=(u,d)=>{(b(),C)[u>>>2>>>0]=d;var h=(b(),C)[u>>>2>>>0];(b(),C)[u+4>>>2>>>0]=(d-h)/4294967296},_l=u=>(b(),C)[u>>>2>>>0]+4294967296*(b(),R)[u+4>>>2>>>0],gt=[],nO=(u,d)=>{gt[u>>>0]=d},xr=[],Yu=[],Pn=(u,d)=>{Yu[u]=new Promise(h=>d.finally(()=>h(u)))},oe=u=>{if(u)return gt[u>>>0]},oO=(u,d)=>{for(u=(b(),C)[u>>>2>>>0];u;u=(b(),C)[u>>>2>>>0])d[(b(),R)[u+4>>>2>>>0]](u)},Qu=(u,d,h)=>{(b(),C)[u>>>2>>>0]=d,(b(),C)[u+4>>>2>>>0]=h},hk=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],In(d,u)},yr=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],d?In(d,u):u===0?"":void 0},aO=u=>{var d=yr(u+4),h=(h=(b(),C)[u+12>>>2>>>0])?oe(h):"auto";if(u+=16){var g=oe((b(),C)[u+4>>>2>>>0]),v=(b(),C)[u+16>>>2>>>0],M=(b(),C)[u+20>>>2>>>0];if(v){for(var P={},L=0;L>>3>>>0]}v=P}else v=void 0;u={module:g,constants:v,entryPoint:yr(u+8)}}else u=void 0;return{label:d,layout:h,compute:u}},gk=(u,d)=>{function h(g,v){g=u[g],(b(),C)[d+v>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),wb(d+64,u.maxUniformBufferBindingSize),wb(d+72,u.maxStorageBufferBindingSize),h("maxVertexBuffers",88),wb(d+96,u.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&h("maxImmediateSize",148)},iO=[,"validation","out-of-memory","internal"],lO=[,"compatibility","core"],wk={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},cO=[,"low-power","high-performance"],uO=[,"occlusion","timestamp"],pO={undefined:1,unknown:1,destroyed:2};function fO(u,d,h,g,v,M){d=ht(d),h=ht(h),g>>>=0,v>>>=0,M>>>=0;var P=oe(u>>>0);if(u={},M){var L=(b(),C)[M+12>>>2>>>0];if(L){var G=(b(),C)[M+16>>>2>>>0];u.requiredFeatures=Array.from((b(),C).subarray(G>>>2>>>0,G+4*L>>>2>>>0),ae=>wk[ae])}var Z=(b(),C)[M+20>>>2>>>0];if(Z){let ae=function(Tt,pt,Ss=!1){pt=Z+pt,(pt=(b(),C)[pt>>>2>>>0])==4294967295||Ss&&pt==0||(Ue[Tt]=pt)},ut=function(Tt,pt){pt=Z+pt;var Ss=(b(),C)[pt>>>2>>>0],RI=(b(),C)[pt+4>>>2>>>0];Ss==4294967295&&RI==4294967295||(Ue[Tt]=_l(pt))};var Ie=ae,$e=ut,Ue={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),ut("maxUniformBufferBindingSize",64),ut("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),ut("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),u.requiredLimits=Ue}(L=(b(),C)[M+24>>>2>>>0])&&(L={label:yr(L+4)},u.defaultQueue=L),u.label=yr(M+4)}Oe+=1,Pn(d,P.requestDevice(u).then(ae=>{--Oe,Mt(()=>{gt[v>>>0]=ae.queue,gt[g>>>0]=ae,Oe+=1,Pn(h,ae.lost.then(ut=>{Mt(()=>{ae.onuncapturederror=()=>{};var Tt=fe(),pt=ir(ut.message);kb(h,pO[ut.reason],pt),pe(Tt)}),--Oe})),ae.onuncapturederror=ut=>{var Tt=5;ut.error instanceof GPUValidationError?Tt=2:ut.error instanceof GPUOutOfMemoryError?Tt=3:ut.error instanceof GPUInternalError&&(Tt=4);var pt=fe();ut=ir(ut.error.message),Fk(g,Tt,ut),pe(pt)},"adapterInfo"in ae||(ae.adapterInfo=P.info),Mb(d,1,g,0)})},ae=>{--Oe,Mt(()=>{var ut=fe(),Tt=ir(ae.message);Mb(d,3,g,Tt),h&&kb(h,4,Tt),pe(ut)})}))}function dO(u){var d=oe(u>>>=0),h=xr[u];if(h){for(var g=0;g>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=Ob(16,v.byteLength);return(b(),X).set(new Uint8Array(v),M>>>0),xr[u].push(()=>Ht(M)),M}function mO(u,d,h){h>>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=Ob(16,v.byteLength);return(b(),X).fill(0,M,v.byteLength),xr[u].push(()=>{new Uint8Array(v).set((b(),X).subarray(M>>>0,M+v.byteLength>>>0)),Ht(M)}),M}function hO(u,d,h,g,v){u>>>=0,d=ht(d),h=ht(h),v>>>=0;var M=oe(u);xr[u]=[],v==4294967295&&(v=void 0),Oe+=1,Pn(d,M.mapAsync(h,g>>>0,v).then(()=>{--Oe,Mt(()=>{Eb(d,1,0)})},P=>{--Oe,Mt(()=>{fe();var L=ir(P.message);Eb(d,P.name==="AbortError"?4:P.name==="OperationError"?3:0,L),delete xr[u]})}))}function gO(u){var d=oe(u>>>=0),h=xr[u];if(h){for(var g=0;g>>0]}function xO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=!!(b(),C)[d+32>>>2>>>0];d={label:yr(d+4),usage:(b(),C)[d+16>>>2>>>0],size:_l(d+24),mappedAtCreation:g},u=oe(u);try{var v=u.createBuffer(d)}catch{return!1}return gt[h>>>0]=v,g&&(xr[h]=[]),!0}function yO(u,d,h,g){u>>>=0,d=ht(d),g>>>=0,h=aO(h>>>0),u=oe(u),Oe+=1,Pn(d,u.createComputePipelineAsync(h).then(v=>{--Oe,Mt(()=>{gt[g>>>0]=v,vb(d,1,g,0)})},v=>{--Oe,Mt(()=>{var M=fe(),P=ir(v.message);vb(d,v.reason==="validation"?3:v.reason==="internal"?4:0,g,P),pe(M)})}))}function bO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=(b(),C)[d>>>2>>>0],v=(b(),R)[g+4>>>2>>>0];d={label:yr(d+4),code:""},v===2&&(d.code=hk(g+8)),u=oe(u).createShaderModule(d),gt[h>>>0]=u}var vO=u=>{(u=oe(u)).onuncapturederror=null,u.destroy()};function kO(u,d){d=ht(d),u=oe(u>>>0),Oe+=1,Pn(d,u.popErrorScope().then(h=>{--Oe,Mt(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var v=fe(),M=h?ir(h.message):0;Ab(d,1,g,M),pe(v)})},h=>{--Oe,Mt(()=>{var g=fe(),v=ir(h.message);Ab(d,1,5,v),pe(g)})}))}function EO(u,d,h,g){if(d=ht(d),g>>>=0,h>>>=0){var v={featureLevel:lO[(b(),R)[h+4>>>2>>>0]],powerPreference:cO[(b(),R)[h+8>>>2>>>0]],forceFallbackAdapter:!!(b(),C)[h+12>>>2>>>0]};(u=(b(),C)[h>>>2>>>0])!==0&&(b(),v.De=!!(b(),C)[u+8>>>2>>>0])}"gpu"in navigator?(Oe+=1,Pn(d,navigator.gpu.requestAdapter(v).then(M=>{--Oe,Mt(()=>{if(M)gt[g>>>0]=M,ml(d,1,g,0);else{var P=fe(),L=ir("WebGPU not available on this browser (requestAdapter returned null)");ml(d,3,g,L),pe(P)}})},M=>{--Oe,Mt(()=>{var P=fe(),L=ir(M.message);ml(d,4,g,L),pe(P)})}))):(v=fe(),u=ir("WebGPU not available on this browser (navigator.gpu is not available)"),ml(d,3,g,u),pe(v))}function AO(u,d,h){return u>>>=0,d>>>=0,h>>>=0,ik(async()=>{var g=[];if(h){var v=(b(),R)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(L=>setTimeout(L,v,0))}else g.length=d;for(var M=0;M{if(!xb){var u,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in yb)yb[u]===void 0?delete d[u]:d[u]=yb[u];var h=[];for(u in d)h.push(`${u}=${d[u]}`);xb=h}return xb};function yk(u,d){if(n)return Be(19,1,u,d);u>>>=0,d>>>=0;var h,g=0,v=0;for(h of xk()){var M=d+g;(b(),C)[u+v>>>2>>>0]=M,g+=gr(h,M,1/0)+1,v+=4}return 0}function bk(u,d){if(n)return Be(20,1,u,d);u>>>=0,d>>>=0;var h=xk();for(var g of((b(),C)[u>>>2>>>0]=h.length,u=0,h))u+=wr(g)+1;return(b(),C)[d>>>2>>>0]=u,0}function vk(u){return n?Be(21,1,u):52}function kk(u,d,h,g){return n?Be(22,1,u,d,h,g):52}function Ek(u,d,h,g){return n?Be(23,1,u,d,h,g):70}var MO=[null,[],[]];function Ak(u,d,h,g){if(n)return Be(24,1,u,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var v=0,M=0;M>>2>>>0],L=(b(),C)[d+4>>>2>>>0];d+=8;for(var G=0;G>>0],$e=MO[Z];Ie===0||Ie===10?((Z===1?S:T)(Uv($e)),$e.length=0):$e.push(Ie)}v+=L}return(b(),C)[g>>>2>>>0]=v,0}function TO(u){return u>>>0}function SO(u,d){return gk(oe(u>>>0).limits,d>>>0),1}function OO(u,d){return oe(u>>>0).features.has(wk[d])}function IO(u){return BigInt(oe(u>>>0).size)}function CO(u){return BigInt(oe(u>>>0).usage)}function PO(u,d){if(u>>>=0,d>>>=0){var h=yr(d+4);h={label:h,timestampWrites:d=(d=(b(),C)[d+12>>>2>>>0])!==0?{querySet:oe((b(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(b(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(b(),C)[d+12>>>2>>>0]}:void 0}}return d=oe(u),u=Lk(0),h=d.beginComputePass(h),gt[u>>>0]=h,u}function zO(u,d,h,g){h=ht(h),(g=ht(g))==-1&&(g=void 0),(u=oe(u>>>0)).clearBuffer(oe(d>>>0),h,g)}function LO(u,d,h,g,v,M){h=ht(h),v=ht(v),M=ht(M),oe(u>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),v,M)}function NO(u){var d=oe(u>>>0);return u=Pk(0),d=d.finish(),gt[u>>>0]=d,u}function $O(u,d,h,g,v,M){M=ht(M),oe(u>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(v>>>0),M)}function RO(u,d,h,g){oe(u>>>0).dispatchWorkgroups(d,h,g)}function DO(u,d,h){h=ht(h),oe(u>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function FO(u){oe(u>>>0).end()}function BO(u,d,h,g,v){g>>>=0,v>>>=0,u=oe(u>>>0),h=oe(h>>>0),g==0?u.setBindGroup(d,h):u.setBindGroup(d,h,(b(),C),v>>>2,g)}function UO(u,d){oe(u>>>0).setPipeline(oe(d>>>0))}function jO(u,d,h){oe(u>>>0).Ce(oe(d>>>0),h)}function GO(u,d){var h=oe(u>>>0);return u=Ck(0),d=h.getBindGroupLayout(d),gt[u>>>0]=d,u}function qO(u,d){function h(v){var M=(b(),C)[v+8>>>2>>>0],P=(b(),C)[v+32>>>2>>>0],L=(b(),C)[v+36>>>2>>>0],G=0;return oO(v,{327681:Z=>{G=(b(),C)[Z+8>>>2>>>0]}}),M?((P=_l(v+24))==-1&&(P=void 0),M={buffer:oe(M),offset:_l(v+16),size:P}):M=oe(P||L||G),{binding:(b(),C)[v+4>>>2>>>0],resource:M}}u>>>=0,d={label:yr(4+(d>>>=0)),layout:oe((b(),C)[d+12>>>2>>>0]),entries:(function(v,M){for(var P=[],L=0;L>>2>>>0],(b(),C)[d+20>>>2>>>0])},u=oe(u);var g=Ik(0);return nO(g,u.createBindGroup(d)),g}function WO(u,d){var h;return u>>>=0,(d>>>=0)&&(h={label:yr(d+4)}),d=oe(u),u=zk(0),h=d.createCommandEncoder(h),gt[u>>>0]=h,u}function VO(u,d){u>>>=0,d>>>=0,d={type:uO[(b(),R)[d+12>>>2>>>0]],count:(b(),C)[d+16>>>2>>>0]};var h=oe(u);return u=Nk(0),d=h.createQuerySet(d),gt[u>>>0]=d,u}function HO(u,d){u=oe(u>>>0).adapterInfo,d>>>=0,(b(),C)[d+52>>>2>>>0]=u.subgroupMinSize,(b(),C)[d+56>>>2>>>0]=u.subgroupMaxSize;var h=u.vendor+u.architecture+u.device+u.description,g=wr(h)+1,v=zn(g);return v&&gr(h,v,g),h=v,g=wr(u.vendor),Qu(d+4,h,g),h+=g,g=wr(u.architecture),Qu(d+12,h,g),h+=g,g=wr(u.device),Qu(d+20,h,g),Qu(d+28,h+g,wr(u.description)),(b(),R)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(b(),R)[d+40>>>2>>>0]=u,(b(),C)[d+44>>>2>>>0]=0,(b(),C)[d+48>>>2>>>0]=0,1}var XO={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function KO(u,d){d>>>=0;var h=oe(u>>>0);u=zn(4*h.features.size);var g=0,v=0;for(let M of h.features)0<=(h=XO[M])&&((b(),R)[u+g>>>2>>>0]=h,g+=4,v++);(b(),C)[d+4>>>2>>>0]=u,(b(),C)[d>>>2>>>0]=v}function YO(u,d){return gk(oe(u>>>0).limits,d>>>0),1}function QO(u,d){oe(u>>>0).pushErrorScope(iO[d])}function JO(u,d,h){d>>>=0,h>>>=0,u=oe(u>>>0),d=Array.from((b(),R).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),u.submit(d)}function ZO(u,d,h,g,v){h=ht(h),g>>>=0,v>>>=0,u=oe(u>>>0),d=oe(d>>>0),g=(b(),X).subarray(g>>>0,g+v>>>0),u.writeBuffer(d,h,g,0,v)}n||(function(){for(var u=e.numThreads-1;u--;)Lv();Fe.push(async()=>{var d=(async function(){if(!n)return Promise.all(qr.map(zv))})();Se++,await d,--Se==0&&rt&&(d=rt,rt=null,d())})})(),n||(Wr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>fe(),e.stackRestore=u=>pe(u),e.stackAlloc=u=>Zu(u),e.setValue=function(u,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(b(),U)[u>>>0]=d;break;case"i16":(b(),K)[u>>>1>>>0]=d;break;case"i32":(b(),R)[u>>>2>>>0]=d;break;case"i64":(b(),z)[u>>>3>>>0]=BigInt(d);break;case"float":(b(),ne)[u>>>2>>>0]=d;break;case"double":(b(),Y)[u>>>3>>>0]=d;break;case"*":(b(),C)[u>>>2>>>0]=d;break;default:ce(`invalid type for setValue: ${h}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(b(),U)[u>>>0];case"i16":return(b(),K)[u>>>1>>>0];case"i32":return(b(),R)[u>>>2>>>0];case"i64":return(b(),z)[u>>>3>>>0];case"float":return(b(),ne)[u>>>2>>>0];case"double":return(b(),Y)[u>>>3>>>0];case"*":return(b(),C)[u>>>2>>>0];default:ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=In,e.stringToUTF8=gr,e.lengthBytesUTF8=wr;var Mk,Tk,bb,Ju,Ht,zn,Sk,Ok,Ik,Ck,Pk,zk,Lk,Nk,$k,Rk,Dk,vb,kb,Eb,Ab,ml,Mb,Fk,Tb,Bk,Uk,jk,Sb,Gk,qk,Ob,xe,hl,Wk,pe,Zu,fe,Vk,Ib,Hk,Xk,Kk,Cb,Yk,Qk,Jk,Zk,eE,tE,rE,sE,nE,oE,aE,iE,lE,cE,uE,pE,fE,dE,_E,mE,hE,gE,wE,xE,yE,bE,vE,kE,EE,AE,ME,TE,SE,OE,IE,CE,PE,zE,br,eI=[Tn,pl,Rv,jv,Gv,qv,Wv,Vv,Hv,Xv,Kv,Yv,Qv,Jv,Zv,ek,fk,dk,_k,yk,bk,vk,kk,Ek,Ak],Pb={970348:(u,d,h,g,v)=>{if(e===void 0||!e.Uc)return 1;if((u=In(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>u.byteLength)return 3;try{let M=u.subarray(d,d+h);switch(v){case 0:(b(),X).set(M,g>>>0);break;case 1:e.ad?e.ad(g,M):e.ne(g,M);break;default:return 4}return 0}catch{return 4}},971172:(u,d,h)=>{e.Sd(u,(b(),X).subarray(d>>>0,d+h>>>0))},971236:()=>e.le(),971278:u=>{e.jd(u)},971315:()=>typeof wasmOffsetConverter<"u"};function tI(u,d,h,g){var v=fe();try{return sE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function rI(u,d,h){var g=fe();try{return eE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function sI(u){var d=fe();try{Yk(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function nI(u,d){var h=fe();try{return Cb(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function oI(u,d,h){var g=fe();try{Kk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function aI(u,d){var h=fe();try{nE(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function iI(u,d,h,g,v,M,P){var L=fe();try{return Zk(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function lI(u,d,h,g,v,M){var P=fe();try{Qk(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function cI(u,d,h,g){var v=fe();try{rE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function uI(u,d,h,g,v,M,P){var L=fe();try{aE(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function pI(u,d,h,g,v,M,P){var L=fe();try{iE(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function fI(u,d,h,g,v,M,P,L){var G=fe();try{hE(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function dI(u,d,h,g,v,M,P,L,G,Z,Ie,$e){var Ue=fe();try{lE(u,d,h,g,v,M,P,L,G,Z,Ie,$e)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function _I(u,d,h,g,v){var M=fe();try{return oE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function mI(u,d,h,g,v){var M=fe();try{Jk(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function hI(u,d,h,g,v,M,P,L){var G=fe();try{tE(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function gI(u){var d=fe();try{return gE(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function wI(u,d,h){var g=fe();try{return wE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function xI(u,d){var h=fe();try{return OE(u,d)}catch(g){if(pe(h),g!==g+0)throw g;return xe(1,0),0n}}function yI(u){var d=fe();try{return cE(u)}catch(h){if(pe(d),h!==h+0)throw h;return xe(1,0),0n}}function bI(u,d,h,g){var v=fe();try{return xE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function vI(u,d,h,g,v){var M=fe();try{return yE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function kI(u,d,h,g,v,M){var P=fe();try{return bE(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function EI(u,d,h,g,v,M){var P=fe();try{return _E(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function AI(u,d,h,g,v,M){var P=fe();try{return vE(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function MI(u,d,h,g,v,M,P,L){var G=fe();try{return mE(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function TI(u,d,h,g,v){var M=fe();try{return kE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;return xe(1,0),0n}}function SI(u,d,h,g){var v=fe();try{return EE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function OI(u,d,h,g){var v=fe();try{return AE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function II(u,d,h,g,v,M,P,L,G,Z,Ie,$e){var Ue=fe();try{return ME(u,d,h,g,v,M,P,L,G,Z,Ie,$e)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function CI(u,d,h,g,v,M,P,L,G,Z,Ie){var $e=fe();try{TE(u,d,h,g,v,M,P,L,G,Z,Ie)}catch(Ue){if(pe($e),Ue!==Ue+0)throw Ue;xe(1,0)}}function PI(u,d,h,g,v,M,P,L,G,Z,Ie,$e,Ue,ae,ut,Tt){var pt=fe();try{SE(u,d,h,g,v,M,P,L,G,Z,Ie,$e,Ue,ae,ut,Tt)}catch(Ss){if(pe(pt),Ss!==Ss+0)throw Ss;xe(1,0)}}function zI(u,d,h){var g=fe();try{return pE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;return xe(1,0),0n}}function LI(u,d,h){var g=fe();try{return uE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function NI(u,d,h){var g=fe();try{return fE(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function $I(u,d,h,g){var v=fe();try{dE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function ep(){if(0{let d=new WeakMap,h,g,v=1;e.webgpuRegisterDevice=L=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(L){var G=d.get(L);if(!G){let Z=((Ie,$e=0)=>{var Ue=Dk($e);return $e=Rk($e,Ue),gt[Ue>>>0]=Ie.queue,gt[$e>>>0]=Ie,$e})(L,G=Ok(0));G=[v++,G,Z],d.set(L,G)}return h=L,g=G[0],G}h=void 0,g=0};let M=new Map;e.webgpuOnCreateSession=L=>{if(g!==void 0){var G=g;if(g=void 0,L){let Z=bb(G);M.set(L,Z),G===0&&u(h??oe(Z))}h=void 0}},e.webgpuOnReleaseSession=L=>{M.delete(L)};let P=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(L,G,Z)=>{if(Z)return L[P]=[Z,NaN],Z;if(Z=L[P])return Z[1]++,Z[0];if((G=M.get(G))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return G=((Ie,$e=0)=>(Ie.mapState==="unmapped"||ce(),$e=$k($e),gt[$e>>>0]=Ie,$e))(L,G),L[P]=[G,1],G},e.webgpuUnregisterBuffer=L=>{let G=L[P];if(!G)throw Error("Buffer is not registered");G[1]--,G[1]===0&&(Sk(G[0]),delete L[P])},e.webgpuGetBuffer=L=>oe(L),e.webgpuCreateDownloader=(L,G,Z)=>{if((Z=M.get(Z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Ie=oe(Z),$e=16*Math.ceil(Number(G)/16);return async()=>{let Ue=Ie.createBuffer({size:$e,usage:9});try{let ae=Ie.createCommandEncoder();return ae.copyBufferToBuffer(L,0,Ue,0,$e),Ie.queue.submit([ae.finish()]),await Ue.mapAsync(GPUMapMode.READ),Ue.getMappedRange().slice(0,G)}finally{Ue.destroy()}}},e.ad=(L,G)=>{var Z=G.buffer;let Ie=G.byteOffset,$e=G.byteLength;if(G=16*Math.ceil(Number($e)/16),L=oe(L),!h){var Ue=bb(g);h=oe(Ue)}let ae=(Ue=h.createBuffer({mappedAtCreation:!0,size:G,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(Z,Ie,$e)),Ue.unmap(),(Z=h.createCommandEncoder()).copyBufferToBuffer(Ue,0,L,0,G),h.queue.submit([Z.finish()]),Ue.destroy()}},e.webnnInit=u=>{let d=u[0];[e.le,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.ke,e.webnnEnableTraceEvent]=u.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.ke,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,v,M)=>d.registerMLTensor(h,g,v,M),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,v,M,P,L)=>d.registerMLConstant(h,g,v,M,P,e.Uc,L),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},Q?e:new Promise((u,d)=>{w=u,x=d})}var L2,UA,NL=ve(()=>{"use strict";L2=BA,UA=globalThis.self?.name?.startsWith("em-pthread"),UA&&BA()}),t1,g1,jA,zt,N2,wp,GA,qA,r1,WA,s1,$2,n1,R2,M1=ve(()=>{"use strict";A1(),t1=typeof location>"u"?void 0:location.origin,g1=Zt.url>"file:"&&Zt.url<"file;",jA=()=>{if(g1){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",Zt.url).href,t1).href}return Zt.url},zt=jA(),N2=()=>{if(zt&&!zt.startsWith("blob:"))return zt.substring(0,zt.lastIndexOf("/")+1)},wp=(t,e)=>{try{let r=e??zt;return(r?new URL(t,r):new URL(t)).origin===t1}catch{return!1}},GA=(t,e)=>{let r=e??zt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},qA=(t,e)=>`${e??"./"}${t}`,r1=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},WA=async t=>(await import(t)).default,s1=(LL(),Ep(C2)).default,$2=async()=>{if(!zt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(wp(zt))return[void 0,s1()];let t=await r1(zt);return[t,s1(t)]},n1=(NL(),Ep(z2)).default,R2=async(t,e,r,s)=>{let n=n1&&!(t||e);if(n)if(zt)n=wp(zt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,n1];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??GA(o,e),i=r&&a&&!wp(a,e),l=i?await r1(a):a??qA(o,e);return[i?l:void 0,await WA(l)]}}}),o1,xp,Ol,a1,VA,HA,XA,T1,De,qs=ve(()=>{"use strict";M1(),xp=!1,Ol=!1,a1=!1,VA=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},HA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},XA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},T1=async t=>{if(xp)return Promise.resolve();if(Ol)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(a1)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ol=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!XA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!HA())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=VA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=t.wasmBinary,[f,_]=await R2(i,o,r>1,!!p||!!c),m=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{m=!0,x()},e)})),w.push(new Promise((x,k)=>{let A={numThreads:r};if(p)A.wasmBinary=p,A.locateFile=E=>E;else if(c||o)A.locateFile=E=>c??o+E;else if(i&&i.indexOf("blob:")!==0)A.locateFile=E=>new URL(E,i).href;else if(f){let E=N2();E&&(A.locateFile=S=>E+S)}_(A).then(E=>{Ol=!1,xp=!0,o1=E,x(),f&&URL.revokeObjectURL(f)},E=>{Ol=!1,a1=!0,k(E)})})),await Promise.race(w),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(xp&&o1)return o1;throw new Error("WebAssembly is not initialized yet.")}}),Lt,Mp,Le,S1=ve(()=>{"use strict";qs(),Lt=(t,e)=>{let r=De(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Mp=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Mp(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Le=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),D2,$L=ve(()=>{"use strict";qs(),S1(),D2=t=>{let e=De(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=Lt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Le("Can't create run options."),t?.extra!==void 0&&Mp(t.extra,"",new WeakSet,(a,i)=>{let l=Lt(a,s),c=Lt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Le(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),KA,YA,QA,yp,ts,JA,F2,RL=ve(()=>{"use strict";qs(),S1(),KA=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},YA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},QA=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},yp=(t,e,r,s)=>{let n=Lt(e,s),o=Lt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&Le(`Can't set a session config entry: ${e} - ${r}.`)},ts=(t,e,r,s)=>{let n=Lt(e,s),o=Lt(r,s);t.push([n,o])},JA=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&yp(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let m=n;if(m.device)if(typeof GPUDevice<"u"&&m.device instanceof GPUDevice)f=m.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&ts(a,"enableGraphCapture","1",r),typeof m.preferredLayout=="string"&&ts(a,"preferredLayout",m.preferredLayout,r),m.forceCpuNodeNames){let x=Array.isArray(m.forceCpuNodeNames)?m.forceCpuNodeNames:[m.forceCpuNodeNames];ts(a,"forceCpuNodeNames",x.join(` `),r)}m.validationMode&&ts(a,"validationMode",m.validationMode,r)}let _=De().webgpuRegisterDevice(f);if(_){let[m,w,x]=_;ts(a,"deviceId",m.toString(),r),ts(a,"webgpuInstance",w.toString(),r),ts(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Lt(o,r),l=a.length,c=0,p=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),p=De()._malloc(l*De().PTR_SIZE),r.push(p);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};QA(n);try{let o=KA(n.graphOptimizationLevel??"all"),a=YA(n.executionMode??"sequential"),i=typeof n.logId=="string"?Lt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?Lt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&Le("Can't create session options."),n.executionProviders&&await JA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);yp(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,_]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let m=Lt(f,s);e._OrtAddFreeDimensionOverride(r,m,_)!==0&&Le(`Can't set a free dimension override: ${f} - ${_}.`)}return n.extra!==void 0&&Mp(n.extra,"",new WeakSet,(f,_)=>{yp(r,f,_,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Le("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),Fs,kp,Un,Ll,Tp,O1,I1,w1,jn=ve(()=>{"use strict";Fs=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},kp=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},Un=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},Ll=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Tp=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},O1=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",I1=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",w1=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),C1,B2=ve(()=>{"use strict";A1(),C1=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),U2,DL=ve(()=>{"use strict";jn(),U2=(t,e)=>new(Ll(e))(t)}),ZA,e2,t2,r2,j2,s2,vt,G2=ve(()=>{"use strict";jn(),ZA=["V","I","W","E","F"],e2=(t,e)=>{console.log(`[${ZA[t]},${new Date().toISOString()}]${e}`)},j2=(t,e)=>{t2=t,r2=e},s2=(t,e)=>{let r=Tp(t),s=Tp(t2);r>=s&&e2(r,typeof e=="function"?e():e)},vt=(...t)=>{r2&&s2(...t)}}),i1,x1,l1,n2,c1,o2,u1,p1,f1,a2,q2,FL=ve(()=>{"use strict";jn(),G2(),i1=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),x1=(t,e)=>{if(e==="int32")return t;let r=i1.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(Ll(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},l1=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},n2=1,c1=()=>n2++,o2=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),u1=(t,e)=>{let r=i1.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},p1=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return u1(this.dataType,this.tensorShape)}destroy(){vt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=l1(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},f1=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=o2.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);vt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==u1(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=x1(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else vt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?l1(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},a2=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=c1();return this.tensorTrackersById.set(t,new f1(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){vt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=c1(),a=new p1({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new f1(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){vt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}vt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new p1({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},q2=(...t)=>new a2(...t)}),W2={};Nl(W2,{WebNNBackend:()=>V2});var Il,i2,V2,BL=ve(()=>{"use strict";jn(),qs(),DL(),FL(),G2(),Il=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),i2=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},V2=class{constructor(t){this.tensorManager=q2(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,j2(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){vt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){vt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)vt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>i2(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){vt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Il.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){vt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Il.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");vt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return U2(r,e)}}registerMLTensor(t,e,r,s){let n=Il.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let f=x1(new Uint8Array(c),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=Il.get(Fs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),l2,P1,z1,rs,c2,d1,Sp,L1,N1,_1,$1,R1,D1,H2=ve(()=>{"use strict";Gs(),$L(),RL(),jn(),qs(),S1(),B2(),l2=(t,e)=>{De()._OrtInit(t,e)!==0&&Le("Can't initialize onnxruntime.")},P1=async t=>{l2(t.wasm.numThreads,Tp(t.logLevel))},z1=async(t,e)=>{De().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&De().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(BL(),Ep(W2)).WebNNBackend(t);De().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},rs=new Map,c2=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Le("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},d1=(t,e)=>{let r=De(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Le("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],p=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},L1=async(t,e)=>{let r,s,n=De();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=Sp(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await F2(e),e?.externalData&&n.mountExternalData){let T=[];for(let I of e.externalData){let O=typeof I=="string"?I:I.path;T.push(C1(typeof I=="string"?I:I.data).then(b=>{n.mountExternalData(O,b)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let I=T,O=I?.context,b=I?.gpuDevice,F=I?.deviceType,j=I?.powerPreference;O?n.currentContext=O:b?n.currentContext=await n.webnnCreateMLContext(b):n.currentContext=await n.webnnCreateMLContext({deviceType:F,powerPreference:j})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Le("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,_]=c2(o),m=!!e?.enableGraphCapture,w=[],x=[],k=[],A=[],E=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Le("Can't create IO binding."),S={handle:i,outputPreferredLocations:E,outputPreferredLocationsEncoded:E.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>w1(T))}),rs.set(o,[o,c,p,S,m,!1]),[o,w,x,k,A]}catch(f){throw c.forEach(_=>n._OrtFree(_)),p.forEach(_=>n._OrtFree(_)),i!==0&&n._OrtReleaseBinding(i)!==0&&Le("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Le("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Le("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},N1=t=>{let e=De(),r=rs.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Le("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Le("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Le("Can't release session."),rs.delete(t)},_1=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],p=t[1],f=t[3],_=f,m,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=Un(Fs(c),p);{let E=i.webgpuRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=E(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=Un(Fs(c),p);let E=i.webnnRegisterMLTensor;if(!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=E(s,A,Fs(c),p)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,m=i._malloc(w),r.push(m);for(let E=0;Ei.setValue(k+S*l,E,l===4?"i32":"i64"));let A=i._OrtCreateTensor(Fs(c),m,w,k,p.length,w1(_));A===0&&Le(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},$1=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=rs.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],f=l[2],_=l[3],m=l[4],w=l[5],x=e.length,k=s.length,A=0,E=[],S=[],T=[],I=[],O=[],b=a.stackSave(),F=a.stackAlloc(x*i),j=a.stackAlloc(x*i),U=a.stackAlloc(k*i),X=a.stackAlloc(k*i);try{[A,E]=D2(o),ns("wasm prepareInputOutputTensor");for(let C=0;CFe*Se,1);B=kp(Ge);let At=_?.outputPreferredLocations[s[C]];if(B==="string"){if(At==="gpu-buffer"||At==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Fe=[];for(let Se=0;Se0){let Fe=a.webgpuGetBuffer;if(!Fe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Se=Fe(Q),rt=Un(Ge,ct);if(rt===void 0||!O1(B))throw new Error(`Unsupported data type: ${B}`);$=!0;{a.webgpuRegisterBuffer(Se,t,Q);let nr=a.webgpuCreateDownloader(Se,rt,t);J.push([B,qe,{gpuBuffer:Se,download:async()=>{let Oe=await nr();return new(Ll(B))(Oe)},dispose:()=>{a._OrtReleaseTensor(ne)!==0&&Le("Can't release tensor.")}},"gpu-buffer"])}}else if(At==="ml-tensor"&&ct>0){let Fe=a.webnnEnsureTensor,Se=a.webnnIsGraphInputOutputTypeSupported;if(!Fe||!Se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Un(Ge,ct)===void 0||!I1(B))throw new Error(`Unsupported data type: ${B}`);if(!Se(t,B,!1))throw new Error(`preferredLocation "ml-tensor" for ${B} output is not supported by current WebNN Context.`);let rt=await Fe(t,Q,Ge,qe,!1);$=!0,J.push([B,qe,{mlTensor:rt,download:a.webnnCreateMLTensorDownloader(Q,B),dispose:()=>{a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(ne)}},"ml-tensor"])}else if(At==="ml-tensor-cpu-output"&&ct>0){let Fe=a.webnnCreateMLTensorDownloader(Q,B)(),Se=J.length;$=!0,R.push((async()=>{let rt=[Se,await Fe];return a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(ne),rt})()),J.push([B,qe,[],"cpu"])}else{let Fe=Ll(B),Se=new Fe(ct);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(Q,Q+Se.byteLength)),J.push([B,qe,Se,"cpu"])}}finally{a.stackRestore(Y),B==="string"&&Q&&a._free(Q),$||a._OrtReleaseTensor(ne)}}_&&!m&&(a._OrtClearBoundOutputs(_.handle)!==0&&Le("Can't clear bound outputs."),rs.set(t,[c,p,f,_,m,!1]));for(let[C,ne]of await Promise.all(R))J[C][2]=ne;return os("wasm ProcessOutputTensor"),J}finally{a.webnnOnRunEnd?.(c),a.stackRestore(b),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),n.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),S.forEach(K=>a._OrtReleaseTensor(K)),T.forEach(K=>a._OrtReleaseTensor(K)),I.forEach(K=>a._free(K)),A!==0&&a._OrtReleaseRunOptions(A),E.forEach(K=>a._free(K))}},R1=t=>{let e=De(),r=rs.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Le("Can't get an profile file name."),e._OrtFree(n)},D1=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),ss,Ut,Bn,Cl,Pl,bp,m1,vp,$s,Rs,u2,X2,K2,Y2,Q2,J2,Z2,eM,tM=ve(()=>{"use strict";Gs(),H2(),qs(),M1(),ss=()=>!!Qe.wasm.proxy&&typeof document<"u",Bn=!1,Cl=!1,Pl=!1,vp=new Map,$s=(t,e)=>{let r=vp.get(t);r?r.push(e):vp.set(t,[e])},Rs=()=>{if(Bn||!Cl||Pl||!Ut)throw new Error("worker not ready")},u2=t=>{switch(t.data.type){case"init-wasm":Bn=!1,t.data.err?(Pl=!0,m1[1](t.data.err)):(Cl=!0,m1[0]()),bp&&(URL.revokeObjectURL(bp),bp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=vp.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},X2=async()=>{if(!Cl){if(Bn)throw new Error("multiple calls to 'initWasm()' detected.");if(Pl)throw new Error("previous call to 'initWasm()' failed.");if(Bn=!0,ss())return new Promise((t,e)=>{Ut?.terminate(),$2().then(([r,s])=>{try{Ut=s,Ut.onerror=o=>e(o),Ut.onmessage=u2,m1=[t,e];let n={type:"init-wasm",in:Qe};!n.in.wasm.wasmPaths&&(r||g1)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",Zt.url).href}),Ut.postMessage(n),bp=r}catch(n){e(n)}},e)});try{await T1(Qe.wasm),await P1(Qe),Cl=!0}catch(t){throw Pl=!0,t}finally{Bn=!1}}},K2=async t=>{if(ss())return Rs(),new Promise((e,r)=>{$s("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Qe}};Ut.postMessage(s)});await z1(Qe,t)},Y2=async t=>ss()?(Rs(),new Promise((e,r)=>{$s("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Ut.postMessage(s,[t.buffer])})):Sp(t),Q2=async(t,e)=>{if(ss()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Rs(),new Promise((r,s)=>{$s("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Ut.postMessage(n,o)})}else return L1(t,e)},J2=async t=>{if(ss())return Rs(),new Promise((e,r)=>{$s("release",[e,r]);let s={type:"release",in:t};Ut.postMessage(s)});N1(t)},Z2=async(t,e,r,s,n,o)=>{if(ss()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Rs(),new Promise((a,i)=>{$s("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Ut.postMessage(c,D1(l))})}else return $1(t,e,r,s,n,o)},eM=async t=>{if(ss())return Rs(),new Promise((e,r)=>{$s("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Ut.postMessage(s)});R1(t)}}),h1,p2,rM,UL=ve(()=>{"use strict";Gs(),tM(),jn(),A1(),B2(),h1=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},p2=t=>{switch(t[3]){case"cpu":return new er(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!O1(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return er.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!I1(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return er.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},rM=class{async fetchModelAndCopyToWasmMemory(t){return Y2(await C1(t))}async loadModel(t,e){Us();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Q2(r,e),js()}async dispose(){return J2(this.sessionId)}async run(t,e,r){Us();let s=[],n=[];Object.entries(t).forEach(f=>{let _=f[0],m=f[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(m),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let _=f[0],m=f[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);o.push(m),a.push(w)});let i=s.map((f,_)=>h1(f,()=>`input "${this.inputNames[n[_]]}"`)),l=o.map((f,_)=>f?h1(f,()=>`output "${this.outputNames[a[_]]}"`):null),c=await Z2(this.sessionId,n,i,a,l,r),p={};for(let f=0;fb1,initializeFlags:()=>y1,wasmBackend:()=>nM});var y1,b1,nM,jL=ve(()=>{"use strict";Gs(),tM(),UL(),y1=()=>{(typeof Qe.wasm.initTimeout!="number"||Qe.wasm.initTimeout<0)&&(Qe.wasm.initTimeout=0);let t=Qe.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Qe.wasm.simd=!1),typeof Qe.wasm.proxy!="boolean"&&(Qe.wasm.proxy=!1),typeof Qe.wasm.trace!="boolean"&&(Qe.wasm.trace=!1),typeof Qe.wasm.numThreads!="number"||!Number.isInteger(Qe.wasm.numThreads)||Qe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Qe.wasm.numThreads=1;else{let e=typeof navigator>"u"?xL("node:os").cpus().length:navigator.hardwareConcurrency;Qe.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},b1=class{async init(t){y1(),await X2(),await K2(t)}async createInferenceSessionHandler(t,e){let r=new rM;return await r.loadModel(t,e),r}},nM=new b1});Gs();Gs();Gs();var GL="1.26.0-dev.20260416-b7804b056c",qL=I2;{let t=(jL(),Ep(sM)).wasmBackend;Bs("webgpu",t,5),Bs("webnn",t,5),Bs("cpu",t,10),Bs("wasm",t,10)}Object.defineProperty(Qe.versions,"web",{value:GL,enumerable:!0});async function oM(t){let e=t.split("/").pop(),r;try{if(r=await Jt(),r){let n=await r.match(t);if(n)return n}}catch(n){ee.warn(`Failed to load ${e} from cache:`,n)}let s=await _e.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){ee.warn(`Failed to cache ${e}:`,n)}return s}async function aM(t){let e=await oM(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return ee.warn("Failed to read WASM binary:",r),null}}async function iM(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await oM(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ee.warn("Failed to read WASM factory:",r),null}}var U1=require("onnxruntime-common"),VL=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function pM(t){return t<=St.DEBUG?0:t<=St.INFO?2:t<=St.WARNING||t<=St.ERROR?3:4}var HL={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},jt=[],B1,qn,lM=Symbol.for("onnxruntime");if(lM in globalThis)qn=globalThis[lM];else if(ie.IS_NODE_ENV){switch(qn=WL,process.platform){case"win32":jt.push("dml");break;case"linux":process.arch==="x64"&&jt.push("cuda");break;case"darwin":jt.push("coreml");break}jt.push("webgpu"),jt.push("cpu"),B1=["cpu"]}else qn=F1,ie.IS_WEBNN_AVAILABLE&&jt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&jt.push("webgpu"),jt.push("wasm"),B1=["wasm"];var XL=qn.InferenceSession;function fM(t=null){if(!t)return B1;switch(t){case"auto":return jt;case"gpu":return jt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(jt.includes(t))return[VL[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${jt.join(", ")}.`)}var cM=Promise.resolve(),Gn=null;async function KL(){if(Gn)return Gn;if(!(_e.useWasmCache&&typeof it?.wasm?.wasmPaths=="object"&&it?.wasm?.wasmPaths?.wasm&&it?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Gn=Promise.resolve(),Gn}return Gn=(async()=>{let e=it.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!qb(e.wasm)?(async()=>{try{let s=await aM(Wb(e.wasm));s&&(it.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!qb(e.mjs)?(async()=>{try{let s=await iM(Wb(e.mjs));s&&(it.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(it.wasm.wasmPaths.mjs=e.mjs)})(),Gn}async function Op(t,e,r){await KL();let s=pM(_e.logLevel??St.WARNING),n=()=>XL.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?cM=cM.then(n):n());return o.config=r,o}var uM=Promise.resolve();async function Ip(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?uM=uM.then(r):r()}function Cp(t){return t instanceof qn.Tensor}var it=qn?.env;function $l(){return it?.wasm?.proxy}if(it){let t=function(e){let r=pM(e);it.logLevel=HL[r]};if(it.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&it.versions?.web&&!it.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${it.versions.web}/dist/`;it.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}it.wasm.proxy=!1}it.webgpu&&(it.webgpu.powerPreference="high-performance"),t(_e.logLevel??St.WARNING),_e.backends.onnx={...it,setLogLevel:t}}var as=async(t,e,r)=>{let s=await Op(new Uint8Array(t),e);return(async n=>{let o=$l(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Ip(s,a);return Array.isArray(r)?r.map(l=>new N(i[l])):new N(i[r])})},pr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=as([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=as([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=as([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=as([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=as([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=as([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=as([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=as([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}};var dM=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),j1=ie.IS_NODE_ENV?"cpu":"wasm";function Pp(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${j1}).`),j1):j1}var hM=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),_M=st.fp32,mM=Object.freeze({[dM.wasm]:st.q8}),is=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q2]:"_q2",[st.q1]:"_q1",[st.q4f16]:"_q4f16",[st.q2f16]:"_q2f16",[st.q1f16]:"_q1f16",[st.bnb4]:"_bnb4"});function zp(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===st.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==st.auto&&st.hasOwnProperty(l))return l}i=mM[r]??_M}else o&&st.hasOwnProperty(o)?i=o:i=mM[r]??_M;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var ls=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var N=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return Cp(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new U1.Tensor(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;sm)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(_,0),Math.min(m,this.dims[p])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([p,f])=>f-p),o=n.reduce((p,f)=>p*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let p=1;p=0;--_){let w=n[_];f+=(m%w+s[_][0])*l[_],m=Math.floor(m/w)}i[p]=a[f]}return new t(this.type,i,r)}permute(...e){return xM(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,_)=>f+_,i=0n):(a=(f,_)=>f+_**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,p]=Rl(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let _=c%f;i+=_*p,p*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return G1(this.dims)}squeeze(e=null){return new t(this.type,this.data,gM(this.dims,e))}squeeze_(e=null){return this.dims=gM(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,wM(this.dims,e))}unsqueeze_(e){return this.dims=wM(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=ze(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Rl((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Tl(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=ze(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthp===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,f=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((p,f)=>p*e[f]),o=n.reduce((p,f)=>p*f,1),a=this.data,i=new a.constructor(o),l=G1(s),c=G1(n);for(let p=0;pBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,DA(this.data),this.dims);return new t(e,ls[e].from(this.data,r),this.dims)}};function YL(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew N("int64",t,[t.length]);async function Dl(t,e,r,s,n){return await(await pr.slice)({x:t,s:Lp(e),e:Lp(r),a:Lp(s),t:Lp(n??new Array(s.length).fill(1))})}function W1(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;pr!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function wM(t,e){return e=fr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function fr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ye(t,e=0){e=fr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--_){let x=c[_],k=m%x;_===e&&(k+=a),f+=k*w,w*=r[_],m=Math.floor(m/x)}n[f]=l[p]}a+=c[e]}}return new N(o,n,r)}function _t(t,e=0){return ye(t.map(r=>r.unsqueeze(e)),e)}function Rl(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=fr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=_%w;p+=x*m,m*=i[f]}_=Math.floor(_/w)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function $p(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let m=n.reduce((A,E)=>A+E,0)/n.length,w=Math.sqrt(n.reduce((A,E)=>A+(E-m)**2,0)/(n.length-r)),x=new N(t.type,[m],[]);return[new N(t.type,[w],[]),x]}e=fr(e,o.length);let a=Fl(t,e,s),i=a.data,[l,c,p]=Rl((_,m,w,x)=>_+(m-i[x])**2,t,e,s);for(let _=0;_c+p,0);return new N(t.type,[l/n.length],[])}e=fr(e,s.length);let[o,a,i]=Rl((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function V1(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new N(r,new s(n).fill(e),t)}function Ke(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return V1(t,e,r,s)}function Wn(t,e){return Ke(t.dims,e)}function Ze(t){return V1(t,1n,"int64",BigInt64Array)}function Bl(t){return Ze(t.dims)}function Rp(t){return V1(t,0n,"int64",BigInt64Array)}function Dp(t){return Rp(t.dims)}function ZL(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>Kr.random()),t)}function H1(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>Kr.gauss()),t)}function X1(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new N(s,a,[t.dims[0],t.dims[1]/8])}async function Vn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ot(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function K1(t,e){let r=await Vn(t);return await Promise.all(r.map(s=>nt(t,s,!0,e)))}function Ul(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var eN=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function tN(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?wt(t[n],i):wt(i,t[n])}}function rN(t,e){for(let r of Object.keys(t))t[r].length=e}function Ws(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function sN(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var W=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new iA(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ws(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ws(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ws(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ws(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ws(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ws(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=sN(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await K1(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,p=Array.isArray(e),f;if(p){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((m,w)=>this._encode_plus(m,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(m=>this._encode_plus(m,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(ze(f.map(m=>m.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let m=0;ml?i&&rN(f[m],l):o&&tN(f[m],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let _={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))_[w]=new N("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),m)}else{for(let m of Object.keys(f[0]))_[m]=f.map(w=>w[m]);if(!p)for(let m of Object.keys(_))_[m]=_[m][0]}return _}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof N&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof N&&(e=Ul(e)),!Array.isArray(e)||e.length===0||!GE(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:p=null,return_tensor:f=!0,return_dict:_=!0,tokenizer_kwargs:m={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new xA(o),this._compiled_template_cache.set(o,x));let k=Object.create(null);for(let E of eN){let S=Ws(this.config,E);S&&(k[E]=S)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...k,...w});if(i){let E=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:p,return_tensor:f,...m});return _?E:E.input_ids}return A}};function Hn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var Q1={};Os(Q1,{AlbertTokenizer:()=>Fp,AutoTokenizer:()=>se,BartTokenizer:()=>Bp,BertTokenizer:()=>Up,BlenderbotSmallTokenizer:()=>jp,BlenderbotTokenizer:()=>Gp,BloomTokenizer:()=>qp,CLIPTokenizer:()=>Vp,CamembertTokenizer:()=>Wp,CodeGenTokenizer:()=>Xp,CodeLlamaTokenizer:()=>Hp,CohereAsrTokenizer:()=>Yp,CohereTokenizer:()=>Kp,ConvBertTokenizer:()=>Qp,DebertaTokenizer:()=>Zp,DebertaV2Tokenizer:()=>Jp,DistilBertTokenizer:()=>ef,ElectraTokenizer:()=>tf,EsmTokenizer:()=>rf,FalconTokenizer:()=>sf,GPT2Tokenizer:()=>af,GPTNeoXTokenizer:()=>of,GemmaTokenizer:()=>nf,HerbertTokenizer:()=>lf,LlamaTokenizer:()=>cf,M2M100Tokenizer:()=>uf,MBart50Tokenizer:()=>ff,MBartTokenizer:()=>Xn,MPNetTokenizer:()=>mf,MarianTokenizer:()=>pf,MgpstrTokenizer:()=>df,MobileBertTokenizer:()=>_f,NllbTokenizer:()=>hf,NougatTokenizer:()=>gf,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>wf,RoFormerTokenizer:()=>yf,RobertaTokenizer:()=>xf,SiglipTokenizer:()=>bf,SpeechT5Tokenizer:()=>vf,SqueezeBertTokenizer:()=>kf,T5Tokenizer:()=>Ef,TokenizersBackend:()=>W,VitsTokenizer:()=>Af,Wav2Vec2CTCTokenizer:()=>Mf,WhisperTokenizer:()=>Tf,XLMRobertaTokenizer:()=>Sf,XLMTokenizer:()=>Of});var Fp=class extends W{return_token_type_ids=!0};var Bp=class extends W{};var Up=class extends W{return_token_type_ids=!0};var jp=class extends W{};var Gp=class extends W{};var qp=class extends W{};var Wp=class extends W{};var Vp=class extends W{};var Hp=class extends W{};var Xp=class extends W{};var Kp=class extends W{};var Yp=class extends W{};var Qp=class extends W{return_token_type_ids=!0};var Jp=class extends W{return_token_type_ids=!0};var Zp=class extends W{return_token_type_ids=!0};var ef=class extends W{};var tf=class extends W{return_token_type_ids=!0};var rf=class extends W{};var sf=class extends W{};var nf=class extends W{};var of=class extends W{};var af=class extends W{};var lf=class extends W{return_token_type_ids=!0};var cf=class extends W{padding_side="left"};var uf=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return Hn(this,e,r,s)}};var pf=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),ee.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||ee.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),wt([n],super._encode_text(o))}}};var Xn=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Hn(this,e,r,s)}};var ff=class extends Xn{};var df=class extends W{};var _f=class extends W{return_token_type_ids=!0};var mf=class extends W{};var hf=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Hn(this,e,r,s)}};var gf=class extends W{};var wf=class extends W{};var xf=class extends W{};var yf=class extends W{return_token_type_ids=!0};var bf=class extends W{};var vf=class extends W{};var kf=class extends W{return_token_type_ids=!0};var Ef=class extends W{};var Y1=class extends Ft{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function bM(t){t=t.toLowerCase();let e=nN.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),jl.has(t))e=t;else{let n=t.length===2?jl.keys():jl.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var oN="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",vM=new RegExp(`^[${oN}]+$`,"gu"),aN=.1,Tf=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],p=l(),f=0,_=this.timestamp_begin,w=_+1500,x=[],k=[],A=!1,E=null,S=new Set(this.all_special_ids);for(let O of e){let b=O.tokens,F=i?O.token_timestamps:null,j=null,U=_;if("stride"in O){let[J,R,C]=O.stride;if(f-=R,E=J-C,R&&(U=R/n+_),C)for(let ne=b.length-1;ne>=0;--ne){let Y=Number(b[ne]);if(Y>=_){if(j!==null&&(Y-_)*n=_&&R<=w){let C=(R-_)*n+f,ne=Ns(C,2);if(j!==null&&R>=j)A=!0;else if(A||x.length>0&&R0&&p.timestamp[1]!==null))for(let B of p.words)B.timestamp[1]>p.timestamp[1]&&p.timestamp[1]>=B.timestamp[0]&&(B.timestamp[1]=p.timestamp[1]);c.push(p),x=[],X=[],k=[],K=[],p=l()}}else if(X.push(R),i){let C=Ns(F[J]+f,2),ne;if(J+10?(x.push(X),i&&k.push(K)):x.every(J=>J.length===0)&&(p=l(),x=[],X=[],k=[],K=[])}if(x.length>0){if(o&&r)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.");let[O,b]=this.findLongestCommonSequence(x,k),F=this.decode(O);p.text=F,i&&(p.words=this.collateWordTimestamps(O,b,a)),c.push(p)}let T=Object.create(null),I=c.map(O=>O.text).join("");if(r||s){for(let O=0;O0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cR===U[C]&&l[I+C][0]-aN<=r[c][F+C][0]).length:X=b.filter((R,C)=>R===U[C]).length;let K=T/1e4,J=X/T+K;X>1&&J>f&&(f=J,_=[I,O,F,j])}let[w,x,k,A]=_,E=Math.floor((x+w)/2),S=Math.floor((A+k)/2);if(a&&f===0&&n>0){let T=l[n-1][0],I=r[c].findIndex(O=>O[0]>=T);S=I===-1?p.length:I}o.push(...s.slice(0,E)),s=p.slice(S),n=s.length,a&&(i.push(...l.slice(0,E)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),m=c.startsWith(" "),w=c.trim(),x=vM.test(w);if(_||m||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let k=o.length-1;o[k]+=c,a[k].push(...p),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=wt(i[c],i[p]),l[p]=wt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;pf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var Sf=class extends W{};var Of=class extends W{return_token_type_ids=!0;constructor(e,r){super(e,r),ee.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var se=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await K1(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=Q1[c];return p||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=W),new p(i,l)}};var cs="https://github.com/huggingface/transformers.js/issues/new/choose";var Gl="preprocessor_config.json",Er=Gl,If="processor_config.json",Cf="chat_template.jinja";var re=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}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,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}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,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?nt(e,If,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?Ml(e,Cf,!0,r):null]);return new this(s,n,o)}};var g_={};Os(g_,{ChatterboxProcessor:()=>Xf,CohereAsrProcessor:()=>Kf,Florence2Processor:()=>jd,Gemma3Processor:()=>Gd,Gemma3nProcessor:()=>qd,Gemma4Processor:()=>Wd,Glm46VProcessor:()=>Vd,GraniteSpeechProcessor:()=>Hd,GroundingDinoProcessor:()=>Xd,Idefics3Processor:()=>ac,JinaCLIPProcessor:()=>Yd,Lfm2VlProcessor:()=>Qd,LlavaProcessor:()=>Jd,MgpstrProcessor:()=>Zd,MoonshineProcessor:()=>e_,OwlViTProcessor:()=>t_,PaliGemmaProcessor:()=>r_,Phi3VProcessor:()=>s_,PixtralProcessor:()=>n_,Processor:()=>re,PyAnnoteProcessor:()=>o_,Qwen2VLProcessor:()=>fs,Qwen2_5_VLProcessor:()=>co,Qwen3VLProcessor:()=>a_,Sam2Processor:()=>ic,Sam2VideoProcessor:()=>i_,SamProcessor:()=>uo,SmolVLMProcessor:()=>ac,SpeechT5Processor:()=>l_,UltravoxProcessor:()=>c_,VLChatProcessor:()=>Kd,VoxtralProcessor:()=>p_,VoxtralRealtimeProcessor:()=>d_,Wav2Vec2Processor:()=>__,Wav2Vec2ProcessorWithLM:()=>m_,WhisperProcessor:()=>h_});var Ee=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await nt(e,Gl,!0,r);return new this(s)}};function Me(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var ql={};Os(ql,{ASTFeatureExtractor:()=>Nf,ChatterboxFeatureExtractor:()=>$f,ClapFeatureExtractor:()=>Rf,CohereAsrFeatureExtractor:()=>Df,DacFeatureExtractor:()=>Jn,EncodecFeatureExtractor:()=>Yn,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Zn,Gemma4AudioFeatureExtractor:()=>eo,GraniteSpeechFeatureExtractor:()=>Ff,MoonshineFeatureExtractor:()=>Bf,ParakeetFeatureExtractor:()=>Qn,PyAnnoteFeatureExtractor:()=>to,SeamlessM4TFeatureExtractor:()=>Uf,SnacFeatureExtractor:()=>jf,SpeechT5FeatureExtractor:()=>Gf,VoxtralRealtimeFeatureExtractor:()=>Vf,Wav2Vec2FeatureExtractor:()=>qf,WeSpeakerFeatureExtractor:()=>Wf,WhisperFeatureExtractor:()=>Hf});var kM=vr(require("fs"),1),EM=require("stream"),AM=require("stream/promises");async function Pf(t,e){if(ie.IS_BROWSER_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ie.IS_FS_AVAILABLE){let r=e.stream(),s=EM.Readable.fromWeb(r),n=kM.default.createWriteStream(t);await(0,AM.pipeline)(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function Z1(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Qr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&ee.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function J1(t,e="htk"){let r=lN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var cN={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function uN(t,e="htk"){let r=cN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function pN(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function lt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=J1(r,a),c=J1(s,a),p=TM(l,c,e+2),f=uN(p,a),_;if(i){let w=n/((t-1)*2);_=J1(Float64Array.from({length:t},(x,k)=>k*w),a),f=p}else _=TM(0,Math.floor(n/2),t);let m=pN(_,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(j!==r)throw new Error(`Length of the window (${j}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let Q=Math.floor(r/2);switch(i){case"reflect":{t=fN(t,Q,Q);break}case"constant":{let le=new t.constructor(t.length+2*Q);le.set(t,Q),t=le;break}case"semicausal":{let le=new t.constructor(t.length+Q);le.set(t,Q),t=le;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let U=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&UU?I&&(J=T):J=K=T);let R=new mp(n),C=new Float64Array(n),ne=new Float64Array(R.outputBufferSize),Y=new Float32Array(X*J);for(let Q=0;Q=1;--ce)C[ce]-=c*C[ce-1];C[0]*=1-c}for(let ce=0;ceMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function mN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return zf(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),zf(n,8,"WAVE"),zf(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),zf(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function zf(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),mN(e,this.sampling_rate)}async save(e){return Pf(e,this.toBlob())}};var Nf=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Me(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(Kr.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ot(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Me(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=p){l.push(e.slice(c,p));break}let f=Math.max(c,c+a-i),_=Math.min(c+a,p),m;_<=f?m=c+a:m=this._find_split_point_energy(e,f,_,n),m=Math.max(c+1,Math.min(m,p)),l.push(e.slice(c,m)),c=m}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let p=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Ke([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var eo=class extends Zn{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ot(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Me(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,p=Math.floor(l/2),f=l+1,_=new Uint8Array(s+p+(r.pad_to_multiple_of??128));_.fill(1,p,p+s);let m=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:p*s,confidence:f/(p-c)})))}return n}};var Uf=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Me(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let A=0;A0){let E=new Float32Array(x*(w+A));E.set(k),E.fill(this.config.padding_value,k.length);let S=w+A;a=new N(a.type,E,[S,x]),o&&(i=new N("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let _=a.view(1,Math.floor(l/p),c*p),m={input_features:_};if(o){let w=_.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let A=1,E=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Me(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new N("float32",r,s),attention_mask:new N("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Wf=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=mt(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Me(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&ee.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)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var je=class{static async from_pretrained(e,r={}){let s=await nt(e,Gl,!0,r),n=s.feature_extractor_type,o=ql[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${cs}.`);return new o(s)}};var Xf=class extends re{static tokenizer_class=se;static feature_extractor_class=je;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var gN=new Set(["ja","zh"]),Kf=class extends re{static tokenizer_class=se;static feature_extractor_class=je;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=gN.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var Yf=vr(require("sharp"),1);var Vs,IM,us;if(ie.IS_WEB_ENV)Vs=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},us=self.createImageBitmap,IM=self.ImageData;else if(Yf.default)us=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Je(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var wN={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},xN=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Je=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Qr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await us(e),s=Vs(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=(0,Yf.default)(await e.arrayBuffer());return await us(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);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 t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:p=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await us(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new N("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Vs(e.width,e.height),s=new IM(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(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(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=xN.get(r)??"image/png",n=await this.toBlob(s);return Pf(e,n)}else if(ie.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return(0,Yf.default)(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},CM=Je.read.bind(Je);function PM(t,e,r=0,s=null){let n=t/e,o=$A(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),oe&&A.push(S)}else{let S=ze(k.data)[1];if(S===l-1||(E=Pe(k.data),E[S]I*f[(O+1)%2])),_.boxes.push(T),_.classes.push(S),_.scores.push(E[S])}}c.push(_)}return c}function Qf(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[A]&&(f[A]=k[A],_[A]=x)}let m=new Array(i.dims[0]);for(let x=0;x<_.length;++x){let k=_[x];m[k]=k}let w=m.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function yN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(_),a.push(p))}return[n,o,a]}function bN(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let p=0;p=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function vN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new N("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x_[E]&&(f[E]=x,_[E]=A[E])}let m=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=Tl(s.data)[0],a=ze(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,p=0,f=0,_=s.data;for(let m=0;mthis.preprocess(o)));return{pixel_values:_t(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await nt(e,Er,!0,r);return new this(s)}};var io={};Os(io,{BeitFeatureExtractor:()=>ed,BitImageProcessor:()=>td,CHMv2ImageProcessor:()=>sd,CLIPFeatureExtractor:()=>nd,CLIPImageProcessor:()=>Wl,ChineseCLIPFeatureExtractor:()=>rd,ConvNextFeatureExtractor:()=>od,ConvNextImageProcessor:()=>Vl,DINOv3ViTImageProcessor:()=>ld,DPTFeatureExtractor:()=>ud,DPTImageProcessor:()=>Kl,DeiTFeatureExtractor:()=>ad,DeiTImageProcessor:()=>Hl,DetrFeatureExtractor:()=>id,DetrImageProcessor:()=>Xl,DonutFeatureExtractor:()=>cd,DonutImageProcessor:()=>Hs,EfficientNetImageProcessor:()=>pd,GLPNFeatureExtractor:()=>_d,Gemma3ImageProcessor:()=>fd,Gemma4ImageProcessor:()=>so,Glm46VImageProcessor:()=>dd,GroundingDinoImageProcessor:()=>md,Idefics3ImageProcessor:()=>Yl,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,JinaCLIPImageProcessor:()=>gd,Lfm2VlImageProcessor:()=>wd,LlavaOnevisionImageProcessor:()=>xd,Mask2FormerImageProcessor:()=>bd,MaskFormerFeatureExtractor:()=>yd,MaskFormerImageProcessor:()=>Xs,MobileNetV1FeatureExtractor:()=>vd,MobileNetV1ImageProcessor:()=>Ql,MobileNetV2FeatureExtractor:()=>kd,MobileNetV2ImageProcessor:()=>Jl,MobileNetV3FeatureExtractor:()=>Ed,MobileNetV3ImageProcessor:()=>Zl,MobileNetV4FeatureExtractor:()=>Ad,MobileNetV4ImageProcessor:()=>ec,MobileViTFeatureExtractor:()=>Md,MobileViTImageProcessor:()=>tc,NougatImageProcessor:()=>Td,OwlViTFeatureExtractor:()=>Sd,OwlViTImageProcessor:()=>Ks,Owlv2ImageProcessor:()=>Od,Phi3VImageProcessor:()=>Id,PixtralImageProcessor:()=>Cd,PvtImageProcessor:()=>Pd,Qwen2VLImageProcessor:()=>no,RTDetrImageProcessor:()=>zd,Sam2ImageProcessor:()=>ao,Sam3ImageProcessor:()=>ao,SamImageProcessor:()=>ao,SapiensFeatureExtractor:()=>Ld,SapiensImageProcessor:()=>rc,SegformerFeatureExtractor:()=>Nd,SegformerImageProcessor:()=>sc,SiglipImageProcessor:()=>$d,SmolVLMImageProcessor:()=>Yl,Swin2SRImageProcessor:()=>Rd,VLMImageProcessor:()=>hd,ViTFeatureExtractor:()=>Dd,ViTImageProcessor:()=>nc,VitMatteImageProcessor:()=>Fd,VitPoseImageProcessor:()=>Bd,YolosFeatureExtractor:()=>Ud,YolosImageProcessor:()=>oc});var ed=class extends H{};var td=class extends H{};var rd=class extends H{};var sd=class extends H{};var Wl=class extends H{},nd=class extends Wl{};var Vl=class extends H{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},od=class extends Vl{};var Hl=class extends H{},ad=class extends Hl{};var Xl=class extends H{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ke(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return ps(...e)}post_process_panoptic_segmentation(...e){return Jf(...e)}post_process_instance_segmentation(...e){return Zf(...e)}},id=class extends Xl{};var ld=class extends H{};var Hs=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((f,_)=>-f/c[_]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},cd=class extends Hs{};var Kl=class extends H{},ud=class extends Kl{};var pd=class extends H{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var fd=class extends H{};function kN(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let p=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,p)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,p)),[l,c]}function EN(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,p=n*n*s,f=new Float32Array(o*p),_=0;for(let x=0;xa),0));let p=a.dims[0]/i,f=a.dims[1],_=Math.floor(a.dims[2]/c),m=Math.floor(a.dims[3]/c),w=a.view(p,i,f,Math.floor(_/l),l,c,Math.floor(m/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*_*m,f*i*c*c),x=new N("int64",[p,_,m],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var dd=class extends no{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return ro(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var _d=class extends H{};var md=class extends H{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=Ze([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Yl=class extends H{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,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let E=await Promise.all(A.map(I=>this.preprocess(I)));l.push(...E.map(I=>I.original_size)),c.push(...E.map(I=>I.reshaped_input_size)),E.forEach(I=>I.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,T;if(r??this.do_image_splitting){let I=new Array(E.length),O=new Array(E.length);T=await Promise.all(E.map(async(b,F)=>{let j=this.get_resize_for_vision_encoder(b.pixel_values,S),U=await yt(b.pixel_values,{size:[j.height,j.width]}),{frames:X,num_splits_h:K,num_splits_w:J}=await this.split_image(U,this.max_image_size);return I[F]=K,O[F]=J,ye(X,0)})),a.push(I),i.push(O)}else{let I=[S,S];T=await Promise.all(E.map(O=>yt(O.pixel_values,{size:I}))),a.push(new Array(E.length).fill(0)),i.push(new Array(E.length).fill(0))}o.push(ye(T,0))}let p=o.length,[f,_,m,w]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=Ke([p,f,m,w],!0);else{let A=Math.max(...o.map(T=>T.dims.at(0)));k=Ke([p,A,m,w],!0);let E=k.data,S=A*m*w;for(let T=0;Ts||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var gd=class extends H{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function LM(t,e){return Math.round(t/e)*e}function AN(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function MN(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function TN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,p=new Float32Array(r*a*i*l),f=n*o;for(let _=0;_this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=MN(this.min_tiles,this.max_tiles),[n,o]=AN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let _=await Promise.all(f.map(m=>this.preprocess(m,{do_pad:!1})));for(let{pixel_values:m}of _){let[,w,x]=m.dims,k=m.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,E=A**2,[S,T]=ro(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*E,this.max_image_tokens*E).map(U=>Math.max(A,U)),I,O=1,b=1,F=this._is_image_too_large(w,x),j=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(F&&j){let{grid_width:U,grid_height:X,target_width:K,target_height:J}=this._get_grid_layout(w,x);O=X,b=U;let R=await yt(k,{size:[J,K]});I=[];for(let C=0;C(p-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||rv(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(_=>this.preprocess(_))),o=n.map(_=>_.original_size),a=n.map(_=>_.reshaped_input_size),i=[];for(let{pixel_values:_}of n){_.unsqueeze_(0);let[m,w]=_.dims.slice(-2),x=await yt(_,{size:[$t,$t],mode:"bicubic"});if(r>0){let k=[],A=rv(r),E=oo(w/A),S=oo(m/A);for(let I=0;I_.map(m=>$t*tv(m/$t))),p=new N("int64",c.flat(),[s,2]),f=c.map(([_,m])=>this.calc_num_image_tokens_from_image_size(m,_));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:f}}};var Cd=class extends H{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=c*p,_=Math.floor((i-1)/f)+1,m=Math.floor((l-1)/f)+1;return[_*f,m*f]}};var Pd=class extends H{};var zd=class extends H{post_process_object_detection(...e){return ps(...e)}};var ao=class extends H{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Db(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);_=new N("bool",w,_.dims)}i.push(_)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var rc=class extends H{post_process_semantic_segmentation(...e){return Qf(...e)}},Ld=class extends rc{};var sc=class extends H{post_process_semantic_segmentation(...e){return Qf(...e)}},Nd=class extends sc{};var $d=class extends H{};var Rd=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var nc=class extends H{},Dd=class extends nc{};var Fd=class extends H{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:_t(s.map((a,i)=>ye([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var Bd=class extends H{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[p,f,..._]of i)l.push(f?f.trim():l.at(-1)??""),c.push(_.map((m,w)=>(Number(m)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Gd=class extends re{static tokenizer_class=se;static image_processor_class=Ae;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` ${n}${i}${a} `}async _call(e,r=null,s={}){typeof e=="string"&&(e=[e]);let n;return r&&(n=await this.image_processor(r,s),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,s),...n}}};var qd=class extends re{static image_processor_class=Ae;static feature_extractor_class=je;static tokenizer_class=se;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:c,image_token:p,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let _=a.repeat(this.audio_seq_length);this.full_audio_sequence=` ${o}${_}${i} `,this.image_token_id=l,this.boi_token=c,this.image_token=p;let m=p.repeat(this.image_seq_length);this.full_image_sequence=` ${c}${m}${f} `}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;s&&(o=await this.feature_extractor(s,n),e=e.map(l=>l.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return r&&(a=await this.image_processor(r,n),e=e.map(l=>l.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...o}}};var Wd=class extends re{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:n,boa_token:o,eoa_token:a,image_token:i,boi_token:l,eoi_token:c}=this.tokenizer.config;this.audio_token=n,this.boa_token=o,this.eoa_token=a,this.image_token=i,this.boi_token=l,this.eoi_token=c}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([nt(e,If,!0,r),se.from_pretrained(e,r),Ml(e,Cf,!1,r)]),a={tokenizer:n};return s.image_processor&&(a.image_processor=new so(s.image_processor)),s.feature_extractor&&(a.feature_extractor=new eo(s.feature_extractor)),new this(s,a,o)}_compute_audio_num_tokens(e,r){let s=Math.round(r*20/1e3),n=Math.round(r*10/1e3),o=Math.floor(s/2),a=Math.floor((e+o-s-1)/n)+1;if(a<=0)return 0;for(let i=0;i<2;++i)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;if(r){o=await this.image_processor(r,n);let i=o.num_soft_tokens_per_image,l=0;e=e.map(c=>c.replaceAll(this.image_token,()=>` ${this.boi_token}${this.image_token.repeat(i[l++])}${this.eoi_token} `))}let a;if(s){let i=Array.isArray(s)?s:[s];a=await this.feature_extractor(i[0],n);let l=this.feature_extractor.config.sampling_rate??16e3,c=0;e=e.map(p=>p.replaceAll(this.audio_token,()=>` ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[c++].length,l))}${this.eoa_token} `))}return{...this.tokenizer(e,n),...o,...a}}};var fs=class extends re{static image_processor_class=Ae;static tokenizer_class=se;static image_token="<|image_pad|>";async _call(e,r=null,...s){Array.isArray(e)||(e=[e]);let n,o;if(r&&(n=await this.image_processor(r),o=n.image_grid_thw),o){let i=this.image_processor.config.merge_size**2,l=0,c=this.constructor.image_token,p=o.tolist();e=e.map(f=>{for(;f.includes(c);){let _=Number(p[l++].reduce((m,w)=>m*w,1n));f=f.replace(c,"<|placeholder|>".repeat(Math.floor(_/i)))}return f.replaceAll("<|placeholder|>",c)})}return{...this.tokenizer(e),...n}}};var Vd=class extends fs{static image_token="<|image|>"};var Hd=class extends re{static tokenizer_class=se;static feature_extractor_class=je;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:r}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:n}=this.feature_extractor.config,o=Math.floor(s/n),a=Math.floor(e/r)+1,i=Math.floor(a/2);return Math.ceil(i/s)*o}async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let{input_features:a}=await this.feature_extractor(r);n.input_features=a;let i=this._get_num_audio_features(r.length),l=new Uint8Array(i).fill(1);n.input_features_mask=new N("bool",l,[1,i]);let c=this.config.audio_token??"<|audio|>";if(!e.includes(c))throw new Error(`The input text does not contain the audio token ${c}.`);e=e.replaceAll(c,c.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};function IN(t,e){let s=t.dims.at(-1)-1,n=t.tolist();n.fill(!1,0,1),n.fill(!1,s);let o=e.tolist();return n.map((a,i)=>a?i:null).filter(a=>a!==null).map(a=>o[a])}var Xd=class extends re{static tokenizer_class=se;static image_processor_class=Ae;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=a.dims.at(1),p=a.sigmoid(),f=p.max(-1).tolist(),_=i.tolist().map(w=>w.map(x=>ev(x))),m=[];for(let w=0;wT.map((I,O)=>I*x[(O+1)%2])));let k=f[w],A=[],E=[],S=[];for(let T=0;T`+n.repeat(t);a+=` `}return a+=` ${s}${o}`+n.repeat(t)+`${s}`,a}function PN(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function zN(t,e,r,s,n,o){return t===0&&e===0?PN(r,s,n,o):CN(r,t,e,s,n,o)}var ac=class extends re{static image_processor_class=Ae;static tokenizer_class=se;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(e,r=null,s={}){s.return_row_col_info??=!0;let n;r&&(n=await this.image_processor(r,s)),Array.isArray(e)||(e=[e]);let o=n.rows??[new Array(e.length).fill(0)],a=n.cols??[new Array(e.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let f=0;fzN(E,w[S],i,this.fake_image_token,this.image_token,this.global_img_token)),k=_.split(this.image_token);if(k.length===0)throw new Error("The image token should be present in the text.");let A=k[0];for(let E=0;Ek.images).flatMap(k=>k.images).map(k=>Je.read(k)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=k=>n.encode(k,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[c,p,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),_=a(i[0]),m=new Array(_.length).fill(!1);for(let k=1;k0){let k=await this.image_processor(r);return k.pixel_values.unsqueeze_(0),{...x,...k}}return x}};var Yd=class extends re{static tokenizer_class=se;static image_processor_class=Ae;async _call(e=null,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},o=r?await this.image_processor(r,s):{};return{...n,...o}}};var Qd=class extends re{static tokenizer_class=se;static image_processor_class=Ae;async _call(e,r=null,s={}){let{image_rows:n,image_cols:o,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(r){let l=this.config.image_token??"",{tile_size:c=512,downsample_factor:p=2,encoder_patch_size:f=16,use_thumbnail:_=!0}=this.image_processor.config,m=S=>Math.ceil(Math.floor(S/f)/p),w=m(c)**2,x=this.config.image_start_token??"<|image_start|>",k=this.config.image_end_token??"<|image_end|>",A=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(r)||(r=[r]);let E=0;r=r.map(S=>{let T=S.split(l);return T[0]+T.slice(1).map(I=>{let O=E++,[b,F]=a[O],j=n[O],U=o[O],X=m(b)*m(F),K=x;if(j>1||U>1){let J=l.repeat(w);for(let R=0;R`+J;_&&(K+=A+l.repeat(X))}else K+=l.repeat(X);return K+k+I}).join("")})}return{...i,...r?this.tokenizer(r,s):{}}}};var Jd=class extends re{static tokenizer_class=se;static image_processor_class=Ae;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:c,num_additional_image_tokens:p}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+p;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let _=0;_0?x.reduce((A,E)=>A*E,1):0;c.push(w),l.push(k)}return[o(c),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,c]=this._decode_helper(s,"wp"),p=[],f=[];for(let _=0;_c.includes(lo))?a=r.map(c=>{let p=c.replaceAll(lo,lo.repeat(o)),f=p.lastIndexOf(lo),_=f===-1?0:f+lo.length;return p.slice(0,_)+n+p.slice(_)+` `}):(ee.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(c=>LN(c,n,o,lo,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var $M="<|image|>",NN=/<\|image_\d+\|>/g,s_=class extends re{static image_processor_class=Ae;static tokenizer_class=se;async _call(e,r=null,{padding:s=!0,truncation:n=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(r){i=await this.image_processor(r,{num_crops:o});let{num_img_tokens:l}=i,c=e.map((f,_)=>f.split(NN).join($M.repeat(l[_])));a=this.tokenizer(c,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id($M);a.input_ids.map_(f=>f==p?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var n_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:c,image_end_token:p,patch_size:f,spatial_merge_size:_}=this.config,m=f*_,w=Math.floor(a/m),x=Math.floor(i/m);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let k=0;kDN(w,l)),p=c.map(w=>w.length),f=c.flat(),_=(await Promise.all(f.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=_.length>1?ye(_,0):_[0];let m=a[0];for(let w=0;w0){if(c>up)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${up}).`);let p=ov(a,c);for(let f of p){let _=`${s.subfolder??""}/${f}`;l.push(new Promise(async(m,w)=>{let x=await Al(t,_,!0,s,i);m(x instanceof Uint8Array?{path:f,data:x}:f)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async p=>{if(typeof p.data=="string"){let f=await Al(t,p.data,!0,s);return{...p,data:f}}return p}));return Promise.all(l)}async function GN(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=Pp(r.device??o.device,e,{warn:E=>ee.info(E)}),i=fM(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=zp(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:E=>ee.info(E)});if(is.hasOwnProperty(c)){if(a==="webgpu"&&!ie.IS_NODE_ENV&&c===st.fp16&&!await hM())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(st).join(", ")}`);let p=is[c],f={...r.session_options};f.executionProviders??=i;let _=o.free_dimension_overrides;_?f.freeDimensionOverrides??=_:a.startsWith("webnn")&&!f.freeDimensionOverrides&&ee.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${a}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let m=DM(t,e,r,p),w=r.use_external_data_format??o.use_external_data_format,x=await FM(t,e,p,r,w,f);if(x.length>0&&(!ie.IS_NODE_ENV||x.some(E=>typeof E!="string"))&&(f.externalData=x),s&&a==="webgpu"){let E=Qs(r.config,{prefix:"present",session_name:n});if(E.size>0&&!$l()){let S={};for(let T of E)S[T]="gpu-buffer";f.preferredOutputLocation=S}}return{buffer_or_path:await m,session_options:f,session_config:{dtype:c,device:a}}}async function BM(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let o=s?.[n]??!1,{buffer_or_path:a,session_options:i,session_config:l}=await GN(t,e[n],r,o,n),c=await Op(a,i,l);return[n,c]})))}function UM(t){for(let e in t)Cp(t[e])?t[e]=new N(t[e]):typeof t[e]=="object"&&UM(t[e]);return t}async function ue(t,e){let r=qN(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return ie.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await Ip(t,s);return UM(n)}catch(s){let n=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i={type:a.type,dims:a.dims,location:a.location};return i.location!=="gpu-buffer"&&(i.data=a.data),[o,i]}));throw ee.error(`An error occurred during model execution: "${s}".`),ee.error("Inputs given to model:",n),s}}function qN(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof N)){s.push(a);continue}r[a]=$l()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(e).length,o=t.inputNames.length;if(n>o){let a=Object.keys(e).filter(i=>!t.inputNames.includes(i));ee.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Re=class{};var q=class extends Re{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},ge=class extends Re{constructor({logits:e}){super(),this.logits=e}},we=class extends Re{constructor({logits:e}){super(),this.logits=e}},Te=class extends Re{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},kt=class extends Re{constructor({logits:e}){super(),this.logits=e}};var w_=class extends Re{constructor({alphas:e}){super(),this.alphas=e}};var It=class extends We{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},fo=class extends We{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},ds=class extends We{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,r){let s=r;for(let n of this.processors)s=n(e,s);return s}[Symbol.iterator](){return this.processors.values()}},cc=class extends It{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s=1&&o[o.length-1]>=this.timestamp_begin,i=o.length<2||o[o.length-2]>=this.timestamp_begin;if(a&&(i?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&this.max_initial_timestamp_index!==null){let f=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(f+1).fill(-1/0)}let l=hp(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,_)=>f+_)),p=ze(l.subarray(0,this.timestamp_begin))[0];c>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},dc=class extends It{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.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 ${r.dims[0]} for the logits and ${e.length} for the input ids.`);let s=e.length,n=r.slice([0,s],null),o=r.slice([s,r.dims[0]],null);for(let a=0;a1)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=r,this.min_tokens_to_keep=s}},iv=class extends fo{constructor(e,{filter_value:r=-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=r}};var _o=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,Ve(e,Object.getOwnPropertyNames(this)))}};var Ar=class extends We{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Zs=class t extends We{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof Ar&&(e=[e]),this.criteria.push(...e)}_call(e,r){let s=new Array(e.length).fill(!1);for(let n of this.criteria){let o=n(e,r);for(let a=0;ar.length>=this.max_length)}},bc=class extends Ar{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(s=>{let n=s.at(-1);return this.eos_token_id.some(o=>n==o)})}},lv=class extends Ar{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var en=class extends We{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,r){let s=e.dims.at(-1),n=e.data;if(r===-1)n=n.slice(-s);else{let o=r*s;n=n.slice(o,o+s)}return n}randomSelect(e){return bA(e)}static getSampler(e){if(e.do_sample)return new uv(e);if(e.num_beams>1)return new pv(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 cv(e)}},cv=class extends en{async sample(e){let r=ze(e.data)[1];return[[BigInt(r),0]]}},uv=class extends en{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await Gt(e,r),o=Pe(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},pv=class extends en{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await Gt(e,r),o=Pe(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var fv=class{constructor(e){if(e)for(let r in e){if(r in this)throw new TypeError(`Key "${r}" conflicts with an existing property on DynamicCache`);let s=e[r];if(!(s instanceof N))throw new TypeError(`Expected a Tensor for key "${r}", got ${typeof s}`);this[r]=s}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let r in e)if(r.startsWith("past_key_values."))return e[r].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(let r in e){let s=this[r],n=e[r];s&&s!==n&&s.location==="gpu-buffer"&&s.dispose(),this[r]=n}}async dispose(){let e=[];for(let r of Object.values(this))r.location==="gpu-buffer"&&e.push(r.dispose());await Promise.all(e)}},tn=fv;var V={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},dr={[V.DecoderOnly]:{sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[V.DecoderOnlyWithoutHead]:{sessions:(t,e)=>({model:e.model_file_name??"model"})},[V.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[V.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[V.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[V.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),t.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[V.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[V.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},optional_configs:{generation_config:"generation_config.json"}},[V.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[V.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[V.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[V.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[V.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[V.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[V.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(t,e)=>({model:e.model_file_name??"model"})}};function dv(t){return dr[t]?.text_only_sessions??null}function vc(t,e,r={}){let s=dr[t]??dr.default;return{sessions:s.sessions(e,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function mo(t,{warn:e=!0}={}){let r=t.architectures||[];for(let s of r){let n=tr.get(s);if(n!==void 0)return n}if(t.model_type){let s=tr.get(t.model_type);if(s!==void 0)return s;for(let n of Object.values(rn))if(n.has(t.model_type)){let o=tr.get(n.get(t.model_type));if(o!==void 0)return o}}if(e){let s=r.length>0?r.join(", "):"(none)";ee.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${cs}`)}return V.EncoderOnly}function kc(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return Rt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=JSON.stringify([t,r,s,n]);return fp(o,()=>Rt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n}))}async function ho(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await kc(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,p=r??a.dtype,f=mo(e),_=(x,k=null)=>{k=k??x;let A=Pp(c,x),E=zp(p,x,A),S=is[E]??"",T=`${k}${S}.onnx`,I=l?`${l}/${T}`:T;o.push(I);let O=nv(i,T,x);for(let b of ov(T,O)){let F=l?`${l}/${b}`:b;o.push(F)}},{sessions:m,optional_configs:w}=vc(f,e,{model_file_name:n});for(let[x,k]of Object.entries(m))_(x,k);if(w)for(let x of Object.values(w))o.push(x);return o}var rn=null;function qM(t){rn=t}function _v(t){if(t instanceof N)return t;if(t.length===0)throw Error("items must be non-empty");if(Array.isArray(t[0])){if(t.some(e=>e.length!==t[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 N("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new N("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function mv(t){return new N("bool",[t],[1])}var jM={[V.DecoderOnly]:{can_generate:!0,forward:Ct,prepare_inputs:go},[V.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Ct,prepare_inputs:go},[V.Seq2Seq]:{can_generate:!0,forward:x_,prepare_inputs:Ec},[V.Vision2Seq]:{can_generate:!0,forward:x_,prepare_inputs:Ec},[V.Musicgen]:{can_generate:!0,forward:x_},[V.EncoderDecoder]:{can_generate:!1,forward:x_},[V.ImageTextToText]:{can_generate:!0,forward:XN,prepare_inputs:y_},[V.AudioTextToText]:{can_generate:!0,forward:HN,prepare_inputs:y_},[V.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:y_},[V.Phi3V]:{can_generate:!0,prepare_inputs:y_},[V.MultiModality]:{can_generate:!0},[V.AutoEncoder]:{can_generate:!1,forward:WN},[V.Chatterbox]:{can_generate:!0,forward:qt},[V.VoxtralRealtime]:{can_generate:!0,prepare_inputs:go},default:{can_generate:!1,forward:qt}};function GM(t,e){let r=tr.get(t),s=!1,n=e?.architectures?.[0];if(n&&n!==t&&t?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let i=tr.get(n);i!==void 0&&(r=i,s=!0)}let o=jM[r]??jM.default,a=dr[r]??dr.default;return{typeConfig:{...o,...a},textOnly:s,modelType:r}}var tr=new Map,v_=new Map,sn=new Map,y=class extends We{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,r,s){super(),this.config=e,this.sessions=r,this.configs=s;let n=sn.get(this.constructor),{typeConfig:o}=GM(n,e);this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:p=null,use_external_data_format:f=null,session_options:_={}}={}){let m={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:p,use_external_data_format:f,session_options:_},w=sn.get(this);s=m.config=await Rt.from_pretrained(e,m);let{typeConfig:x,textOnly:k,modelType:A}=GM(w,s);if(A===void 0){let I=w??s?.model_type;I!=="custom"&&ee.warn(`Model type for '${I}' not found, assuming encoder-only architecture. Please report this at ${cs}.`)}if(r&&!(r instanceof Cs)){let I={};try{let O=await ho(e,{config:s,dtype:p,device:c,model_file_name:i});(await Promise.all(O.map(F=>Ot(e,F,m)))).forEach((F,j)=>{if(F.exists){let U=O[j]==="config.json";I[O[j]]={loaded:U?F.size??0:0,total:F.size??0}}})}catch(O){ee.warn(`Unable to fetch model file metadata for total progress tracking: ${O}`)}Object.keys(I).length>0&&(m.progress_callback=new Cs(r,I))}let E=x.sessions(s,m,k),S=[BM(e,E,m,x.cache_sessions)];x.optional_configs&&S.push(YN(e,x.optional_configs,m));let T=await Promise.all(S);return new this(s,...T)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new ds;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new _c(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new dc(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new gc(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new mc(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&n.push(new hc(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new cc(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new uc(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&n.push(new pc(e.suppress_tokens)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new Js(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new wc(e.guidance_scale)),e.temperature===0&&e.do_sample&&(ee.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&n.push(new xc(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=_o){let n={...this.config};for(let a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);let o=new s(n);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),r&&Object.assign(o,Ve(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Zs;return e.max_length!==null&&s.push(new yc(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new bc(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[rn.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,rn.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,rn.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,rn.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=sn.get(this.constructor),s=new Set,n=this.config.model_type;for(let a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=b_(r,s.past_key_values),s.input_ids=new N("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=ye([s.decoder_attention_mask,Ze([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=ye([s.attention_mask,Ze([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:r,model_kwargs:s}){let n=Ve(s,this.forward_params),o=this.main_input_name;if(o 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[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...c}=r,p=await this._prepare_inputs_embeds(r);r={...c,...Ve(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await qt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=ye([o,Wn(o,0)],0),"attention_mask"in r&&(r.attention_mask=ye([r.attention_mask,Dp(r.attention_mask)],0));else if(r.decoder_input_ids){let a=_v(r.decoder_input_ids).dims[0];if(a!==o.dims[0]){if(o.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${o.dims[0]}) than the decoder inputs (${a}).`);o=ye(Array.from({length:a},()=>o),0)}}return r.encoder_outputs=o,r}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:o,generation_config:a}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof N)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=o,this.config.model_type==="musicgen")i=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}`);i=n}else i=Array.from({length:e},()=>[n]);i=_v(i)}return l.decoder_attention_mask=Bl(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),p=this.config.is_encoder_decoder;p&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let f;p?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];let _=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=_+r.max_new_tokens);let m=this._get_logits_processor(r,_,s),w=this._get_stopping_criteria(r,n),x=l[c].dims.at(0),k=en.getSampler(r),A=new Array(x).fill(0),E=f.tolist();o&&o.put(E);let S,T={},I={};for(;;){if(l=this.prepare_inputs_for_generation(E,l,r),S=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let R=VN(S);for(let C in R)C in T||(T[C]=[]),T[C].push(R[C])}else this._return_dict_in_generate_keys&&Object.assign(I,Ve(S,this._return_dict_in_generate_keys));let U=S.logits.slice(null,-1,null).to("float32"),X=m(E,U),K=[];for(let R=0;RR))break;l=this._update_model_kwargs_for_generation({generated_input_ids:K,outputs:S,model_inputs:l,is_encoder_decoder:p})}o&&o.end();let O=new N("int64",E.flat(),[E.length,E[0].length]),b=b_(S,l.past_key_values),F=new Set(Object.values(b));for(let U of Object.values(S))U.location==="gpu-buffer"&&!F.has(U)&&U.dispose();return"past_key_values"in a||r.return_dict_in_generate||await b.dispose(),r.return_dict_in_generate?{sequences:O,past_key_values:b,...T,...I}:O}async _encode_input(e,r,s){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);let n=this.sessions[e];return(await ue(n,Ve(r,n.inputNames)))[s]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function x_(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:o,...a}=e;if(!r){let i=Ve(e,t.sessions.model.inputNames);r=(await qt(t,i)).last_hidden_state}return a.input_ids=n,a.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=e.attention_mask),o&&!a.attention_mask&&(a.attention_mask=o),await Ct(t,a,!0)}async function qt(t,e){let r=t.sessions.model,s=Ve(e,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Dp(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let n=s.pixel_values.dims;s.pixel_mask=Ze([n[0],n[2],n[3]])}return await ue(r,s)}async function WN(t,e){let r=await t.encode(e);return await t.decode(r)}function b_(t,e){let r=Object.create(null);for(let s in t)if(s.startsWith("present")){let n=s.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");s.includes("encoder")&&e?r[n]=e[n]:r[n]=t[s]}return e?(e.update(r),e):new tn(r)}function VN(t){let e={};for(let r of["cross_attentions","encoder_attentions","decoder_attentions"])for(let s in t)s.startsWith(r)&&(r in e||(e[r]=[]),e[r].push(t[s]));return e}function hv(t,e){return t.map(r=>typeof r=="number"?r:e[r]??0)}function Ac(t,e,r){if(r&&Object.keys(r).length>0)return Object.assign(e,r),r;let s=t.sessions.decoder_model_merged??t.sessions.model,n=(e[t.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=Qs(t.config),a=t.config?.normalized_config?.num_heads,i={batch_size:n};typeof a=="number"&&(i["batch_size x num_heads"]=n*a);let l=Object.create(null);for(let c of s.inputMetadata){if(!o.has(c.name))continue;let p=hv(c.shape,i),f=p.reduce((w,x)=>w*x,1),_=ls[c.type],m=new N(c.type,new _(f),p);e[c.name]=m,l[c.name]=m}return r?(r.update(l),r):new tn(l)}async function Ct(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=mv(n!=null&&Object.keys(n).length>0)),s.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(t.config.model_type)?1:0;o.position_ids=KN(o,n,i)}s.inputNames.includes("num_logits_to_keep")&&!o.num_logits_to_keep&&(o.num_logits_to_keep=new N("int64",[0n],[])),Ac(t,o,n);let a=Ve(o,s.inputNames);return await ue(s,a)}async function WM(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:f=null,..._}){if(!l){l=await t.encode_text({input_ids:o,..._});let w=Ve(_,s);if(Object.keys(w).length>0){if(o.dims[1]!==1){let x=await e({...w,..._});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&o.dims[1]===1){let x=o.dims[1],k=c.get_seq_length();a=ye([Ze([o.dims[0],k]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(t.config.model_type)){let{image_grid_thw:w,video_grid_thw:x}=_;[i]=t.get_rope_index(o,w,x,a)}return await Ct(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:p,logits_processor:f},!0)}async function HN(t,e){return await WM(t,{...e,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:t.encode_audio.bind(t),merge_function:t._merge_input_ids_with_audio_features.bind(t)})}async function XN(t,e){return await WM(t,{...e,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:t.encode_image.bind(t),merge_function:t._merge_input_ids_with_image_features.bind(t)})}function gv(t,e=0){let[r,s]=t.dims,n=t.data,o=new BigInt64Array(n.length);for(let a=0;aa.dims[1]||n[n.at(-1)])),{...r,decoder_input_ids:_v(e)}}function y_(t,...e){return t.config.is_encoder_decoder?Ec(t,...e):go(t,...e)}function VM({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((p,f,_)=>(f==t&&p.push(_),p),[])),a=o.reduce((c,p)=>c+p.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let c=0;c{let n=await nt(t,e[s],!1,r);return[s,n]})))}var Eu={};Os(Eu,{ASTForAudioClassification:()=>N_,ASTModel:()=>L_,ASTPreTrainedModel:()=>vo,AfmoeForCausalLM:()=>C_,AfmoeModel:()=>I_,AfmoePreTrainedModel:()=>yo,AlbertForMaskedLM:()=>T_,AlbertForQuestionAnswering:()=>M_,AlbertForSequenceClassification:()=>A_,AlbertModel:()=>E_,AlbertPreTrainedModel:()=>_s,ApertusForCausalLM:()=>O_,ApertusModel:()=>S_,ApertusPreTrainedModel:()=>xo,ArceeForCausalLM:()=>z_,ArceeModel:()=>P_,ArceePreTrainedModel:()=>bo,BartForConditionalGeneration:()=>R_,BartForSequenceClassification:()=>D_,BartModel:()=>$_,BartPretrainedModel:()=>nn,BeitForImageClassification:()=>B_,BeitModel:()=>F_,BeitPreTrainedModel:()=>ko,BertForMaskedLM:()=>j_,BertForQuestionAnswering:()=>W_,BertForSequenceClassification:()=>G_,BertForTokenClassification:()=>q_,BertModel:()=>U_,BertPreTrainedModel:()=>Mr,BlenderbotForConditionalGeneration:()=>H_,BlenderbotModel:()=>V_,BlenderbotPreTrainedModel:()=>Eo,BlenderbotSmallForConditionalGeneration:()=>K_,BlenderbotSmallModel:()=>X_,BlenderbotSmallPreTrainedModel:()=>Ao,BloomForCausalLM:()=>Q_,BloomModel:()=>Y_,BloomPreTrainedModel:()=>Mo,CHMv2ForDepthEstimation:()=>nm,CHMv2PreTrainedModel:()=>Sc,CLIPModel:()=>am,CLIPPreTrainedModel:()=>rr,CLIPSegForImageSegmentation:()=>pm,CLIPSegModel:()=>um,CLIPSegPreTrainedModel:()=>Co,CLIPTextModel:()=>im,CLIPTextModelWithProjection:()=>Io,CLIPVisionModel:()=>lm,CLIPVisionModelWithProjection:()=>cm,CamembertForMaskedLM:()=>Z_,CamembertForQuestionAnswering:()=>rm,CamembertForSequenceClassification:()=>em,CamembertForTokenClassification:()=>tm,CamembertModel:()=>J_,CamembertPreTrainedModel:()=>Tr,ChatterboxModel:()=>To,ChatterboxPreTrainedModel:()=>Mc,ChineseCLIPModel:()=>sm,ChineseCLIPPreTrainedModel:()=>Tc,ClapAudioModelWithProjection:()=>Oo,ClapModel:()=>om,ClapPreTrainedModel:()=>on,ClapTextModelWithProjection:()=>So,CodeGenForCausalLM:()=>dm,CodeGenModel:()=>fm,CodeGenPreTrainedModel:()=>Po,Cohere2ForCausalLM:()=>gm,Cohere2Model:()=>hm,Cohere2PreTrainedModel:()=>Lo,CohereAsrForConditionalGeneration:()=>xm,CohereAsrModel:()=>wm,CohereAsrPreTrainedModel:()=>No,CohereForCausalLM:()=>mm,CohereModel:()=>_m,CoherePreTrainedModel:()=>zo,ConvBertForMaskedLM:()=>bm,ConvBertForQuestionAnswering:()=>Em,ConvBertForSequenceClassification:()=>vm,ConvBertForTokenClassification:()=>km,ConvBertModel:()=>ym,ConvBertPreTrainedModel:()=>Sr,ConvNextForImageClassification:()=>Mm,ConvNextModel:()=>Am,ConvNextPreTrainedModel:()=>$o,ConvNextV2ForImageClassification:()=>Sm,ConvNextV2Model:()=>Tm,ConvNextV2PreTrainedModel:()=>Ro,DFineForObjectDetection:()=>Pm,DFineModel:()=>Cm,DFinePreTrainedModel:()=>Fo,DINOv3ConvNextModel:()=>nh,DINOv3ConvNextPreTrainedModel:()=>Nc,DINOv3ViTModel:()=>oh,DINOv3ViTPreTrainedModel:()=>$c,DPTForDepthEstimation:()=>dh,DPTModel:()=>fh,DPTPreTrainedModel:()=>Vo,DacDecoderModel:()=>Uo,DacDecoderOutput:()=>Ic,DacEncoderModel:()=>Bo,DacEncoderOutput:()=>Oc,DacModel:()=>zm,DacPreTrainedModel:()=>an,DebertaForMaskedLM:()=>Nm,DebertaForQuestionAnswering:()=>Dm,DebertaForSequenceClassification:()=>$m,DebertaForTokenClassification:()=>Rm,DebertaModel:()=>Lm,DebertaPreTrainedModel:()=>Or,DebertaV2ForMaskedLM:()=>jm,DebertaV2ForQuestionAnswering:()=>Wm,DebertaV2ForSequenceClassification:()=>Gm,DebertaV2ForTokenClassification:()=>qm,DebertaV2Model:()=>Um,DebertaV2PreTrainedModel:()=>Ir,DecisionTransformerModel:()=>Vm,DecisionTransformerPreTrainedModel:()=>Cc,DeepseekV3ForCausalLM:()=>Bm,DeepseekV3Model:()=>Fm,DeepseekV3PreTrainedModel:()=>jo,DeiTForImageClassification:()=>Xm,DeiTModel:()=>Hm,DeiTPreTrainedModel:()=>Go,DepthAnythingForDepthEstimation:()=>Km,DepthAnythingPreTrainedModel:()=>Pc,DepthProForDepthEstimation:()=>Ym,DepthProPreTrainedModel:()=>zc,DetrForObjectDetection:()=>Jm,DetrForSegmentation:()=>Zm,DetrModel:()=>Qm,DetrObjectDetectionOutput:()=>cn,DetrPreTrainedModel:()=>ln,DetrSegmentationOutput:()=>Lc,Dinov2ForImageClassification:()=>th,Dinov2Model:()=>eh,Dinov2PreTrainedModel:()=>qo,Dinov2WithRegistersForImageClassification:()=>sh,Dinov2WithRegistersModel:()=>rh,Dinov2WithRegistersPreTrainedModel:()=>Wo,DistilBertForMaskedLM:()=>uh,DistilBertForQuestionAnswering:()=>ch,DistilBertForSequenceClassification:()=>ih,DistilBertForTokenClassification:()=>lh,DistilBertModel:()=>ah,DistilBertPreTrainedModel:()=>Cr,DonutSwinModel:()=>ph,DonutSwinPreTrainedModel:()=>Rc,EdgeTamModel:()=>Ey,EfficientNetForImageClassification:()=>mh,EfficientNetModel:()=>_h,EfficientNetPreTrainedModel:()=>Ho,ElectraForMaskedLM:()=>gh,ElectraForQuestionAnswering:()=>yh,ElectraForSequenceClassification:()=>wh,ElectraForTokenClassification:()=>xh,ElectraModel:()=>hh,ElectraPreTrainedModel:()=>Pr,Ernie4_5ForCausalLM:()=>vh,Ernie4_5Model:()=>bh,Ernie4_5PretrainedModel:()=>Xo,EsmForMaskedLM:()=>Eh,EsmForSequenceClassification:()=>Ah,EsmForTokenClassification:()=>Mh,EsmModel:()=>kh,EsmPreTrainedModel:()=>ms,EuroBertForMaskedLM:()=>Sh,EuroBertForSequenceClassification:()=>Oh,EuroBertForTokenClassification:()=>Ih,EuroBertModel:()=>Th,EuroBertPreTrainedModel:()=>hs,ExaoneForCausalLM:()=>Ph,ExaoneModel:()=>Ch,ExaonePreTrainedModel:()=>Ko,FalconForCausalLM:()=>Lh,FalconH1ForCausalLM:()=>$h,FalconH1Model:()=>Nh,FalconH1PreTrainedModel:()=>Qo,FalconModel:()=>zh,FalconPreTrainedModel:()=>Yo,FastViTForImageClassification:()=>Dh,FastViTModel:()=>Rh,FastViTPreTrainedModel:()=>Jo,Florence2ForConditionalGeneration:()=>Fh,Florence2PreTrainedModel:()=>Dc,GLPNForDepthEstimation:()=>rg,GLPNModel:()=>tg,GLPNPreTrainedModel:()=>oa,GPT2LMHeadModel:()=>fg,GPT2Model:()=>pg,GPT2PreTrainedModel:()=>ua,GPTBigCodeForCausalLM:()=>ng,GPTBigCodeModel:()=>sg,GPTBigCodePreTrainedModel:()=>aa,GPTJForCausalLM:()=>_g,GPTJModel:()=>dg,GPTJPreTrainedModel:()=>pa,GPTNeoForCausalLM:()=>ag,GPTNeoModel:()=>og,GPTNeoPreTrainedModel:()=>ia,GPTNeoXForCausalLM:()=>lg,GPTNeoXModel:()=>ig,GPTNeoXPreTrainedModel:()=>la,Gemma2ForCausalLM:()=>Gh,Gemma2Model:()=>jh,Gemma2PreTrainedModel:()=>ea,Gemma3ForCausalLM:()=>Hh,Gemma3ForConditionalGeneration:()=>Uc,Gemma3Model:()=>Vh,Gemma3PreTrainedModel:()=>Bc,Gemma3nForCausalLM:()=>Xh,Gemma3nForConditionalGeneration:()=>zr,Gemma3nPreTrainedModel:()=>jc,Gemma4ForCausalLM:()=>Kh,Gemma4ForConditionalGeneration:()=>un,GemmaForCausalLM:()=>Uh,GemmaModel:()=>Bh,GemmaPreTrainedModel:()=>Zo,GlmForCausalLM:()=>Qh,GlmModel:()=>Yh,GlmMoeDsaForCausalLM:()=>Zh,GlmMoeDsaModel:()=>Jh,GlmMoeDsaPreTrainedModel:()=>ra,GlmOcrForConditionalGeneration:()=>eg,GlmPreTrainedModel:()=>ta,GptOssForCausalLM:()=>ug,GptOssModel:()=>cg,GptOssPreTrainedModel:()=>ca,GraniteForCausalLM:()=>hg,GraniteModel:()=>mg,GraniteMoeHybridForCausalLM:()=>wg,GraniteMoeHybridModel:()=>gg,GraniteMoeHybridPreTrainedModel:()=>da,GranitePreTrainedModel:()=>fa,GraniteSpeechForConditionalGeneration:()=>xg,GroundingDinoForObjectDetection:()=>yg,GroundingDinoPreTrainedModel:()=>Wc,GroupViTModel:()=>bg,GroupViTPreTrainedModel:()=>Vc,HeliumForCausalLM:()=>kg,HeliumModel:()=>vg,HeliumPreTrainedModel:()=>_a,HieraForImageClassification:()=>Ag,HieraModel:()=>Eg,HieraPreTrainedModel:()=>ma,HubertForCTC:()=>Pg,HubertForSequenceClassification:()=>zg,HubertModel:()=>Cg,HubertPreTrainedModel:()=>Ig,HunYuanDenseV1ForCausalLM:()=>Ng,HunYuanDenseV1Model:()=>Lg,HunYuanDenseV1PreTrainedModel:()=>ha,IJepaForImageClassification:()=>Rg,IJepaModel:()=>$g,IJepaPreTrainedModel:()=>wa,Idefics3ForConditionalGeneration:()=>ga,JAISLMHeadModel:()=>Fg,JAISModel:()=>Dg,JAISPreTrainedModel:()=>xa,JinaCLIPModel:()=>Bg,JinaCLIPPreTrainedModel:()=>fn,JinaCLIPTextModel:()=>ya,JinaCLIPVisionModel:()=>Ug,Lfm2ForCausalLM:()=>Gg,Lfm2Model:()=>jg,Lfm2MoeForCausalLM:()=>Vg,Lfm2MoeModel:()=>Wg,Lfm2MoePreTrainedModel:()=>va,Lfm2PreTrainedModel:()=>ba,Lfm2VlForConditionalGeneration:()=>Hg,LightOnOcrForConditionalGeneration:()=>qg,LiteWhisperForConditionalGeneration:()=>F0,Llama4ForCausalLM:()=>Yg,Llama4PreTrainedModel:()=>Hc,LlamaForCausalLM:()=>Kg,LlamaModel:()=>Xg,LlamaPreTrainedModel:()=>ka,LlavaForConditionalGeneration:()=>bt,LlavaOnevisionForConditionalGeneration:()=>bt,LlavaPreTrainedModel:()=>Fc,LlavaQwen2ForCausalLM:()=>Wh,LongT5ForConditionalGeneration:()=>Jg,LongT5Model:()=>Qg,LongT5PreTrainedModel:()=>Ea,M2M100ForConditionalGeneration:()=>ew,M2M100Model:()=>Zg,M2M100PreTrainedModel:()=>Aa,MBartForCausalLM:()=>lw,MBartForConditionalGeneration:()=>aw,MBartForSequenceClassification:()=>iw,MBartModel:()=>ow,MBartPreTrainedModel:()=>xs,MPNetForMaskedLM:()=>Xw,MPNetForQuestionAnswering:()=>Qw,MPNetForSequenceClassification:()=>Kw,MPNetForTokenClassification:()=>Yw,MPNetModel:()=>Hw,MPNetPreTrainedModel:()=>Lr,MT5ForConditionalGeneration:()=>tx,MT5Model:()=>ex,MT5PreTrainedModel:()=>Da,MarianMTModel:()=>rw,MarianModel:()=>tw,MarianPreTrainedModel:()=>Ma,MaskFormerForInstanceSegmentation:()=>nw,MaskFormerModel:()=>sw,MaskFormerPreTrainedModel:()=>Ta,Metric3DForDepthEstimation:()=>cw,Metric3DPreTrainedModel:()=>Xc,Metric3Dv2ForDepthEstimation:()=>uw,Metric3Dv2PreTrainedModel:()=>Kc,MgpstrForSceneTextRecognition:()=>pw,MgpstrModelOutput:()=>Yc,MgpstrPreTrainedModel:()=>Qc,MimiDecoderModel:()=>Oa,MimiDecoderOutput:()=>Zc,MimiEncoderModel:()=>Sa,MimiEncoderOutput:()=>Jc,MimiModel:()=>fw,MimiPreTrainedModel:()=>dn,Mistral4ForCausalLM:()=>hw,Mistral4Model:()=>mw,Mistral4PreTrainedModel:()=>Ca,MistralForCausalLM:()=>_w,MistralModel:()=>dw,MistralPreTrainedModel:()=>Ia,MobileBertForMaskedLM:()=>ww,MobileBertForQuestionAnswering:()=>yw,MobileBertForSequenceClassification:()=>xw,MobileBertModel:()=>gw,MobileBertPreTrainedModel:()=>ys,MobileLLMForCausalLM:()=>vw,MobileLLMModel:()=>bw,MobileLLMPreTrainedModel:()=>Pa,MobileNetV1ForImageClassification:()=>Ew,MobileNetV1ForSemanticSegmentation:()=>Aw,MobileNetV1Model:()=>kw,MobileNetV1PreTrainedModel:()=>_n,MobileNetV2ForImageClassification:()=>Tw,MobileNetV2ForSemanticSegmentation:()=>Sw,MobileNetV2Model:()=>Mw,MobileNetV2PreTrainedModel:()=>mn,MobileNetV3ForImageClassification:()=>Iw,MobileNetV3ForSemanticSegmentation:()=>Cw,MobileNetV3Model:()=>Ow,MobileNetV3PreTrainedModel:()=>hn,MobileNetV4ForImageClassification:()=>zw,MobileNetV4ForSemanticSegmentation:()=>Lw,MobileNetV4Model:()=>Pw,MobileNetV4PreTrainedModel:()=>gn,MobileViTForImageClassification:()=>$w,MobileViTModel:()=>Nw,MobileViTPreTrainedModel:()=>za,MobileViTV2ForImageClassification:()=>Dw,MobileViTV2Model:()=>Rw,MobileViTV2PreTrainedModel:()=>La,ModernBertDecoderForCausalLM:()=>qw,ModernBertDecoderModel:()=>Gw,ModernBertDecoderPreTrainedModel:()=>Na,ModernBertForMaskedLM:()=>Bw,ModernBertForSequenceClassification:()=>Uw,ModernBertForTokenClassification:()=>jw,ModernBertModel:()=>Fw,ModernBertPreTrainedModel:()=>bs,Moondream1ForConditionalGeneration:()=>qh,MoonshineForConditionalGeneration:()=>Vw,MoonshineModel:()=>Ww,MoonshinePreTrainedModel:()=>$a,MptForCausalLM:()=>Zw,MptModel:()=>Jw,MptPreTrainedModel:()=>Ra,MultiModalityCausalLM:()=>rx,MultiModalityPreTrainedModel:()=>eu,MusicgenForCausalLM:()=>nx,MusicgenForConditionalGeneration:()=>Ba,MusicgenModel:()=>sx,MusicgenPreTrainedModel:()=>Fa,NanoChatForCausalLM:()=>ax,NanoChatModel:()=>ox,NanoChatPreTrainedModel:()=>Ua,NemotronHForCausalLM:()=>lx,NemotronHModel:()=>ix,NemotronHPreTrainedModel:()=>ja,NeoBertForMaskedLM:()=>ux,NeoBertForQuestionAnswering:()=>dx,NeoBertForSequenceClassification:()=>px,NeoBertForTokenClassification:()=>fx,NeoBertModel:()=>cx,NeoBertPreTrainedModel:()=>Nr,NomicBertModel:()=>_x,NomicBertPreTrainedModel:()=>tu,OPTForCausalLM:()=>Sx,OPTModel:()=>Tx,OPTPreTrainedModel:()=>Ka,Olmo2ForCausalLM:()=>wx,Olmo2Model:()=>gx,Olmo2PreTrainedModel:()=>qa,Olmo3ForCausalLM:()=>yx,Olmo3Model:()=>xx,Olmo3PreTrainedModel:()=>Wa,OlmoForCausalLM:()=>hx,OlmoHybridForCausalLM:()=>vx,OlmoHybridModel:()=>bx,OlmoHybridPreTrainedModel:()=>Va,OlmoModel:()=>mx,OlmoPreTrainedModel:()=>Ga,OpenAIPrivacyFilterForTokenClassification:()=>Ex,OpenAIPrivacyFilterModel:()=>kx,OpenAIPrivacyFilterPreTrainedModel:()=>Ha,OpenELMForCausalLM:()=>Mx,OpenELMModel:()=>Ax,OpenELMPreTrainedModel:()=>Xa,OwlViTForObjectDetection:()=>Px,OwlViTModel:()=>Cx,OwlViTPreTrainedModel:()=>Qa,Owlv2ForObjectDetection:()=>Ix,Owlv2Model:()=>Ox,Owlv2PreTrainedModel:()=>Ya,PaliGemmaForConditionalGeneration:()=>zx,ParakeetForCTC:()=>Lx,ParakeetPreTrainedModel:()=>ru,PatchTSMixerForPrediction:()=>$x,PatchTSMixerModel:()=>Nx,PatchTSMixerPreTrainedModel:()=>Ja,PatchTSTForPrediction:()=>Dx,PatchTSTModel:()=>Rx,PatchTSTPreTrainedModel:()=>Za,Phi3ForCausalLM:()=>jx,Phi3Model:()=>Ux,Phi3PreTrainedModel:()=>ti,Phi3VForCausalLM:()=>ri,Phi3VPreTrainedModel:()=>su,PhiForCausalLM:()=>Bx,PhiModel:()=>Fx,PhiPreTrainedModel:()=>ei,PreTrainedModel:()=>y,PvtForImageClassification:()=>qx,PvtModel:()=>Gx,PvtPreTrainedModel:()=>si,PyAnnoteForAudioFrameClassification:()=>Vx,PyAnnoteModel:()=>Wx,PyAnnotePreTrainedModel:()=>ni,Qwen2ForCausalLM:()=>Xx,Qwen2Model:()=>Hx,Qwen2MoeForCausalLM:()=>Yx,Qwen2MoeModel:()=>Kx,Qwen2MoePreTrainedModel:()=>ai,Qwen2PreTrainedModel:()=>oi,Qwen2VLForCausalLM:()=>sa,Qwen2VLForConditionalGeneration:()=>pn,Qwen2VLPreTrainedModel:()=>Gc,Qwen2_5_VLForCausalLM:()=>na,Qwen2_5_VLForConditionalGeneration:()=>gs,Qwen3ForCausalLM:()=>Jx,Qwen3Model:()=>Qx,Qwen3MoeForCausalLM:()=>ey,Qwen3MoeModel:()=>Zx,Qwen3MoePreTrainedModel:()=>li,Qwen3NextForCausalLM:()=>ry,Qwen3NextModel:()=>ty,Qwen3NextPreTrainedModel:()=>ci,Qwen3PreTrainedModel:()=>ii,Qwen3VLForCausalLM:()=>ui,Qwen3VLForConditionalGeneration:()=>vs,Qwen3VLMoeForCausalLM:()=>ny,Qwen3VLMoeForConditionalGeneration:()=>sy,Qwen3_5ForCausalLM:()=>pi,Qwen3_5ForConditionalGeneration:()=>wn,Qwen3_5MoeForCausalLM:()=>ay,Qwen3_5MoeForConditionalGeneration:()=>oy,RFDetrForObjectDetection:()=>uy,RFDetrModel:()=>cy,RFDetrObjectDetectionOutput:()=>nu,RFDetrPreTrainedModel:()=>di,RTDetrForObjectDetection:()=>Im,RTDetrModel:()=>Om,RTDetrObjectDetectionOutput:()=>sr,RTDetrPreTrainedModel:()=>Do,RTDetrV2ForObjectDetection:()=>vy,RTDetrV2Model:()=>by,RTDetrV2ObjectDetectionOutput:()=>ou,RTDetrV2PreTrainedModel:()=>_i,ResNetForImageClassification:()=>ly,ResNetModel:()=>iy,ResNetPreTrainedModel:()=>fi,RoFormerForMaskedLM:()=>gy,RoFormerForQuestionAnswering:()=>yy,RoFormerForSequenceClassification:()=>wy,RoFormerForTokenClassification:()=>xy,RoFormerModel:()=>hy,RoFormerPreTrainedModel:()=>Rr,RobertaForMaskedLM:()=>fy,RobertaForQuestionAnswering:()=>my,RobertaForSequenceClassification:()=>dy,RobertaForTokenClassification:()=>_y,RobertaModel:()=>py,RobertaPreTrainedModel:()=>$r,Sam2ImageSegmentationOutput:()=>lu,Sam2Model:()=>mi,Sam2PreTrainedModel:()=>cu,Sam3TrackerModel:()=>Ay,SamImageSegmentationOutput:()=>au,SamModel:()=>ky,SamPreTrainedModel:()=>iu,SapiensForDepthEstimation:()=>Ty,SapiensForNormalEstimation:()=>Sy,SapiensForSemanticSegmentation:()=>My,SapiensPreTrainedModel:()=>xn,SegformerForImageClassification:()=>Iy,SegformerForSemanticSegmentation:()=>Cy,SegformerModel:()=>Oy,SegformerPreTrainedModel:()=>yn,SiglipModel:()=>Py,SiglipPreTrainedModel:()=>hi,SiglipTextModel:()=>gi,SiglipVisionModel:()=>zy,SmolLM3ForCausalLM:()=>Ny,SmolLM3Model:()=>Ly,SmolLM3PreTrainedModel:()=>wi,SmolVLMForConditionalGeneration:()=>$y,SnacDecoderModel:()=>yi,SnacEncoderModel:()=>xi,SnacModel:()=>Ry,SnacPreTrainedModel:()=>bn,SolarOpenForCausalLM:()=>Fy,SolarOpenModel:()=>Dy,SolarOpenPreTrainedModel:()=>bi,SpeechT5ForSpeechToText:()=>Uy,SpeechT5ForTextToSpeech:()=>jy,SpeechT5HifiGan:()=>Gy,SpeechT5Model:()=>By,SpeechT5PreTrainedModel:()=>vn,SqueezeBertForMaskedLM:()=>Wy,SqueezeBertForQuestionAnswering:()=>Hy,SqueezeBertForSequenceClassification:()=>Vy,SqueezeBertModel:()=>qy,SqueezeBertPreTrainedModel:()=>ks,StableLmForCausalLM:()=>Ky,StableLmModel:()=>Xy,StableLmPreTrainedModel:()=>vi,Starcoder2ForCausalLM:()=>Qy,Starcoder2Model:()=>Yy,Starcoder2PreTrainedModel:()=>ki,StyleTextToSpeech2Model:()=>Jy,StyleTextToSpeech2PreTrainedModel:()=>uu,SupertonicForConditionalGeneration:()=>Ei,SupertonicPreTrainedModel:()=>pu,Swin2SRForImageSuperResolution:()=>s0,Swin2SRModel:()=>r0,Swin2SRPreTrainedModel:()=>Ai,SwinForImageClassification:()=>e0,SwinForSemanticSegmentation:()=>t0,SwinModel:()=>Zy,SwinPreTrainedModel:()=>kn,T5ForConditionalGeneration:()=>o0,T5Model:()=>n0,T5PreTrainedModel:()=>Mi,TableTransformerForObjectDetection:()=>i0,TableTransformerModel:()=>a0,TableTransformerObjectDetectionOutput:()=>fu,TableTransformerPreTrainedModel:()=>Ti,TrOCRForCausalLM:()=>l0,TrOCRPreTrainedModel:()=>du,UltravoxModel:()=>ws,UltravoxPreTrainedModel:()=>qc,UniSpeechForCTC:()=>u0,UniSpeechForSequenceClassification:()=>p0,UniSpeechModel:()=>c0,UniSpeechPreTrainedModel:()=>En,UniSpeechSatForAudioFrameClassification:()=>m0,UniSpeechSatForCTC:()=>d0,UniSpeechSatForSequenceClassification:()=>_0,UniSpeechSatModel:()=>f0,UniSpeechSatPreTrainedModel:()=>Es,VaultGemmaForCausalLM:()=>g0,VaultGemmaModel:()=>h0,VaultGemmaPreTrainedModel:()=>Si,ViTForImageClassification:()=>y0,ViTMAEModel:()=>b0,ViTMAEPreTrainedModel:()=>_u,ViTMSNForImageClassification:()=>k0,ViTMSNModel:()=>v0,ViTMSNPreTrainedModel:()=>Ii,ViTModel:()=>x0,ViTPreTrainedModel:()=>Oi,VisionEncoderDecoderModel:()=>w0,VitMatteForImageMatting:()=>E0,VitMattePreTrainedModel:()=>mu,VitPoseForPoseEstimation:()=>A0,VitPosePreTrainedModel:()=>hu,VitsModel:()=>M0,VitsModelOutput:()=>gu,VitsPreTrainedModel:()=>wu,VoxtralForConditionalGeneration:()=>T0,VoxtralRealtimeForConditionalGeneration:()=>Ci,VoxtralRealtimePreTrainedModel:()=>xu,Wav2Vec2BertForCTC:()=>O0,Wav2Vec2BertForSequenceClassification:()=>I0,Wav2Vec2BertModel:()=>S0,Wav2Vec2BertPreTrainedModel:()=>An,Wav2Vec2ForAudioFrameClassification:()=>Og,Wav2Vec2ForCTC:()=>Tg,Wav2Vec2ForSequenceClassification:()=>Sg,Wav2Vec2Model:()=>Mg,Wav2Vec2PreTrainedModel:()=>Wt,WavLMForAudioFrameClassification:()=>N0,WavLMForCTC:()=>P0,WavLMForSequenceClassification:()=>z0,WavLMForXVector:()=>L0,WavLMModel:()=>C0,WavLMPreTrainedModel:()=>Dr,WeSpeakerResNetModel:()=>$0,WeSpeakerResNetPreTrainedModel:()=>bu,WhisperForConditionalGeneration:()=>vu,WhisperModel:()=>D0,WhisperPreTrainedModel:()=>Pi,XLMForQuestionAnswering:()=>q0,XLMForSequenceClassification:()=>j0,XLMForTokenClassification:()=>G0,XLMModel:()=>B0,XLMPreTrainedModel:()=>Fr,XLMRobertaForMaskedLM:()=>V0,XLMRobertaForQuestionAnswering:()=>K0,XLMRobertaForSequenceClassification:()=>H0,XLMRobertaForTokenClassification:()=>X0,XLMRobertaModel:()=>W0,XLMRobertaPreTrainedModel:()=>Br,XLMWithLMHeadModel:()=>U0,XVectorOutput:()=>yu,YolosForObjectDetection:()=>Q0,YolosModel:()=>Y0,YolosObjectDetectionOutput:()=>ku,YolosPreTrainedModel:()=>zi,YoutuForCausalLM:()=>Z0,YoutuModel:()=>J0,YoutuPreTrainedModel:()=>Li});var _s=class extends y{},E_=class extends _s{},A_=class extends _s{async _call(e){return new q(await super._call(e))}},M_=class extends _s{async _call(e){return new Te(await super._call(e))}},T_=class extends _s{async _call(e){return new we(await super._call(e))}};var xo=class extends y{},S_=class extends xo{},O_=class extends xo{};var yo=class extends y{},I_=class extends yo{},C_=class extends yo{};var bo=class extends y{},P_=class extends bo{},z_=class extends bo{};var vo=class extends y{},L_=class extends vo{},N_=class extends vo{};var nn=class extends y{},$_=class extends nn{},R_=class extends nn{},D_=class extends nn{async _call(e){return new q(await super._call(e))}};var ko=class extends y{},F_=class extends ko{},B_=class extends ko{async _call(e){return new q(await super._call(e))}};var Mr=class extends y{},U_=class extends Mr{},j_=class extends Mr{async _call(e){return new we(await super._call(e))}},G_=class extends Mr{async _call(e){return new q(await super._call(e))}},q_=class extends Mr{async _call(e){return new ge(await super._call(e))}},W_=class extends Mr{async _call(e){return new Te(await super._call(e))}};var Eo=class extends y{},V_=class extends Eo{},H_=class extends Eo{};var Ao=class extends y{},X_=class extends Ao{},K_=class extends Ao{};var Mo=class extends y{},Y_=class extends Mo{},Q_=class extends Mo{};var Tr=class extends y{},J_=class extends Tr{},Z_=class extends Tr{async _call(e){return new we(await super._call(e))}},em=class extends Tr{async _call(e){return new q(await super._call(e))}},tm=class extends Tr{async _call(e){return new ge(await super._call(e))}},rm=class extends Tr{async _call(e){return new Te(await super._call(e))}};var QN=4299n,HM=6561n,Mc=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},To=class extends Mc{async encode_speech(e){return ue(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,audio_features:p=null,audio_tokens:f=null,speaker_embeddings:_=null,speaker_features:m=null,...w}){let x;if(!a){let A=this.sessions.embed_tokens.inputNames,E={input_ids:e};if(A.includes("exaggeration")){if(!(n instanceof N)){let S=e.dims[0];if(n==null)n=Ke([S],.5);else if(typeof n=="number")n=Ke([S],n);else if(Array.isArray(n))n=new N("float32",n,[S]);else throw new Error("Unsupported type for `exaggeration` input")}E.exaggeration=n}if(A.includes("position_ids")&&(E.position_ids=o),{inputs_embeds:a}=await ue(this.sessions.embed_tokens,E),p&&f&&_&&m&&(x={audio_features:p,audio_tokens:f,speaker_embeddings:_,speaker_features:m}),x||s)x??=await this.encode_speech(s),a=ye([x.audio_features,a],1),r=Ze([a.dims[0],a.dims[1]]);else{let S=a.dims[1];if(!i||S!==1)throw new Error("Incorrect state encountered during generation.");let T=i.get_seq_length();r=Ze([a.dims[0],T+S])}}return{...await Ct(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c},!1),...x}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==HM)-1);r.position_ids=new N("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=HM?0:i++)});r.position_ids=new N("int64",o.flat(),r.input_ids.dims)}return r.input_ids.dims[1]===1&&(delete r.audio_values,delete r.audio_features,delete r.audio_tokens,delete r.speaker_embeddings,delete r.speaker_features),go(this,e,r,s)}async generate(e){let{sequences:r,audio_tokens:s,speaker_embeddings:n,speaker_features:o}=await super.generate({...e,return_dict_in_generate:!0}),a=r.slice(null,[e.input_ids.dims[1],-1]),i=Ke([a.dims[0],3],QN),l=ye([s,a,i],1),{waveform:c}=await ue(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var Tc=class extends y{},sm=class extends Tc{};var Sc=class extends y{},nm=class extends Sc{};var on=class extends y{},om=class extends on{},So=class extends on{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Oo=class extends on{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var rr=class extends y{},am=class extends rr{},im=class extends rr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Io=class extends rr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},lm=class extends rr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},cm=class extends rr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Co=class extends y{},um=class extends Co{},pm=class extends Co{};var Po=class extends y{},fm=class extends Po{},dm=class extends Po{};var zo=class extends y{},_m=class extends zo{},mm=class extends zo{};var Lo=class extends y{},hm=class extends Lo{},gm=class extends Lo{};var No=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},wm=class extends No{},xm=class extends No{};var Sr=class extends y{},ym=class extends Sr{},bm=class extends Sr{async _call(e){return new we(await super._call(e))}},vm=class extends Sr{async _call(e){return new q(await super._call(e))}},km=class extends Sr{async _call(e){return new ge(await super._call(e))}},Em=class extends Sr{async _call(e){return new Te(await super._call(e))}};var $o=class extends y{},Am=class extends $o{},Mm=class extends $o{async _call(e){return new q(await super._call(e))}};var Ro=class extends y{},Tm=class extends Ro{},Sm=class extends Ro{async _call(e){return new q(await super._call(e))}};var Do=class extends y{},Om=class extends Do{},Im=class extends Do{async _call(e){return new sr(await super._call(e))}},sr=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Fo=class extends y{},Cm=class extends Fo{},Pm=class extends Fo{async _call(e){return new sr(await super._call(e))}};var Oc=class extends Re{constructor({audio_codes:e}){super(),this.audio_codes=e}},Ic=class extends Re{constructor({audio_values:e}){super(),this.audio_values=e}},an=class extends y{main_input_name="input_values";forward_params=["input_values"]},zm=class extends an{async encode(e){return new Oc(await ue(this.sessions.encoder_model,e))}async decode(e){return new Ic(await ue(this.sessions.decoder_model,e))}},Bo=class extends an{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Uo=class extends an{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Or=class extends y{},Lm=class extends Or{},Nm=class extends Or{async _call(e){return new we(await super._call(e))}},$m=class extends Or{async _call(e){return new q(await super._call(e))}},Rm=class extends Or{async _call(e){return new ge(await super._call(e))}},Dm=class extends Or{async _call(e){return new Te(await super._call(e))}};var jo=class extends y{},Fm=class extends jo{},Bm=class extends jo{};var Ir=class extends y{},Um=class extends Ir{},jm=class extends Ir{async _call(e){return new we(await super._call(e))}},Gm=class extends Ir{async _call(e){return new q(await super._call(e))}},qm=class extends Ir{async _call(e){return new ge(await super._call(e))}},Wm=class extends Ir{async _call(e){return new Te(await super._call(e))}};var Cc=class extends y{},Vm=class extends Cc{};var Go=class extends y{},Hm=class extends Go{},Xm=class extends Go{async _call(e){return new q(await super._call(e))}};var Pc=class extends y{},Km=class extends Pc{};var zc=class extends y{},Ym=class extends zc{};var ln=class extends y{},Qm=class extends ln{},Jm=class extends ln{async _call(e){return new cn(await super._call(e))}},Zm=class extends ln{async _call(e){return new Lc(await super._call(e))}},cn=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},Lc=class extends Re{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var qo=class extends y{},eh=class extends qo{},th=class extends qo{async _call(e){return new q(await super._call(e))}};var Wo=class extends y{},rh=class extends Wo{},sh=class extends Wo{async _call(e){return new q(await super._call(e))}};var Nc=class extends y{},nh=class extends Nc{};var $c=class extends y{},oh=class extends $c{};var Cr=class extends y{},ah=class extends Cr{},ih=class extends Cr{async _call(e){return new q(await super._call(e))}},lh=class extends Cr{async _call(e){return new ge(await super._call(e))}},ch=class extends Cr{async _call(e){return new Te(await super._call(e))}},uh=class extends Cr{async _call(e){return new we(await super._call(e))}};var Rc=class extends y{},ph=class extends Rc{};var Vo=class extends y{},fh=class extends Vo{},dh=class extends Vo{};var Ho=class extends y{},_h=class extends Ho{},mh=class extends Ho{async _call(e){return new q(await super._call(e))}};var Pr=class extends y{},hh=class extends Pr{},gh=class extends Pr{async _call(e){return new we(await super._call(e))}},wh=class extends Pr{async _call(e){return new q(await super._call(e))}},xh=class extends Pr{async _call(e){return new ge(await super._call(e))}},yh=class extends Pr{async _call(e){return new Te(await super._call(e))}};var Xo=class extends y{},bh=class extends Xo{},vh=class extends Xo{};var ms=class extends y{},kh=class extends ms{},Eh=class extends ms{async _call(e){return new we(await super._call(e))}},Ah=class extends ms{async _call(e){return new q(await super._call(e))}},Mh=class extends ms{async _call(e){return new ge(await super._call(e))}};var hs=class extends y{},Th=class extends hs{},Sh=class extends hs{async _call(e){return new we(await super._call(e))}},Oh=class extends hs{async _call(e){return new q(await super._call(e))}},Ih=class extends hs{async _call(e){return new ge(await super._call(e))}};var Ko=class extends y{},Ch=class extends Ko{},Ph=class extends Ko{};var Yo=class extends y{},zh=class extends Yo{},Lh=class extends Yo{};var Qo=class extends y{},Nh=class extends Qo{},$h=class extends Qo{};var Jo=class extends y{},Rh=class extends Jo{},Dh=class extends Jo{async _call(e){return new q(await super._call(e))}};var Dc=class extends y{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"},Fh=class extends Dc{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:ye([r,e],1),attention_mask:ye([Ze(r.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:s,attention_mask:n}){if(!e&&!r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,a;return e&&(o=await this.encode_text({input_ids:e})),r&&(a=await this.encode_image({pixel_values:r})),o&&a?{inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:a,input_ids:e,attention_mask:n}):s=o||a,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:r,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:o,encoder_outputs:a,past_key_values:i,inputs_embeds:l,decoder_inputs_embeds:c}){if(l||({inputs_embeds:l,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:l,attention_mask:s})),!a){let{last_hidden_state:f}=await qt(this,{inputs_embeds:l,attention_mask:s});a=f}if(!c){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:n})}return await Ct(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var Zo=class extends y{},Bh=class extends Zo{},Uh=class extends Zo{};var ea=class extends y{},jh=class extends ea{},Gh=class extends ea{};var Fc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},bt=class extends Fc{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return wo({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},qh=class extends bt{},Wh=class extends bt{};var Bc=class extends y{},Vh=class extends Bc{},Uc=class extends bt{},Hh=class extends Uc{};var jc=class extends y{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},zr=class extends jc{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:f=null,..._}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await ue(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:w}=await this._encode_vision({pixel_values:s,..._});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:w}=await ue(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Ct(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,attention_mask:r,position_ids:a,generation_config:p,logits_processor:f},!0)}_encode_vision(e){return ue(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return wo({image_token_id:this.config.image_token_id,...e,image_features:s})}_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return k_({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},Xh=class extends zr{};var un=class extends zr{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(e){return ue(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},Kh=class extends un{};var ta=class extends y{},Yh=class extends ta{},Qh=class extends ta{};var ra=class extends y{},Jh=class extends ra{},Zh=class extends ra{};var Gc=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},pn=class extends Gc{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,r){if(r){let{data:s,dims:n}=gv(r),o=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),a=Array.from({length:n[0]},(i,l)=>ze(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return[new N("int64",o,[3,...n]),new N("int64",a,[a.length,1])]}else{let[s,n]=e.dims,o=BigInt64Array.from({length:3*s*n},(a,i)=>BigInt(Math.floor(i%n/s)));return[new N("int64",o,[3,...e.dims]),Rp([s,1])]}}_reorder_and_write_positions(e,r,s,n){let o=e.reduce((c,p)=>c+p.length,0),a=new Array(o),i=0;for(let c=0;c<3;++c)for(let p of e){let f=p.length/3;for(let _=c*f;_<(c+1)*f;++_)a[i++]=p[_]}let l=0;for(let c=0;c(S==l&&E.push(T),E),[]).map(E=>c[E+1]),_=f.filter(E=>E==a).length,m=f.filter(E=>E==i).length,w=[],x=0,k=_,A=m;for(let E=0;Ele>x&&Q==a),T=c.findIndex((Q,le)=>le>x&&Q==i),I=k>0&&S!==-1?S:c.length+1,O=A>0&&T!==-1?T:c.length+1,b,F,j,U;I0?ze(w.at(-1))[0]+1:0;w.push(Array.from({length:3*R},(Q,le)=>C+le%R));let ne=R+C,Y=X*K*J,z=Array.from({length:Y},(Q,le)=>ne+Math.floor(le/(K*J))),$=Array.from({length:Y},(Q,le)=>ne+Math.floor(le/J)%K),B=Array.from({length:Y},(Q,le)=>ne+le%J);w.push([z,$,B].flat()),x=b+Y}if(x0?ze(w.at(-1))[0]+1:0,S=c.length-x;w.push(Array.from({length:3*S},(T,I)=>E+I%S))}return w}get_rope_index(e,r,s,n){let{vision_config:o}=this.config,a=o.spatial_merge_size??2;if(r||s){let i=e.tolist();n||(n=Bl(e));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),p=r?r.tolist():[],f=s?s.tolist():[],_={image_index:0,video_index:0},m=[];for(let w=0;wl[w][S]==1),k=this._get_multimodal_rope_positions({filtered_ids:x,image_grid_thw_list:p,video_grid_thw_list:f,spatial_merge_size:a,state:_}),A=this._reorder_and_write_positions(k,l[w],c,w);m.push(ze(A)[0]+1-i[w].length)}return[new N("int64",c.flat(1/0),[3,e.dims[0],e.dims[1]]),new N("int64",m,[m.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:r}){return(await ue(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(e){return wo({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,r,s){if(!r.attention_mask||r.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return r;if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;let o=r.past_key_values.get_seq_length();if(oa+l);r.position_ids=_t([i,i,i],0)}}return r}},sa=class extends pn{};var gs=class extends pn{image_grid_thw_name="image_grid_thw"},na=class extends sa{image_grid_thw_name="image_grid_thw"};var eg=class extends gs{get_vision_position_ids(e,r,s,n){let o=Math.floor(r[0]/s),a=Math.floor(r[1]/n),i=Math.floor(r[2]/n),l=a*i*o,c=Array.from({length:l},()=>e),p=Array.from({length:l},(_,m)=>e+Math.floor(m/(i*o))),f=Array.from({length:l},(_,m)=>e+m%i);return[...c,...p,...f]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:o}){let{image_token_id:a}=this.config,i=[],l=0,c=e[0]==a?1:0;for(let _=1;_<=e.length;++_){let m=_p+A%x)),p+=x}else{let x=r[o.image_index++].map(Number),k=x[0];f.push(this.get_vision_position_ids(p,x,k,n)),p+=Math.max(x[1],x[2])/n}return f}};var oa=class extends y{},tg=class extends oa{},rg=class extends oa{};var aa=class extends y{},sg=class extends aa{},ng=class extends aa{};var ia=class extends y{},og=class extends ia{},ag=class extends ia{};var la=class extends y{},ig=class extends la{},lg=class extends la{};var ca=class extends y{},cg=class extends ca{},ug=class extends ca{};var ua=class extends y{},pg=class extends ua{},fg=class extends ua{};var pa=class extends y{},dg=class extends pa{},_g=class extends pa{};var fa=class extends y{},mg=class extends fa{},hg=class extends fa{};var da=class extends y{},gg=class extends da{},wg=class extends da{};var qc=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},ws=class extends qc{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return k_({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}};var xg=class extends ws{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var Wc=class extends y{},yg=class extends Wc{};var Vc=class extends y{},bg=class extends Vc{};var _a=class extends y{},vg=class extends _a{},kg=class extends _a{};var ma=class extends y{},Eg=class extends ma{},Ag=class extends ma{async _call(e){return new q(await super._call(e))}};var Wt=class extends y{},Mg=class extends Wt{},Tg=class extends Wt{async _call(e){return new kt(await super._call(e))}},Sg=class extends Wt{async _call(e){return new q(await super._call(e))}},Og=class extends Wt{async _call(e){return new ge(await super._call(e))}};var Ig=class extends y{},Cg=class extends Wt{},Pg=class extends Wt{async _call(e){return new kt(await super._call(e))}},zg=class extends Wt{async _call(e){return new q(await super._call(e))}};var ha=class extends y{},Lg=class extends ha{},Ng=class extends ha{};var ga=class extends bt{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var wa=class extends y{},$g=class extends wa{},Rg=class extends wa{async _call(e){return new q(await super._call(e))}};var xa=class extends y{},Dg=class extends xa{},Fg=class extends xa{};var fn=class extends y{},Bg=class extends fn{async forward(e){let r=!e.input_ids,s=!e.pixel_values;if(r&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(r&&(e.input_ids=Ze([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=Ke([0,3,c,c],0)}let{text_embeddings:n,image_embeddings:o,l2norm_text_embeddings:a,l2norm_image_embeddings:i}=await super.forward(e),l={};return r||(l.text_embeddings=n,l.l2norm_text_embeddings=a),s||(l.image_embeddings=o,l.l2norm_image_embeddings=i),l}},ya=class extends fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Ug=class extends fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var ba=class extends y{},jg=class extends ba{},Gg=class extends ba{};var qg=class extends bt{};var va=class extends y{},Wg=class extends va{},Vg=class extends va{};var Hg=class extends bt{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var ka=class extends y{},Xg=class extends ka{},Kg=class extends ka{};var Hc=class extends y{},Yg=class extends Hc{};var Ea=class extends y{},Qg=class extends Ea{},Jg=class extends Ea{};var Aa=class extends y{},Zg=class extends Aa{},ew=class extends Aa{};var Ma=class extends y{},tw=class extends Ma{},rw=class extends Ma{};var Ta=class extends y{},sw=class extends Ta{},nw=class extends Ta{};var xs=class extends y{},ow=class extends xs{},aw=class extends xs{},iw=class extends xs{async _call(e){return new q(await super._call(e))}},lw=class extends xs{};var Xc=class extends y{},cw=class extends Xc{};var Kc=class extends y{},uw=class extends Kc{};var Yc=class extends Re{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Qc=class extends y{},pw=class extends Qc{async _call(e){return new Yc(await super._call(e))}};var Jc=class extends Re{constructor({audio_codes:e}){super(),this.audio_codes=e}},Zc=class extends Re{constructor({audio_values:e}){super(),this.audio_values=e}},dn=class extends y{main_input_name="input_values";forward_params=["input_values"]},fw=class extends dn{async encode(e){return new Jc(await ue(this.sessions.encoder_model,e))}async decode(e){return new Zc(await ue(this.sessions.decoder_model,e))}},Sa=class extends dn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Oa=class extends dn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Ia=class extends y{},dw=class extends Ia{},_w=class extends Ia{};var Ca=class extends y{},mw=class extends Ca{},hw=class extends Ca{};var ys=class extends y{},gw=class extends ys{},ww=class extends ys{async _call(e){return new we(await super._call(e))}},xw=class extends ys{async _call(e){return new q(await super._call(e))}},yw=class extends ys{async _call(e){return new Te(await super._call(e))}};var Pa=class extends y{},bw=class extends Pa{},vw=class extends Pa{};var _n=class extends y{},kw=class extends _n{},Ew=class extends _n{async _call(e){return new q(await super._call(e))}},Aw=class extends _n{};var mn=class extends y{},Mw=class extends mn{},Tw=class extends mn{async _call(e){return new q(await super._call(e))}},Sw=class extends mn{};var hn=class extends y{},Ow=class extends hn{},Iw=class extends hn{async _call(e){return new q(await super._call(e))}},Cw=class extends hn{};var gn=class extends y{},Pw=class extends gn{},zw=class extends gn{async _call(e){return new q(await super._call(e))}},Lw=class extends gn{};var za=class extends y{},Nw=class extends za{},$w=class extends za{async _call(e){return new q(await super._call(e))}};var La=class extends y{},Rw=class extends La{},Dw=class extends La{async _call(e){return new q(await super._call(e))}};var bs=class extends y{},Fw=class extends bs{},Bw=class extends bs{async _call(e){return new we(await super._call(e))}},Uw=class extends bs{async _call(e){return new q(await super._call(e))}},jw=class extends bs{async _call(e){return new ge(await super._call(e))}};var Na=class extends y{},Gw=class extends Na{},qw=class extends Na{};var $a=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Ww=class extends $a{},Vw=class extends $a{};var Lr=class extends y{},Hw=class extends Lr{},Xw=class extends Lr{async _call(e){return new we(await super._call(e))}},Kw=class extends Lr{async _call(e){return new q(await super._call(e))}},Yw=class extends Lr{async _call(e){return new ge(await super._call(e))}},Qw=class extends Lr{async _call(e){return new Te(await super._call(e))}};var Ra=class extends y{},Jw=class extends Ra{},Zw=class extends Ra{};var Da=class extends y{},ex=class extends Da{},tx=class extends Da{};var eu=class extends y{},rx=class extends eu{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){let r=this._generation_mode??"text",s;if(r==="text"||!e.past_key_values){let l=this.sessions.prepare_inputs_embeds,c=Ve(e,l.inputNames);s=await ue(l,c)}else{let l=this.sessions.gen_img_embeds,c=Ve({image_ids:e.input_ids},l.inputNames);s=await ue(l,c)}let n={...e,...s},o=await Ct(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await ue(a,Ve(o,a.inputNames));return{...s,...o,...i}}prepare_inputs_for_generation(e,r,s){let n=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=ye([r.input_ids,r.input_ids],0):(r.input_ids=ye([r.input_ids,Wn(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=ye([r.attention_mask,Wn(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Ke([0,0,3,384,384],1)),n&&(r.images_seq_mask=new N("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new N("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let r=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[r,null]),o=this.sessions.image_decode,{decoded_image:a}=await ue(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let p=Je.fromTensor(c);l.push(p)}return l}};var Fa=class extends y{},sx=class extends Fa{},nx=class extends Fa{},Ba=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[r,s]=e.dims,n=this.config.decoder.num_codebooks,o=s-n,a=0;for(let c=0;c0&&_<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new N(e.type,e.data.slice(0,a),[i,n,l])}prepare_inputs_for_generation(e,r,s){let n=BigInt(this.config.decoder.pad_token_id),o=structuredClone(e);for(let a=0;a=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),Ec(this,o,r,s)}async generate(e){let r=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await ue(this.sessions.encodec_decode,{audio_codes:s});return n}};var Ua=class extends y{},ox=class extends Ua{},ax=class extends Ua{};var ja=class extends y{},ix=class extends ja{},lx=class extends ja{};var Nr=class extends y{},cx=class extends Nr{},ux=class extends Nr{async _call(e){return new we(await super._call(e))}},px=class extends Nr{async _call(e){return new q(await super._call(e))}},fx=class extends Nr{async _call(e){return new ge(await super._call(e))}},dx=class extends Nr{async _call(e){return new Te(await super._call(e))}};var tu=class extends y{},_x=class extends tu{};var Ga=class extends y{},mx=class extends Ga{},hx=class extends Ga{};var qa=class extends y{},gx=class extends qa{},wx=class extends qa{};var Wa=class extends y{},xx=class extends Wa{},yx=class extends Wa{};var Va=class extends y{},bx=class extends Va{},vx=class extends Va{};var Ha=class extends y{},kx=class extends Ha{},Ex=class extends Ha{async _call(e){return new q(await super._call(e))}};var Xa=class extends y{},Ax=class extends Xa{},Mx=class extends Xa{};var Ka=class extends y{},Tx=class extends Ka{},Sx=class extends Ka{};var Ya=class extends y{},Ox=class extends Ya{},Ix=class extends Ya{};var Qa=class extends y{},Cx=class extends Qa{},Px=class extends Qa{};var zx=class extends bt{};var ru=class extends y{},Lx=class extends ru{async _call(e){return new kt(await super._call(e))}};var Ja=class extends y{},Nx=class extends Ja{},$x=class extends Ja{};var Za=class extends y{},Rx=class extends Za{},Dx=class extends Za{};var ei=class extends y{},Fx=class extends ei{},Bx=class extends ei{};var ti=class extends y{},Ux=class extends ti{},jx=class extends ti{};var su=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},ri=class extends su{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,...p}){if(!a){let _;if(s&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:_}=await ue(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let m=this.config.normalized_config.hidden_size;_=new N("float32",[],[0,m])}({inputs_embeds:a}=await ue(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:_}))}return await Ct(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var si=class extends y{},Gx=class extends si{},qx=class extends si{async _call(e){return new q(await super._call(e))}};var ni=class extends y{},Wx=class extends ni{},Vx=class extends ni{async _call(e){return new ge(await super._call(e))}};var oi=class extends y{},Hx=class extends oi{},Xx=class extends oi{};var ai=class extends y{},Kx=class extends ai{},Yx=class extends ai{};var ii=class extends y{},Qx=class extends ii{},Jx=class extends ii{};var li=class extends y{},Zx=class extends li{},ey=class extends li{};var ci=class extends y{},ty=class extends ci{},ry=class extends ci{};var vs=class extends gs{},ui=class extends na{};var sy=class extends vs{},ny=class extends ui{};var wn=class extends vs{},pi=class extends wn{};var oy=class extends wn{},ay=class extends pi{};var fi=class extends y{},iy=class extends fi{},ly=class extends fi{async _call(e){return new q(await super._call(e))}};var di=class extends y{},cy=class extends di{},uy=class extends di{async _call(e){return new nu(await super._call(e))}},nu=class extends sr{};var $r=class extends y{},py=class extends $r{},fy=class extends $r{async _call(e){return new we(await super._call(e))}},dy=class extends $r{async _call(e){return new q(await super._call(e))}},_y=class extends $r{async _call(e){return new ge(await super._call(e))}},my=class extends $r{async _call(e){return new Te(await super._call(e))}};var Rr=class extends y{},hy=class extends Rr{},gy=class extends Rr{async _call(e){return new we(await super._call(e))}},wy=class extends Rr{async _call(e){return new q(await super._call(e))}},xy=class extends Rr{async _call(e){return new ge(await super._call(e))}},yy=class extends Rr{async _call(e){return new Te(await super._call(e))}};var _i=class extends y{},by=class extends _i{},vy=class extends _i{async _call(e){return new ou(await super._call(e))}},ou=class extends sr{};var au=class extends Re{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},iu=class extends y{},ky=class extends iu{async get_image_embeddings({pixel_values:e}){return await qt(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=Ze(e.input_points.dims.slice(0,-1));let r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await ue(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new au(await super._call(e))}};var lu=class extends Re{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},cu=class extends y{},mi=class extends cu{async get_image_embeddings({pixel_values:e}){return await qt(this,{pixel_values:e})}async forward(e){let{num_feature_levels:r}=this.config.vision_config;if(Array.from({length:r},(a,i)=>`image_embeddings.${i}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??=Ze(a.slice(0,-1)),e.input_boxes??=Ke([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Ke([a[0],a[1],0],-1n),e.input_points=Ke([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,o=Ve(e,n.inputNames);return await ue(n,o)}async _call(e){return new lu(await super._call(e))}},Ey=class extends mi{},Ay=class extends mi{};var xn=class extends y{},My=class extends xn{},Ty=class extends xn{},Sy=class extends xn{};var yn=class extends y{},Oy=class extends yn{},Iy=class extends yn{},Cy=class extends yn{};var hi=class extends y{},Py=class extends hi{},gi=class extends hi{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},zy=class extends rr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var wi=class extends y{},Ly=class extends wi{},Ny=class extends wi{};var $y=class extends ga{};var bn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Ry=class extends bn{async encode(e){return await ue(this.sessions.encoder_model,e)}async decode(e){return await ue(this.sessions.decoder_model,e)}},xi=class extends bn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},yi=class extends bn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var bi=class extends y{},Dy=class extends bi{},Fy=class extends bi{};var vn=class extends y{},By=class extends vn{},Uy=class extends vn{},jy=class extends vn{async generate_speech(e,r,{threshold:s=.5,minlenratio:n=0,maxlenratio:o=20,vocoder:a=null}={}){let i={input_ids:e},{encoder_outputs:l,encoder_attention_mask:c}=await qt(this,i),p=l.dims[1]/this.config.reduction_factor,f=Math.floor(p*o),_=Math.floor(p*n),m=this.config.num_mel_bins,w=[],x=null,k=null,A=0;for(;;){++A;let T=mv(!!k),I;k?I=k.output_sequence_out:I=new N("float32",new Float32Array(m),[1,1,m]);let O={use_cache_branch:T,output_sequence:I,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};Ac(this,O,x),k=await ue(this.sessions.decoder_model_merged,O),x=b_(k,x);let{prob:b,spectrum:F}=k;if(w.push(F),A>=_&&(Array.from(b.data).filter(j=>j>=s).length>0||A>=f))break}let E=ye(w),{waveform:S}=await ue(a.sessions.model,{spectrogram:E});return{spectrogram:E,waveform:S}}},Gy=class extends y{main_input_name="spectrogram"};var ks=class extends y{},qy=class extends ks{},Wy=class extends ks{async _call(e){return new we(await super._call(e))}},Vy=class extends ks{async _call(e){return new q(await super._call(e))}},Hy=class extends ks{async _call(e){return new Te(await super._call(e))}};var vi=class extends y{},Xy=class extends vi{},Ky=class extends vi{};var ki=class extends y{},Yy=class extends ki{},Qy=class extends ki{};var uu=class extends y{},Jy=class extends uu{};var pu=class extends y{},Ei=class extends pu{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:c}=this.config,{last_hidden_state:p,durations:f}=await ue(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),_=f.div(o).mul_(a),m=l*i,w=_.data,x=Int32Array.from(w,U=>Math.ceil(U/m)),k=Math.max(...x),A=e.dims[0],E=new BigInt64Array(A*k);for(let U=0;US*T,1),E=ls[x.type];l[x.name]=new N(x.type,new E(A),k)}let _=ls[f],m=new N(f,new _(i*XM),[1,i,XM]),w=e[Symbol.asyncIterator]?.()??e[Symbol.iterator]?.();if(!w)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:m,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:w,text_hidden_size:r.hidden_size}}async function e3(t,e){let r=e.dims[2],s=Math.floor((JN+r-3)/2)+1,n=new N("int64",BigInt64Array.from({length:s},(p,f)=>BigInt(t.enc_past_seq_len+f)),[1,s]),o=t.enc_past_seq_len+s,a=Ze([1,o]),{audio_embeds:i,present_padding_cache:l,...c}=await ue(t.encoder_session,{input_features:e,attention_mask:a,position_ids:n,past_padding_cache:t.enc_padding_cache,...t.enc_kv_cache});t.enc_padding_cache.location==="gpu-buffer"&&t.enc_padding_cache.dispose(),t.enc_padding_cache=l;for(let p in c)if(p.startsWith("present.")){let f=p.replace("present","past_key_values"),_=t.enc_kv_cache[f];_?.location==="gpu-buffer"&&_.dispose(),t.enc_kv_cache[f]=c[p]}return t.enc_past_seq_len=o,i}async function t3(t,e){for(;t.audio_embed_total_tokens0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let p=0;p=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var xv=class extends Ar{constructor(e){super(),this._s=e}_call(e){let r=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>r)}},xu=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},Ci=class extends xu{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=wv.get(this);o&&await t3(o,o.audio_consumed+n);let{inputs_embeds:a}=await ue(this.sessions.embed_tokens,{input_ids:e});o&&r3(o,a,n);let i={inputs_embeds:a,...s};Ac(this,i,r);let l=this.sessions.decoder_model_merged,c=Ve(i,l.inputNames);return await ue(l,c)}async generate({input_features:e,stopping_criteria:r,...s}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let n=ZN(this,e);wv.set(this,n);let o=new Zs;o.push(new xv(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),wv.delete(this)}}};var An=class extends y{},S0=class extends An{},O0=class extends An{async _call(e){return new kt(await super._call(e))}},I0=class extends An{async _call(e){return new q(await super._call(e))}};var yu=class extends Re{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},Dr=class extends y{},C0=class extends Dr{},P0=class extends Dr{async _call(e){return new kt(await super._call(e))}},z0=class extends Dr{async _call(e){return new q(await super._call(e))}},L0=class extends Dr{async _call(e){return new yu(await super._call(e))}},N0=class extends Dr{async _call(e){return new ge(await super._call(e))}};var bu=class extends y{},$0=class extends bu{};var R0=class extends _o{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};var Pi=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},D0=class extends Pi{},vu=class extends Pi{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,R0)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(ee.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${bM(s)}|>`;r.push(e.lang_to_id[a]),r.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&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(ee.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,...o}){r=this._prepare_generation_config(r,o);let a=o.decoder_input_ids instanceof N?Ul(o.decoder_input_ids):o.decoder_input_ids??this._retrieve_init_tokens(r);if(r.return_timestamps&&(s??=new ds,s.push(new fc(r,a))),r.begin_suppress_tokens&&(s??=new ds,s.push(new Js(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.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.");r.task==="translate"&&ee.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}if(r.return_timestamps&&!o.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:a,kwargs:o});let i=await super.generate({inputs:e,generation_config:r,logits_processor:s,decoder_input_ids:a,...o});return r.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,r.alignment_heads,r.num_frames,.02,a.length)),i}async _generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:n,kwargs:o}){let a=r.no_timestamps_token_id+1,i=Array.isArray(r.eos_token_id)?r.eos_token_id[0]:r.eos_token_id,l=r.return_token_timestamps,c=e,p=c.dims[2],f=2,_=this.config.max_source_positions,m=f*_,w=0,x=[],k=[];for(;wz+Y)}if(F.length>0&&F.at(-1)===i&&F.pop(),F.length===0)break;let U=F.map(Y=>Y>=a),X=F.length>=2&&U[F.length-1]&&!U[F.length-2],K=[];for(let Y=0;Y0)if(X)J=E-w;else{let Y=K.at(-1);J=(F[Y-1]-a)*f,R=Y}else J=E-w;let C=Math.floor(w/f),ne=a+1500;for(let Y=0;Y=a&&(F[Y]=Math.min(F[Y]+C,ne));x.push(...F.slice(0,R)),j&&k.push(...j.slice(0,R)),w+=J}x.push(i);let A=[...n,...x];if(l){let E=new N("int64",A.map(BigInt),[1,A.length]),S=[...new Array(n.length).fill(0),...k,0],T=new N("float32",new Float32Array(S),[1,S.length]);return{sequences:E,token_timestamps:T}}return new N("int64",A.map(BigInt),[1,A.length])}_extract_token_timestamps(e,r,s=null,n=.02,o=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");s==null&&ee.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(ee.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let i=e.cross_attentions,l=Array.from({length:this.config.decoder_layers},(A,E)=>ye(i.map(S=>S[E]),2)),c=_t(r.map(([A,E])=>{if(A>=l.length)throw new Error(`Layer index ${A} is out of bounds for cross attentions (length ${l.length}).`);return s?l[A].slice(null,E,null,[0,s]):l[A].slice(null,E)})).transpose(1,0,2,3),[p,f]=$p(c,-2,0,!0),_=c.clone();for(let A=0;A<_.dims[0];++A){let E=_[A];for(let S=0;S0?_.slice(null,null,[o,_.dims[2]],null):_,w=[Fl(m,1)],x=e.sequences.dims,k=new N("float32",new Float32Array(x[0]*x[1]),x);for(let A=0;AS[U+1]-S[U]),O=wt([1],I).map(j=>!!j),b=[];for(let j=0;j0&&F.push(b.at(-1)),k[A].data.set(F)}return k}},F0=class extends vu{};var Fr=class extends y{},B0=class extends Fr{},U0=class extends Fr{async _call(e){return new we(await super._call(e))}},j0=class extends Fr{async _call(e){return new q(await super._call(e))}},G0=class extends Fr{async _call(e){return new ge(await super._call(e))}},q0=class extends Fr{async _call(e){return new Te(await super._call(e))}};var Br=class extends y{},W0=class extends Br{},V0=class extends Br{async _call(e){return new we(await super._call(e))}},H0=class extends Br{async _call(e){return new q(await super._call(e))}},X0=class extends Br{async _call(e){return new ge(await super._call(e))}},K0=class extends Br{async _call(e){return new Te(await super._call(e))}};var zi=class extends y{},Y0=class extends zi{},Q0=class extends zi{async _call(e){return new ku(await super._call(e))}},ku=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Li=class extends y{},J0=class extends Li{},Z0=class extends Li{};var s3=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"]]),n3=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["cohere_asr","CohereAsrModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),o3=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),a3=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),KM=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),YM=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),QM=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),JM=new Map([["bert","BertForSequenceClassification"],["eurobert","EuroBertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraForSequenceClassification"],["esm","EsmForSequenceClassification"],["convbert","ConvBertForSequenceClassification"],["camembert","CamembertForSequenceClassification"],["deberta","DebertaForSequenceClassification"],["deberta-v2","DebertaV2ForSequenceClassification"],["mpnet","MPNetForSequenceClassification"],["albert","AlbertForSequenceClassification"],["distilbert","DistilBertForSequenceClassification"],["roberta","RobertaForSequenceClassification"],["xlm","XLMForSequenceClassification"],["xlm-roberta","XLMRobertaForSequenceClassification"],["bart","BartForSequenceClassification"],["mbart","MBartForSequenceClassification"],["mobilebert","MobileBertForSequenceClassification"],["squeezebert","SqueezeBertForSequenceClassification"]]),ZM=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),eT=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),tT=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),i3=new Map([["multi_modality","MultiModalityCausalLM"]]),rT=new Map([["bert","BertForMaskedLM"],["eurobert","EuroBertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),sT=new Map([["bert","BertForQuestionAnswering"],["neobert","NeoBertForQuestionAnswering"],["roformer","RoFormerForQuestionAnswering"],["electra","ElectraForQuestionAnswering"],["convbert","ConvBertForQuestionAnswering"],["camembert","CamembertForQuestionAnswering"],["deberta","DebertaForQuestionAnswering"],["deberta-v2","DebertaV2ForQuestionAnswering"],["mpnet","MPNetForQuestionAnswering"],["albert","AlbertForQuestionAnswering"],["distilbert","DistilBertForQuestionAnswering"],["roberta","RobertaForQuestionAnswering"],["xlm","XLMForQuestionAnswering"],["xlm-roberta","XLMRobertaForQuestionAnswering"],["mobilebert","MobileBertForQuestionAnswering"],["squeezebert","SqueezeBertForQuestionAnswering"]]),nT=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),oT=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),aT=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),l3=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),iT=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),lT=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),cT=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Ni=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),uT=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),pT=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),fT=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),dT=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),_T=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),mT=new Map([["wavlm","WavLMForXVector"]]),hT=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),gT=new Map([["vitmatte","VitMatteForImageMatting"]]),c3=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),wT=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),xT=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),yT=new Map([["sapiens","SapiensForNormalEstimation"]]),bT=new Map([["vitpose","VitPoseForPoseEstimation"]]),vT=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),yv=[[s3,V.EncoderOnly],[n3,V.EncoderDecoder],[a3,V.DecoderOnlyWithoutHead],[o3,V.AutoEncoder],[JM,V.EncoderOnly],[ZM,V.EncoderOnly],[eT,V.Seq2Seq],[KM,V.Seq2Seq],[tT,V.DecoderOnly],[i3,V.MultiModality],[rT,V.EncoderOnly],[sT,V.EncoderOnly],[nT,V.Vision2Seq],[oT,V.ImageTextToText],[aT,V.AudioTextToText],[iT,V.EncoderOnly],[Ni,V.EncoderOnly],[pT,V.EncoderOnly],[uT,V.EncoderOnly],[gT,V.EncoderOnly],[c3,V.EncoderOnly],[wT,V.EncoderOnly],[xT,V.EncoderOnly],[yT,V.EncoderOnly],[bT,V.EncoderOnly],[lT,V.EncoderOnly],[cT,V.EncoderOnly],[fT,V.MaskGeneration],[dT,V.EncoderOnly],[_T,V.EncoderOnly],[YM,V.Seq2Seq],[QM,V.EncoderOnly],[mT,V.EncoderOnly],[hT,V.EncoderOnly],[vT,V.EncoderOnly]];for(let[t,e]of yv)for(let r of t.values()){tr.set(r,e);let s=Eu[r];sn.set(s,r),v_.set(r,s)}var u3=[["MusicgenForConditionalGeneration",Ba,V.Musicgen],["Phi3VForCausalLM",ri,V.Phi3V],["CLIPTextModelWithProjection",Io,V.EncoderOnly],["SiglipTextModel",gi,V.EncoderOnly],["JinaCLIPTextModel",ya,V.EncoderOnly],["ClapTextModelWithProjection",So,V.EncoderOnly],["ClapAudioModelWithProjection",Oo,V.EncoderOnly],["DacEncoderModel",Bo,V.EncoderOnly],["DacDecoderModel",Uo,V.EncoderOnly],["MimiEncoderModel",Sa,V.EncoderOnly],["MimiDecoderModel",Oa,V.EncoderOnly],["SnacEncoderModel",xi,V.EncoderOnly],["SnacDecoderModel",yi,V.EncoderOnly],["Gemma3nForConditionalGeneration",zr,V.ImageAudioTextToText],["Gemma4ForConditionalGeneration",un,V.ImageAudioTextToText],["SupertonicForConditionalGeneration",Ei,V.Supertonic],["ChatterboxModel",To,V.Chatterbox],["VoxtralRealtimeForConditionalGeneration",Ci,V.VoxtralRealtime]];for(let[t,e,r]of u3)tr.set(t,r),sn.set(e,t),v_.set(t,e);var kT=new Map([["modnet",Ni],["birefnet",Ni],["isnet",Ni],["ben",Ni]]);for(let[t,e]of kT.entries())e.set(t,"PreTrainedModel"),tr.set(t,V.EncoderOnly),v_.set(t,y);var ET=new Set(kT.keys());tr.set("PreTrainedModel",V.EncoderOnly);sn.set(y,"PreTrainedModel");var Ne={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:JM,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:ZM,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:YM,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:QM,MODEL_FOR_MASKED_LM_MAPPING_NAMES:rT,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:sT,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:iT,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Ni,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:uT,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:pT,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:lT,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:cT,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:fT,MODEL_FOR_CTC_MAPPING_NAMES:dT,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:_T,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:mT,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:hT,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:l3,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:gT,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:wT,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:xT,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:yT,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:bT,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:vT,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:oT,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:aT,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:eT,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:KM,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:tT,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:nT};qM(Ne);var Ce=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let r of this.MODEL_CLASS_MAPPINGS)if(r.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:p=null,use_external_data_format:f=null,session_options:_={}}={}){let m={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:p,use_external_data_format:f,session_options:_};if(m.config=await Rt.from_pretrained(e,m),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:w}=m.config;for(let x of this.MODEL_CLASS_MAPPINGS){let k=x.get(w);if(!k){for(let A of x.values())if(A[0]===w){k=A;break}if(!k)continue}return await Eu[k].from_pretrained(e,m)}if(this.BASE_IF_FAIL)return ET.has(w)||ee.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,m);throw Error(`Unsupported model type: ${w}`)}},_r=class extends Ce{static MODEL_CLASS_MAPPINGS=yv.map(e=>e[0]);static BASE_IF_FAIL=!0},$i=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},Au=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Mn=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},Mu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},Tu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},Su=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},Ou=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},Iu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},Cu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},Pu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},zu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Ri=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},Di=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},Fi=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},Lu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Nu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},bv=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},$u=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_CTC_MAPPING_NAMES]},Ru=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},vv=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},kv=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},Du=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},Ev=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},Fu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},Bu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},Av=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},Mv=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},Uu=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},Tv=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},Sv=class extends Ce{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function tt(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Je.read(e)))}async function Ur(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?Lf(r,e):r instanceof Float64Array?new Float32Array(r):r))}function ju(t,e){e&&(t=t.map(a=>a|0));let[r,s,n,o]=t;return{xmin:r,ymin:s,xmax:n,ymax:o}}var me=class extends We{constructor({task:e,model:r,tokenizer:s=null,processor:n=null}){super(),this.task=e,this.model=r,this.tokenizer=s,this.processor=n}async dispose(){await this.model.dispose()}};var Bi=class extends me{async _call(e,{top_k:r=1}={}){let s=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(s),{problem_type:o,id2label:a}=this.model.config,i=o==="multi_label_classification"?c=>c.sigmoid():c=>new N("float32",Pe(c.data),c.dims),l=[];for(let c of n.logits){let p=i(c),f=await Gt(p,r),_=f[0].tolist(),w=f[1].tolist().map((x,k)=>({label:a?a[x]:`LABEL_${x}`,score:_[k]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var Ui=class extends me{async _call(e,{ignore_labels:r=["O"],aggregation_strategy:s="none"}={}){if(s!=="none"&&s!=="simple")throw new Error(`Invalid aggregation_strategy: "${s}". Must be one of "none" or "simple".`);let n=Array.isArray(e),o=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(o)).logits,l=this.model.config.id2label,c=[];for(let p=0;p{let l=0,c=[];for(let p=a;pO==f),k=a[m].tolist(),A=i[m].tolist();for(let O=1;Ob==w[O])!==-1)&&(k[O]=-1/0,A[O]=-1/0);let E=Pe(k).map((O,b)=>[O,b]),S=Pe(A).map((O,b)=>[O,b]);E[0][0]=0,S[0][0]=0;let T=qE(E,S).filter(O=>O[0][1]<=O[1][1]).map(O=>[O[0][1],O[1][1],O[0][0]*O[1][0]]).sort((O,b)=>b[2]-O[2]),I=[];for(let O=0;Ok==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let _=a[c][f],m=await Gt(new N("float32",Pe(_.data),_.dims),r),w=m[0].tolist(),x=m[1].tolist();i.push(x.map((k,A)=>{let E=p.slice();return E[f]=k,{score:w[A],token:Number(k),token_str:this.tokenizer.decode([k]),sequence:this.tokenizer.decode(E,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var mr=class extends me{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,r={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(l=>s[this.task].prefix+l));let n=this.tokenizer,o={padding:!0,truncation:!0},a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,o,r):a=n(e,o);let i=await this.model.generate({...a,...this._default_generation_config,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}};var qi=class extends mr{_key="summary_text"};var Wi=class extends mr{_key="translation_text"};function AT(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Vi=class extends me{_default_generation_config={max_new_tokens:256};async _call(e,r={}){let{add_special_tokens:s,return_full_text:n,tools:o,documents:a,chat_template:i,tokenizer_encode_kwargs:l,...c}=r,p=!1,f=!1,_=s??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,m=l,w;if(typeof e=="string")w=e=[e];else if(Array.isArray(e)&&e.every(I=>typeof I=="string"))p=!0,w=e;else{if(AT(e))e=[e];else if(Array.isArray(e)&&e.every(AT))p=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");f=!0;let I={tokenize:!1,add_generation_prompt:!0,...Ve({tools:o,documents:a,chat_template:i},["tools","documents","chat_template"]),...m};w=e.map(O=>this.tokenizer.apply_chat_template(O,I)),_=!1,m=void 0}let x=f?!1:n??!0;this.tokenizer.padding_side="left";let k=this.tokenizer(w,{add_special_tokens:_,padding:!0,truncation:!0,...m}),A=await this.model.generate({...k,...this._default_generation_config,...c}),E=this.tokenizer.batch_decode(A,{skip_special_tokens:!0}),S;!x&&k.input_ids.dims.at(-1)>0&&(S=this.tokenizer.batch_decode(k.input_ids,{skip_special_tokens:!0}).map(I=>I.length));let T=Array.from({length:e.length},I=>[]);for(let I=0;I[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(ee.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(ee.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let p=[];for(let m of a){let w=this.tokenizer(c,{text_pair:m,padding:!0,truncation:!0}),x=await this.model(w);i?p.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):p.push(x.logits.data[this.entailment_id])}let _=(i?p.map(m=>Pe(m)[1]):Pe(p)).map((m,w)=>[m,w]).sort((m,w)=>w[0]-m[0]);l.push({sequence:c,labels:_.map(m=>r[m[1]]),scores:_.map(m=>m[0])})}return o?l:l[0]}};var Xi=class extends me{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await Ur(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),p=(await this.model(l)).logits[0],f=await Gt(new N("float32",Pe(p.data),p.dims),r),_=f[0].tolist(),w=f[1].tolist().map((x,k)=>({label:o?o[x]:`LABEL_${x}`,score:_[k]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var Ki=class extends me{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(p=>s.replace("{}",p)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await Ur(e,i),c=[];for(let p of l){let f=await this.processor(p),_=await this.model({...a,...f}),m=Pe(_.logits_per_audio.data);c.push([...m].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var Yi=class extends me{_default_generation_config={};async _call(e,r={}){switch(r={...this._default_generation_config,...r},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,r);case"moonshine":return this._call_moonshine(e,r);case"cohere_asr":return this._call_cohere_asr(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&ee.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&ee.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Ur(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).logits[0],_=[];for(let w of f)_.push(ze(w.data)[1]);let m=this.tokenizer.decode(_,{skip_special_tokens:!0}).trim();i.push({text:m})}return s?i[0]:i}async _call_whisper(e,r){let s=r.return_timestamps??!1,n=r.chunk_length_s??0,o=r.force_full_sequences??!1,a=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);let l=!Array.isArray(e),c=l?[e]:e,p=this.processor.feature_extractor.config,f=p.chunk_length/this.model.config.max_source_positions,_=p.hop_length,m=p.sampling_rate,w=await Ur(c,m),x=[];for(let k of w){let A=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let T=m*n,I=m*a,O=T-2*I,b=0;for(;;){let F=b+T,j=k.subarray(b,F),U=await this.processor(j),X=b===0,K=F>=k.length;if(A.push({stride:[j.length,X?0:I,K?0:I],input_features:U.input_features,is_last:K}),K)break;b+=O}}else A=[{stride:[k.length,0,0],input_features:(await this.processor(k)).input_features,is_last:!0}];for(let T of A){i.num_frames=Math.floor(T.stride[0]/_);let I=await this.model.generate({inputs:T.input_features,...i});if(s==="word"){let O=I.sequences.tolist()[0],b=I.token_timestamps.tolist()[0],F=this.tokenizer.timestamp_begin,j=Math.max(O.findIndex(U=>Number(U)>=F),0);T.tokens=O.slice(j),T.token_timestamps=b.slice(j).map(U=>Ns(U,2))}else T.tokens=I[0].tolist();T.stride=T.stride.map(O=>O/m)}let[E,S]=this.tokenizer._decode_asr(A,{time_precision:f,return_timestamps:s,force_full_sequences:o});x.push({text:E,...S})}return l?x[0]:x}async _call_moonshine(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Ur(n,o),i=[];for(let l of a){let c=await this.processor(l),p=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:p,...r,...c}),_=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:_})}return s?i[0]:i}async _call_cohere_asr(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor,a=o.config.sampling_rate,i=await Ur(n,a),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),p=[];for(let f of i){let _=o.split_audio(f),m=[];for(let x of _){let k=await this.processor(x),A=await this.model.generate({...k,decoder_input_ids:c,...r}),E=this.tokenizer.decode(A[0].tolist(),{skip_special_tokens:!0}).trim();m.push(E)}let w=this.processor.constructor.join_chunks(m,l);p.push({text:w})}return s?p[0]:p}};var Qi=class extends me{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,r){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await _e.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new N("float32",e,[e.length]);else if(!(e instanceof N))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,c=[];for(let p=0;p({generated_text:p.trim()}));a.push(c)}return s?a:a[0]}};var Zi=class extends me{async _call(e,{top_k:r=5}={}){let s=await tt(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),{id2label:a}=this.model.config,i=[];for(let l of o.logits){let c=await Gt(new N("float32",Pe(l.data),l.dims),r),p=c[0].tolist(),_=c[1].tolist().map((m,w)=>({label:a?a[m]:`LABEL_${m}`,score:p[w]}));i.push(_)}return Array.isArray(e)?i:i[0]}};var MT={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},As=class extends me{async _call(e,{threshold:r=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:o=null,target_sizes:a=null,subtask:i=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let c=await tt(e),p=c.map(E=>[E.height,E.width]),f=await this.processor(c),{inputNames:_,outputNames:m}=this.model.sessions.model;if(!_.includes("pixel_values")){if(_.length!==1)throw Error(`Expected a single input name, but got ${_.length} inputs: ${_}.`);let E=_[0];if(E in f)throw Error(`Input name ${E} already exists in the inputs.`);f[E]=f.pixel_values}let w=await this.model(f),x=null;if(i!==null)x=MT[i];else if(this.processor.image_processor){for(let[E,S]of Object.entries(MT))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=E;break}}let k=this.model.config.id2label,A=[];if(i)if(i==="panoptic"||i==="instance"){let E=x(w,r,s,n,o,a??p)[0],S=E.segmentation;for(let T of E.segments_info){let I=new Uint8ClampedArray(S.data.length);for(let b=0;bF<-1e-5||F>1+1e-5)&&O.sigmoid_();let b=await Je.fromTensor(O.mul_(255).to("uint8")).resize(I[1],I[0]);A.push({label:null,score:null,mask:b})}}return A}};var el=class extends As{async _call(e,r={}){let s=await tt(e),n=await super._call(e,r),o=s.map((a,i)=>{let l=a.clone();return l.putAlpha(n[i].mask),l});return Array.isArray(e)?o:o[0]}};var tl=class extends me{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await tt(e),a=r.map(_=>s.replace("{}",_)),i=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(o),c=await this.model({...i,pixel_values:l}),p=this.model.config.model_type==="siglip"?_=>_.sigmoid().data:_=>Pe(_.data),f=[];for(let _ of c.logits_per_image){let w=[...p(_)].map((x,k)=>({score:x,label:r[k]}));w.sort((x,k)=>k.score-x.score),f.push(w)}return n?f:f[0]}};var rl=class extends me{async _call(e,{threshold:r=.9,percentage:s=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let o=await tt(e),a=s?null:o.map(m=>[m.height,m.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),c=await this.model({pixel_values:i,pixel_mask:l}),p=this.processor.image_processor.post_process_object_detection(c,r,a),{id2label:f}=this.model.config,_=p.map(m=>m.boxes.map((w,x)=>({score:m.scores[x],label:f[m.classes[x]],box:ju(w,!s)})));return n?_:_[0]}};var sl=class extends me{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await tt(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=await this.processor(i),p=[];for(let f=0;f({score:A.scores[S],label:A.labels[S],box:ju(E,!o)}))}else{let A=this.processor.image_processor.post_process_object_detection(x,s,m,!0)[0];k=A.boxes.map((E,S)=>({score:A.scores[S],label:r[A.classes[S]],box:ju(E,!o)}))}k.sort((A,E)=>E.score-A.score),n!==null&&(k=k.slice(0,n)),p.push(k)}return a?p:p[0]}};var nl=class extends me{_default_generation_config={max_new_tokens:256};async _call(e,r,s={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await tt(e))[0],{pixel_values:o}=await this.processor(n),a=`${r}`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...s}),p=this.tokenizer.batch_decode(l)[0].match(/(.*?)<\/s_answer>/),f=null;return p&&p.length>=2&&(f=p[1].trim()),[{answer:f}]}};var ol=class extends me{async _call(e){let r=await tt(e),s=await this.processor(r),n=await this.model(s),o=[];for(let a of n.reconstruction){let i=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(Je.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var al=class extends me{async _call(e){let r=await tt(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a`onnx/${_}`);return i.filter(_=>!_.startsWith("onnx/")||f.some(m=>_.startsWith(m)))}}return i}async function d3(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:p=null,model_file_name:f=null,session_options:_={}}={}){t=eb[t]??t;let m=cl[t.split("_",1)[0]];if(!m)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(cl)}]`);e||(e=m.default.model,ee.info(`No model specified. Using default model: "${e}".`),!l&&m.default.dtype&&(l=m.default.dtype));let w=await Gr(t,e,{device:i,dtype:l}),x={};r&&(await Promise.all(w.map(async X=>Ot(e,X)))).forEach((X,K)=>{X.exists&&(x[w[K]]={loaded:0,total:X.size??0})});let k={progress_callback:r?new Cs(r,x):void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:p,model_file_name:f,session_options:_},A=w.includes("tokenizer.json"),E=w.includes("preprocessor_config.json"),S=m.model,T;if(Array.isArray(S)){let U=s??await Rt.from_pretrained(e,k),{model_type:X}=U,K=S.find(J=>J.supports(X));if(!K)throw Error(`Unsupported model type "${X}" for task "${t}". None of the candidate model classes support this type.`);T=K.from_pretrained(e,{...k,config:U})}else T=S.from_pretrained(e,k);let[I,O,b]=await Promise.all([A?se.from_pretrained(e,k):null,E?lc.from_pretrained(e,k):null,T]),F={task:t,model:b};I&&(F.tokenizer=I),O&&(F.processor=O),lr(r,{status:"ready",task:t,model:e});let j=m.pipeline;return new j(F)}var _3=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,rb=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},TT=ie.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),sb=class extends rb{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,skip_special_tokens:o=!0,decode_kwargs:a={},...i}={}){super(),this.tokenizer=e,this.skip_prompt=r,this.callback_function=s??TT,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:o,...a,...i},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let r=this.next_tokens_are_prompt;if(r&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let s=e[0];if(this.token_callback_function?.(s),s.length===1&&this.special_ids.has(s[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let l=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(l,!1),this.token_cache=[],this.print_len=0}let a=this.tokenizer.decode(s,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=wt(this.token_cache,s);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),o;r||n.endsWith(` `)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&_3(n.charCodeAt(n.length-1))?(o=n.slice(this.print_len),this.print_len+=o.length):(o=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=o.length),this.on_finalized_text(o,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,r){e.length>0&&this.callback_function?.(e),r&&this.callback_function===TT&&ie.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}},Ov=class extends sb{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:c=!0,decode_kwargs:p={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,callback_function:s,token_callback_function:n,decode_kwargs:p}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var ul=class{constructor(e,r){this.image=e,this.timestamp=r}},Gu=class{constructor(e,r){e.length>0&&e[0]instanceof Je&&(e=e.map((s,n)=>new ul(s,(n+1)/(e.length+1)*r))),this.frames=e,this.duration=r}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 ST(t,{num_frames:e=null,fps:r=null}={}){if(!ie.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(e==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let s=[],n=document.createElement("video");if(n.crossOrigin="anonymous",n.muted=!0,typeof t=="string")n.src=t;else if(t instanceof Blob)n.src=URL.createObjectURL(t);else if(t instanceof HTMLVideoElement)n.src=t.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(f=>n.onloadedmetadata=f),n.seekable.start(0)===n.seekable.end(0)){let _=await(await _e.fetch(n.src)).blob();n.src=URL.createObjectURL(_),await new Promise(m=>n.onloadedmetadata=m)}let o=n.duration,a,i;e!=null?(a=e,i=e===1?0:o/(e-1)):(i=1/r,a=Math.floor(o/i));let l=[];for(let f=0;f{n.onseeked=x}),p.drawImage(n,0,0,c.width,c.height);let _=p.getImageData(0,0,c.width,c.height),m=new Je(_.data,c.width,c.height,4),w=new ul(m,f);s.push(w)}return n.remove(),new Gu(s,o)}async function nb(t,e,r={}){let s=await Jt(r?.cache_dir);if(!s)return{allCached:!1,files:e.map(a=>({file:a,cached:!1}))};let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=Jr(t,o,r,s),l=await Zr(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function OT(t,e,r={}){let s=await Jt(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=Jr(t,e,r,s);return!!await Zr(s,n,o)}async function IT(t,e={}){if(!t)throw new Error("modelId is required");if(!await OT(t,"config.json",e))return!1;let r=await jr(t,e);return(await nb(t,r,e)).allCached}async function CT(t,e={}){if(!t)throw new Error("modelId is required");let r=await jr(t,e);return await nb(t,r,e)}async function PT(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await OT(e,"config.json",r))return!1;let s=await Gr(t,e,r);return(await nb(e,s,r)).allCached}async function zT(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Gr(t,e,r);return await nb(e,s,r)}async function LT(t,e,r={}){let s=await Jt(r?.cache_dir);if(!s)return{filesDeleted:0,filesCached:0,files:e.map(o=>({file:o,deleted:!1,wasCached:!1}))};if(!s.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=Jr(t,o,r,s),c=!!await Zr(s,a,i),p=!1;if(c){let f=await s.delete(i),_=!f&&i!==a?await s.delete(a):!1;p=f||_}return{file:o,deleted:p,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function NT(t,e={}){if(!t)throw new Error("modelId is required");let r=await jr(t,e);return await LT(t,r,e)}async function $T(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Gr(t,e,r);return await LT(e,s,r)}var m3=Object.keys(is);async function RT(t,{config:e=null,model_file_name:r=null,revision:s="main",cache_dir:n=null,local_files_only:o=!1}={}){e=await kc(t,{config:e,cache_dir:n,local_files_only:o,revision:s});let a="onnx",i=mo(e),{sessions:l}=vc(i,e,{model_file_name:r}),c=Object.values(l),p={revision:s,cache_dir:n,local_files_only:o};return(await Promise.all(m3.map(async _=>{let m=is[_]??"",w=await Promise.all(c.map(async x=>{let k=`${a}/${x}${m}.onnx`;return(await Ot(t,k,p)).exists}));return{dtype:_,available:w.every(Boolean)}}))).filter(_=>_.available).map(_=>_.dtype)}var ob=class{static async get_files(e,r={}){return jr(e,r)}static async get_pipeline_files(e,r,s={}){return Gr(e,r,s)}static async get_model_files(e,r={}){return ho(e,r)}static async get_tokenizer_files(e){return Vn(e)}static async get_processor_files(e){return tb(e)}static async get_available_dtypes(e,r={}){return RT(e,r)}static async is_cached(e,r={}){return IT(e,r)}static async is_cached_files(e,r={}){return CT(e,r)}static async is_pipeline_cached(e,r,s={}){return PT(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return zT(e,r,s)}static async get_file_metadata(e,r,s={}){return Ot(e,r,s)}static async clear_cache(e,r={}){return NT(e,r)}static async clear_pipeline_cache(e,r,s={}){return $T(e,r,s)}};0&&(module.exports={ASTFeatureExtractor,ASTForAudioClassification,ASTModel,ASTPreTrainedModel,AfmoeForCausalLM,AfmoeModel,AfmoePreTrainedModel,AlbertForMaskedLM,AlbertForQuestionAnswering,AlbertForSequenceClassification,AlbertModel,AlbertPreTrainedModel,AlbertTokenizer,ApertusForCausalLM,ApertusModel,ApertusPreTrainedModel,ArceeForCausalLM,ArceeModel,ArceePreTrainedModel,AudioClassificationPipeline,AutoConfig,AutoFeatureExtractor,AutoImageProcessor,AutoModel,AutoModelForAudioClassification,AutoModelForAudioFrameClassification,AutoModelForAudioTextToText,AutoModelForCTC,AutoModelForCausalLM,AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification,AutoModelForImageFeatureExtraction,AutoModelForImageMatting,AutoModelForImageSegmentation,AutoModelForImageTextToText,AutoModelForImageToImage,AutoModelForMaskGeneration,AutoModelForMaskedLM,AutoModelForNormalEstimation,AutoModelForObjectDetection,AutoModelForPoseEstimation,AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM,AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram,AutoModelForTextToWaveform,AutoModelForTokenClassification,AutoModelForUniversalSegmentation,AutoModelForVision2Seq,AutoModelForXVector,AutoModelForZeroShotObjectDetection,AutoProcessor,AutoTokenizer,AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline,BartForConditionalGeneration,BartForSequenceClassification,BartModel,BartPretrainedModel,BartTokenizer,BaseStreamer,BeitFeatureExtractor,BeitForImageClassification,BeitModel,BeitPreTrainedModel,BertForMaskedLM,BertForQuestionAnswering,BertForSequenceClassification,BertForTokenClassification,BertModel,BertPreTrainedModel,BertTokenizer,BitImageProcessor,BlenderbotForConditionalGeneration,BlenderbotModel,BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel,BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer,BlenderbotTokenizer,BloomForCausalLM,BloomModel,BloomPreTrainedModel,BloomTokenizer,CHMv2ForDepthEstimation,CHMv2ImageProcessor,CHMv2PreTrainedModel,CLIPFeatureExtractor,CLIPImageProcessor,CLIPModel,CLIPPreTrainedModel,CLIPSegForImageSegmentation,CLIPSegModel,CLIPSegPreTrainedModel,CLIPTextModel,CLIPTextModelWithProjection,CLIPTokenizer,CLIPVisionModel,CLIPVisionModelWithProjection,CamembertForMaskedLM,CamembertForQuestionAnswering,CamembertForSequenceClassification,CamembertForTokenClassification,CamembertModel,CamembertPreTrainedModel,CamembertTokenizer,ChatterboxFeatureExtractor,ChatterboxModel,ChatterboxPreTrainedModel,ChatterboxProcessor,ChineseCLIPFeatureExtractor,ChineseCLIPModel,ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection,ClapFeatureExtractor,ClapModel,ClapPreTrainedModel,ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM,CodeGenModel,CodeGenPreTrainedModel,CodeGenTokenizer,CodeLlamaTokenizer,Cohere2ForCausalLM,Cohere2Model,Cohere2PreTrainedModel,CohereAsrFeatureExtractor,CohereAsrForConditionalGeneration,CohereAsrModel,CohereAsrPreTrainedModel,CohereAsrProcessor,CohereAsrTokenizer,CohereForCausalLM,CohereModel,CoherePreTrainedModel,CohereTokenizer,ConvBertForMaskedLM,ConvBertForQuestionAnswering,ConvBertForSequenceClassification,ConvBertForTokenClassification,ConvBertModel,ConvBertPreTrainedModel,ConvBertTokenizer,ConvNextFeatureExtractor,ConvNextForImageClassification,ConvNextImageProcessor,ConvNextModel,ConvNextPreTrainedModel,ConvNextV2ForImageClassification,ConvNextV2Model,ConvNextV2PreTrainedModel,DFineForObjectDetection,DFineModel,DFinePreTrainedModel,DINOv3ConvNextModel,DINOv3ConvNextPreTrainedModel,DINOv3ViTImageProcessor,DINOv3ViTModel,DINOv3ViTPreTrainedModel,DPTFeatureExtractor,DPTForDepthEstimation,DPTImageProcessor,DPTModel,DPTPreTrainedModel,DacDecoderModel,DacDecoderOutput,DacEncoderModel,DacEncoderOutput,DacFeatureExtractor,DacModel,DacPreTrainedModel,DebertaForMaskedLM,DebertaForQuestionAnswering,DebertaForSequenceClassification,DebertaForTokenClassification,DebertaModel,DebertaPreTrainedModel,DebertaTokenizer,DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification,DebertaV2Model,DebertaV2PreTrainedModel,DebertaV2Tokenizer,DecisionTransformerModel,DecisionTransformerPreTrainedModel,DeepseekV3ForCausalLM,DeepseekV3Model,DeepseekV3PreTrainedModel,DeiTFeatureExtractor,DeiTForImageClassification,DeiTImageProcessor,DeiTModel,DeiTPreTrainedModel,DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel,DepthEstimationPipeline,DepthProForDepthEstimation,DepthProPreTrainedModel,DetrFeatureExtractor,DetrForObjectDetection,DetrForSegmentation,DetrImageProcessor,DetrModel,DetrObjectDetectionOutput,DetrPreTrainedModel,DetrSegmentationOutput,Dinov2ForImageClassification,Dinov2Model,Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM,DistilBertForQuestionAnswering,DistilBertForSequenceClassification,DistilBertForTokenClassification,DistilBertModel,DistilBertPreTrainedModel,DistilBertTokenizer,DocumentQuestionAnsweringPipeline,DonutFeatureExtractor,DonutImageProcessor,DonutSwinModel,DonutSwinPreTrainedModel,DynamicCache,EdgeTamModel,EfficientNetForImageClassification,EfficientNetImageProcessor,EfficientNetModel,EfficientNetPreTrainedModel,ElectraForMaskedLM,ElectraForQuestionAnswering,ElectraForSequenceClassification,ElectraForTokenClassification,ElectraModel,ElectraPreTrainedModel,ElectraTokenizer,EncodecFeatureExtractor,EosTokenCriteria,Ernie4_5ForCausalLM,Ernie4_5Model,Ernie4_5PretrainedModel,EsmForMaskedLM,EsmForSequenceClassification,EsmForTokenClassification,EsmModel,EsmPreTrainedModel,EsmTokenizer,EuroBertForMaskedLM,EuroBertForSequenceClassification,EuroBertForTokenClassification,EuroBertModel,EuroBertPreTrainedModel,ExaoneForCausalLM,ExaoneModel,ExaonePreTrainedModel,FalconForCausalLM,FalconH1ForCausalLM,FalconH1Model,FalconH1PreTrainedModel,FalconModel,FalconPreTrainedModel,FalconTokenizer,FastViTForImageClassification,FastViTModel,FastViTPreTrainedModel,FeatureExtractionPipeline,FeatureExtractor,FillMaskPipeline,Florence2ForConditionalGeneration,Florence2PreTrainedModel,Florence2Processor,ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor,GLPNForDepthEstimation,GLPNModel,GLPNPreTrainedModel,GPT2LMHeadModel,GPT2Model,GPT2PreTrainedModel,GPT2Tokenizer,GPTBigCodeForCausalLM,GPTBigCodeModel,GPTBigCodePreTrainedModel,GPTJForCausalLM,GPTJModel,GPTJPreTrainedModel,GPTNeoForCausalLM,GPTNeoModel,GPTNeoPreTrainedModel,GPTNeoXForCausalLM,GPTNeoXModel,GPTNeoXPreTrainedModel,GPTNeoXTokenizer,Gemma2ForCausalLM,Gemma2Model,Gemma2PreTrainedModel,Gemma3ForCausalLM,Gemma3ForConditionalGeneration,Gemma3ImageProcessor,Gemma3Model,Gemma3PreTrainedModel,Gemma3Processor,Gemma3nAudioFeatureExtractor,Gemma3nForCausalLM,Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel,Gemma3nProcessor,Gemma4AudioFeatureExtractor,Gemma4ForCausalLM,Gemma4ForConditionalGeneration,Gemma4ImageProcessor,Gemma4Processor,GemmaForCausalLM,GemmaModel,GemmaPreTrainedModel,GemmaTokenizer,Glm46VImageProcessor,Glm46VProcessor,GlmForCausalLM,GlmModel,GlmMoeDsaForCausalLM,GlmMoeDsaModel,GlmMoeDsaPreTrainedModel,GlmOcrForConditionalGeneration,GlmPreTrainedModel,GptOssForCausalLM,GptOssModel,GptOssPreTrainedModel,GraniteForCausalLM,GraniteModel,GraniteMoeHybridForCausalLM,GraniteMoeHybridModel,GraniteMoeHybridPreTrainedModel,GranitePreTrainedModel,GraniteSpeechFeatureExtractor,GraniteSpeechForConditionalGeneration,GraniteSpeechProcessor,GroundingDinoForObjectDetection,GroundingDinoImageProcessor,GroundingDinoPreTrainedModel,GroundingDinoProcessor,GroupViTModel,GroupViTPreTrainedModel,HeliumForCausalLM,HeliumModel,HeliumPreTrainedModel,HerbertTokenizer,HieraForImageClassification,HieraModel,HieraPreTrainedModel,HubertForCTC,HubertForSequenceClassification,HubertModel,HubertPreTrainedModel,HunYuanDenseV1ForCausalLM,HunYuanDenseV1Model,HunYuanDenseV1PreTrainedModel,IJepaForImageClassification,IJepaModel,IJepaPreTrainedModel,Idefics3ForConditionalGeneration,Idefics3ImageProcessor,Idefics3Processor,ImageClassificationPipeline,ImageFeatureExtractionPipeline,ImageFeatureExtractor,ImageProcessor,ImageSegmentationPipeline,ImageToImagePipeline,ImageToTextPipeline,InterruptableStoppingCriteria,JAISLMHeadModel,JAISModel,JAISPreTrainedModel,JinaCLIPImageProcessor,JinaCLIPModel,JinaCLIPPreTrainedModel,JinaCLIPProcessor,JinaCLIPTextModel,JinaCLIPVisionModel,Lfm2ForCausalLM,Lfm2Model,Lfm2MoeForCausalLM,Lfm2MoeModel,Lfm2MoePreTrainedModel,Lfm2PreTrainedModel,Lfm2VlForConditionalGeneration,Lfm2VlImageProcessor,Lfm2VlProcessor,LightOnOcrForConditionalGeneration,LiteWhisperForConditionalGeneration,Llama4ForCausalLM,Llama4PreTrainedModel,LlamaForCausalLM,LlamaModel,LlamaPreTrainedModel,LlamaTokenizer,LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor,LlavaPreTrainedModel,LlavaProcessor,LlavaQwen2ForCausalLM,LogLevel,LogitsProcessor,LogitsProcessorList,LogitsWarper,LongT5ForConditionalGeneration,LongT5Model,LongT5PreTrainedModel,M2M100ForConditionalGeneration,M2M100Model,M2M100PreTrainedModel,M2M100Tokenizer,MBart50Tokenizer,MBartForCausalLM,MBartForConditionalGeneration,MBartForSequenceClassification,MBartModel,MBartPreTrainedModel,MBartTokenizer,MPNetForMaskedLM,MPNetForQuestionAnswering,MPNetForSequenceClassification,MPNetForTokenClassification,MPNetModel,MPNetPreTrainedModel,MPNetTokenizer,MT5ForConditionalGeneration,MT5Model,MT5PreTrainedModel,MarianMTModel,MarianModel,MarianPreTrainedModel,MarianTokenizer,Mask2FormerImageProcessor,MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation,MaskFormerImageProcessor,MaskFormerModel,MaskFormerPreTrainedModel,MaxLengthCriteria,Metric3DForDepthEstimation,Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition,MgpstrModelOutput,MgpstrPreTrainedModel,MgpstrProcessor,MgpstrTokenizer,MimiDecoderModel,MimiDecoderOutput,MimiEncoderModel,MimiEncoderOutput,MimiModel,MimiPreTrainedModel,MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor,Mistral4ForCausalLM,Mistral4Model,Mistral4PreTrainedModel,MistralForCausalLM,MistralModel,MistralPreTrainedModel,MobileBertForMaskedLM,MobileBertForQuestionAnswering,MobileBertForSequenceClassification,MobileBertModel,MobileBertPreTrainedModel,MobileBertTokenizer,MobileLLMForCausalLM,MobileLLMModel,MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor,MobileNetV1Model,MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor,MobileNetV2Model,MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor,MobileNetV3Model,MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor,MobileNetV4Model,MobileNetV4PreTrainedModel,MobileViTFeatureExtractor,MobileViTForImageClassification,MobileViTImageProcessor,MobileViTModel,MobileViTPreTrainedModel,MobileViTV2ForImageClassification,MobileViTV2Model,MobileViTV2PreTrainedModel,ModelRegistry,ModernBertDecoderForCausalLM,ModernBertDecoderModel,ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM,ModernBertForSequenceClassification,ModernBertForTokenClassification,ModernBertModel,ModernBertPreTrainedModel,Moondream1ForConditionalGeneration,MoonshineFeatureExtractor,MoonshineForConditionalGeneration,MoonshineModel,MoonshinePreTrainedModel,MoonshineProcessor,MptForCausalLM,MptModel,MptPreTrainedModel,MultiModalityCausalLM,MultiModalityPreTrainedModel,MusicgenForCausalLM,MusicgenForConditionalGeneration,MusicgenModel,MusicgenPreTrainedModel,NanoChatForCausalLM,NanoChatModel,NanoChatPreTrainedModel,NemotronHForCausalLM,NemotronHModel,NemotronHPreTrainedModel,NeoBertForMaskedLM,NeoBertForQuestionAnswering,NeoBertForSequenceClassification,NeoBertForTokenClassification,NeoBertModel,NeoBertPreTrainedModel,NllbTokenizer,NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor,NomicBertModel,NomicBertPreTrainedModel,NougatImageProcessor,NougatTokenizer,OPTForCausalLM,OPTModel,OPTPreTrainedModel,ObjectDetectionPipeline,Olmo2ForCausalLM,Olmo2Model,Olmo2PreTrainedModel,Olmo3ForCausalLM,Olmo3Model,Olmo3PreTrainedModel,OlmoForCausalLM,OlmoHybridForCausalLM,OlmoHybridModel,OlmoHybridPreTrainedModel,OlmoModel,OlmoPreTrainedModel,OpenAIPrivacyFilterForTokenClassification,OpenAIPrivacyFilterModel,OpenAIPrivacyFilterPreTrainedModel,OpenELMForCausalLM,OpenELMModel,OpenELMPreTrainedModel,OwlViTFeatureExtractor,OwlViTForObjectDetection,OwlViTImageProcessor,OwlViTModel,OwlViTPreTrainedModel,OwlViTProcessor,Owlv2ForObjectDetection,Owlv2ImageProcessor,Owlv2Model,Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration,PaliGemmaProcessor,ParakeetFeatureExtractor,ParakeetForCTC,ParakeetPreTrainedModel,PatchTSMixerForPrediction,PatchTSMixerModel,PatchTSMixerPreTrainedModel,PatchTSTForPrediction,PatchTSTModel,PatchTSTPreTrainedModel,Phi3ForCausalLM,Phi3Model,Phi3PreTrainedModel,Phi3VForCausalLM,Phi3VImageProcessor,Phi3VPreTrainedModel,Phi3VProcessor,PhiForCausalLM,PhiModel,PhiPreTrainedModel,PixtralImageProcessor,PixtralProcessor,PreTrainedModel,PreTrainedTokenizer,PretrainedConfig,Processor,PvtForImageClassification,PvtImageProcessor,PvtModel,PvtPreTrainedModel,PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification,PyAnnoteModel,PyAnnotePreTrainedModel,PyAnnoteProcessor,QuestionAnsweringPipeline,Qwen2ForCausalLM,Qwen2Model,Qwen2MoeForCausalLM,Qwen2MoeModel,Qwen2MoePreTrainedModel,Qwen2PreTrainedModel,Qwen2Tokenizer,Qwen2VLForCausalLM,Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor,Qwen2VLPreTrainedModel,Qwen2VLProcessor,Qwen2_5_VLForCausalLM,Qwen2_5_VLForConditionalGeneration,Qwen2_5_VLProcessor,Qwen3ForCausalLM,Qwen3Model,Qwen3MoeForCausalLM,Qwen3MoeModel,Qwen3MoePreTrainedModel,Qwen3NextForCausalLM,Qwen3NextModel,Qwen3NextPreTrainedModel,Qwen3PreTrainedModel,Qwen3VLForCausalLM,Qwen3VLForConditionalGeneration,Qwen3VLMoeForCausalLM,Qwen3VLMoeForConditionalGeneration,Qwen3VLProcessor,Qwen3_5ForCausalLM,Qwen3_5ForConditionalGeneration,Qwen3_5MoeForCausalLM,Qwen3_5MoeForConditionalGeneration,RFDetrForObjectDetection,RFDetrModel,RFDetrObjectDetectionOutput,RFDetrPreTrainedModel,RTDetrForObjectDetection,RTDetrImageProcessor,RTDetrModel,RTDetrObjectDetectionOutput,RTDetrPreTrainedModel,RTDetrV2ForObjectDetection,RTDetrV2Model,RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel,RawAudio,RawImage,RawVideo,RawVideoFrame,RepetitionPenaltyLogitsProcessor,ResNetForImageClassification,ResNetModel,ResNetPreTrainedModel,RoFormerForMaskedLM,RoFormerForQuestionAnswering,RoFormerForSequenceClassification,RoFormerForTokenClassification,RoFormerModel,RoFormerPreTrainedModel,RoFormerTokenizer,RobertaForMaskedLM,RobertaForQuestionAnswering,RobertaForSequenceClassification,RobertaForTokenClassification,RobertaModel,RobertaPreTrainedModel,RobertaTokenizer,Sam2ImageProcessor,Sam2ImageSegmentationOutput,Sam2Model,Sam2PreTrainedModel,Sam2Processor,Sam2VideoProcessor,Sam3ImageProcessor,Sam3TrackerModel,SamImageProcessor,SamImageSegmentationOutput,SamModel,SamPreTrainedModel,SamProcessor,SapiensFeatureExtractor,SapiensForDepthEstimation,SapiensForNormalEstimation,SapiensForSemanticSegmentation,SapiensImageProcessor,SapiensPreTrainedModel,SeamlessM4TFeatureExtractor,SegformerFeatureExtractor,SegformerForImageClassification,SegformerForSemanticSegmentation,SegformerImageProcessor,SegformerModel,SegformerPreTrainedModel,SiglipImageProcessor,SiglipModel,SiglipPreTrainedModel,SiglipTextModel,SiglipTokenizer,SiglipVisionModel,SmolLM3ForCausalLM,SmolLM3Model,SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration,SmolVLMImageProcessor,SmolVLMProcessor,SnacDecoderModel,SnacEncoderModel,SnacFeatureExtractor,SnacModel,SnacPreTrainedModel,SolarOpenForCausalLM,SolarOpenModel,SolarOpenPreTrainedModel,SpeechT5FeatureExtractor,SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech,SpeechT5HifiGan,SpeechT5Model,SpeechT5PreTrainedModel,SpeechT5Processor,SpeechT5Tokenizer,SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification,SqueezeBertModel,SqueezeBertPreTrainedModel,SqueezeBertTokenizer,StableLmForCausalLM,StableLmModel,StableLmPreTrainedModel,Starcoder2ForCausalLM,Starcoder2Model,Starcoder2PreTrainedModel,StoppingCriteria,StoppingCriteriaList,StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel,SummarizationPipeline,SupertonicForConditionalGeneration,SupertonicPreTrainedModel,SuppressTokensAtBeginLogitsProcessor,SuppressTokensLogitsProcessor,Swin2SRForImageSuperResolution,Swin2SRImageProcessor,Swin2SRModel,Swin2SRPreTrainedModel,SwinForImageClassification,SwinForSemanticSegmentation,SwinModel,SwinPreTrainedModel,T5ForConditionalGeneration,T5Model,T5PreTrainedModel,T5Tokenizer,TableTransformerForObjectDetection,TableTransformerModel,TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel,TemperatureLogitsWarper,Tensor,Text2TextGenerationPipeline,TextClassificationPipeline,TextGenerationPipeline,TextStreamer,TextToAudioPipeline,TokenClassificationPipeline,TokenizersBackend,TopKLogitsWarper,TopPLogitsWarper,TrOCRForCausalLM,TrOCRPreTrainedModel,TranslationPipeline,UltravoxModel,UltravoxPreTrainedModel,UltravoxProcessor,UniSpeechForCTC,UniSpeechForSequenceClassification,UniSpeechModel,UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC,UniSpeechSatForSequenceClassification,UniSpeechSatModel,UniSpeechSatPreTrainedModel,VLChatProcessor,VLMImageProcessor,VaultGemmaForCausalLM,VaultGemmaModel,VaultGemmaPreTrainedModel,ViTFeatureExtractor,ViTForImageClassification,ViTImageProcessor,ViTMAEModel,ViTMAEPreTrainedModel,ViTMSNForImageClassification,ViTMSNModel,ViTMSNPreTrainedModel,ViTModel,ViTPreTrainedModel,VisionEncoderDecoderModel,VitMatteForImageMatting,VitMatteImageProcessor,VitMattePreTrainedModel,VitPoseForPoseEstimation,VitPoseImageProcessor,VitPosePreTrainedModel,VitsModel,VitsModelOutput,VitsPreTrainedModel,VitsTokenizer,VoxtralForConditionalGeneration,VoxtralProcessor,VoxtralRealtimeFeatureExtractor,VoxtralRealtimeForConditionalGeneration,VoxtralRealtimePreTrainedModel,VoxtralRealtimeProcessor,Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification,Wav2Vec2Model,Wav2Vec2PreTrainedModel,Wav2Vec2Processor,Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification,WavLMForCTC,WavLMForSequenceClassification,WavLMForXVector,WavLMModel,WavLMPreTrainedModel,WeSpeakerFeatureExtractor,WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor,WhisperForConditionalGeneration,WhisperModel,WhisperPreTrainedModel,WhisperProcessor,WhisperTextStreamer,WhisperTimeStampLogitsProcessor,WhisperTokenizer,XLMForQuestionAnswering,XLMForSequenceClassification,XLMForTokenClassification,XLMModel,XLMPreTrainedModel,XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification,XLMRobertaModel,XLMRobertaPreTrainedModel,XLMRobertaTokenizer,XLMTokenizer,XLMWithLMHeadModel,XVectorOutput,YolosFeatureExtractor,YolosForObjectDetection,YolosImageProcessor,YolosModel,YolosObjectDetectionOutput,YolosPreTrainedModel,YoutuForCausalLM,YoutuModel,YoutuPreTrainedModel,ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline,cat,cos_sim,dot,env,full,full_like,interpolate,interpolate_4d,layer_norm,load_audio,load_image,load_video,log_softmax,matmul,mean,mean_pooling,ones,ones_like,permute,pipeline,quantize_embeddings,rand,randn,random,read_audio,rfft,slice,softmax,stack,std_mean,topk,zeros,zeros_like});