@dvai-bridge/core 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +51 -0
- package/README.md +199 -0
- package/bin/dvai-bridge.js +72 -0
- package/dist/dvai-transformers.worker.js +48 -0
- package/dist/dvai-webllm.worker.js +89 -0
- package/dist/index.cjs +69 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1030 -0
- package/dist/index.d.ts +1030 -0
- package/dist/index.js +69 -0
- package/dist/index.js.map +1 -0
- package/package.json +75 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
var qp=Object.defineProperty;var Wp=e=>{throw TypeError(e)};var _F=(e,t,r)=>t in e?qp(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var Dr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Hp=(e,t)=>{for(var r in t)qp(e,r,{get:t[r],enumerable:true});};var k=(e,t,r)=>_F(e,typeof t!="symbol"?t+"":t,r),Qp=(e,t,r)=>t.has(e)||Wp("Cannot "+r);var dt=(e,t,r)=>(Qp(e,t,"read from private field"),r?r.call(e):t.get(e)),xa=(e,t,r)=>t.has(e)?Wp("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ka=(e,t,r,s)=>(Qp(e,t,"write to private field"),t.set(e,r),r);var da={};Hp(da,{ASTFeatureExtractor:()=>lv,ASTForAudioClassification:()=>T0,ASTModel:()=>k0,ASTPreTrainedModel:()=>Uo,AfmoeForCausalLM:()=>b0,AfmoeModel:()=>v0,AfmoePreTrainedModel:()=>$o,AlbertForMaskedLM:()=>g0,AlbertForQuestionAnswering:()=>m0,AlbertForSequenceClassification:()=>p0,AlbertModel:()=>_0,AlbertPreTrainedModel:()=>Ws,AlbertTokenizer:()=>cy,ApertusForCausalLM:()=>y0,ApertusModel:()=>w0,ApertusPreTrainedModel:()=>Go,ArceeForCausalLM:()=>x0,ArceeModel:()=>M0,ArceePreTrainedModel:()=>Vo,AudioClassificationPipeline:()=>VA,AutoConfig:()=>Gs,AutoFeatureExtractor:()=>St,AutoImageProcessor:()=>ut,AutoModel:()=>Os,AutoModelForAudioClassification:()=>SA,AutoModelForAudioFrameClassification:()=>Nz,AutoModelForAudioTextToText:()=>Gz,AutoModelForCTC:()=>CA,AutoModelForCausalLM:()=>bA,AutoModelForDepthEstimation:()=>LA,AutoModelForDocumentQuestionAnswering:()=>PA,AutoModelForImageClassification:()=>TA,AutoModelForImageFeatureExtraction:()=>IA,AutoModelForImageMatting:()=>zz,AutoModelForImageSegmentation:()=>fd,AutoModelForImageTextToText:()=>Rz,AutoModelForImageToImage:()=>FA,AutoModelForMaskGeneration:()=>Iz,AutoModelForMaskedLM:()=>MA,AutoModelForNormalEstimation:()=>Dz,AutoModelForObjectDetection:()=>EA,AutoModelForPoseEstimation:()=>Bz,AutoModelForQuestionAnswering:()=>xA,AutoModelForSemanticSegmentation:()=>_d,AutoModelForSeq2SeqLM:()=>uo,AutoModelForSequenceClassification:()=>hd,AutoModelForSpeechSeq2Seq:()=>wA,AutoModelForTextToSpectrogram:()=>yA,AutoModelForTextToWaveform:()=>vA,AutoModelForTokenClassification:()=>gA,AutoModelForUniversalSegmentation:()=>pd,AutoModelForVision2Seq:()=>kA,AutoModelForXVector:()=>Oz,AutoModelForZeroShotObjectDetection:()=>AA,AutoProcessor:()=>Ub,AutoTokenizer:()=>xe,AutomaticSpeechRecognitionPipeline:()=>jA,BackgroundRemovalPipeline:()=>QA,BartForConditionalGeneration:()=>A0,BartForSequenceClassification:()=>C0,BartModel:()=>E0,BartPretrainedModel:()=>qn,BartTokenizer:()=>uy,BaseStreamer:()=>aC,BeitFeatureExtractor:()=>Cv,BeitForImageClassification:()=>P0,BeitModel:()=>S0,BeitPreTrainedModel:()=>jo,BertForMaskedLM:()=>L0,BertForQuestionAnswering:()=>N0,BertForSequenceClassification:()=>I0,BertForTokenClassification:()=>O0,BertModel:()=>F0,BertPreTrainedModel:()=>ss,BertTokenizer:()=>dy,BitImageProcessor:()=>Sv,BlenderbotForConditionalGeneration:()=>D0,BlenderbotModel:()=>z0,BlenderbotPreTrainedModel:()=>qo,BlenderbotSmallForConditionalGeneration:()=>R0,BlenderbotSmallModel:()=>B0,BlenderbotSmallPreTrainedModel:()=>Wo,BlenderbotSmallTokenizer:()=>hy,BlenderbotTokenizer:()=>fy,BloomForCausalLM:()=>$0,BloomModel:()=>G0,BloomPreTrainedModel:()=>Ho,BloomTokenizer:()=>_y,CHMv2ForDepthEstimation:()=>Q0,CHMv2ImageProcessor:()=>Fv,CHMv2PreTrainedModel:()=>Mh,CLIPFeatureExtractor:()=>Lv,CLIPImageProcessor:()=>qd,CLIPModel:()=>Y0,CLIPPreTrainedModel:()=>Lr,CLIPSegForImageSegmentation:()=>tM,CLIPSegModel:()=>eM,CLIPSegPreTrainedModel:()=>Qo,CLIPTextModel:()=>J0,CLIPTextModelWithProjection:()=>Th,CLIPTokenizer:()=>my,CLIPVisionModel:()=>K0,CLIPVisionModelWithProjection:()=>Z0,CamembertForMaskedLM:()=>U0,CamembertForQuestionAnswering:()=>W0,CamembertForSequenceClassification:()=>j0,CamembertForTokenClassification:()=>q0,CamembertModel:()=>V0,CamembertPreTrainedModel:()=>ns,CamembertTokenizer:()=>py,ChatterboxFeatureExtractor:()=>cv,ChatterboxModel:()=>vh,ChatterboxPreTrainedModel:()=>yh,ChatterboxProcessor:()=>bv,ChineseCLIPFeatureExtractor:()=>Pv,ChineseCLIPModel:()=>H0,ChineseCLIPPreTrainedModel:()=>bh,ClapAudioModelWithProjection:()=>kh,ClapFeatureExtractor:()=>uv,ClapModel:()=>X0,ClapPreTrainedModel:()=>Wn,ClapTextModelWithProjection:()=>xh,ClassifierFreeGuidanceLogitsProcessor:()=>r0,CodeGenForCausalLM:()=>sM,CodeGenModel:()=>rM,CodeGenPreTrainedModel:()=>Xo,CodeGenTokenizer:()=>wy,CodeLlamaTokenizer:()=>gy,Cohere2ForCausalLM:()=>iM,Cohere2Model:()=>oM,Cohere2PreTrainedModel:()=>Jo,CohereAsrFeatureExtractor:()=>dv,CohereAsrForConditionalGeneration:()=>cM,CohereAsrModel:()=>lM,CohereAsrPreTrainedModel:()=>Ko,CohereAsrProcessor:()=>Mv,CohereAsrTokenizer:()=>vy,CohereForCausalLM:()=>aM,CohereModel:()=>nM,CoherePreTrainedModel:()=>Yo,CohereTokenizer:()=>yy,ConvBertForMaskedLM:()=>dM,ConvBertForQuestionAnswering:()=>_M,ConvBertForSequenceClassification:()=>hM,ConvBertForTokenClassification:()=>fM,ConvBertModel:()=>uM,ConvBertPreTrainedModel:()=>as,ConvBertTokenizer:()=>by,ConvNextFeatureExtractor:()=>Iv,ConvNextForImageClassification:()=>mM,ConvNextImageProcessor:()=>Wd,ConvNextModel:()=>pM,ConvNextPreTrainedModel:()=>Zo,ConvNextV2ForImageClassification:()=>wM,ConvNextV2Model:()=>gM,ConvNextV2PreTrainedModel:()=>ei,DFineForObjectDetection:()=>MM,DFineModel:()=>bM,DFinePreTrainedModel:()=>ri,DINOv3ConvNextModel:()=>QM,DINOv3ConvNextPreTrainedModel:()=>Oh,DINOv3ViTImageProcessor:()=>zv,DINOv3ViTModel:()=>XM,DINOv3ViTPreTrainedModel:()=>Nh,DPTFeatureExtractor:()=>Bv,DPTForDepthEstimation:()=>sx,DPTImageProcessor:()=>Xd,DPTModel:()=>rx,DPTPreTrainedModel:()=>li,DacDecoderModel:()=>Sh,DacDecoderOutput:()=>Ah,DacEncoderModel:()=>Ch,DacEncoderOutput:()=>Eh,DacFeatureExtractor:()=>Gd,DacModel:()=>xM,DacPreTrainedModel:()=>Hn,DebertaForMaskedLM:()=>TM,DebertaForQuestionAnswering:()=>CM,DebertaForSequenceClassification:()=>EM,DebertaForTokenClassification:()=>AM,DebertaModel:()=>kM,DebertaPreTrainedModel:()=>os,DebertaTokenizer:()=>xy,DebertaV2ForMaskedLM:()=>LM,DebertaV2ForQuestionAnswering:()=>NM,DebertaV2ForSequenceClassification:()=>IM,DebertaV2ForTokenClassification:()=>OM,DebertaV2Model:()=>FM,DebertaV2PreTrainedModel:()=>is,DebertaV2Tokenizer:()=>My,DecisionTransformerModel:()=>zM,DecisionTransformerPreTrainedModel:()=>Ph,DeepseekV3ForCausalLM:()=>PM,DeepseekV3Model:()=>SM,DeepseekV3PreTrainedModel:()=>si,DeiTFeatureExtractor:()=>Ov,DeiTForImageClassification:()=>BM,DeiTImageProcessor:()=>Hd,DeiTModel:()=>DM,DeiTPreTrainedModel:()=>ni,DepthAnythingForDepthEstimation:()=>RM,DepthAnythingPreTrainedModel:()=>Fh,DepthEstimationPipeline:()=>eC,DepthProForDepthEstimation:()=>GM,DepthProPreTrainedModel:()=>Lh,DetrFeatureExtractor:()=>Nv,DetrForObjectDetection:()=>VM,DetrForSegmentation:()=>UM,DetrImageProcessor:()=>Qd,DetrModel:()=>$M,DetrObjectDetectionOutput:()=>ai,DetrPreTrainedModel:()=>Qn,DetrSegmentationOutput:()=>Ih,Dinov2ForImageClassification:()=>qM,Dinov2Model:()=>jM,Dinov2PreTrainedModel:()=>oi,Dinov2WithRegistersForImageClassification:()=>HM,Dinov2WithRegistersModel:()=>WM,Dinov2WithRegistersPreTrainedModel:()=>ii,DistilBertForMaskedLM:()=>ex,DistilBertForQuestionAnswering:()=>ZM,DistilBertForSequenceClassification:()=>JM,DistilBertForTokenClassification:()=>KM,DistilBertModel:()=>YM,DistilBertPreTrainedModel:()=>ls,DistilBertTokenizer:()=>ky,DocumentQuestionAnsweringPipeline:()=>KA,DonutFeatureExtractor:()=>Dv,DonutImageProcessor:()=>Lo,DonutSwinModel:()=>tx,DonutSwinPreTrainedModel:()=>zh,DynamicCache:()=>Ro,EdgeTamModel:()=>hE,EfficientNetForImageClassification:()=>ax,EfficientNetImageProcessor:()=>Rv,EfficientNetModel:()=>nx,EfficientNetPreTrainedModel:()=>ci,ElectraForMaskedLM:()=>ix,ElectraForQuestionAnswering:()=>ux,ElectraForSequenceClassification:()=>lx,ElectraForTokenClassification:()=>cx,ElectraModel:()=>ox,ElectraPreTrainedModel:()=>cs,ElectraTokenizer:()=>Ty,EncodecFeatureExtractor:()=>Bd,EosTokenCriteria:()=>i0,Ernie4_5ForCausalLM:()=>hx,Ernie4_5Model:()=>dx,Ernie4_5PretrainedModel:()=>ui,EsmForMaskedLM:()=>_x,EsmForSequenceClassification:()=>px,EsmForTokenClassification:()=>mx,EsmModel:()=>fx,EsmPreTrainedModel:()=>Qs,EsmTokenizer:()=>Ey,EuroBertForMaskedLM:()=>wx,EuroBertForSequenceClassification:()=>yx,EuroBertForTokenClassification:()=>vx,EuroBertModel:()=>gx,EuroBertPreTrainedModel:()=>Xs,ExaoneForCausalLM:()=>Mx,ExaoneModel:()=>bx,ExaonePreTrainedModel:()=>di,FalconForCausalLM:()=>kx,FalconH1ForCausalLM:()=>Ex,FalconH1Model:()=>Tx,FalconH1PreTrainedModel:()=>fi,FalconModel:()=>xx,FalconPreTrainedModel:()=>hi,FalconTokenizer:()=>Ay,FastViTForImageClassification:()=>Cx,FastViTModel:()=>Ax,FastViTPreTrainedModel:()=>_i,FeatureExtractionPipeline:()=>tC,FeatureExtractor:()=>lt,FillMaskPipeline:()=>DA,Florence2ForConditionalGeneration:()=>Sx,Florence2PreTrainedModel:()=>Dh,Florence2Processor:()=>mb,ForcedBOSTokenLogitsProcessor:()=>Hb,ForcedEOSTokenLogitsProcessor:()=>Qb,GLPNFeatureExtractor:()=>Vv,GLPNForDepthEstimation:()=>Wx,GLPNModel:()=>qx,GLPNPreTrainedModel:()=>Mi,GPT2LMHeadModel:()=>r1,GPT2Model:()=>t1,GPT2PreTrainedModel:()=>Ai,GPT2Tokenizer:()=>Py,GPTBigCodeForCausalLM:()=>Qx,GPTBigCodeModel:()=>Hx,GPTBigCodePreTrainedModel:()=>xi,GPTJForCausalLM:()=>n1,GPTJModel:()=>s1,GPTJPreTrainedModel:()=>Ci,GPTNeoForCausalLM:()=>Yx,GPTNeoModel:()=>Xx,GPTNeoPreTrainedModel:()=>ki,GPTNeoXForCausalLM:()=>Kx,GPTNeoXModel:()=>Jx,GPTNeoXPreTrainedModel:()=>Ti,GPTNeoXTokenizer:()=>Sy,Gemma2ForCausalLM:()=>Ix,Gemma2Model:()=>Lx,Gemma2PreTrainedModel:()=>mi,Gemma3ForCausalLM:()=>Dx,Gemma3ForConditionalGeneration:()=>Gh,Gemma3ImageProcessor:()=>Gv,Gemma3Model:()=>zx,Gemma3PreTrainedModel:()=>Rh,Gemma3Processor:()=>gb,Gemma3nAudioFeatureExtractor:()=>$d,Gemma3nForCausalLM:()=>Bx,Gemma3nForConditionalGeneration:()=>Xn,Gemma3nPreTrainedModel:()=>$h,Gemma3nProcessor:()=>wb,Gemma4AudioFeatureExtractor:()=>Vd,Gemma4ForCausalLM:()=>Rx,Gemma4ForConditionalGeneration:()=>gi,Gemma4ImageProcessor:()=>Yd,Gemma4Processor:()=>yb,GemmaForCausalLM:()=>Fx,GemmaModel:()=>Px,GemmaPreTrainedModel:()=>pi,GemmaTokenizer:()=>Cy,Glm46VImageProcessor:()=>$v,Glm46VProcessor:()=>vb,GlmForCausalLM:()=>$x,GlmModel:()=>Gx,GlmMoeDsaForCausalLM:()=>Ux,GlmMoeDsaModel:()=>Vx,GlmMoeDsaPreTrainedModel:()=>yi,GlmOcrForConditionalGeneration:()=>jx,GlmPreTrainedModel:()=>wi,GptOssForCausalLM:()=>e1,GptOssModel:()=>Zx,GptOssPreTrainedModel:()=>Ei,GraniteForCausalLM:()=>o1,GraniteModel:()=>a1,GraniteMoeHybridForCausalLM:()=>l1,GraniteMoeHybridModel:()=>i1,GraniteMoeHybridPreTrainedModel:()=>Pi,GranitePreTrainedModel:()=>Si,GraniteSpeechFeatureExtractor:()=>hv,GraniteSpeechForConditionalGeneration:()=>c1,GraniteSpeechProcessor:()=>bb,GroundingDinoForObjectDetection:()=>u1,GroundingDinoImageProcessor:()=>Uv,GroundingDinoPreTrainedModel:()=>Wh,GroundingDinoProcessor:()=>Mb,GroupViTModel:()=>d1,GroupViTPreTrainedModel:()=>Hh,HeliumForCausalLM:()=>f1,HeliumModel:()=>h1,HeliumPreTrainedModel:()=>Li,HerbertTokenizer:()=>Fy,HieraForImageClassification:()=>p1,HieraModel:()=>_1,HieraPreTrainedModel:()=>Ii,HubertForCTC:()=>M1,HubertForSequenceClassification:()=>x1,HubertModel:()=>b1,HubertPreTrainedModel:()=>v1,HunYuanDenseV1ForCausalLM:()=>T1,HunYuanDenseV1Model:()=>k1,HunYuanDenseV1PreTrainedModel:()=>Oi,IJepaForImageClassification:()=>A1,IJepaModel:()=>E1,IJepaPreTrainedModel:()=>Ni,Idefics3ForConditionalGeneration:()=>Qh,Idefics3ImageProcessor:()=>id,Idefics3Processor:()=>ld,ImageClassificationPipeline:()=>HA,ImageFeatureExtractionPipeline:()=>rC,ImageFeatureExtractor:()=>ue,ImageProcessor:()=>ue,ImageSegmentationPipeline:()=>Rf,ImageToImagePipeline:()=>ZA,ImageToTextPipeline:()=>WA,InterruptableStoppingCriteria:()=>sz,JAISLMHeadModel:()=>S1,JAISModel:()=>C1,JAISPreTrainedModel:()=>zi,JinaCLIPImageProcessor:()=>qv,JinaCLIPModel:()=>P1,JinaCLIPPreTrainedModel:()=>Yn,JinaCLIPProcessor:()=>kb,JinaCLIPTextModel:()=>Xh,JinaCLIPVisionModel:()=>F1,Lfm2ForCausalLM:()=>I1,Lfm2Model:()=>L1,Lfm2MoeForCausalLM:()=>z1,Lfm2MoeModel:()=>N1,Lfm2MoePreTrainedModel:()=>Bi,Lfm2PreTrainedModel:()=>Di,Lfm2VlForConditionalGeneration:()=>D1,Lfm2VlImageProcessor:()=>Wv,Lfm2VlProcessor:()=>Tb,LightOnOcrForConditionalGeneration:()=>O1,LiteWhisperForConditionalGeneration:()=>E2,Llama4ForCausalLM:()=>G1,Llama4PreTrainedModel:()=>Yh,LlamaForCausalLM:()=>R1,LlamaModel:()=>B1,LlamaPreTrainedModel:()=>Ri,LlamaTokenizer:()=>Ly,LlavaForConditionalGeneration:()=>sr,LlavaOnevisionForConditionalGeneration:()=>sr,LlavaOnevisionImageProcessor:()=>Hv,LlavaPreTrainedModel:()=>Bh,LlavaProcessor:()=>Eb,LlavaQwen2ForCausalLM:()=>Nx,LogLevel:()=>Ot,LogitsProcessor:()=>zt,LogitsProcessorList:()=>bo,LogitsWarper:()=>Do,LongT5ForConditionalGeneration:()=>V1,LongT5Model:()=>$1,LongT5PreTrainedModel:()=>Gi,M2M100ForConditionalGeneration:()=>j1,M2M100Model:()=>U1,M2M100PreTrainedModel:()=>$i,M2M100Tokenizer:()=>Iy,MBart50Tokenizer:()=>Ny,MBartForCausalLM:()=>K1,MBartForConditionalGeneration:()=>Y1,MBartForSequenceClassification:()=>J1,MBartModel:()=>X1,MBartPreTrainedModel:()=>Ys,MBartTokenizer:()=>Nd,MPNetForMaskedLM:()=>Bk,MPNetForQuestionAnswering:()=>$k,MPNetForSequenceClassification:()=>Rk,MPNetForTokenClassification:()=>Gk,MPNetModel:()=>Dk,MPNetPreTrainedModel:()=>us,MPNetTokenizer:()=>By,MT5ForConditionalGeneration:()=>qk,MT5Model:()=>jk,MT5PreTrainedModel:()=>Ki,MarianMTModel:()=>W1,MarianModel:()=>q1,MarianPreTrainedModel:()=>Vi,MarianTokenizer:()=>Oy,Mask2FormerImageProcessor:()=>Xv,MaskFormerFeatureExtractor:()=>Qv,MaskFormerForInstanceSegmentation:()=>Q1,MaskFormerImageProcessor:()=>Io,MaskFormerModel:()=>H1,MaskFormerPreTrainedModel:()=>Ui,MaxLengthCriteria:()=>o0,Metric3DForDepthEstimation:()=>Z1,Metric3DPreTrainedModel:()=>Jh,Metric3Dv2ForDepthEstimation:()=>ek,Metric3Dv2PreTrainedModel:()=>Kh,MgpstrForSceneTextRecognition:()=>tk,MgpstrModelOutput:()=>Zh,MgpstrPreTrainedModel:()=>ef,MgpstrProcessor:()=>Ab,MgpstrTokenizer:()=>zy,MimiDecoderModel:()=>nf,MimiDecoderOutput:()=>rf,MimiEncoderModel:()=>sf,MimiEncoderOutput:()=>tf,MimiModel:()=>rk,MimiPreTrainedModel:()=>Jn,MinLengthLogitsProcessor:()=>Zb,MinNewTokensLengthLogitsProcessor:()=>e0,Mistral4ForCausalLM:()=>ok,Mistral4Model:()=>ak,Mistral4PreTrainedModel:()=>qi,MistralForCausalLM:()=>nk,MistralModel:()=>sk,MistralPreTrainedModel:()=>ji,MobileBertForMaskedLM:()=>lk,MobileBertForQuestionAnswering:()=>uk,MobileBertForSequenceClassification:()=>ck,MobileBertModel:()=>ik,MobileBertPreTrainedModel:()=>Js,MobileBertTokenizer:()=>Dy,MobileLLMForCausalLM:()=>hk,MobileLLMModel:()=>dk,MobileLLMPreTrainedModel:()=>Wi,MobileNetV1FeatureExtractor:()=>Yv,MobileNetV1ForImageClassification:()=>_k,MobileNetV1ForSemanticSegmentation:()=>pk,MobileNetV1ImageProcessor:()=>Kd,MobileNetV1Model:()=>fk,MobileNetV1PreTrainedModel:()=>Kn,MobileNetV2FeatureExtractor:()=>Jv,MobileNetV2ForImageClassification:()=>gk,MobileNetV2ForSemanticSegmentation:()=>wk,MobileNetV2ImageProcessor:()=>Zd,MobileNetV2Model:()=>mk,MobileNetV2PreTrainedModel:()=>Zn,MobileNetV3FeatureExtractor:()=>Kv,MobileNetV3ForImageClassification:()=>vk,MobileNetV3ForSemanticSegmentation:()=>bk,MobileNetV3ImageProcessor:()=>eh,MobileNetV3Model:()=>yk,MobileNetV3PreTrainedModel:()=>ea,MobileNetV4FeatureExtractor:()=>Zv,MobileNetV4ForImageClassification:()=>xk,MobileNetV4ForSemanticSegmentation:()=>kk,MobileNetV4ImageProcessor:()=>th,MobileNetV4Model:()=>Mk,MobileNetV4PreTrainedModel:()=>ta,MobileViTFeatureExtractor:()=>eb,MobileViTForImageClassification:()=>Ek,MobileViTImageProcessor:()=>rh,MobileViTModel:()=>Tk,MobileViTPreTrainedModel:()=>Hi,MobileViTV2ForImageClassification:()=>Ck,MobileViTV2Model:()=>Ak,MobileViTV2PreTrainedModel:()=>Qi,ModelRegistry:()=>Zz,ModernBertDecoderForCausalLM:()=>Ok,ModernBertDecoderModel:()=>Ik,ModernBertDecoderPreTrainedModel:()=>Xi,ModernBertForMaskedLM:()=>Pk,ModernBertForSequenceClassification:()=>Fk,ModernBertForTokenClassification:()=>Lk,ModernBertModel:()=>Sk,ModernBertPreTrainedModel:()=>Ks,Moondream1ForConditionalGeneration:()=>Ox,MoonshineFeatureExtractor:()=>fv,MoonshineForConditionalGeneration:()=>zk,MoonshineModel:()=>Nk,MoonshinePreTrainedModel:()=>Yi,MoonshineProcessor:()=>Cb,MptForCausalLM:()=>Uk,MptModel:()=>Vk,MptPreTrainedModel:()=>Ji,MultiModalityCausalLM:()=>Wk,MultiModalityPreTrainedModel:()=>af,MusicgenForCausalLM:()=>Qk,MusicgenForConditionalGeneration:()=>of,MusicgenModel:()=>Hk,MusicgenPreTrainedModel:()=>Zi,NanoChatForCausalLM:()=>Yk,NanoChatModel:()=>Xk,NanoChatPreTrainedModel:()=>el,NemotronHForCausalLM:()=>Kk,NemotronHModel:()=>Jk,NemotronHPreTrainedModel:()=>tl,NeoBertForMaskedLM:()=>eT,NeoBertForQuestionAnswering:()=>sT,NeoBertForSequenceClassification:()=>tT,NeoBertForTokenClassification:()=>rT,NeoBertModel:()=>Zk,NeoBertPreTrainedModel:()=>ds,NllbTokenizer:()=>Ry,NoBadWordsLogitsProcessor:()=>t0,NoRepeatNGramLogitsProcessor:()=>Jb,NomicBertModel:()=>nT,NomicBertPreTrainedModel:()=>lf,NougatImageProcessor:()=>tb,NougatTokenizer:()=>Gy,OPTForCausalLM:()=>mT,OPTModel:()=>pT,OPTPreTrainedModel:()=>il,ObjectDetectionPipeline:()=>YA,Olmo2ForCausalLM:()=>lT,Olmo2Model:()=>iT,Olmo2PreTrainedModel:()=>sl,Olmo3ForCausalLM:()=>uT,Olmo3Model:()=>cT,Olmo3PreTrainedModel:()=>nl,OlmoForCausalLM:()=>oT,OlmoHybridForCausalLM:()=>hT,OlmoHybridModel:()=>dT,OlmoHybridPreTrainedModel:()=>al,OlmoModel:()=>aT,OlmoPreTrainedModel:()=>rl,OpenELMForCausalLM:()=>_T,OpenELMModel:()=>fT,OpenELMPreTrainedModel:()=>ol,OwlViTFeatureExtractor:()=>rb,OwlViTForObjectDetection:()=>vT,OwlViTImageProcessor:()=>Oo,OwlViTModel:()=>yT,OwlViTPreTrainedModel:()=>cl,OwlViTProcessor:()=>Sb,Owlv2ForObjectDetection:()=>wT,Owlv2ImageProcessor:()=>sb,Owlv2Model:()=>gT,Owlv2PreTrainedModel:()=>ll,PaliGemmaForConditionalGeneration:()=>bT,PaliGemmaProcessor:()=>Pb,ParakeetFeatureExtractor:()=>Rd,ParakeetForCTC:()=>MT,ParakeetPreTrainedModel:()=>cf,PatchTSMixerForPrediction:()=>kT,PatchTSMixerModel:()=>xT,PatchTSMixerPreTrainedModel:()=>ul,PatchTSTForPrediction:()=>ET,PatchTSTModel:()=>TT,PatchTSTPreTrainedModel:()=>dl,Phi3ForCausalLM:()=>PT,Phi3Model:()=>ST,Phi3PreTrainedModel:()=>fl,Phi3VForCausalLM:()=>df,Phi3VImageProcessor:()=>nb,Phi3VPreTrainedModel:()=>uf,Phi3VProcessor:()=>Fb,PhiForCausalLM:()=>CT,PhiModel:()=>AT,PhiPreTrainedModel:()=>hl,PixtralImageProcessor:()=>ab,PixtralProcessor:()=>Lb,PreTrainedModel:()=>P,PreTrainedTokenizer:()=>ie,PretrainedConfig:()=>vo,Processor:()=>ke,PvtForImageClassification:()=>LT,PvtImageProcessor:()=>ob,PvtModel:()=>FT,PvtPreTrainedModel:()=>_l,PyAnnoteFeatureExtractor:()=>Ud,PyAnnoteForAudioFrameClassification:()=>OT,PyAnnoteModel:()=>IT,PyAnnotePreTrainedModel:()=>pl,PyAnnoteProcessor:()=>Ib,QuestionAnsweringPipeline:()=>zA,Qwen2ForCausalLM:()=>zT,Qwen2Model:()=>NT,Qwen2MoeForCausalLM:()=>BT,Qwen2MoeModel:()=>DT,Qwen2MoePreTrainedModel:()=>gl,Qwen2PreTrainedModel:()=>ml,Qwen2Tokenizer:()=>$y,Qwen2VLForCausalLM:()=>Uh,Qwen2VLForConditionalGeneration:()=>vi,Qwen2VLImageProcessor:()=>Jd,Qwen2VLPreTrainedModel:()=>Vh,Qwen2VLProcessor:()=>No,Qwen2_5_VLForCausalLM:()=>jh,Qwen2_5_VLForConditionalGeneration:()=>bi,Qwen2_5_VLProcessor:()=>ih,Qwen3ForCausalLM:()=>GT,Qwen3Model:()=>RT,Qwen3MoeForCausalLM:()=>VT,Qwen3MoeModel:()=>$T,Qwen3MoePreTrainedModel:()=>yl,Qwen3NextForCausalLM:()=>jT,Qwen3NextModel:()=>UT,Qwen3NextPreTrainedModel:()=>vl,Qwen3PreTrainedModel:()=>wl,Qwen3VLForCausalLM:()=>hf,Qwen3VLForConditionalGeneration:()=>bl,Qwen3VLMoeForCausalLM:()=>WT,Qwen3VLMoeForConditionalGeneration:()=>qT,Qwen3VLProcessor:()=>Ob,Qwen3_5ForCausalLM:()=>ff,Qwen3_5ForConditionalGeneration:()=>Ml,Qwen3_5MoeForCausalLM:()=>QT,Qwen3_5MoeForConditionalGeneration:()=>HT,RFDetrForObjectDetection:()=>KT,RFDetrModel:()=>JT,RFDetrObjectDetectionOutput:()=>_f,RFDetrPreTrainedModel:()=>kl,RTDetrForObjectDetection:()=>vM,RTDetrImageProcessor:()=>ib,RTDetrModel:()=>yM,RTDetrObjectDetectionOutput:()=>Hs,RTDetrPreTrainedModel:()=>ti,RTDetrV2ForObjectDetection:()=>uE,RTDetrV2Model:()=>cE,RTDetrV2ObjectDetectionOutput:()=>pf,RTDetrV2PreTrainedModel:()=>Tl,RawAudio:()=>iv,RawImage:()=>vt,RawVideo:()=>iC,RawVideoFrame:()=>Gf,RepetitionPenaltyLogitsProcessor:()=>Kb,ResNetForImageClassification:()=>YT,ResNetModel:()=>XT,ResNetPreTrainedModel:()=>xl,RoFormerForMaskedLM:()=>aE,RoFormerForQuestionAnswering:()=>lE,RoFormerForSequenceClassification:()=>oE,RoFormerForTokenClassification:()=>iE,RoFormerModel:()=>nE,RoFormerPreTrainedModel:()=>fs,RoFormerTokenizer:()=>Uy,RobertaForMaskedLM:()=>eE,RobertaForQuestionAnswering:()=>sE,RobertaForSequenceClassification:()=>tE,RobertaForTokenClassification:()=>rE,RobertaModel:()=>ZT,RobertaPreTrainedModel:()=>hs,RobertaTokenizer:()=>Vy,Sam2ImageProcessor:()=>co,Sam2ImageSegmentationOutput:()=>wf,Sam2Model:()=>El,Sam2PreTrainedModel:()=>yf,Sam2Processor:()=>ch,Sam2VideoProcessor:()=>Nb,Sam3ImageProcessor:()=>co,Sam3TrackerModel:()=>fE,SamImageProcessor:()=>co,SamImageSegmentationOutput:()=>mf,SamModel:()=>dE,SamPreTrainedModel:()=>gf,SamProcessor:()=>lh,SapiensFeatureExtractor:()=>lb,SapiensForDepthEstimation:()=>pE,SapiensForNormalEstimation:()=>mE,SapiensForSemanticSegmentation:()=>_E,SapiensImageProcessor:()=>sh,SapiensPreTrainedModel:()=>ra,SeamlessM4TFeatureExtractor:()=>_v,SegformerFeatureExtractor:()=>cb,SegformerForImageClassification:()=>wE,SegformerForSemanticSegmentation:()=>yE,SegformerImageProcessor:()=>nh,SegformerModel:()=>gE,SegformerPreTrainedModel:()=>sa,SiglipImageProcessor:()=>ub,SiglipModel:()=>vE,SiglipPreTrainedModel:()=>Al,SiglipTextModel:()=>vf,SiglipTokenizer:()=>jy,SiglipVisionModel:()=>bE,SmolLM3ForCausalLM:()=>xE,SmolLM3Model:()=>ME,SmolLM3PreTrainedModel:()=>Cl,SmolVLMForConditionalGeneration:()=>kE,SmolVLMImageProcessor:()=>id,SmolVLMProcessor:()=>ld,SnacDecoderModel:()=>Mf,SnacEncoderModel:()=>bf,SnacFeatureExtractor:()=>pv,SnacModel:()=>TE,SnacPreTrainedModel:()=>na,SolarOpenForCausalLM:()=>AE,SolarOpenModel:()=>EE,SolarOpenPreTrainedModel:()=>Sl,SpeechT5FeatureExtractor:()=>mv,SpeechT5ForSpeechToText:()=>SE,SpeechT5ForTextToSpeech:()=>PE,SpeechT5HifiGan:()=>FE,SpeechT5Model:()=>CE,SpeechT5PreTrainedModel:()=>aa,SpeechT5Processor:()=>zb,SpeechT5Tokenizer:()=>qy,SqueezeBertForMaskedLM:()=>IE,SqueezeBertForQuestionAnswering:()=>NE,SqueezeBertForSequenceClassification:()=>OE,SqueezeBertModel:()=>LE,SqueezeBertPreTrainedModel:()=>Zs,SqueezeBertTokenizer:()=>Wy,StableLmForCausalLM:()=>DE,StableLmModel:()=>zE,StableLmPreTrainedModel:()=>Pl,Starcoder2ForCausalLM:()=>RE,Starcoder2Model:()=>BE,Starcoder2PreTrainedModel:()=>Fl,StoppingCriteria:()=>qs,StoppingCriteriaList:()=>dh,StyleTextToSpeech2Model:()=>GE,StyleTextToSpeech2PreTrainedModel:()=>xf,SummarizationPipeline:()=>BA,SupertonicForConditionalGeneration:()=>Tf,SupertonicPreTrainedModel:()=>kf,SuppressTokensAtBeginLogitsProcessor:()=>uh,SuppressTokensLogitsProcessor:()=>Xb,Swin2SRForImageSuperResolution:()=>qE,Swin2SRImageProcessor:()=>db,Swin2SRModel:()=>jE,Swin2SRPreTrainedModel:()=>Ll,SwinForImageClassification:()=>VE,SwinForSemanticSegmentation:()=>UE,SwinModel:()=>$E,SwinPreTrainedModel:()=>oa,T5ForConditionalGeneration:()=>HE,T5Model:()=>WE,T5PreTrainedModel:()=>Il,T5Tokenizer:()=>Hy,TableTransformerForObjectDetection:()=>XE,TableTransformerModel:()=>QE,TableTransformerObjectDetectionOutput:()=>Ef,TableTransformerPreTrainedModel:()=>Ol,TemperatureLogitsWarper:()=>s0,Tensor:()=>V,Text2TextGenerationPipeline:()=>$l,TextClassificationPipeline:()=>OA,TextGenerationPipeline:()=>GA,TextStreamer:()=>oC,TextToAudioPipeline:()=>qA,TokenClassificationPipeline:()=>NA,TokenizersBackend:()=>ie,TopKLogitsWarper:()=>rz,TopPLogitsWarper:()=>tz,TrOCRForCausalLM:()=>YE,TrOCRPreTrainedModel:()=>Af,TranslationPipeline:()=>RA,UltravoxModel:()=>Fi,UltravoxPreTrainedModel:()=>qh,UltravoxProcessor:()=>Db,UniSpeechForCTC:()=>KE,UniSpeechForSequenceClassification:()=>ZE,UniSpeechModel:()=>JE,UniSpeechPreTrainedModel:()=>ia,UniSpeechSatForAudioFrameClassification:()=>s2,UniSpeechSatForCTC:()=>t2,UniSpeechSatForSequenceClassification:()=>r2,UniSpeechSatModel:()=>e2,UniSpeechSatPreTrainedModel:()=>en,VLChatProcessor:()=>xb,VLMImageProcessor:()=>jv,VaultGemmaForCausalLM:()=>a2,VaultGemmaModel:()=>n2,VaultGemmaPreTrainedModel:()=>Nl,ViTFeatureExtractor:()=>hb,ViTForImageClassification:()=>l2,ViTImageProcessor:()=>ah,ViTMAEModel:()=>c2,ViTMAEPreTrainedModel:()=>Cf,ViTMSNForImageClassification:()=>d2,ViTMSNModel:()=>u2,ViTMSNPreTrainedModel:()=>Dl,ViTModel:()=>i2,ViTPreTrainedModel:()=>zl,VisionEncoderDecoderModel:()=>o2,VitMatteForImageMatting:()=>h2,VitMatteImageProcessor:()=>fb,VitMattePreTrainedModel:()=>Sf,VitPoseForPoseEstimation:()=>f2,VitPoseImageProcessor:()=>_b,VitPosePreTrainedModel:()=>Pf,VitsModel:()=>_2,VitsModelOutput:()=>Ff,VitsPreTrainedModel:()=>Lf,VitsTokenizer:()=>Qy,VoxtralForConditionalGeneration:()=>p2,VoxtralProcessor:()=>Bb,VoxtralRealtimeFeatureExtractor:()=>yv,VoxtralRealtimeForConditionalGeneration:()=>Of,VoxtralRealtimePreTrainedModel:()=>If,VoxtralRealtimeProcessor:()=>Rb,Wav2Vec2BertForCTC:()=>g2,Wav2Vec2BertForSequenceClassification:()=>w2,Wav2Vec2BertModel:()=>m2,Wav2Vec2BertPreTrainedModel:()=>la,Wav2Vec2CTCTokenizer:()=>Xy,Wav2Vec2FeatureExtractor:()=>gv,Wav2Vec2ForAudioFrameClassification:()=>y1,Wav2Vec2ForCTC:()=>g1,Wav2Vec2ForSequenceClassification:()=>w1,Wav2Vec2Model:()=>m1,Wav2Vec2PreTrainedModel:()=>wr,Wav2Vec2Processor:()=>Gb,Wav2Vec2ProcessorWithLM:()=>$b,WavLMForAudioFrameClassification:()=>x2,WavLMForCTC:()=>v2,WavLMForSequenceClassification:()=>b2,WavLMForXVector:()=>M2,WavLMModel:()=>y2,WavLMPreTrainedModel:()=>_s,WeSpeakerFeatureExtractor:()=>wv,WeSpeakerResNetModel:()=>k2,WeSpeakerResNetPreTrainedModel:()=>zf,WhisperFeatureExtractor:()=>vv,WhisperForConditionalGeneration:()=>Df,WhisperModel:()=>T2,WhisperPreTrainedModel:()=>Bl,WhisperProcessor:()=>Vb,WhisperTextStreamer:()=>Uz,WhisperTimeStampLogitsProcessor:()=>Yb,WhisperTokenizer:()=>Jy,XLMForQuestionAnswering:()=>F2,XLMForSequenceClassification:()=>S2,XLMForTokenClassification:()=>P2,XLMModel:()=>A2,XLMPreTrainedModel:()=>ps,XLMRobertaForMaskedLM:()=>I2,XLMRobertaForQuestionAnswering:()=>z2,XLMRobertaForSequenceClassification:()=>O2,XLMRobertaForTokenClassification:()=>N2,XLMRobertaModel:()=>L2,XLMRobertaPreTrainedModel:()=>ms,XLMRobertaTokenizer:()=>Ky,XLMTokenizer:()=>Zy,XLMWithLMHeadModel:()=>C2,XVectorOutput:()=>Nf,YolosFeatureExtractor:()=>pb,YolosForObjectDetection:()=>B2,YolosImageProcessor:()=>oh,YolosModel:()=>D2,YolosObjectDetectionOutput:()=>Bf,YolosPreTrainedModel:()=>Rl,YoutuForCausalLM:()=>G2,YoutuModel:()=>R2,YoutuPreTrainedModel:()=>Gl,ZeroShotAudioClassificationPipeline:()=>UA,ZeroShotClassificationPipeline:()=>$A,ZeroShotImageClassificationPipeline:()=>XA,ZeroShotObjectDetectionPipeline:()=>JA,cat:()=>Le,cos_sim:()=>LN,dot:()=>qw,env:()=>me,full:()=>it,full_like:()=>wo,interpolate:()=>Td,interpolate_4d:()=>Nt,layer_norm:()=>JN,load_audio:()=>sv,load_image:()=>T3,load_video:()=>jz,log_softmax:()=>jw,matmul:()=>sy,mean:()=>So,mean_pooling:()=>ny,ones:()=>yt,ones_like:()=>Sd,permute:()=>ry,pipeline:()=>$z,quantize_embeddings:()=>oy,rand:()=>KN,randn:()=>ay,random:()=>Vn,read_audio:()=>nv,rfft:()=>YN,slice:()=>Ed,softmax:()=>tt,stack:()=>tr,std_mean:()=>Ad,topk:()=>ts,zeros:()=>Pd,zeros_like:()=>Fd});var iu={};Hp(iu,{InferenceSession:()=>Wc,TRACE:()=>Ia,TRACE_EVENT_BEGIN:()=>Er,TRACE_EVENT_END:()=>Ar,TRACE_FUNC_BEGIN:()=>Ur,TRACE_FUNC_END:()=>jr,Tensor:()=>Rt,default:()=>UF,env:()=>De,registerBackend:()=>Vr});var jc=Object.defineProperty,pF=Object.getOwnPropertyDescriptor,mF=Object.getOwnPropertyNames,gF=Object.prototype.hasOwnProperty,wF=(e=>typeof Dr<"u"?Dr:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof Dr<"u"?Dr:t)[r]}):e)(function(e){if(typeof Dr<"u")return Dr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),_e=(e,t)=>()=>(e&&(t=e(e=0)),t),pn=(e,t)=>{for(var r in t)jc(e,r,{get:t[r],enumerable:true});},yF=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of mF(t))!gF.call(e,n)&&n!==r&&jc(e,n,{get:()=>t[n],enumerable:!(s=pF(t,n))||s.enumerable});return e},La=e=>yF(jc({},"__esModule",{value:true}),e),ln,Mr,Vr,Xp,Mm,xm=_e(()=>{ln=new Map,Mr=[],Vr=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let s=ln.get(e);if(s===void 0)ln.set(e,{backend:t,priority:r});else {if(s.priority>r)return;if(s.priority===r&&s.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let n=Mr.indexOf(e);n!==-1&&Mr.splice(n,1);for(let a=0;a<Mr.length;a++)if(ln.get(Mr[a]).priority<=r){Mr.splice(a,0,e);return}Mr.push(e);}return}throw new TypeError("not a valid backend")},Xp=async e=>{let t=ln.get(e);if(!t)return "backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(s){return r||(t.error=`${s}`,t.aborted=true),t.error}finally{delete t.initPromise;}}},Mm=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Mr:r,n,a=[],o=new Set;for(let l of s){let c=await Xp(l);typeof c=="string"?a.push({name:l,err:c}):(n||(n=c),n===c&&o.add(l));}if(!n)throw new Error(`no available backend found. ERR: ${a.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of a)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=t.filter(l=>o.has(typeof l=="string"?l:l.name));return [n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]};}),vF=_e(()=>{xm();}),km,bF=_e(()=>{km="1.24.0-dev.20251116-b39e144322";}),wc,Ze,Tm=_e(()=>{bF(),wc="warning",Ze={wasm:{},webgl:{},webgpu:{},versions:{common:km},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);wc=e;}},get logLevel(){return wc}},Object.defineProperty(Ze,"logLevel",{enumerable:true});}),De,MF=_e(()=>{Tm(),De=Ze;}),Em,Am,xF=_e(()=>{Em=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let s=r.getContext("2d");if(s!=null){let n,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);let o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let d=a*n,h=0,_=d,p=d*2,w=-1;o==="RGBA"?(h=0,_=d,p=d*2,w=d*3):o==="RGB"?(h=0,_=d,p=d*2):o==="RBG"&&(h=0,p=d,_=d*2);for(let y=0;y<a;y++)for(let b=0;b<n;b++){let x=(e.data[h++]-c[0])*l[0],T=(e.data[_++]-c[1])*l[1],C=(e.data[p++]-c[2])*l[2],A=w===-1?255:(e.data[w++]-c[3])*l[3];s.fillStyle="rgba("+x+","+T+","+C+","+A+")",s.fillRect(b,y,1,1);}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Am=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let h=a*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,p=0,w=1,y=2,b=3,x=0,T=h,C=h*2,A=-1;i==="RGBA"?(x=0,T=h,C=h*2,A=h*3):i==="RGB"?(x=0,T=h,C=h*2):i==="RBG"&&(x=0,C=h,T=h*2),s=r.createImageData(n,a);for(let S=0;S<a*n;p+=_,w+=_,y+=_,b+=_,S++)s.data[p]=(e.data[x++]-d[0])*c[0],s.data[w]=(e.data[T++]-d[1])*c[1],s.data[y]=(e.data[C++]-d[2])*c[2],s.data[b]=A===-1?255:(e.data[A++]-d[3])*c[3];}else throw new Error("Can not access image data");return s};}),Ta,Cm,Sm,Pm,Fm,Lm,kF=_e(()=>{qc(),Ta=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=t,n=t.norm??{mean:255,bias:0},a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*s,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,_=0,p=1,w=2,y=3,b=0,x=c,T=c*2,C=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,y=-1),l==="RGBA"?C=c*3:l==="RBG"?(b=0,T=c,x=c*2):l==="BGR"&&(T=0,x=c,b=c*2);for(let A=0;A<c;A++,_+=h,w+=h,p+=h,y+=h)d[b++]=(e[_]+o[0])/a[0],d[x++]=(e[p]+o[1])/a[1],d[T++]=(e[w]+o[2])/a[2],C!==-1&&y!==-1&&(d[C++]=(e[y]+o[3])/a[3]);return l==="RGBA"?new Tt("float32",d,[1,4,r,s]):new Tt("float32",d,[1,3,r,s])},Cm=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=e.width,d.height=e.height;let h=c(d);if(h!=null){let _=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,p=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=p;}else i.tensorFormat="RGBA",i.height=_,i.width=p;h.drawImage(e,0,0),o=h.getImageData(0,0,p,_).data;}else throw new Error("Can not access image data")}else if(s){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){let _=l();_.width=h,_.height=d;let p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else o=e.data;}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=e.width,d.height=e.height;let h=c(d);if(h!=null){let _=e.height,p=e.width;return h.drawImage(e,0,0,p,_),o=h.getImageData(0,0,p,_).data,i.height=_,i.width=p,Ta(o,i)}else throw new Error("Can not access image data")}else {if(a)return new Promise((d,h)=>{let _=l(),p=c(_);if(!e||!p)return h();let w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,p.drawImage(w,0,0,_.width,_.height);let y=p.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(Ta(y.data,i));};});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Ta(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Sm=(e,t)=>{let{width:r,height:s,download:n,dispose:a}=t,o=[1,s,r,4];return new Tt({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},Pm=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new Tt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:a})},Fm=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new Tt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:a})},Lm=(e,t,r)=>new Tt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]});}),Gr,fn,yc,Im,TF=_e(()=>{Gr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),fn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),yc=false,Im=()=>{if(!yc){yc=true;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(Gr.set("int64",BigInt64Array),fn.set(BigInt64Array,"int64")),t&&(Gr.set("uint64",BigUint64Array),fn.set(BigUint64Array,"uint64")),s?(Gr.set("float16",r),fn.set(r,"float16")):Gr.set("float16",Uint16Array);}};}),Om,Nm,EF=_e(()=>{qc(),Om=e=>{let t=1;for(let r=0;r<e.length;r++){let s=e[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);t*=s;}return t},Nm=(e,t)=>{switch(e.location){case "cpu":return new Tt(e.type,e.data,t);case "cpu-pinned":return new Tt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case "texture":return new Tt({location:"texture",texture:e.texture,type:e.type,dims:t});case "gpu-buffer":return new Tt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case "ml-tensor":return new Tt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};}),Tt,qc=_e(()=>{xF(),kF(),TF(),EF(),Tt=class{constructor(e,t,r){Im();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case "cpu-pinned":{let o=Gr.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case "texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case "gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case "ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else {let o,i;if(typeof e=="string")if(s=e,i=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t;}else {let l=Gr.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(t,BigInt):o=l.from(t);}else if(t instanceof l)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",o=e;else if(l==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else {let l=fn.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,o=e;}if(i===void 0)i=[o.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=o,this.dataLocation="cpu";}let a=Om(n);if(this.cpuData&&a!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=a;}static async fromImage(e,t){return Cm(e,t)}static fromTexture(e,t){return Sm(e,t)}static fromGpuBuffer(e,t){return Pm(e,t)}static fromMLTensor(e,t){return Fm(e,t)}static fromPinnedBuffer(e,t,r){return Lm(e,t,r)}toDataURL(e){return Em(this,e)}toImageData(e){return Am(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case "cpu":case "cpu-pinned":return this.data;case "texture":case "gpu-buffer":case "ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=false;}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none";}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Nm(this,e)}};}),Rt,zm=_e(()=>{qc(),Rt=Tt;}),Ia,vc,Ur,jr,Er,Ar,Dm=_e(()=>{Tm(),Ia=(e,t)=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||console.timeStamp(`${e}::ORT::${t}`);},vc=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=false;for(let n=0;n<r.length;n++){if(s&&!r[n].includes("TRACE_FUNC")){let a=`FUNC_${e}::${r[n].trim().split(" ")[1]}`;t&&(a+=`::${t}`),Ia("CPU",a);return}r[n].includes("TRACE_FUNC")&&(s=true);}},Ur=e=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||vc("BEGIN",e);},jr=e=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||vc("END",e);},Er=e=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||console.time(`ORT::${e}`);},Ar=e=>{(typeof Ze.trace>"u"?!Ze.wasm.trace:!Ze.trace)||console.timeEnd(`ORT::${e}`);};}),Bm,AF=_e(()=>{xm(),zm(),Dm(),Bm=class Rm{constructor(t){this.handler=t;}async run(t,r,s){Ur(),Er("InferenceSession.run");let n={},a={};if(typeof t!="object"||t===null||t instanceof Rt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=true;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Rt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=false;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null;}if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else {let c=false,d=Object.getOwnPropertyNames(r);for(let h of this.outputNames)if(d.indexOf(h)!==-1){let _=r[h];(_===null||_ instanceof Rt)&&(c=true,o=false,n[h]=_);}if(c){if(typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else a=r;}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(o)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(t,n,a),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let d=i[c];d instanceof Rt?l[c]=d:l[c]=new Rt(d.type,d.data,d.dims);}return Ar("InferenceSession.run"),jr(),l}async release(){return this.handler.dispose()}static async create(t,r,s,n){Ur(),Er("InferenceSession.create");let a,o={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let d=t,h=0,_=t.byteLength;if(typeof r=="object"&&r!==null)o=r;else if(typeof r=="number"){if(h=r,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(_=t.byteLength-h,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||h+_>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-h}].`);if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(d,h,_);}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await Mm(o),c=await i.createInferenceSessionHandler(a,l);return Ar("InferenceSession.create"),jr(),new Rm(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}};}),Wc,CF=_e(()=>{AF(),Wc=Bm;}),SF=_e(()=>{}),PF=_e(()=>{}),FF=_e(()=>{}),LF=_e(()=>{}),Gm={};pn(Gm,{InferenceSession:()=>Wc,TRACE:()=>Ia,TRACE_EVENT_BEGIN:()=>Er,TRACE_EVENT_END:()=>Ar,TRACE_FUNC_BEGIN:()=>Ur,TRACE_FUNC_END:()=>jr,Tensor:()=>Rt,env:()=>De,registerBackend:()=>Vr});var qr=_e(()=>{vF(),MF(),CF(),zm(),SF(),PF(),Dm(),FF(),LF();}),Hc=_e(()=>{}),$m={};pn($m,{default:()=>Vm});var bc,Mc,Vm,IF=_e(()=>{sg(),Wr(),Qc(),bc="ort-wasm-proxy-worker",Mc=globalThis.self?.name===bc,Mc&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case "init-wasm":Xc(r.wasm).then(()=>{eu(r).then(()=>{postMessage({type:t});},s=>{postMessage({type:t,err:s});});},s=>{postMessage({type:t,err:s});});break;case "init-ep":{let{epName:s,env:n}=r;tu(n,s).then(()=>{postMessage({type:t});},a=>{postMessage({type:t,err:a});});break}case "copy-from":{let{buffer:s}=r,n=za(s);postMessage({type:t,out:n});break}case "create":{let{model:s,options:n}=r;ru(s,n).then(a=>{postMessage({type:t,out:a});},a=>{postMessage({type:t,err:a});});break}case "release":su(r),postMessage({type:t});break;case "run":{let{sessionId:s,inputIndices:n,inputs:a,outputIndices:o,options:i}=r;nu(s,n,a,o,new Array(o.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:l},ou([...a,...l]));},l=>{postMessage({type:t,err:l});});break}case "end-profiling":au(r),postMessage({type:t});break;default:}}catch(s){postMessage({type:t,err:s});}}),Vm=Mc?null:e=>new Worker(e??xt,{type:"module",name:bc});}),Um={};pn(Um,{default:()=>jm});async function Yp(e={}){var t=e,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");t.mountExternalData=(u,f)=>{u.startsWith("./")&&(u=u.substring(2)),(t.Uc||(t.Uc=new Map)).set(u,f);},t.unmountExternalData=()=>{delete t.Uc;},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:true}).buffer.constructor;let a=()=>{let u=f=>(...m)=>{let g=Xt;return m=f(...m),Xt!=g?new Promise((v,E)=>{ec={resolve:v,reject:E};}):m};(()=>{for(let f of ["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[f]=u(t[f]);})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0;};t.asyncInit=()=>{a?.();};var o,i,l=(u,f)=>{throw f},c=import.meta.url,d="";if(r||s){try{d=new URL(".",c).href;}catch{}s&&(i=u=>{var f=new XMLHttpRequest;return f.open("GET",u,false),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),o=async u=>{if(N(u))return new Promise((m,g)=>{var v=new XMLHttpRequest;v.open("GET",u,true),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?m(v.response):g(v.status);},v.onerror=g,v.send(null);});var f=await fetch(u,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)};}var h,_,p,w,y,b,x=console.log.bind(console),T=console.error.bind(console),C=x,A=T,S=false,N=u=>u.startsWith("file://");function M(){vr.buffer!=j.buffer&&re();}if(n){let u=function(f){try{var m=f.data,g=m.Oc;if(g==="load"){let v=[];self.onmessage=E=>v.push(E),b=()=>{postMessage({Oc:"loaded"});for(let E of v)u(E);self.onmessage=u;};for(let E of m.ce)t[E]&&!t[E].proxy||(t[E]=(...F)=>{postMessage({Oc:"callHandler",be:E,args:F});},E=="print"&&(C=t[E]),E=="printErr"&&(A=t[E]));vr=m.ie,re(),_=m.je,Oe(),Ma();}else if(g==="run"){((function(v){var E=(M(),L)[v+52>>>2>>>0];v=(M(),L)[v+56>>>2>>>0],rp(E,E-v),ne(E);}))(m.Nc),hc(m.Nc,0,0,1,0,0),Uf(),Jl(m.Nc),G||(B_(),G=!0);try{_C(m.ge,m.Wc);}catch(v){if(v!="unwind")throw v}}else m.target!=="setimmediate"&&(g==="checkMailbox"?G&&_a():g&&(A(`worker: received unknown command ${g}`),A(m)));}catch(v){throw J_(),v}};var G=false;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=u;}var j,Q,q,X,D,L,Y,te,I,z,R,H=false;function re(){var u=vr.buffer;t.HEAP8=j=new Int8Array(u),q=new Int16Array(u),t.HEAPU8=Q=new Uint8Array(u),X=new Uint16Array(u),t.HEAP32=D=new Int32Array(u),t.HEAPU32=L=new Uint32Array(u),Y=new Float32Array(u),te=new Float64Array(u),I=new BigInt64Array(u),z=new BigUint64Array(u);}function Ie(){H=true,n?b():hr._b();}function se(u){throw A(u="Aborted("+u+")"),S=true,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),y?.(u),u}function pt(){return {a:{f:pC,J:mC,k:gC,p:wC,l:yC,sa:vC,b:bC,ca:MC,Ja:Xf,q:xC,da:Zf,Za:e_,Fa:t_,Ha:r_,_a:s_,Xa:n_,Qa:a_,Wa:o_,oa:i_,Ga:l_,Xb:c_,Ya:u_,Yb:d_,db:kC,Da:EC,Sb:AC,Qb:SC,Ca:FC,M:LC,I:IC,Rb:OC,ja:$C,Tb:VC,Ta:UC,Vb:qC,Ka:WC,Ob:HC,ka:QC,Sa:Jl,ab:XC,U:ZC,n:nS,c:Xl,rb:aS,w:oS,L:iS,z:lS,j:cS,o:y_,sb:uS,G:dS,T:hS,h:fS,u:_S,m:pS,i:mS,Na:gS,Oa:wS,Pa:yS,La:x_,Ma:k_,Pb:T_,eb:bS,cb:kS,Y:TS,qb:ES,la:AS,bb:MS,fb:CS,$a:SS,Wb:PS,N:vS,gb:FS,X:LS,Ub:IS,nb:VS,C:US,ra:jS,qa:qS,pb:WS,W:HS,v:QS,mb:XS,lb:YS,kb:JS,ob:KS,jb:ZS,ib:eP,hb:tP,Ua:F_,Va:L_,Ia:jl,V:I_,na:O_,Ra:N_,ma:z_,Cb:dF,xa:aF,Db:uF,ya:nF,F:HP,e:OP,s:LP,x:FP,B:jP,Fb:tF,ba:eF,D:DP,za:rF,$:oF,ga:ZP,Gb:KP,Hb:JP,Ba:QP,Aa:YP,Ib:XP,wa:cF,aa:sF,d:IP,A:zP,r:NP,Bb:hF,t:RP,y:qP,H:BP,E:GP,K:WP,R:iF,ia:UP,_:lF,Jb:VP,Kb:$P,g:sP,a:vr,Nb:gs,Eb:nP,ha:aP,O:oP,pa:iP,Lb:lP,ta:cP,Q:uP,yb:dP,zb:hP,ua:fP,ea:_P,P:pP,Ea:mP,va:gP,Z:wP,wb:yP,Zb:vP,S:bP,Ab:MP,tb:xP,ub:TP,vb:EP,fa:AP,xb:CP,Mb:SP}}}async function Oe(){function u(g,v){var E=hr=g.exports;g={};for(let[F,O]of Object.entries(E))typeof O=="function"?(E=YC(O),g[F]=E):g[F]=O;return hr=g,hr=(function(){var F=hr,O=J=>ve=>J(ve)>>>0,U=J=>()=>J()>>>0;return (F=Object.assign({},F)).$b=O(F.$b),F.Cc=U(F.Cc),F.Ec=O(F.Ec),F.rd=(J=>(ve,Te)=>J(ve,Te)>>>0)(F.rd),F.wd=O(F.wd),F.xd=U(F.xd),F.Bd=O(F.Bd),F})(),$f.push(hr.id),D_=(g=hr).$b,B_=g.ac,t._OrtInit=g.bc,t._OrtGetLastError=g.cc,t._OrtCreateSessionOptions=g.dc,t._OrtAppendExecutionProvider=g.ec,t._OrtAddFreeDimensionOverride=g.fc,t._OrtAddSessionConfigEntry=g.gc,t._OrtReleaseSessionOptions=g.hc,t._OrtCreateSession=g.ic,t._OrtReleaseSession=g.jc,t._OrtGetInputOutputCount=g.kc,t._OrtGetInputOutputMetadata=g.lc,t._OrtFree=g.mc,t._OrtCreateTensor=g.nc,t._OrtGetTensorData=g.oc,t._OrtReleaseTensor=g.pc,t._OrtCreateRunOptions=g.qc,t._OrtAddRunConfigEntry=g.rc,t._OrtReleaseRunOptions=g.sc,t._OrtCreateBinding=g.tc,t._OrtBindInput=g.uc,t._OrtBindOutput=g.vc,t._OrtClearBoundOutputs=g.wc,t._OrtReleaseBinding=g.xc,t._OrtRunWithBinding=g.yc,t._OrtRun=g.zc,t._OrtEndProfiling=g.Ac,oc=t._OrtGetWebGpuDevice=g.Bc,va=g.Cc,Bt=t._free=g.Dc,Ms=t._malloc=g.Ec,R_=t._wgpuBufferRelease=g.Fc,G_=t._wgpuCreateInstance=g.Gc,$_=g.Hc,V_=g.Ic,U_=g.Jc,j_=g.Kc,q_=g.Lc,W_=g.Pc,H_=g.Zc,Q_=g._c,X_=g.$c,ic=g.bd,lc=g.cd,cc=g.dd,uc=g.ed,an=g.fd,dc=g.gd,Y_=g.hd,hc=g.kd,J_=g.ld,K_=g.md,Z_=g.nd,fc=g.od,ep=g.pd,tp=g.qd,_c=g.rd,fe=g.sd,on=g.td,rp=g.ud,ne=g.vd,ba=g.wd,ae=g.xd,sp=g.yd,pc=g.zd,np=g.Ad,ap=g.Bd,op=g.Cd,mc=g.Dd,ip=g.Ed,lp=g.Fd,cp=g.Gd,up=g.Hd,dp=g.Id,hp=g.Jd,fp=g.Kd,_p=g.Ld,pp=g.Md,mp=g.Nd,gp=g.Od,wp=g.Pd,yp=g.Qd,vp=g.Rd,bp=g.Td,Mp=g.Ud,xp=g.Vd,kp=g.Wd,Tp=g.Yd,Ep=g.Zd,Ap=g._d,Cp=g.$d,Sp=g.ae,Pp=g.oe,Fp=g.pe,Lp=g.qe,Ip=g.re,Op=g.se,Np=g.te,zp=g.ue,Dp=g.ve,Bp=g.we,Rp=g.xe,Gp=g.ye,$p=g.Ye,Vp=g.Ze,Up=g._e,jp=g.$e,_=v,hr}var f,m=pt();return t.instantiateWasm?new Promise(g=>{t.instantiateWasm(m,(v,E)=>{g(u(v,E));});}):n?u(new WebAssembly.Instance(_,pt()),_):(R??(R=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href),f=await(async function(g){var v=R;if(!h&&!N(v))try{var E=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(E,g)}catch(F){A(`wasm streaming compile failed: ${F}`),A("falling back to ArrayBuffer instantiation");}return (async function(F,O){try{var U=await(async function(J){if(!h)try{var ve=await o(J);return new Uint8Array(ve)}catch{}if(J==R&&h)J=new Uint8Array(h);else {if(!i)throw "both async and sync fetching of the wasm failed";J=i(J);}return J})(F);return await WebAssembly.instantiate(U,O)}catch(J){A(`failed to asynchronously prepare wasm: ${J}`),se(J);}})(v,g)})(m),u(f.instance,f.module))}class qe{constructor(f){k(this,"name","ExitStatus");this.message=`Program terminated with exit(${f})`,this.status=f;}}var mt=u=>{u.terminate(),u.onmessage=()=>{};},Pe=[],ye=0,We=null,Ht=u=>{yr.length==0&&(qf(),jf(yr[0]));var f=yr.pop();if(!f)return 6;rn.push(f),Or[u.Nc]=f,f.Nc=u.Nc;var m={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return f.postMessage(m,u.Yc),0},be=0,Se=(u,f,...m)=>{var g,v=16*m.length,E=ae(),F=ba(v),O=F>>>3;for(g of m)typeof g=="bigint"?((M(),I)[O++>>>0]=1n,(M(),I)[O++>>>0]=g):((M(),I)[O++>>>0]=0n,(M(),te)[O++>>>0]=g);return u=K_(u,0,v,F,f),ne(E),u};function gs(u){if(n)return Se(0,1,u);if(p=u,!(0<be)){for(var f of rn)mt(f);for(f of yr)mt(f);yr=[],rn=[],Or={},S=true;}l(0,new qe(u));}function tn(u){if(n)return Se(1,0,u);jl(u);}var jl=u=>{if(p=u,n)throw tn(u),"unwind";gs(u);},yr=[],rn=[],$f=[],Or={},Vf=u=>{var f=u.Nc;delete Or[f],yr.push(u),rn.splice(rn.indexOf(u),1),u.Nc=0,Z_(f);};function Uf(){$f.forEach(u=>u());}var jf=u=>new Promise(f=>{u.onmessage=v=>{var E=v.data;if(v=E.Oc,E.Vc&&E.Vc!=va()){var F=Or[E.Vc];F?F.postMessage(E,E.Yc):A(`Internal error! Worker sent a message "${v}" to target pthread ${E.Vc}, but that thread no longer exists!`);}else v==="checkMailbox"?_a():v==="spawnThread"?Ht(E):v==="cleanupThread"?gt(()=>{Vf(Or[E.he]);}):v==="loaded"?(u.loaded=true,f(u)):E.target==="setimmediate"?u.postMessage(E):v==="uncaughtException"?u.onerror(E.error):v==="callHandler"?t[E.be](...E.args):v&&A(`worker sent an unknown command ${v}`);},u.onerror=v=>{throw A(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var m,g=[];for(m of [])t.propertyIsEnumerable(m)&&g.push(m);u.postMessage({Oc:"load",ce:g,ie:vr,je:_});});function qf(){var u=new Worker((()=>{let f=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new f("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});yr.push(u);}var vr,_C=(u,f)=>{be=0,u=mc(u,f),0<be?p=u:fc(u);},ha=[],fa=0,rt=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function pC(u){var f=new ql(u>>>=0);return (M(),j)[f.Qc+12>>>0]==0&&(Wf(f,true),fa--),Hf(f,false),ha.push(f),ap(u)}var ws=0,mC=()=>{fe(0,0);var u=ha.pop();sp(u.Xc),ws=0;};function Wf(u,f){f=f?1:0,(M(),j)[u.Qc+12>>>0]=f;}function Hf(u,f){f=f?1:0,(M(),j)[u.Qc+13>>>0]=f;}class ql{constructor(f){this.Xc=f,this.Qc=f-24;}}var Wl=u=>{var f=ws;if(!f)return on(0),0;var m=new ql(f);(M(),L)[m.Qc+16>>>2>>>0]=f;var g=(M(),L)[m.Qc+4>>>2>>>0];if(!g)return on(0),f;for(var v of u){if(v===0||v===g)break;if(np(v,g,m.Qc+16))return on(v),f}return on(g),f};function gC(){return Wl([])}function wC(u){return Wl([u>>>0])}function yC(u,f,m,g){return Wl([u>>>0,f>>>0,m>>>0,g>>>0])}var vC=()=>{var u=ha.pop();u||se("no exception to throw");var f=u.Xc;throw (M(),j)[u.Qc+13>>>0]==0&&(ha.push(u),Hf(u,true),Wf(u,false),fa++),pc(f),ws=f};function bC(u,f,m){var g=new ql(u>>>=0);throw f>>>=0,m>>>=0,(M(),L)[g.Qc+16>>>2>>>0]=0,(M(),L)[g.Qc+4>>>2>>>0]=f,(M(),L)[g.Qc+8>>>2>>>0]=m,pc(u),fa++,ws=u}var MC=()=>fa;function Qf(u,f,m,g){return n?Se(2,1,u,f,m,g):Xf(u,f,m,g)}function Xf(u,f,m,g){if(u>>>=0,f>>>=0,m>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?Qf(u,f,m,g):(u={fe:m,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):Ht(u))}function xC(u){throw ws||(ws=u>>>0),ws}var Yf=globalThis.TextDecoder&&new TextDecoder,Jf=(u,f,m,g)=>{if(m=f+m,g)return m;for(;u[f]&&!(f>=m);)++f;return f},Kf=(u,f=0,m,g)=>{if(16<(m=Jf(u,f>>>=0,m,g))-f&&u.buffer&&Yf)return Yf.decode(u.buffer instanceof ArrayBuffer?u.subarray(f,m):u.slice(f,m));for(g="";f<m;){var v=u[f++];if(128&v){var E=63&u[f++];if((224&v)==192)g+=String.fromCharCode((31&v)<<6|E);else {var F=63&u[f++];65536>(v=(240&v)==224?(15&v)<<12|E<<6|F:(7&v)<<18|E<<12|F<<6|63&u[f++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v));}}else g+=String.fromCharCode(v);}return g},ys=(u,f,m)=>(u>>>=0)?Kf((M(),Q),u,f,m):"";function Zf(u,f,m){return n?Se(3,1,u,f,m):0}function e_(u,f){if(n)return Se(4,1,u,f)}function t_(u,f){if(n)return Se(5,1,u,f)}function r_(u,f,m){if(n)return Se(6,1,u,f,m)}function s_(u,f,m){return n?Se(7,1,u,f,m):0}function n_(u,f){if(n)return Se(8,1,u,f)}function a_(u,f,m){if(n)return Se(9,1,u,f,m)}function o_(u,f,m,g){if(n)return Se(10,1,u,f,m,g)}function i_(u,f,m,g){if(n)return Se(11,1,u,f,m,g)}function l_(u,f,m,g){if(n)return Se(12,1,u,f,m,g)}function c_(u){if(n)return Se(13,1,u)}function u_(u,f){if(n)return Se(14,1,u,f)}function d_(u,f,m){if(n)return Se(15,1,u,f,m)}var kC=()=>se(""),Qt=u=>{u>>>=0;for(var f="";;){var m=(M(),Q)[u++>>>0];if(!m)return f;f+=String.fromCharCode(m);}},Hl={},Ql={},vs=class extends Error{constructor(u){super(u),this.name="BindingError";}};function ir(u,f,m={}){return (function(g,v,E={}){var F=v.name;if(!g)throw new vs(`type "${F}" must have a positive integer typeid pointer`);if(Ql.hasOwnProperty(g)){if(E.de)return;throw new vs(`Cannot register type '${F}' twice`)}Ql[g]=v,Hl.hasOwnProperty(g)&&(v=Hl[g],delete Hl[g],v.forEach(O=>O()));})(u,f,m)}var h_=(u,f,m)=>{switch(f){case 1:return m?g=>(M(),j)[g>>>0]:g=>(M(),Q)[g>>>0];case 2:return m?g=>(M(),q)[g>>>1>>>0]:g=>(M(),X)[g>>>1>>>0];case 4:return m?g=>(M(),D)[g>>>2>>>0]:g=>(M(),L)[g>>>2>>>0];case 8:return m?g=>(M(),I)[g>>>3>>>0]:g=>(M(),z)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${f}): ${u}`)}};function EC(u,f,m,g,v){u>>>=0,m>>>=0,f=Qt(f>>>0);let E=F=>F;if(g=g===0n){let F=8*m;E=O=>BigInt.asUintN(F,O),v=E(v);}ir(u,{name:f,Mc:E,Sc:(F,O)=>(typeof O=="number"&&(O=BigInt(O)),O),Rc:h_(f,m,!g),Tc:null});}function AC(u,f,m,g){ir(u>>>=0,{name:f=Qt(f>>>0),Mc:function(v){return !!v},Sc:function(v,E){return E?m:g},Rc:function(v){return this.Mc((M(),Q)[v>>>0])},Tc:null});}var f_=[],Nr=[0,1,,1,null,1,true,1,false,1];function Xl(u){9<(u>>>=0)&&--Nr[u+1]==0&&(Nr[u]=void 0,f_.push(u));}var Pt=u=>{if(!u)throw new vs(`Cannot use deleted val. handle = ${u}`);return Nr[u]},Dt=u=>{switch(u){case void 0:return 2;case null:return 4;case true:return 6;case false:return 8;default:let f=f_.pop()||Nr.length;return Nr[f]=u,Nr[f+1]=1,f}};function Yl(u){return this.Mc((M(),L)[u>>>2>>>0])}var CC={name:"emscripten::val",Mc:u=>{var f=Pt(u);return Xl(u),f},Sc:(u,f)=>Dt(f),Rc:Yl,Tc:null};function SC(u){return ir(u>>>0,CC)}var PC=(u,f)=>{switch(f){case 4:return function(m){return this.Mc((M(),Y)[m>>>2>>>0])};case 8:return function(m){return this.Mc((M(),te)[m>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${u}`)}};function FC(u,f,m){m>>>=0,ir(u>>>=0,{name:f=Qt(f>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:PC(f,m),Tc:null});}function LC(u,f,m,g,v){u>>>=0,m>>>=0,f=Qt(f>>>0);let E=O=>O;if(g===0){var F=32-8*m;E=O=>O<<F>>>F,v=E(v);}ir(u,{name:f,Mc:E,Sc:(O,U)=>U,Rc:h_(f,m,g!==0),Tc:null});}function IC(u,f,m){function g(E){var F=(M(),L)[E>>>2>>>0];return E=(M(),L)[E+4>>>2>>>0],new v((M(),j).buffer,E,F)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];ir(u>>>=0,{name:m=Qt(m>>>0),Mc:g,Rc:g},{de:true});}var lr=(u,f,m)=>{var g=(M(),Q);if(f>>>=0,0<m){var v=f;m=f+m-1;for(var E=0;E<u.length;++E){var F=u.codePointAt(E);if(127>=F){if(f>=m)break;g[f++>>>0]=F;}else if(2047>=F){if(f+1>=m)break;g[f++>>>0]=192|F>>6,g[f++>>>0]=128|63&F;}else if(65535>=F){if(f+2>=m)break;g[f++>>>0]=224|F>>12,g[f++>>>0]=128|F>>6&63,g[f++>>>0]=128|63&F;}else {if(f+3>=m)break;g[f++>>>0]=240|F>>18,g[f++>>>0]=128|F>>12&63,g[f++>>>0]=128|F>>6&63,g[f++>>>0]=128|63&F,E++;}}g[f>>>0]=0,u=f-v;}else u=0;return u},cr=u=>{for(var f=0,m=0;m<u.length;++m){var g=u.charCodeAt(m);127>=g?f++:2047>=g?f+=2:55296<=g&&57343>=g?(f+=4,++m):f+=3;}return f};function OC(u,f){ir(u>>>=0,{name:f=Qt(f>>>0),Mc(m){var g=(M(),L)[m>>>2>>>0];return g=ys(m+4,g,true),Bt(m),g},Sc(m,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 vs("Cannot pass non-string to std::string");var E=v?cr(g):g.length,F=Ms(4+E+1),O=F+4;return (M(),L)[F>>>2>>>0]=E,v?lr(g,O,E+1):(M(),Q).set(g,O>>>0),m!==null&&m.push(Bt,F),F},Rc:Yl,Tc(m){Bt(m);}});}var __=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,NC=(u,f,m)=>{if(u>>>=1,16<(f=Jf((M(),X),u,f/2,m))-u&&__)return __.decode((M(),X).slice(u,f));for(m="";u<f;++u){var g=(M(),X)[u>>>0];m+=String.fromCharCode(g);}return m},zC=(u,f,m)=>{if(m??(m=2147483647),2>m)return 0;var g=f;m=(m-=2)<2*u.length?m/2:u.length;for(var v=0;v<m;++v){var E=u.charCodeAt(v);(M(),q)[f>>>1>>>0]=E,f+=2;}return (M(),q)[f>>>1>>>0]=0,f-g},DC=u=>2*u.length,BC=(u,f,m)=>{var g="";u>>>=2;for(var v=0;!(v>=f/4);v++){var E=(M(),L)[u+v>>>0];if(!E&&!m)break;g+=String.fromCodePoint(E);}return g},RC=(u,f,m)=>{if(f>>>=0,m??(m=2147483647),4>m)return 0;var g=f;m=g+m-4;for(var v=0;v<u.length;++v){var E=u.codePointAt(v);if(65535<E&&v++,(M(),D)[f>>>2>>>0]=E,(f+=4)+4>m)break}return (M(),D)[f>>>2>>>0]=0,f-g},GC=u=>{for(var f=0,m=0;m<u.length;++m)65535<u.codePointAt(m)&&m++,f+=4;return f};function $C(u,f,m){if(u>>>=0,f>>>=0,m=Qt(m>>>=0),f===2)var g=NC,v=zC,E=DC;else g=BC,v=RC,E=GC;ir(u,{name:m,Mc:F=>{var O=(M(),L)[F>>>2>>>0];return O=g(F+4,O*f,true),Bt(F),O},Sc:(F,O)=>{if(typeof O!="string")throw new vs(`Cannot pass non-string to C++ string type ${m}`);var U=E(O),J=Ms(4+U+f);return (M(),L)[J>>>2>>>0]=U/f,v(O,J+4,U+f),F!==null&&F.push(Bt,J),J},Rc:Yl,Tc(F){Bt(F);}});}function VC(u,f){ir(u>>>=0,{ee:true,name:f=Qt(f>>>0),Mc:()=>{},Sc:()=>{}});}function UC(u){hc(u>>>0,!s,1,!r,131072,false),Uf();}var gt=u=>{if(!S)try{if(u(),!(0<be))try{n?va()&&fc(p):jl(p);}catch(f){f instanceof qe||f=="unwind"||l(0,f);}}catch(f){f instanceof qe||f=="unwind"||l(0,f);}},jC=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Jl(u){u>>>=0,jC||(Atomics.waitAsync((M(),D),u>>>2,u).value.then(_a),u+=128,Atomics.store((M(),D),u>>>2,1));}var _a=()=>gt(()=>{var u=va();u&&(Jl(u),tp());});function qC(u,f){(u>>>=0)==f>>>0?setTimeout(_a):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=Or[u])&&u.postMessage({Oc:"checkMailbox"});}var Kl=[];function WC(u,f,m,g,v){for(f>>>=0,v>>>=0,Kl.length=0,m=v>>>3,g=v+g>>>3;m<g;){var E;E=(M(),I)[m++>>>0]?(M(),I)[m++>>>0]:(M(),te)[m++>>>0],Kl.push(E);}return (f?gc[f]:PP[u])(...Kl)}var HC=()=>{be=0;};function QC(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):Vf(Or[u]);}function XC(u){}var pa=u=>{try{u();}catch(f){se(f);}};function YC(u){var f=(...m)=>{ma.push(u);try{return u(...m)}finally{S||(ma.pop(),Xt&&br===1&&ma.length===0&&(br=0,be+=1,pa(Vp),typeof Fibers<"u"&&Fibers.Be()));}};return g_.set(u,f),f}var br=0,Xt=null,p_=0,ma=[],Zl=new Map,m_=new Map,g_=new Map,JC=0,ec=null,KC=[],w_=u=>(function(f){if(!S){if(br===0){var m=false,g=false;f((v=0)=>{if(!S&&(p_=v,m=true,g)){br=2,pa(()=>Up(Xt)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=false;try{var E=(function(){var U=(M(),D)[Xt+8>>>2>>>0];return U=m_.get(U),U=g_.get(U),--be,U()})();}catch(U){E=U,v=true;}var F=false;if(!Xt){var O=ec;O&&(ec=null,(v?O.reject:O.resolve)(E),F=true);}if(v&&!F)throw E}}),g=true,m||(br=1,Xt=(function(){var v=Ms(65548),E=v+12;if((M(),L)[v>>>2>>>0]=E,(M(),L)[v+4>>>2>>>0]=E+65536,E=ma[0],!Zl.has(E)){var F=JC++;Zl.set(E,F),m_.set(F,E);}return E=Zl.get(E),(M(),D)[v+8>>>2>>>0]=E,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),pa(()=>$p(Xt)));}else br===2?(br=0,pa(jp),Bt(Xt),Xt=null,KC.forEach(gt)):se(`invalid state: ${br}`);return p_}})(f=>{u().then(f);});function ZC(u){return u>>>=0,w_(async()=>{var f=await Pt(u);return Dt(f)})}var tc=[],eS=u=>{var f=tc.length;return tc.push(u),f},tS=(u,f)=>{for(var m=Array(u),g=0;g<u;++g){var v=g,E=(M(),L)[f+4*g>>>2>>>0],F=Ql[E];if(F===void 0)throw u=`parameter ${g}`,E=D_(E),f=Qt(E),Bt(E),new vs(`${u} has unknown type ${f}`);m[v]=F;}return m},rS=(u,f,m)=>{var g=[];return u=u(g,m),g.length&&((M(),L)[f>>>2>>>0]=Dt(g)),u},sS={},ga=u=>{var f=sS[u];return f===void 0?Qt(u):f};function nS(u,f,m){var[g,...v]=tS(u,f>>>0);f=g.Sc.bind(g);var E=v.map(U=>U.Rc.bind(U));u--;var F={toValue:Pt};switch(u=E.map((U,J)=>{var ve=`argFromPtr${J}`;return F[ve]=U,`${ve}(args${J?"+"+8*J:""})`}),m){case 0:var O="toValue(handle)";break;case 2:O="new (toValue(handle))";break;case 3:O="";break;case 1:F.getStringOrSymbol=ga,O="toValue(handle)[getStringOrSymbol(methodName)]";}return O+=`(${u})`,g.ee||(F.toReturnWire=f,F.emval_returnValue=rS,O=`return emval_returnValue(toReturnWire, destructorsRef, ${O})`),O=`return function (handle, methodName, destructorsRef, args) {
|
|
2
|
+
${O}
|
|
3
|
+
}`,m=new Function(Object.keys(F),O)(...Object.values(F)),O=`methodCaller<(${v.map(U=>U.name)}) => ${g.name}>`,eS(Object.defineProperty(m,"name",{value:O}))}function aS(u,f){return f>>>=0,(u=Pt(u>>>0))==Pt(f)}function oS(u){return (u>>>=0)?(u=ga(u),Dt(globalThis[u])):Dt(globalThis)}function iS(u){return u=ga(u>>>0),Dt(t[u])}function lS(u,f){return f>>>=0,u=Pt(u>>>0),f=Pt(f),Dt(u[f])}function cS(u){9<(u>>>=0)&&(Nr[u+1]+=1);}function y_(u,f,m,g,v){return tc[u>>>0](f>>>0,m>>>0,g>>>0,v>>>0)}function uS(u,f,m,g,v){return y_(u>>>0,f>>>0,m>>>0,g>>>0,v>>>0)}function dS(){return Dt([])}function hS(u){u=Pt(u>>>0);for(var f=Array(u.length),m=0;m<u.length;m++)f[m]=u[m];return Dt(f)}function fS(u){return Dt(ga(u>>>0))}function _S(){return Dt({})}function pS(u){for(var f=Pt(u>>>=0);f.length;){var m=f.pop();f.pop()(m);}Xl(u);}function mS(u,f,m){f>>>=0,m>>>=0,u=Pt(u>>>0),f=Pt(f),m=Pt(m),u[f]=m;}function gS(u,f){u=rt(u),f>>>=0,u=new Date(1e3*u),(M(),D)[f>>>2>>>0]=u.getUTCSeconds(),(M(),D)[f+4>>>2>>>0]=u.getUTCMinutes(),(M(),D)[f+8>>>2>>>0]=u.getUTCHours(),(M(),D)[f+12>>>2>>>0]=u.getUTCDate(),(M(),D)[f+16>>>2>>>0]=u.getUTCMonth(),(M(),D)[f+20>>>2>>>0]=u.getUTCFullYear()-1900,(M(),D)[f+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(M(),D)[f+28>>>2>>>0]=u;}var v_=u=>u%4==0&&(u%100!=0||u%400==0),b_=[0,31,60,91,121,152,182,213,244,274,305,335],M_=[0,31,59,90,120,151,181,212,243,273,304,334];function wS(u,f){u=rt(u),f>>>=0,u=new Date(1e3*u),(M(),D)[f>>>2>>>0]=u.getSeconds(),(M(),D)[f+4>>>2>>>0]=u.getMinutes(),(M(),D)[f+8>>>2>>>0]=u.getHours(),(M(),D)[f+12>>>2>>>0]=u.getDate(),(M(),D)[f+16>>>2>>>0]=u.getMonth(),(M(),D)[f+20>>>2>>>0]=u.getFullYear()-1900,(M(),D)[f+24>>>2>>>0]=u.getDay();var m=(v_(u.getFullYear())?b_:M_)[u.getMonth()]+u.getDate()-1|0;(M(),D)[f+28>>>2>>>0]=m,(M(),D)[f+36>>>2>>>0]=-60*u.getTimezoneOffset(),m=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(m!=g&&u.getTimezoneOffset()==Math.min(g,m)),(M(),D)[f+32>>>2>>>0]=u;}function yS(u){u>>>=0;var f=new Date((M(),D)[u+20>>>2>>>0]+1900,(M(),D)[u+16>>>2>>>0],(M(),D)[u+12>>>2>>>0],(M(),D)[u+8>>>2>>>0],(M(),D)[u+4>>>2>>>0],(M(),D)[u>>>2>>>0],0),m=(M(),D)[u+32>>>2>>>0],g=f.getTimezoneOffset(),v=new Date(f.getFullYear(),6,1).getTimezoneOffset(),E=new Date(f.getFullYear(),0,1).getTimezoneOffset(),F=Math.min(E,v);return 0>m?(M(),D)[u+32>>>2>>>0]=+(v!=E&&F==g):0<m!=(F==g)&&(v=Math.max(E,v),f.setTime(f.getTime()+6e4*((0<m?F:v)-g))),(M(),D)[u+24>>>2>>>0]=f.getDay(),m=(v_(f.getFullYear())?b_:M_)[f.getMonth()]+f.getDate()-1|0,(M(),D)[u+28>>>2>>>0]=m,(M(),D)[u>>>2>>>0]=f.getSeconds(),(M(),D)[u+4>>>2>>>0]=f.getMinutes(),(M(),D)[u+8>>>2>>>0]=f.getHours(),(M(),D)[u+12>>>2>>>0]=f.getDate(),(M(),D)[u+16>>>2>>>0]=f.getMonth(),(M(),D)[u+20>>>2>>>0]=f.getYear(),u=f.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function x_(u,f,m,g,v,E,F){return n?Se(16,1,u,f,m,g,v,E,F):-52}function k_(u,f,m,g,v,E){if(n)return Se(17,1,u,f,m,g,v,E)}var sn={},vS=()=>performance.timeOrigin+performance.now();function T_(u,f){if(n)return Se(18,1,u,f);if(sn[u]&&(clearTimeout(sn[u].id),delete sn[u]),!f)return 0;var m=setTimeout(()=>{delete sn[u],gt(()=>ep(u,performance.timeOrigin+performance.now()));},f);return sn[u]={id:m,Ae:f},0}function bS(u,f,m,g){u>>>=0,f>>>=0,m>>>=0,g>>>=0;var v=new Date().getFullYear(),E=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var F=Math.max(E,v);(M(),L)[u>>>2>>>0]=60*F,(M(),D)[f>>>2>>>0]=+(E!=v),u=(f=O=>{var U=Math.abs(O);return `UTC${0<=O?"-":"+"}${String(Math.floor(U/60)).padStart(2,"0")}${String(U%60).padStart(2,"0")}`})(E),f=f(v),v<E?(lr(u,m,17),lr(f,g,17)):(lr(u,g,17),lr(f,m,17));}var MS=()=>Date.now();function kS(u,f,m){if(m>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else {u=performance.timeOrigin+performance.now();}return u=Math.round(1e6*u),(M(),I)[m>>>3>>>0]=BigInt(u),0}var rc=[],E_=(u,f)=>{rc.length=0;for(var m;m=(M(),Q)[u++>>>0];){var g=m!=105;f+=(g&=m!=112)&&f%8?4:0,rc.push(m==112?(M(),L)[f>>>2>>>0]:m==106?(M(),I)[f>>>3>>>0]:m==105?(M(),D)[f>>>2>>>0]:(M(),te)[f>>>3>>>0]),f+=g?8:4;}return rc};function TS(u,f,m){return u>>>=0,f=E_(f>>>0,m>>>0),gc[u](...f)}function ES(u,f,m){return u>>>=0,f=E_(f>>>0,m>>>0),gc[u](...f)}var AS=()=>{};function CS(u,f){return A(ys(u>>>0,f>>>0))}var SS=()=>{throw be+=1,"unwind"};function PS(){return 4294901760}var FS=()=>1,LS=()=>navigator.hardwareConcurrency;function IS(u){u>>>=0;var f=(M(),Q).length;if(u<=f||4294901760<u)return false;for(var m=1;4>=m;m*=2){var g=f*(1+.2/m);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-vr.buffer.byteLength+65535)/65536|0;try{vr.grow(g),re();var v=1;break e}catch{}v=void 0;}if(v)return true}return false}var Yt=u=>{var f=cr(u)+1,m=ba(f);return lr(u,m,f),m},sc=(u,f)=>{(M(),L)[u>>>2>>>0]=f;var m=(M(),L)[u>>>2>>>0];(M(),L)[u+4>>>2>>>0]=(f-m)/4294967296;},nn=u=>(M(),L)[u>>>2>>>0]+4294967296*(M(),D)[u+4>>>2>>>0],st=[],OS=(u,f)=>{st[u>>>0]=f;},ur=[],wa=[],bs=(u,f)=>{wa[u]=new Promise(m=>f.finally(()=>m(u)));},Z=u=>{if(u)return st[u>>>0]},NS=(u,f)=>{for(u=(M(),L)[u>>>2>>>0];u;u=(M(),L)[u>>>2>>>0])f[(M(),D)[u+4>>>2>>>0]](u);},ya=(u,f,m)=>{(M(),L)[u>>>2>>>0]=f,(M(),L)[u+4>>>2>>>0]=m;},A_=u=>{var f=(M(),L)[u>>>2>>>0];return u=(M(),L)[u+4>>>2>>>0],ys(f,u)},dr=u=>{var f=(M(),L)[u>>>2>>>0];return u=(M(),L)[u+4>>>2>>>0],f?ys(f,u):u===0?"":void 0},zS=u=>{var f=dr(u+4),m=(m=(M(),L)[u+12>>>2>>>0])?Z(m):"auto";if(u+=16){var g=Z((M(),L)[u+4>>>2>>>0]),v=(M(),L)[u+16>>>2>>>0],E=(M(),L)[u+20>>>2>>>0];if(v){for(var F={},O=0;O<v;++O){var U=E+24*O;F[A_(U+4)]=(M(),te)[U+16>>>3>>>0];}v=F;}else v=void 0;u={module:g,constants:v,entryPoint:dr(u+8)};}else u=void 0;return {label:f,layout:m,compute:u}},C_=(u,f)=>{function m(g,v){g=u[g],(M(),L)[f+v>>>2>>>0]=g;}m("maxTextureDimension1D",4),m("maxTextureDimension2D",8),m("maxTextureDimension3D",12),m("maxTextureArrayLayers",16),m("maxBindGroups",20),m("maxBindGroupsPlusVertexBuffers",24),m("maxBindingsPerBindGroup",28),m("maxDynamicUniformBuffersPerPipelineLayout",32),m("maxDynamicStorageBuffersPerPipelineLayout",36),m("maxSampledTexturesPerShaderStage",40),m("maxSamplersPerShaderStage",44),m("maxStorageBuffersPerShaderStage",48),m("maxStorageTexturesPerShaderStage",52),m("maxUniformBuffersPerShaderStage",56),m("minUniformBufferOffsetAlignment",80),m("minStorageBufferOffsetAlignment",84),sc(f+64,u.maxUniformBufferBindingSize),sc(f+72,u.maxStorageBufferBindingSize),m("maxVertexBuffers",88),sc(f+96,u.maxBufferSize),m("maxVertexAttributes",104),m("maxVertexBufferArrayStride",108),m("maxInterStageShaderVariables",112),m("maxColorAttachments",116),m("maxColorAttachmentBytesPerSample",120),m("maxComputeWorkgroupStorageSize",124),m("maxComputeInvocationsPerWorkgroup",128),m("maxComputeWorkgroupSizeX",132),m("maxComputeWorkgroupSizeY",136),m("maxComputeWorkgroupSizeZ",140),m("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&m("maxImmediateSize",148);},DS=[,"validation","out-of-memory","internal"],BS=[,"compatibility","core"],S_={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"},RS=[,"low-power","high-performance"],GS=[,"occlusion","timestamp"],$S={undefined:1,unknown:1,destroyed:2};function VS(u,f,m,g,v,E){f=rt(f),m=rt(m),g>>>=0,v>>>=0,E>>>=0;var F=Z(u>>>0);if(u={},E){var O=(M(),L)[E+12>>>2>>>0];if(O){var U=(M(),L)[E+16>>>2>>>0];u.requiredFeatures=Array.from((M(),L).subarray(U>>>2>>>0,U+4*O>>>2>>>0),ee=>S_[ee]);}var J=(M(),L)[E+20>>>2>>>0];if(J){let ee=function(wt,Ke,zr=false){Ke=J+Ke,(Ke=(M(),L)[Ke>>>2>>>0])==4294967295||zr&&Ke==0||(Fe[wt]=Ke);},Je=function(wt,Ke){Ke=J+Ke;var zr=(M(),L)[Ke>>>2>>>0],fF=(M(),L)[Ke+4>>>2>>>0];zr==4294967295&&fF==4294967295||(Fe[wt]=nn(Ke));};var Fe={};ee("maxTextureDimension1D",4),ee("maxTextureDimension2D",8),ee("maxTextureDimension3D",12),ee("maxTextureArrayLayers",16),ee("maxBindGroups",20),ee("maxBindGroupsPlusVertexBuffers",24),ee("maxDynamicUniformBuffersPerPipelineLayout",32),ee("maxDynamicStorageBuffersPerPipelineLayout",36),ee("maxSampledTexturesPerShaderStage",40),ee("maxSamplersPerShaderStage",44),ee("maxStorageBuffersPerShaderStage",48),ee("maxStorageTexturesPerShaderStage",52),ee("maxUniformBuffersPerShaderStage",56),ee("minUniformBufferOffsetAlignment",80),ee("minStorageBufferOffsetAlignment",84),Je("maxUniformBufferBindingSize",64),Je("maxStorageBufferBindingSize",72),ee("maxVertexBuffers",88),Je("maxBufferSize",96),ee("maxVertexAttributes",104),ee("maxVertexBufferArrayStride",108),ee("maxInterStageShaderVariables",112),ee("maxColorAttachments",116),ee("maxColorAttachmentBytesPerSample",120),ee("maxComputeWorkgroupStorageSize",124),ee("maxComputeInvocationsPerWorkgroup",128),ee("maxComputeWorkgroupSizeX",132),ee("maxComputeWorkgroupSizeY",136),ee("maxComputeWorkgroupSizeZ",140),ee("maxComputeWorkgroupsPerDimension",144),ee("maxImmediateSize",148,true),u.requiredLimits=Fe;}(O=(M(),L)[E+24>>>2>>>0])&&(O={label:dr(O+4)},u.defaultQueue=O),u.label=dr(E+4);}be+=1,bs(f,F.requestDevice(u).then(ee=>{--be,gt(()=>{st[v>>>0]=ee.queue,st[g>>>0]=ee,be+=1,bs(m,ee.lost.then(Je=>{gt(()=>{ee.onuncapturederror=()=>{};var wt=ae(),Ke=Yt(Je.message);lc(m,$S[Je.reason],Ke),ne(wt);}),--be;})),ee.onuncapturederror=Je=>{var wt=5;Je.error instanceof GPUValidationError?wt=2:Je.error instanceof GPUOutOfMemoryError?wt=3:Je.error instanceof GPUInternalError&&(wt=4);var Ke=ae();Je=Yt(Je.error.message),Y_(g,wt,Je),ne(Ke);},"adapterInfo"in ee||(ee.adapterInfo=F.info),dc(f,1,g,0);});},ee=>{--be,gt(()=>{var Je=ae(),wt=Yt(ee.message);dc(f,3,g,wt),m&&lc(m,4,wt),ne(Je);});}));}function US(u){var f=Z(u>>>=0),m=ur[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete ur[u];}f.destroy();}function jS(u,f,m){m>>>=0;var g=Z(u>>>=0);m==4294967295&&(m=void 0);try{var v=g.getMappedRange(f>>>0,m);}catch{return 0}var E=_c(16,v.byteLength);return (M(),Q).set(new Uint8Array(v),E>>>0),ur[u].push(()=>Bt(E)),E}function qS(u,f,m){m>>>=0;var g=Z(u>>>=0);m==4294967295&&(m=void 0);try{var v=g.getMappedRange(f>>>0,m);}catch{return 0}var E=_c(16,v.byteLength);return (M(),Q).fill(0,E,v.byteLength),ur[u].push(()=>{new Uint8Array(v).set((M(),Q).subarray(E>>>0,E+v.byteLength>>>0)),Bt(E);}),E}function WS(u,f,m,g,v){u>>>=0,f=rt(f),m=rt(m),v>>>=0;var E=Z(u);ur[u]=[],v==4294967295&&(v=void 0),be+=1,bs(f,E.mapAsync(m,g>>>0,v).then(()=>{--be,gt(()=>{cc(f,1,0);});},F=>{--be,gt(()=>{ae();var O=Yt(F.message);cc(f,F.name==="AbortError"?4:F.name==="OperationError"?3:0,O),delete ur[u];});}));}function HS(u){var f=Z(u>>>=0),m=ur[u];if(m){for(var g=0;g<m.length;++g)m[g]();delete ur[u],f.unmap();}}function QS(u){delete st[u>>>0];}function XS(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=!!(M(),L)[f+32>>>2>>>0];f={label:dr(f+4),usage:(M(),L)[f+16>>>2>>>0],size:nn(f+24),mappedAtCreation:g},u=Z(u);try{var v=u.createBuffer(f);}catch{return false}return st[m>>>0]=v,g&&(ur[m]=[]),true}function YS(u,f,m,g){u>>>=0,f=rt(f),g>>>=0,m=zS(m>>>0),u=Z(u),be+=1,bs(f,u.createComputePipelineAsync(m).then(v=>{--be,gt(()=>{st[g>>>0]=v,ic(f,1,g,0);});},v=>{--be,gt(()=>{var E=ae(),F=Yt(v.message);ic(f,v.reason==="validation"?3:v.reason==="internal"?4:0,g,F),ne(E);});}));}function JS(u,f,m){u>>>=0,f>>>=0,m>>>=0;var g=(M(),L)[f>>>2>>>0],v=(M(),D)[g+4>>>2>>>0];f={label:dr(f+4),code:""},v===2&&(f.code=A_(g+8)),u=Z(u).createShaderModule(f),st[m>>>0]=u;}var KS=u=>{(u=Z(u)).onuncapturederror=null,u.destroy();};function ZS(u,f){f=rt(f),u=Z(u>>>0),be+=1,bs(f,u.popErrorScope().then(m=>{--be,gt(()=>{var g=5;m?m instanceof GPUValidationError?g=2:m instanceof GPUOutOfMemoryError?g=3:m instanceof GPUInternalError&&(g=4):g=1;var v=ae(),E=m?Yt(m.message):0;uc(f,1,g,E),ne(v);});},m=>{--be,gt(()=>{var g=ae(),v=Yt(m.message);uc(f,1,5,v),ne(g);});}));}function eP(u,f,m,g){if(f=rt(f),g>>>=0,m>>>=0){var v={featureLevel:BS[(M(),D)[m+4>>>2>>>0]],powerPreference:RS[(M(),D)[m+8>>>2>>>0]],forceFallbackAdapter:!!(M(),L)[m+12>>>2>>>0]};(u=(M(),L)[m>>>2>>>0])!==0&&(M(),v.De=!!(M(),L)[u+8>>>2>>>0]);}"gpu"in navigator?(be+=1,bs(f,navigator.gpu.requestAdapter(v).then(E=>{--be,gt(()=>{if(E)st[g>>>0]=E,an(f,1,g,0);else {var F=ae(),O=Yt("WebGPU not available on this browser (requestAdapter returned null)");an(f,3,g,O),ne(F);}});},E=>{--be,gt(()=>{var F=ae(),O=Yt(E.message);an(f,4,g,O),ne(F);});}))):(v=ae(),u=Yt("WebGPU not available on this browser (navigator.gpu is not available)"),an(f,3,g,u),ne(v));}function tP(u,f,m){return u>>>=0,f>>>=0,m>>>=0,w_(async()=>{var g=[];if(m){var v=(M(),D)[m>>>2>>>0];g.length=f+1,g[f]=new Promise(O=>setTimeout(O,v,0));}else g.length=f;for(var E=0;E<f;++E){var F=nn(u+8*E);if(!(F in wa))return F;g[E]=wa[F];}return g=await Promise.race(g),delete wa[g],g})}var nc,ac={},P_=()=>{if(!nc){var u,f={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 ac)ac[u]===void 0?delete f[u]:f[u]=ac[u];var m=[];for(u in f)m.push(`${u}=${f[u]}`);nc=m;}return nc};function F_(u,f){if(n)return Se(19,1,u,f);u>>>=0,f>>>=0;var m,g=0,v=0;for(m of P_()){var E=f+g;(M(),L)[u+v>>>2>>>0]=E,g+=lr(m,E,1/0)+1,v+=4;}return 0}function L_(u,f){if(n)return Se(20,1,u,f);u>>>=0,f>>>=0;var m=P_();for(var g of((M(),L)[u>>>2>>>0]=m.length,u=0,m))u+=cr(g)+1;return (M(),L)[f>>>2>>>0]=u,0}function I_(u){return n?Se(21,1,u):52}function O_(u,f,m,g){return n?Se(22,1,u,f,m,g):52}function N_(u,f,m,g){return n?Se(23,1,u,f,m,g):70}var rP=[null,[],[]];function z_(u,f,m,g){if(n)return Se(24,1,u,f,m,g);f>>>=0,m>>>=0,g>>>=0;for(var v=0,E=0;E<m;E++){var F=(M(),L)[f>>>2>>>0],O=(M(),L)[f+4>>>2>>>0];f+=8;for(var U=0;U<O;U++){var J=u,ve=(M(),Q)[F+U>>>0],Te=rP[J];ve===0||ve===10?((J===1?C:A)(Kf(Te)),Te.length=0):Te.push(ve);}v+=O;}return (M(),L)[g>>>2>>>0]=v,0}function sP(u){return u>>>0}function nP(u,f){return C_(Z(u>>>0).limits,f>>>0),1}function aP(u,f){return Z(u>>>0).features.has(S_[f])}function oP(u){return BigInt(Z(u>>>0).size)}function iP(u){return BigInt(Z(u>>>0).usage)}function lP(u,f){if(u>>>=0,f>>>=0){var m=dr(f+4);m={label:m,timestampWrites:f=(f=(M(),L)[f+12>>>2>>>0])!==0?{querySet:Z((M(),L)[f+4>>>2>>>0]),beginningOfPassWriteIndex:(M(),L)[f+8>>>2>>>0],endOfPassWriteIndex:(M(),L)[f+12>>>2>>>0]}:void 0};}return f=Z(u),u=q_(0),m=f.beginComputePass(m),st[u>>>0]=m,u}function cP(u,f,m,g){m=rt(m),(g=rt(g))==-1&&(g=void 0),(u=Z(u>>>0)).clearBuffer(Z(f>>>0),m,g);}function uP(u,f,m,g,v,E){m=rt(m),v=rt(v),E=rt(E),Z(u>>>0).copyBufferToBuffer(Z(f>>>0),m,Z(g>>>0),v,E);}function dP(u){var f=Z(u>>>0);return u=U_(0),f=f.finish(),st[u>>>0]=f,u}function hP(u,f,m,g,v,E){E=rt(E),Z(u>>>0).resolveQuerySet(Z(f>>>0),m,g,Z(v>>>0),E);}function fP(u,f,m,g){Z(u>>>0).dispatchWorkgroups(f,m,g);}function _P(u,f,m){m=rt(m),Z(u>>>0).dispatchWorkgroupsIndirect(Z(f>>>0),m);}function pP(u){Z(u>>>0).end();}function mP(u,f,m,g,v){g>>>=0,v>>>=0,u=Z(u>>>0),m=Z(m>>>0),g==0?u.setBindGroup(f,m):u.setBindGroup(f,m,(M(),L),v>>>2,g);}function gP(u,f){Z(u>>>0).setPipeline(Z(f>>>0));}function wP(u,f,m){Z(u>>>0).Ce(Z(f>>>0),m);}function yP(u,f){var m=Z(u>>>0);return u=V_(0),f=m.getBindGroupLayout(f),st[u>>>0]=f,u}function vP(u,f){function m(v){var E=(M(),L)[v+8>>>2>>>0],F=(M(),L)[v+32>>>2>>>0],O=(M(),L)[v+36>>>2>>>0],U=0;return NS(v,{327681:J=>{U=(M(),L)[J+8>>>2>>>0];}}),E?((F=nn(v+24))==-1&&(F=void 0),E={buffer:Z(E),offset:nn(v+16),size:F}):E=Z(F||O||U),{binding:(M(),L)[v+4>>>2>>>0],resource:E}}u>>>=0,f={label:dr(4+(f>>>=0)),layout:Z((M(),L)[f+12>>>2>>>0]),entries:(function(v,E){for(var F=[],O=0;O<v;++O)F.push(m(E+40*O));return F})((M(),L)[f+16>>>2>>>0],(M(),L)[f+20>>>2>>>0])},u=Z(u);var g=$_(0);return OS(g,u.createBindGroup(f)),g}function bP(u,f){var m;return u>>>=0,(f>>>=0)&&(m={label:dr(f+4)}),f=Z(u),u=j_(0),m=f.createCommandEncoder(m),st[u>>>0]=m,u}function MP(u,f){u>>>=0,f>>>=0,f={type:GS[(M(),D)[f+12>>>2>>>0]],count:(M(),L)[f+16>>>2>>>0]};var m=Z(u);return u=W_(0),f=m.createQuerySet(f),st[u>>>0]=f,u}function xP(u,f){u=Z(u>>>0).adapterInfo,f>>>=0,(M(),L)[f+52>>>2>>>0]=u.subgroupMinSize,(M(),L)[f+56>>>2>>>0]=u.subgroupMaxSize;var m=u.vendor+u.architecture+u.device+u.description,g=cr(m)+1,v=Ms(g);return v&&lr(m,v,g),m=v,g=cr(u.vendor),ya(f+4,m,g),m+=g,g=cr(u.architecture),ya(f+12,m,g),m+=g,g=cr(u.device),ya(f+20,m,g),ya(f+28,m+g,cr(u.description)),(M(),D)[f+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(M(),D)[f+40>>>2>>>0]=u,(M(),L)[f+44>>>2>>>0]=0,(M(),L)[f+48>>>2>>>0]=0,1}var kP={"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 TP(u,f){f>>>=0;var m=Z(u>>>0);u=Ms(4*m.features.size);var g=0,v=0;for(let E of m.features)0<=(m=kP[E])&&((M(),D)[u+g>>>2>>>0]=m,g+=4,v++);(M(),L)[f+4>>>2>>>0]=u,(M(),L)[f>>>2>>>0]=v;}function EP(u,f){return C_(Z(u>>>0).limits,f>>>0),1}function AP(u,f){Z(u>>>0).pushErrorScope(DS[f]);}function CP(u,f,m){f>>>=0,m>>>=0,u=Z(u>>>0),f=Array.from((M(),D).subarray(m>>>2>>>0,m+4*f>>>2>>>0),g=>Z(g)),u.submit(f);}function SP(u,f,m,g,v){m=rt(m),g>>>=0,v>>>=0,u=Z(u>>>0),f=Z(f>>>0),g=(M(),Q).subarray(g>>>0,g+v>>>0),u.writeBuffer(f,m,g,0,v);}n||(function(){for(var u=t.numThreads-1;u--;)qf();Pe.push(async()=>{var f=(async function(){if(!n)return Promise.all(yr.map(jf))})();ye++,await f,--ye==0&&We&&(f=We,We=null,f());});})(),n||(vr=new WebAssembly.Memory({initial:256,maximum:65536,shared:true}),re()),t.wasmBinary&&(h=t.wasmBinary),t.stackSave=()=>ae(),t.stackRestore=u=>ne(u),t.stackAlloc=u=>ba(u),t.setValue=function(u,f,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case "i1":case "i8":(M(),j)[u>>>0]=f;break;case "i16":(M(),q)[u>>>1>>>0]=f;break;case "i32":(M(),D)[u>>>2>>>0]=f;break;case "i64":(M(),I)[u>>>3>>>0]=BigInt(f);break;case "float":(M(),Y)[u>>>2>>>0]=f;break;case "double":(M(),te)[u>>>3>>>0]=f;break;case "*":(M(),L)[u>>>2>>>0]=f;break;default:se(`invalid type for setValue: ${m}`);}},t.getValue=function(u,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case "i1":case "i8":return (M(),j)[u>>>0];case "i16":return (M(),q)[u>>>1>>>0];case "i32":return (M(),D)[u>>>2>>>0];case "i64":return (M(),I)[u>>>3>>>0];case "float":return (M(),Y)[u>>>2>>>0];case "double":return (M(),te)[u>>>3>>>0];case "*":return (M(),L)[u>>>2>>>0];default:se(`invalid type for getValue: ${f}`);}},t.UTF8ToString=ys,t.stringToUTF8=lr,t.lengthBytesUTF8=cr;var D_,B_,oc,va,Bt,Ms,R_,G_,$_,V_,U_,j_,q_,W_,H_,Q_,X_,ic,lc,cc,uc,an,dc,Y_,hc,J_,K_,Z_,fc,ep,tp,_c,fe,on,rp,ne,ba,ae,sp,pc,np,ap,op,mc,ip,lp,cp,up,dp,hp,fp,_p,pp,mp,gp,wp,yp,vp,bp,Mp,xp,kp,Tp,Ep,Ap,Cp,Sp,Pp,Fp,Lp,Ip,Op,Np,zp,Dp,Bp,Rp,Gp,$p,Vp,Up,jp,hr,PP=[gs,tn,Qf,Zf,e_,t_,r_,s_,n_,a_,o_,i_,l_,c_,u_,d_,x_,k_,T_,F_,L_,I_,O_,N_,z_],gc={969132:(u,f,m,g,v)=>{if(t===void 0||!t.Uc)return 1;if((u=ys(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=t.Uc.get(u)))return 2;if(f=Number(f>>>0),m=Number(m>>>0),g=Number(g>>>0),f+m>u.byteLength)return 3;try{let E=u.subarray(f,f+m);switch(v){case 0:(M(),Q).set(E,g>>>0);break;case 1:t.ad?t.ad(g,E):t.ne(g,E);break;default:return 4}return 0}catch{return 4}},969956:(u,f,m)=>{t.Sd(u,(M(),Q).subarray(f>>>0,f+m>>>0));},970020:()=>t.le(),970062:u=>{t.jd(u);},970099:()=>typeof wasmOffsetConverter<"u"};function FP(u,f,m,g){var v=ae();try{return _p(u,f,m,g)}catch(E){if(ne(v),E!==E+0)throw E;fe(1,0);}}function LP(u,f,m){var g=ae();try{return dp(u,f,m)}catch(v){if(ne(g),v!==v+0)throw v;fe(1,0);}}function IP(u){var f=ae();try{ip(u);}catch(m){if(ne(f),m!==m+0)throw m;fe(1,0);}}function OP(u,f){var m=ae();try{return mc(u,f)}catch(g){if(ne(m),g!==g+0)throw g;fe(1,0);}}function NP(u,f,m){var g=ae();try{op(u,f,m);}catch(v){if(ne(g),v!==v+0)throw v;fe(1,0);}}function zP(u,f){var m=ae();try{pp(u,f);}catch(g){if(ne(m),g!==g+0)throw g;fe(1,0);}}function DP(u,f,m,g,v,E,F){var O=ae();try{return up(u,f,m,g,v,E,F)}catch(U){if(ne(O),U!==U+0)throw U;fe(1,0);}}function BP(u,f,m,g,v,E){var F=ae();try{lp(u,f,m,g,v,E);}catch(O){if(ne(F),O!==O+0)throw O;fe(1,0);}}function RP(u,f,m,g){var v=ae();try{fp(u,f,m,g);}catch(E){if(ne(v),E!==E+0)throw E;fe(1,0);}}function GP(u,f,m,g,v,E,F){var O=ae();try{gp(u,f,m,g,v,E,F);}catch(U){if(ne(O),U!==U+0)throw U;fe(1,0);}}function $P(u,f,m,g,v,E,F){var O=ae();try{wp(u,f,m,g,v,E,F);}catch(U){if(ne(O),U!==U+0)throw U;fe(1,0);}}function VP(u,f,m,g,v,E,F,O){var U=ae();try{Ap(u,f,m,g,v,E,F,O);}catch(J){if(ne(U),J!==J+0)throw J;fe(1,0);}}function UP(u,f,m,g,v,E,F,O,U,J,ve,Te){var Fe=ae();try{yp(u,f,m,g,v,E,F,O,U,J,ve,Te);}catch(ee){if(ne(Fe),ee!==ee+0)throw ee;fe(1,0);}}function jP(u,f,m,g,v){var E=ae();try{return mp(u,f,m,g,v)}catch(F){if(ne(E),F!==F+0)throw F;fe(1,0);}}function qP(u,f,m,g,v){var E=ae();try{cp(u,f,m,g,v);}catch(F){if(ne(E),F!==F+0)throw F;fe(1,0);}}function WP(u,f,m,g,v,E,F,O){var U=ae();try{hp(u,f,m,g,v,E,F,O);}catch(J){if(ne(U),J!==J+0)throw J;fe(1,0);}}function HP(u){var f=ae();try{return Cp(u)}catch(m){if(ne(f),m!==m+0)throw m;fe(1,0);}}function QP(u,f,m){var g=ae();try{return Sp(u,f,m)}catch(v){if(ne(g),v!==v+0)throw v;fe(1,0);}}function XP(u,f){var m=ae();try{return Gp(u,f)}catch(g){if(ne(m),g!==g+0)throw g;return fe(1,0),0n}}function YP(u){var f=ae();try{return vp(u)}catch(m){if(ne(f),m!==m+0)throw m;return fe(1,0),0n}}function JP(u,f,m,g){var v=ae();try{return Pp(u,f,m,g)}catch(E){if(ne(v),E!==E+0)throw E;fe(1,0);}}function KP(u,f,m,g,v){var E=ae();try{return Fp(u,f,m,g,v)}catch(F){if(ne(E),F!==F+0)throw F;fe(1,0);}}function ZP(u,f,m,g,v,E){var F=ae();try{return Lp(u,f,m,g,v,E)}catch(O){if(ne(F),O!==O+0)throw O;fe(1,0);}}function eF(u,f,m,g,v,E){var F=ae();try{return Tp(u,f,m,g,v,E)}catch(O){if(ne(F),O!==O+0)throw O;fe(1,0);}}function tF(u,f,m,g,v,E){var F=ae();try{return Ip(u,f,m,g,v,E)}catch(O){if(ne(F),O!==O+0)throw O;fe(1,0);}}function rF(u,f,m,g,v,E,F,O){var U=ae();try{return Ep(u,f,m,g,v,E,F,O)}catch(J){if(ne(U),J!==J+0)throw J;fe(1,0);}}function sF(u,f,m,g,v){var E=ae();try{return Op(u,f,m,g,v)}catch(F){if(ne(E),F!==F+0)throw F;return fe(1,0),0n}}function nF(u,f,m,g){var v=ae();try{return Np(u,f,m,g)}catch(E){if(ne(v),E!==E+0)throw E;fe(1,0);}}function aF(u,f,m,g){var v=ae();try{return zp(u,f,m,g)}catch(E){if(ne(v),E!==E+0)throw E;fe(1,0);}}function oF(u,f,m,g,v,E,F,O,U,J,ve,Te){var Fe=ae();try{return Dp(u,f,m,g,v,E,F,O,U,J,ve,Te)}catch(ee){if(ne(Fe),ee!==ee+0)throw ee;fe(1,0);}}function iF(u,f,m,g,v,E,F,O,U,J,ve){var Te=ae();try{Bp(u,f,m,g,v,E,F,O,U,J,ve);}catch(Fe){if(ne(Te),Fe!==Fe+0)throw Fe;fe(1,0);}}function lF(u,f,m,g,v,E,F,O,U,J,ve,Te,Fe,ee,Je,wt){var Ke=ae();try{Rp(u,f,m,g,v,E,F,O,U,J,ve,Te,Fe,ee,Je,wt);}catch(zr){if(ne(Ke),zr!==zr+0)throw zr;fe(1,0);}}function cF(u,f,m){var g=ae();try{return Mp(u,f,m)}catch(v){if(ne(g),v!==v+0)throw v;return fe(1,0),0n}}function uF(u,f,m){var g=ae();try{return bp(u,f,m)}catch(v){if(ne(g),v!==v+0)throw v;fe(1,0);}}function dF(u,f,m){var g=ae();try{return xp(u,f,m)}catch(v){if(ne(g),v!==v+0)throw v;fe(1,0);}}function hF(u,f,m,g){var v=ae();try{kp(u,f,m,g);}catch(E){if(ne(v),E!==E+0)throw E;fe(1,0);}}function Ma(){if(0<ye)We=Ma;else if(n)w?.(t),Ie();else {for(var u=Pe;0<u.length;)u.shift()(t);0<ye?We=Ma:(t.calledRun=true,S||(Ie(),w?.(t)));}}return n||(hr=await Oe(),Ma()),t.PTR_SIZE=4,t.webgpuInit=u=>{let f=new WeakMap,m,g,v=1;t.webgpuRegisterDevice=O=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(O){var U=f.get(O);if(!U){let J=((ve,Te=0)=>{var Fe=X_(Te);return Te=Q_(Te,Fe),st[Fe>>>0]=ve.queue,st[Te>>>0]=ve,Te})(O,U=G_(0));U=[v++,U,J],f.set(O,U);}return m=O,g=U[0],U}m=void 0,g=0;};let E=new Map;t.webgpuOnCreateSession=O=>{if(g!==void 0){var U=g;if(g=void 0,O){let J=oc(U);E.set(O,J),U===0&&u(m??Z(J));}m=void 0;}},t.webgpuOnReleaseSession=O=>{E.delete(O);};let F=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(O,U,J)=>{if(J)return O[F]=[J,NaN],J;if(J=O[F])return J[1]++,J[0];if((U=E.get(U))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return U=((ve,Te=0)=>(ve.mapState==="unmapped"||se(),Te=H_(Te),st[Te>>>0]=ve,Te))(O,U),O[F]=[U,1],U},t.webgpuUnregisterBuffer=O=>{let U=O[F];if(!U)throw Error("Buffer is not registered");U[1]--,U[1]===0&&(R_(U[0]),delete O[F]);},t.webgpuGetBuffer=O=>Z(O),t.webgpuCreateDownloader=(O,U,J)=>{if((J=E.get(J))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let ve=Z(J),Te=16*Math.ceil(Number(U)/16);return async()=>{let Fe=ve.createBuffer({size:Te,usage:9});try{let ee=ve.createCommandEncoder();return ee.copyBufferToBuffer(O,0,Fe,0,Te),ve.queue.submit([ee.finish()]),await Fe.mapAsync(GPUMapMode.READ),Fe.getMappedRange().slice(0,U)}finally{Fe.destroy();}}},t.ad=(O,U)=>{var J=U.buffer;let ve=U.byteOffset,Te=U.byteLength;if(U=16*Math.ceil(Number(Te)/16),O=Z(O),!m){var Fe=oc(g);m=Z(Fe);}let ee=(Fe=m.createBuffer({mappedAtCreation:true,size:U,usage:6})).getMappedRange();new Uint8Array(ee).set(new Uint8Array(J,ve,Te)),Fe.unmap(),(J=m.createCommandEncoder()).copyBufferToBuffer(Fe,0,O,0,U),m.queue.submit([J.finish()]),Fe.destroy();};},t.webnnInit=u=>{let f=u[0];[t.le,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.ke,t.webnnEnableTraceEvent]=u.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.ke,t.webnnOnRunStart=m=>f.onRunStart(m),t.webnnOnRunEnd=f.onRunEnd.bind(f),t.webnnOnReleaseSession=m=>{f.onReleaseSession(m);},t.webnnCreateMLTensorDownloader=(m,g)=>f.createMLTensorDownloader(m,g),t.webnnRegisterMLTensor=(m,g,v,E)=>f.registerMLTensor(m,g,v,E),t.webnnCreateMLContext=m=>f.createMLContext(m),t.webnnRegisterMLConstant=(m,g,v,E,F,O)=>f.registerMLConstant(m,g,v,E,F,t.Uc,O),t.webnnRegisterGraphInput=f.registerGraphInput.bind(f),t.webnnIsGraphInput=f.isGraphInput.bind(f),t.webnnRegisterGraphOutput=f.registerGraphOutput.bind(f),t.webnnIsGraphOutput=f.isGraphOutput.bind(f),t.webnnCreateTemporaryTensor=f.createTemporaryTensor.bind(f),t.webnnIsGraphInputOutputTypeSupported=f.isGraphInputOutputTypeSupported.bind(f);},H?t:new Promise((u,f)=>{w=u,y=f;})}var jm,Jp,OF=_e(()=>{jm=Yp,Jp=globalThis.self?.name?.startsWith("em-pthread"),Jp&&Yp();}),xc,Rc,Kp,xt,qm,Ea,Zp,em,kc,tm,Tc,Wm,Ec,Hm,Qc=_e(()=>{Hc(),xc=typeof location>"u"?void 0:location.origin,Rc=import.meta.url>"file:"&&import.meta.url<"file;",Kp=()=>{if(Rc){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,xc).href}return import.meta.url},xt=Kp(),qm=()=>{if(xt&&!xt.startsWith("blob:"))return xt.substring(0,xt.lastIndexOf("/")+1)},Ea=(e,t)=>{try{let r=t??xt;return (r?new URL(e,r):new URL(e)).origin===xc}catch{return false}},Zp=(e,t)=>{let r=t??xt;try{return (r?new URL(e,r):new URL(e)).href}catch{return}},em=(e,t)=>`${t??"./"}${e}`,kc=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},tm=async e=>(await import(e)).default,Tc=(IF(),La($m)).default,Wm=async()=>{if(!xt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ea(xt))return [void 0,Tc()];let e=await kc(xt);return [e,Tc(e)]},Ec=(OF(),La(Um)).default,Hm=async(e,t,r,s)=>{let n=Ec&&!(e||t);if(n)if(xt)n=Ea(xt)||s&&!r;else if(s&&!r)n=true;else throw new Error("cannot determine the script source URL.");if(n)return [void 0,Ec];{let a="ort-wasm-simd-threaded.asyncify.mjs",o=e??Zp(a,t),i=r&&o&&!Ea(o,t),l=i?await kc(o):o??em(a,t);return [i?l:void 0,await tm(l)]}};}),Ac,Aa,cn,Cc,rm,sm,nm,Xc,Ce,Wr=_e(()=>{Qc(),Aa=false,cn=false,Cc=false,rm=()=>{if(typeof SharedArrayBuffer>"u")return false;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 false}},sm=()=>{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 false}},nm=()=>{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 false}},Xc=async e=>{if(Aa)return Promise.resolve();if(cn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Cc)throw new Error("previous call to 'initializeWebAssembly()' failed.");cn=true;let t=e.initTimeout,r=e.numThreads;if(e.simd!==false){if(e.simd==="relaxed"){if(!nm())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!sm())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=rm();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let n=e.wasmPaths,a=typeof n=="string"?n:void 0,o=n?.mjs,i=o?.href??o,l=n?.wasm,c=l?.href??l,d=e.wasmBinary,[h,_]=await Hm(i,a,r>1,!!d||!!c),p=false,w=[];if(t>0&&w.push(new Promise(y=>{setTimeout(()=>{p=true,y();},t);})),w.push(new Promise((y,b)=>{let x={numThreads:r};if(d)x.wasmBinary=d,x.locateFile=T=>T;else if(c||a)x.locateFile=T=>c??a+T;else if(i&&i.indexOf("blob:")!==0)x.locateFile=T=>new URL(T,i).href;else if(h){let T=qm();T&&(x.locateFile=C=>T+C);}_(x).then(T=>{cn=false,Aa=true,Ac=T,y(),h&&URL.revokeObjectURL(h);},T=>{cn=false,Cc=true,b(T);});})),await Promise.race(w),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ce=()=>{if(Aa&&Ac)return Ac;throw new Error("WebAssembly is not initialized yet.")};}),kt,Oa,Me,Yc=_e(()=>{Wr(),kt=(e,t)=>{let r=Ce(),s=r.lengthBytesUTF8(e)+1,n=r._malloc(s);return r.stringToUTF8(e,n,s),t.push(n),n},Oa=(e,t,r,s)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e);}Object.entries(e).forEach(([n,a])=>{let o=t?t+n:n;if(typeof a=="object")Oa(a,o+".",r,s);else if(typeof a=="string"||typeof a=="number")s(o,a.toString());else if(typeof a=="boolean")s(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)});},Me=e=>{let t=Ce(),r=t.stackSave();try{let s=t.PTR_SIZE,n=t.stackAlloc(2*s);t._OrtGetLastError(n,n+s);let a=Number(t.getValue(n,s===4?"i32":"i64")),o=t.getValue(n+s,"*"),i=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r);}};}),Qm,NF=_e(()=>{Wr(),Yc(),Qm=e=>{let t=Ce(),r=0,s=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let a=0;return e?.tag!==void 0&&(a=kt(e.tag,s)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,a),r===0&&Me("Can't create run options."),e?.extra!==void 0&&Oa(e.extra,"",new WeakSet,(o,i)=>{let l=kt(o,s),c=kt(i,s);t._OrtAddRunConfigEntry(r,l,c)!==0&&Me(`Can't set a run config entry: ${o} - ${i}.`);}),[r,s]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),s.forEach(o=>t._free(o)),a}};}),am,om,im,Ca,xr,lm,Xm,zF=_e(()=>{Wr(),Yc(),am=e=>{switch(e){case "disabled":return 0;case "basic":return 1;case "extended":return 2;case "layout":return 3;case "all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},om=e=>{switch(e){case "sequential":return 0;case "parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},im=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=false);},Ca=(e,t,r,s)=>{let n=kt(t,s),a=kt(r,s);Ce()._OrtAddSessionConfigEntry(e,n,a)!==0&&Me(`Can't set a session config entry: ${t} - ${r}.`);},xr=(e,t,r,s)=>{let n=kt(t,s),a=kt(r,s);e.push([n,a]);},lm=async(e,t,r)=>{let s=t.executionProviders;for(let n of s){let a=typeof n=="string"?n:n.name,o=[];switch(a){case "webnn":if(a="WEBNN",typeof n!="string"){let h=n?.deviceType;h&&Ca(e,"deviceType",h,r);}break;case "webgpu":{a="WebGPU";let h;if(typeof n!="string"){let p=n;if(p.device)if(typeof GPUDevice<"u"&&p.device instanceof GPUDevice)h=p.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=t;if(typeof w=="boolean"&&w&&xr(o,"enableGraphCapture","1",r),typeof p.preferredLayout=="string"&&xr(o,"preferredLayout",p.preferredLayout,r),p.forceCpuNodeNames){let y=Array.isArray(p.forceCpuNodeNames)?p.forceCpuNodeNames:[p.forceCpuNodeNames];xr(o,"forceCpuNodeNames",y.join(`
|
|
4
|
+
`),r);}p.validationMode&&xr(o,"validationMode",p.validationMode,r);}let _=Ce().webgpuRegisterDevice(h);if(_){let[p,w,y]=_;xr(o,"deviceId",p.toString(),r),xr(o,"webgpuInstance",w.toString(),r),xr(o,"webgpuDevice",y.toString(),r);}}break;case "wasm":case "cpu":continue;default:throw new Error(`not supported execution provider: ${a}`)}let i=kt(a,r),l=o.length,c=0,d=0;if(l>0){c=Ce()._malloc(l*Ce().PTR_SIZE),r.push(c),d=Ce()._malloc(l*Ce().PTR_SIZE),r.push(d);for(let h=0;h<l;h++)Ce().setValue(c+h*Ce().PTR_SIZE,o[h][0],"*"),Ce().setValue(d+h*Ce().PTR_SIZE,o[h][1],"*");}await Ce()._OrtAppendExecutionProvider(e,i,c,d,l)!==0&&Me(`Can't append execution provider: ${a}.`);}},Xm=async e=>{let t=Ce(),r=0,s=[],n=e||{};im(n);try{let a=am(n.graphOptimizationLevel??"all"),o=om(n.executionMode??"sequential"),i=typeof n.logId=="string"?kt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let d=typeof n.optimizedModelFilePath=="string"?kt(n.optimizedModelFilePath,s):0;if(r=t._OrtCreateSessionOptions(a,!!n.enableCpuMemArena,!!n.enableMemPattern,o,!!n.enableProfiling,0,i,l,c,d),r===0&&Me("Can't create session options."),n.executionProviders&&await lm(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Ca(r,"enableGraphCapture",n.enableGraphCapture.toString(),s);}if(n.freeDimensionOverrides)for(let[h,_]of Object.entries(n.freeDimensionOverrides)){if(typeof h!="string")throw new Error(`free dimension override name must be a string: ${h}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let p=kt(h,s);t._OrtAddFreeDimensionOverride(r,p,_)!==0&&Me(`Can't set a free dimension override: ${h} - ${_}.`);}return n.extra!==void 0&&Oa(n.extra,"",new WeakSet,(h,_)=>{Ca(r,h,_,s);}),[r,s]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&Me("Can't release session options."),s.forEach(o=>t._free(o)),a}};}),$r,Fa,ks,_n,Na,Jc,Kc,Gc,Ts=_e(()=>{$r=e=>{switch(e){case "int8":return 3;case "uint8":return 2;case "bool":return 9;case "int16":return 5;case "uint16":return 4;case "int32":return 6;case "uint32":return 12;case "float16":return 10;case "float32":return 1;case "float64":return 11;case "string":return 8;case "int64":return 7;case "uint64":return 13;case "int4":return 22;case "uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Fa=e=>{switch(e){case 3:return "int8";case 2:return "uint8";case 9:return "bool";case 5:return "int16";case 4:return "uint16";case 6:return "int32";case 12:return "uint32";case 10:return "float16";case 1:return "float32";case 11:return "float64";case 8:return "string";case 7:return "int64";case 13:return "uint64";case 22:return "int4";case 21:return "uint4";default:throw new Error(`unsupported data type: ${e}`)}},ks=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof t=="number"?t:t.reduce((n,a)=>n*a,1);return r>0?Math.ceil(s*r):void 0},_n=e=>{switch(e){case "float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case "float32":return Float32Array;case "uint8":return Uint8Array;case "int8":return Int8Array;case "uint16":return Uint16Array;case "int16":return Int16Array;case "int32":return Int32Array;case "bool":return Uint8Array;case "float64":return Float64Array;case "uint32":return Uint32Array;case "int64":return BigInt64Array;case "uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Na=e=>{switch(e){case "verbose":return 0;case "info":return 1;case "warning":return 2;case "error":return 3;case "fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},Jc=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Kc=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Gc=e=>{switch(e){case "none":return 0;case "cpu":return 1;case "cpu-pinned":return 2;case "texture":return 3;case "gpu-buffer":return 4;case "ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}};}),Zc,Ym=_e(()=>{Hc(),Zc=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),a;try{a=new ArrayBuffer(s);}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer;}else throw i}let o=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(a,o,c).set(l),o+=c;}return new Uint8Array(a,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};}),Jm,DF=_e(()=>{Ts(),Jm=(e,t)=>new(_n(t))(e);}),cm,um,dm,hm,Km,fm,ht,Zm=_e(()=>{Ts(),cm=["V","I","W","E","F"],um=(e,t)=>{console.log(`[${cm[e]},${new Date().toISOString()}]${t}`);},Km=(e,t)=>{dm=e,hm=t;},fm=(e,t)=>{let r=Na(e),s=Na(dm);r>=s&&um(r,typeof t=="function"?t():t);},ht=(...e)=>{hm&&fm(...e);};}),Sc,$c,Pc,_m,Fc,pm,Lc,Ic,Oc,mm,eg,BF=_e(()=>{Ts(),Zm(),Sc=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),$c=(e,t)=>{if(t==="int32")return e;let r=Sc.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);let s=r/8;if(e.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=e.byteLength/s,a=new(_n(t))(e.buffer,e.byteOffset,n);switch(t){case "int64":case "uint64":{let o=new Int32Array(n);for(let i=0;i<n;i++){let l=a[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");o[i]=Number(l);}return new Uint8Array(o.buffer)}case "int8":case "uint8":case "uint32":{if(t==="uint32"&&a.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let o=Int32Array.from(a,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Pc=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,r);switch(t){case "int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case "uint64":{if(s.some(a=>a<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case "int8":{if(s.some(a=>a<-128||a>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case "uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case "uint32":{if(s.some(a=>a<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},_m=1,Fc=()=>_m++,pm=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Lc=(e,t)=>{let r=Sc.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((s,n)=>s*n)*r/8):0},Ic=class{constructor(e){this.isDataConverted=false;let{sessionId:t,context:r,tensor:s,dataType:n,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=a,this.fallbackDataType=o;}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Lc(this.dataType,this.tensorShape)}destroy(){ht("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy();}write(e){this.mlContext.writeTensor(this.mlTensor,e);}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=Pc(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(e){this.isDataConverted=e;}},Oc=class{constructor(e,t){this.tensorManager=e,this.wrapper=t;}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0);}async ensureTensor(e,t,r,s){let n=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=pm.get(t),!o||a?.input.dataTypes.includes(o))throw new Error(`WebNN backend does not support data type: ${t}`);ht("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`);}if(this.wrapper){if(this.wrapper.canReuseTensor(n,t,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Lc(t,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read());}this.tensorManager.releaseTensor(this.wrapper);}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,r,i,true,true,o),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=$c(e,this.wrapper.type),this.wrapper.setIsDataConverted(true);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else ht("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t);}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Pc(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},mm=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set;}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Fc();return this.tensorTrackersById.set(e,new Oc(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper));}async ensureTensor(e,t,r,s,n){ht("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let a=this.tensorTrackersById.get(t);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(e,r,s,n)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t);}async download(e,t){ht("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e);}registerTensor(e,t,r,s){let n=this.getMLContext(e),a=Fc(),o=new Ic({sessionId:e,context:n,tensor:t,dataType:r,shape:s});return this.tensorTrackersById.set(a,new Oc(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,r,s,n,a,o){let i=this.getMLContext(e);for(let[c,d]of this.freeTensors.entries())if(d.canReuseTensor(i,t,r)){ht("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}`);let h=this.freeTensors.splice(c,1)[0];return h.sessionId=e,h}ht("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:o??t,shape:r,dimensions:r,usage:s,writable:n,readable:a});return new Ic({sessionId:e,context:i,tensor:l,dataType:t,shape:r,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e);}},eg=(...e)=>new mm(...e);}),tg={};pn(tg,{WebNNBackend:()=>rg});var un,gm,rg,RF=_e(()=>{Ts(),Wr(),DF(),BF(),Zm(),un=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),gm=(e,t)=>{if(e===t)return true;if(e===void 0||t===void 0)return false;let r=Object.keys(e).sort(),s=Object.keys(t).sort();return r.length===s.length&&r.every((n,a)=>n===s[a]&&e[n]===t[n])},rg=class{constructor(e){this.tensorManager=eg(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,Km(e.logLevel,!!e.debug);}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){ht("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e;}onRunEnd(e){ht("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)ht("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0;}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let t=this.mlContextCache.findIndex(r=>gm(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[]);}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let s=this.mlContextCache.findIndex(n=>n.mlContext===t);s!==-1&&this.mlContextCache.splice(s,1);}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ht("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);}async ensureTensor(e,t,r,s,n){let a=un.get(r);if(!a)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,s,n)}async createTemporaryTensor(e,t,r){ht("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let s=un.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,s,r,false);let a=this.temporarySessionTensorIds.get(e);return a?a.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,t){if(!Ce().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ht("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t);}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return Jm(r,t)}}registerMLTensor(e,t,r,s){let n=un.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let a=this.tensorManager.registerTensor(e,t,n,s);return ht("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,r,s,n,a,o=false){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=a.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(t,t+r).buffer,d;switch(n.dataType){case "float32":d=new Float32Array(c);break;case "float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case "int32":d=new Int32Array(c);break;case "uint32":d=new Uint32Array(c);break;case "int64":if(o){let h=$c(new Uint8Array(c),"int64");d=new Int32Array(h.buffer),n.dataType="int32";}else d=new BigInt64Array(c);break;case "uint64":d=new BigUint64Array(c);break;case "int8":d=new Int8Array(c);break;case "int4":case "uint4":case "uint8":d=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return ht("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${o?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,d)}registerGraphInput(e){this.temporaryGraphInputs.push(e);}registerGraphOutput(e){this.temporaryGraphOutputs.push(e);}isGraphInput(e,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):false}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):false}isGraphInputOutputTypeSupported(e,t,r=true){let s=un.get($r(t)),n=this.mlOpSupportLimitsBySessionId.get(e);return typeof s>"u"?false:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}};}),wm,eu,tu,kr,ym,Nc,za,ru,su,zc,nu,au,ou,sg=_e(()=>{qr(),NF(),zF(),Ts(),Wr(),Yc(),Ym(),wm=(e,t)=>{Ce()._OrtInit(e,t)!==0&&Me("Can't initialize onnxruntime.");},eu=async e=>{wm(e.wasm.numThreads,Na(e.logLevel));},tu=async(e,t)=>{Ce().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else {let s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=e.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(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&&Ce().webgpuInit(s=>{e.webgpu.device=s;}),t==="webnn"){let s=new(RF(),La(tg)).WebNNBackend(e);Ce().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,a,o,i,l)=>s.ensureTensor(n,a,o,i,l),(n,a)=>{s.uploadTensor(n,a);},async(n,a)=>s.downloadTensor(n,a),(n,a)=>s.registerMLContext(n,a),!!e.trace]);}},kr=new Map,ym=e=>{let t=Ce(),r=t.stackSave();try{let s=t.PTR_SIZE,n=t.stackAlloc(2*s);t._OrtGetInputOutputCount(e,n,n+s)!==0&&Me("Can't get session input/output count.");let a=s===4?"i32":"i64";return [Number(t.getValue(n,a)),Number(t.getValue(n+s,a))]}finally{t.stackRestore(r);}},Nc=(e,t)=>{let r=Ce(),s=r.stackSave(),n=0;try{let a=r.PTR_SIZE,o=r.stackAlloc(2*a);r._OrtGetInputOutputMetadata(e,t,o,o+a)!==0&&Me("Can't get session input/output metadata.");let i=Number(r.getValue(o,"*"));n=Number(r.getValue(o+a,"*"));let l=r.HEAP32[n/4];if(l===0)return [i,0];let c=r.HEAPU32[n/4+1],d=[];for(let h=0;h<c;h++){let _=Number(r.getValue(n+8+h*a,"*"));d.push(_!==0?r.UTF8ToString(_):Number(r.getValue(n+8+(h+c)*a,"*")));}return [i,l,d]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n);}},za=e=>{let t=Ce(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},ru=async(e,t)=>{let r,s,n=Ce();Array.isArray(e)?[r,s]=e:e.buffer===n.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=za(e);let a=0,o=0,i=0,l=[],c=[],d=[];try{if([o,l]=await Xm(t),t?.externalData&&n.mountExternalData){let A=[];for(let S of t.externalData){let N=typeof S=="string"?S:S.path;A.push(Zc(typeof S=="string"?S:S.data).then(M=>{n.mountExternalData(N,M);}));}await Promise.all(A);}for(let A of t?.executionProviders??[])if((typeof A=="string"?A:A.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof A!="string"){let S=A,N=S?.context,M=S?.gpuDevice,$=S?.deviceType,G=S?.powerPreference;N?n.currentContext=N:M?n.currentContext=await n.webnnCreateMLContext(M):n.currentContext=await n.webnnCreateMLContext({deviceType:$,powerPreference:G});}else n.currentContext=await n.webnnCreateMLContext();break}a=await n._OrtCreateSession(r,s,o),n.webgpuOnCreateSession?.(a),a===0&&Me("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(a,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[h,_]=ym(a),p=!!t?.enableGraphCapture,w=[],y=[],b=[],x=[],T=[];for(let A=0;A<h;A++){let[S,N,M]=Nc(a,A);S===0&&Me("Can't get an input name."),c.push(S);let $=n.UTF8ToString(S);w.push($),b.push(N===0?{name:$,isTensor:!1}:{name:$,isTensor:!0,type:Fa(N),shape:M});}for(let A=0;A<_;A++){let[S,N,M]=Nc(a,A+h);S===0&&Me("Can't get an output name."),d.push(S);let $=n.UTF8ToString(S);y.push($),x.push(N===0?{name:$,isTensor:!1}:{name:$,isTensor:!0,type:Fa(N),shape:M});{if(p&&t?.preferredOutputLocation===void 0){T.push("gpu-buffer");continue}let G=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[$]??"cpu",j=n.webnnIsGraphOutput;if(G==="cpu"&&j&&j(a,$)){T.push("ml-tensor-cpu-output");continue}if(G!=="cpu"&&G!=="cpu-pinned"&&G!=="gpu-buffer"&&G!=="ml-tensor")throw new Error(`Not supported preferred output location: ${G}.`);if(p&&G!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${G}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);T.push(G);}}let C=null;return T.some(A=>A==="gpu-buffer"||A==="ml-tensor"||A==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(a),i===0&&Me("Can't create IO binding."),C={handle:i,outputPreferredLocations:T,outputPreferredLocationsEncoded:T.map(A=>A==="ml-tensor-cpu-output"?"ml-tensor":A).map(A=>Gc(A))}),kr.set(a,[a,c,d,C,p,!1]),[a,w,y,b,x]}catch(h){throw c.forEach(_=>n._OrtFree(_)),d.forEach(_=>n._OrtFree(_)),i!==0&&n._OrtReleaseBinding(i)!==0&&Me("Can't release IO binding."),a!==0&&n._OrtReleaseSession(a)!==0&&Me("Can't release session."),h}finally{n._free(r),o!==0&&n._OrtReleaseSessionOptions(o)!==0&&Me("Can't release session options."),l.forEach(h=>n._free(h)),n.unmountExternalData?.();}},su=e=>{let t=Ce(),r=kr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,a,o,i]=r;o&&(i&&t._OrtClearBoundOutputs(o.handle)!==0&&Me("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&Me("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),n.forEach(l=>t._OrtFree(l)),a.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(s)!==0&&Me("Can't release session."),kr.delete(e);},zc=async(e,t,r,s,n,a,o=false)=>{if(!e){t.push(0);return}let i=Ce(),l=i.PTR_SIZE,c=e[0],d=e[1],h=e[3],_=h,p,w;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let x=e[2].gpuBuffer;w=ks($r(c),d);{let T=i.webgpuRegisterBuffer;if(!T)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');p=T(x,s);}}else if(h==="ml-tensor"){let x=e[2].mlTensor;w=ks($r(c),d);let T=i.webnnRegisterMLTensor;if(!T)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');p=T(s,x,$r(c),d);}else {let x=e[2];if(Array.isArray(x)){w=l*x.length,p=i._malloc(w),r.push(p);for(let T=0;T<x.length;T++){if(typeof x[T]!="string")throw new TypeError(`tensor data at index ${T} is not a string`);i.setValue(p+T*l,kt(x[T],r),"*");}}else {let T=i.webnnIsGraphInput,C=i.webnnIsGraphOutput;if(c!=="string"&&T&&C){let A=i.UTF8ToString(n);if(T(s,A)||C(s,A)){let S=$r(c);w=ks(S,d),_="ml-tensor";let N=i.webnnCreateTemporaryTensor,M=i.webnnUploadTensor;if(!N||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let $=await N(s,S,d);M($,new Uint8Array(x.buffer,x.byteOffset,x.byteLength)),p=$;}else w=x.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(x.buffer,x.byteOffset,w),p);}else w=x.byteLength,p=i._malloc(w),r.push(p),i.HEAPU8.set(new Uint8Array(x.buffer,x.byteOffset,w),p);}}let y=i.stackSave(),b=i.stackAlloc(4*d.length);try{d.forEach((T,C)=>i.setValue(b+C*l,T,l===4?"i32":"i64"));let x=i._OrtCreateTensor($r(c),p,w,b,d.length,Gc(_));x===0&&Me(`Can't create tensor for input/output. session=${s}, index=${a}.`),t.push(x);}finally{i.stackRestore(y);}},nu=async(e,t,r,s,n,a)=>{let o=Ce(),i=o.PTR_SIZE,l=kr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],d=l[1],h=l[2],_=l[3],p=l[4],w=l[5],y=t.length,b=s.length,x=0,T=[],C=[],A=[],S=[],N=[],M=o.stackSave(),$=o.stackAlloc(y*i),G=o.stackAlloc(y*i),j=o.stackAlloc(b*i),Q=o.stackAlloc(b*i);try{[x,T]=Qm(a),Er("wasm prepareInputOutputTensor");for(let L=0;L<y;L++)await zc(r[L],C,S,e,d[t[L]],t[L],p);for(let L=0;L<b;L++)await zc(n[L],A,S,e,h[s[L]],y+s[L],p);Ar("wasm prepareInputOutputTensor");for(let L=0;L<y;L++)o.setValue($+L*i,C[L],"*"),o.setValue(G+L*i,d[t[L]],"*");for(let L=0;L<b;L++)o.setValue(j+L*i,A[L],"*"),o.setValue(Q+L*i,h[s[L]],"*");if(_&&!w){let{handle:L,outputPreferredLocations:Y,outputPreferredLocationsEncoded:te}=_;if(d.length!==y)throw new Error(`input count from feeds (${y}) is expected to be always equal to model's input count (${d.length}).`);Er("wasm bindInputsOutputs");for(let I=0;I<y;I++){let z=t[I];await o._OrtBindInput(L,d[z],C[I])!==0&&Me(`Can't bind input[${I}] for session=${e}.`);}for(let I=0;I<b;I++){let z=s[I];n[I]?.[3]?(N.push(A[I]),o._OrtBindOutput(L,h[z],A[I],0)!==0&&Me(`Can't bind pre-allocated output[${I}] for session=${e}.`)):o._OrtBindOutput(L,h[z],0,te[z])!==0&&Me(`Can't bind output[${I}] to ${Y[I]} for session=${e}.`);}Ar("wasm bindInputsOutputs"),kr.set(e,[c,d,h,_,p,!0]);}o.jsepOnRunStart?.(c),o.webnnOnRunStart?.(c);let q;_?q=await o._OrtRunWithBinding(c,_.handle,b,j,x):q=await o._OrtRun(c,G,$,y,Q,b,j,x),q!==0&&Me("failed to call OrtRun().");let X=[],D=[];Er("wasm ProcessOutputTensor");for(let L=0;L<b;L++){let Y=Number(o.getValue(j+L*i,"*"));if(Y===A[L]||N.includes(A[L])){X.push(n[L]),Y!==A[L]&&o._OrtReleaseTensor(Y)!==0&&Me("Can't release tensor.");continue}let te=o.stackSave(),I=o.stackAlloc(4*i),z=!1,R,H=0;try{o._OrtGetTensorData(Y,I,I+i,I+2*i,I+3*i)!==0&&Me(`Can't access output tensor data on index ${L}.`);let re=i===4?"i32":"i64",Ie=Number(o.getValue(I,re));H=o.getValue(I+i,"*");let se=o.getValue(I+i*2,"*"),pt=Number(o.getValue(I+i*3,re)),Oe=[];for(let Pe=0;Pe<pt;Pe++)Oe.push(Number(o.getValue(se+Pe*i,re)));o._OrtFree(se)!==0&&Me("Can't free memory for tensor dims.");let qe=Oe.reduce((Pe,ye)=>Pe*ye,1);R=Fa(Ie);let mt=_?.outputPreferredLocations[s[L]];if(R==="string"){if(mt==="gpu-buffer"||mt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Pe=[];for(let ye=0;ye<qe;ye++){let We=o.getValue(H+ye*i,"*"),Ht=o.getValue(H+(ye+1)*i,"*"),be=ye===qe-1?void 0:Ht-We;Pe.push(o.UTF8ToString(We,be));}X.push([R,Oe,Pe,"cpu"]);}else if(mt==="gpu-buffer"&&qe>0){let Pe=o.webgpuGetBuffer;if(!Pe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ye=Pe(H),We=ks(Ie,qe);if(We===void 0||!Jc(R))throw new Error(`Unsupported data type: ${R}`);z=!0;{o.webgpuRegisterBuffer(ye,e,H);let Ht=o.webgpuCreateDownloader(ye,We,e);X.push([R,Oe,{gpuBuffer:ye,download:async()=>{let be=await Ht();return new(_n(R))(be)},dispose:()=>{o._OrtReleaseTensor(Y)!==0&&Me("Can't release tensor.");}},"gpu-buffer"]);}}else if(mt==="ml-tensor"&&qe>0){let Pe=o.webnnEnsureTensor,ye=o.webnnIsGraphInputOutputTypeSupported;if(!Pe||!ye)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ks(Ie,qe)===void 0||!Kc(R))throw new Error(`Unsupported data type: ${R}`);if(!ye(e,R,!1))throw new Error(`preferredLocation "ml-tensor" for ${R} output is not supported by current WebNN Context.`);let We=await Pe(e,H,Ie,Oe,!1);z=!0,X.push([R,Oe,{mlTensor:We,download:o.webnnCreateMLTensorDownloader(H,R),dispose:()=>{o.webnnReleaseTensorId(H),o._OrtReleaseTensor(Y);}},"ml-tensor"]);}else if(mt==="ml-tensor-cpu-output"&&qe>0){let Pe=o.webnnCreateMLTensorDownloader(H,R)(),ye=X.length;z=!0,D.push((async()=>{let We=[ye,await Pe];return o.webnnReleaseTensorId(H),o._OrtReleaseTensor(Y),We})()),X.push([R,Oe,[],"cpu"]);}else {let Pe=_n(R),ye=new Pe(qe);new Uint8Array(ye.buffer,ye.byteOffset,ye.byteLength).set(o.HEAPU8.subarray(H,H+ye.byteLength)),X.push([R,Oe,ye,"cpu"]);}}finally{o.stackRestore(te),R==="string"&&H&&o._free(H),z||o._OrtReleaseTensor(Y);}}_&&!p&&(o._OrtClearBoundOutputs(_.handle)!==0&&Me("Can't clear bound outputs."),kr.set(e,[c,d,h,_,p,!1]));for(let[L,Y]of await Promise.all(D))X[L][2]=Y;return Ar("wasm ProcessOutputTensor"),X}finally{o.webnnOnRunEnd?.(c),o.stackRestore(M),r.forEach(q=>{q&&q[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(q[2].gpuBuffer);}),n.forEach(q=>{q&&q[3]==="gpu-buffer"&&o.webgpuUnregisterBuffer(q[2].gpuBuffer);}),C.forEach(q=>o._OrtReleaseTensor(q)),A.forEach(q=>o._OrtReleaseTensor(q)),S.forEach(q=>o._free(q)),x!==0&&o._OrtReleaseRunOptions(x),T.forEach(q=>o._free(q));}},au=e=>{let t=Ce(),r=kr.get(e);if(!r)throw new Error("invalid session id");let s=r[0],n=t._OrtEndProfiling(s);n===0&&Me("Can't get an profile file name."),t._OrtFree(n);},ou=e=>{let t=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&t.push(s.buffer);}return t};}),Tr,Ft,xs,dn,hn,Sa,Dc,Pa,Br,Rr,vm,ng,ag,og,ig,lg,cg,ug,dg=_e(()=>{qr(),sg(),Wr(),Qc(),Tr=()=>!!De.wasm.proxy&&typeof document<"u",xs=false,dn=false,hn=false,Pa=new Map,Br=(e,t)=>{let r=Pa.get(e);r?r.push(t):Pa.set(e,[t]);},Rr=()=>{if(xs||!dn||hn||!Ft)throw new Error("worker not ready")},vm=e=>{switch(e.data.type){case "init-wasm":xs=false,e.data.err?(hn=true,Dc[1](e.data.err)):(dn=true,Dc[0]()),Sa&&(URL.revokeObjectURL(Sa),Sa=void 0);break;case "init-ep":case "copy-from":case "create":case "release":case "run":case "end-profiling":{let t=Pa.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},ng=async()=>{if(!dn){if(xs)throw new Error("multiple calls to 'initWasm()' detected.");if(hn)throw new Error("previous call to 'initWasm()' failed.");if(xs=true,Tr())return new Promise((e,t)=>{Ft?.terminate(),Wm().then(([r,s])=>{try{Ft=s,Ft.onerror=a=>t(a),Ft.onmessage=vm,Dc=[e,t];let n={type:"init-wasm",in:De};!n.in.wasm.wasmPaths&&(r||Rc)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Ft.postMessage(n),Sa=r;}catch(n){t(n);}},t);});try{await Xc(De.wasm),await eu(De),dn=!0;}catch(e){throw hn=true,e}finally{xs=false;}}},ag=async e=>{if(Tr())return Rr(),new Promise((t,r)=>{Br("init-ep",[t,r]);let s={type:"init-ep",in:{epName:e,env:De}};Ft.postMessage(s);});await tu(De,e);},og=async e=>Tr()?(Rr(),new Promise((t,r)=>{Br("copy-from",[t,r]);let s={type:"copy-from",in:{buffer:e}};Ft.postMessage(s,[e.buffer]);})):za(e),ig=async(e,t)=>{if(Tr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Rr(),new Promise((r,s)=>{Br("create",[r,s]);let n={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Ft.postMessage(n,a);})}else return ru(e,t)},lg=async e=>{if(Tr())return Rr(),new Promise((t,r)=>{Br("release",[t,r]);let s={type:"release",in:e};Ft.postMessage(s);});su(e);},cg=async(e,t,r,s,n,a)=>{if(Tr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Rr(),new Promise((o,i)=>{Br("run",[o,i]);let l=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:l,outputIndices:s,options:a}};Ft.postMessage(c,ou(l));})}else return nu(e,t,r,s,n,a)},ug=async e=>{if(Tr())return Rr(),new Promise((t,r)=>{Br("end-profiling",[t,r]);let s={type:"end-profiling",in:e};Ft.postMessage(s);});au(e);};}),Bc,bm,hg,GF=_e(()=>{qr(),dg(),Ts(),Hc(),Ym(),Bc=(e,t)=>{switch(e.location){case "cpu":return [e.type,e.dims,e.data,"cpu"];case "gpu-buffer":return [e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case "ml-tensor":return [e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},bm=e=>{switch(e[3]){case "cpu":return new Rt(e[0],e[2],e[1]);case "gpu-buffer":{let t=e[0];if(!Jc(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=e[2];return Rt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:s,dispose:n})}case "ml-tensor":{let t=e[0];if(!Kc(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=e[2];return Rt.fromMLTensor(r,{dataType:t,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},hg=class{async fetchModelAndCopyToWasmMemory(e){return og(await Zc(e))}async loadModel(e,t){Ur();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ig(r,t),jr();}async dispose(){return lg(this.sessionId)}async run(e,t,r){Ur();let s=[],n=[];Object.entries(e).forEach(h=>{let _=h[0],p=h[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(p),n.push(w);});let a=[],o=[];Object.entries(t).forEach(h=>{let _=h[0],p=h[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);a.push(p),o.push(w);});let i=s.map((h,_)=>Bc(h,()=>`input "${this.inputNames[n[_]]}"`)),l=a.map((h,_)=>h?Bc(h,()=>`output "${this.outputNames[o[_]]}"`):null),c=await cg(this.sessionId,n,i,o,l,r),d={};for(let h=0;h<c.length;h++)d[this.outputNames[o[h]]]=a[h]??bm(c[h]);return jr(),d}startProfiling(){}endProfiling(){ug(this.sessionId);}};}),fg={};pn(fg,{OnnxruntimeWebAssemblyBackend:()=>Uc,initializeFlags:()=>Vc,wasmBackend:()=>_g});var Vc,Uc,_g,$F=_e(()=>{qr(),dg(),GF(),Vc=()=>{(typeof De.wasm.initTimeout!="number"||De.wasm.initTimeout<0)&&(De.wasm.initTimeout=0);let e=De.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),De.wasm.simd=false),typeof De.wasm.proxy!="boolean"&&(De.wasm.proxy=false),typeof De.wasm.trace!="boolean"&&(De.wasm.trace=false),typeof De.wasm.numThreads!="number"||!Number.isInteger(De.wasm.numThreads)||De.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)De.wasm.numThreads=1;else {let t=typeof navigator>"u"?wF("node:os").cpus().length:navigator.hardwareConcurrency;De.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2));}},Uc=class{async init(e){Vc(),await ng(),await ag(e);}async createInferenceSessionHandler(e,t){let r=new hg;return await r.loadModel(e,t),r}},_g=new Uc;});qr();qr();qr();var VF="1.26.0-dev.20260410-5e55544225",UF=Gm;{let e=($F(),La(fg)).wasmBackend;Vr("webgpu",e,5),Vr("webnn",e,5),Vr("cpu",e,10),Vr("wasm",e,10);}Object.defineProperty(De.versions,"web",{value:VF,enumerable:true});var gg=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let s=r.getContext("2d");if(s!=null){let n,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[3]):(n=e.dims[3],a=e.dims[2]);let o=t?.format!==void 0?t.format:"RGB",i=t?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let d=a*n,h=0,_=d,p=d*2,w=-1;o==="RGBA"?(h=0,_=d,p=d*2,w=d*3):o==="RGB"?(h=0,_=d,p=d*2):o==="RBG"&&(h=0,p=d,_=d*2);for(let y=0;y<a;y++)for(let b=0;b<n;b++){let x=(e.data[h++]-c[0])*l[0],T=(e.data[_++]-c[1])*l[1],C=(e.data[p++]-c[2])*l[2],A=w===-1?255:(e.data[w++]-c[3])*l[3];s.fillStyle="rgba("+x+","+T+","+C+","+A+")",s.fillRect(b,y,1,1);}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},wg=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,a,o;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(n=e.dims[2],a=e.dims[1],o=e.dims[3]):(n=e.dims[3],a=e.dims[2],o=e.dims[1]);let i=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t?.norm,c,d;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[3]=l.bias[3]));let h=a*n;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,p=0,w=1,y=2,b=3,x=0,T=h,C=h*2,A=-1;i==="RGBA"?(x=0,T=h,C=h*2,A=h*3):i==="RGB"?(x=0,T=h,C=h*2):i==="RBG"&&(x=0,C=h,T=h*2),s=r.createImageData(n,a);for(let S=0;S<a*n;p+=_,w+=_,y+=_,b+=_,S++)s.data[p]=(e.data[x++]-d[0])*c[0],s.data[w]=(e.data[T++]-d[1])*c[1],s.data[y]=(e.data[C++]-d[2])*c[2],s.data[b]=A===-1?255:(e.data[A++]-d[3])*c[3];}else throw new Error("Can not access image data");return s};var cu=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=t,n=t.norm??{mean:255,bias:0},a,o;typeof n.mean=="number"?a=[n.mean,n.mean,n.mean,n.mean]:a=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?o=[n.bias,n.bias,n.bias,n.bias]:o=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*s,d=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),h=4,_=0,p=1,w=2,y=3,b=0,x=c,T=c*2,C=-1;i==="RGB"&&(h=3,_=0,p=1,w=2,y=-1),l==="RGBA"?C=c*3:l==="RBG"?(b=0,T=c,x=c*2):l==="BGR"&&(T=0,x=c,b=c*2);for(let S=0;S<c;S++,_+=h,w+=h,p+=h,y+=h)d[b++]=(e[_]+o[0])/a[0],d[x++]=(e[p]+o[1])/a[1],d[T++]=(e[w]+o[2])/a[2],C!==-1&&y!==-1&&(d[C++]=(e[y]+o[3])/a[3]);return l==="RGBA"?new nt("float32",d,[1,4,r,s]):new nt("float32",d,[1,3,r,s])},yg=async(e,t)=>{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,i=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=e.width,d.height=e.height;let h=c(d);if(h!=null){let _=e.height,p=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(_=t.resizedHeight,p=t.resizedWidth),t!==void 0){if(i=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=p;}else i.tensorFormat="RGBA",i.height=_,i.width=p;h.drawImage(e,0,0),o=h.getImageData(0,0,p,_).data;}else throw new Error("Can not access image data")}else if(s){let d,h;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(d=t.resizedHeight,h=t.resizedWidth):(d=e.height,h=e.width),t!==void 0&&(i=t),i.format="RGBA",i.height=d,i.width=h,t!==void 0){let _=l();_.width=h,_.height=d;let p=c(_);if(p!=null)p.putImageData(e,0,0),o=p.getImageData(0,0,h,d).data;else throw new Error("Can not access image data")}else o=e.data;}else if(n){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let d=l();d.width=e.width,d.height=e.height;let h=c(d);if(h!=null){let _=e.height,p=e.width;return h.drawImage(e,0,0,p,_),o=h.getImageData(0,0,p,_).data,i.height=_,i.width=p,cu(o,i)}else throw new Error("Can not access image data")}else {if(a)return new Promise((d,h)=>{let _=l(),p=c(_);if(!e||!p)return h();let w=new Image;w.crossOrigin="Anonymous",w.src=e,w.onload=()=>{_.width=w.width,_.height=w.height,p.drawImage(w,0,0,_.width,_.height);let y=p.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,d(cu(y.data,i));};});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return cu(o,i);throw new Error("Input data provided is not supported - aborted tensor creation")},vg=(e,t)=>{let{width:r,height:s,download:n,dispose:a}=t,o=[1,s,r,4];return new nt({location:"texture",type:"float32",texture:e,dims:o,download:n,dispose:a})},bg=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new nt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:n,dispose:a})},Mg=(e,t)=>{let{dataType:r,dims:s,download:n,dispose:a}=t;return new nt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:n,dispose:a})},xg=(e,t,r)=>new nt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]});var Hr=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),mn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),kg=false,Tg=()=>{if(!kg){kg=true;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(Hr.set("int64",BigInt64Array),mn.set(BigInt64Array,"int64")),t&&(Hr.set("uint64",BigUint64Array),mn.set(BigUint64Array,"uint64")),s?(Hr.set("float16",r),mn.set(r,"float16")):Hr.set("float16",Uint16Array);}};var Eg=e=>{let t=1;for(let r=0;r<e.length;r++){let s=e[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);t*=s;}return t},Ag=(e,t)=>{switch(e.location){case "cpu":return new nt(e.type,e.data,t);case "cpu-pinned":return new nt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case "texture":return new nt({location:"texture",texture:e.texture,type:e.type,dims:t});case "gpu-buffer":return new nt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case "ml-tensor":return new nt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};var nt=class{constructor(t,r,s){Tg();let n,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,n=t.type,a=t.dims,t.location){case "cpu-pinned":{let i=Hr.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(t.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=t.data;break}case "texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case "gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case "ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else {let i,l;if(typeof t=="string")if(n=t,l=s,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r;}else {let c=Hr.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?i=c.from(r,BigInt):i=c.from(r);}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof t[0];if(c==="string")n="string",i=t;else if(c==="boolean")n="bool",i=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(t);else {let c=mn.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);n=c,i=t;}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=i,this.dataLocation="cpu";}let o=Eg(a);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=a,this.size=o;}static async fromImage(t,r){return yg(t,r)}static fromTexture(t,r){return vg(t,r)}static fromGpuBuffer(t,r){return bg(t,r)}static fromMLTensor(t,r){return Mg(t,r)}static fromPinnedBuffer(t,r,s){return xg(t,r,s)}toDataURL(t){return gg(this,t)}toImageData(t){return wg(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 r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=false;}}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 Ag(this,t)}};var uu=nt;var jF=Object.defineProperty,$s=(e,t)=>{for(var r in t)jF(e,r,{get:t[r],enumerable:true});},At={},er={},qF={},WF="4.1.0",gd=typeof self<"u",zs=!Sw(At),Ew=!Sw(er),ho=gd&&"caches"in self,HF=typeof globalThis.Deno<"u",ko=HF&&ho&&!zs,Aw=typeof process<"u",Cw=Aw&&process?.release?.name==="node"&&!ko,wd=typeof window<"u"&&typeof window.document<"u",yd=gd&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),QF=wd||yd||ko,XF=Cw||typeof navigator<"u"&&"gpu"in navigator,YF=typeof navigator<"u"&&"ml"in navigator,JF=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",KF=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",ZF=typeof ServiceWorkerGlobalScope<"u"&&gd&&self instanceof ServiceWorkerGlobalScope,eL=()=>{if(typeof navigator>"u")return false;let e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&s},tL=eL(),he=Object.freeze({IS_BROWSER_ENV:wd,IS_WEBWORKER_ENV:yd,IS_WEB_ENV:QF,IS_SERVICE_WORKER_ENV:ZF,IS_DENO_WEB_RUNTIME:ko,IS_WEB_CACHE_AVAILABLE:ho,IS_WEBGPU_AVAILABLE:XF,IS_WEBNN_AVAILABLE:YF,IS_SAFARI:tL,IS_PROCESS_AVAILABLE:Aw,IS_NODE_ENV:Cw,IS_FS_AVAILABLE:zs,IS_PATH_AVAILABLE:Ew,IS_CRYPTO_AVAILABLE:JF,IS_CHROME_AVAILABLE:KF}),vd=zs&&Ew,fo="./";if(vd){let e=Object(import.meta).url;e?fo=er.dirname(er.dirname(qF.fileURLToPath(e))):typeof __dirname<"u"&&(fo=er.dirname(__dirname));}var rL=vd?er.join(fo,"/.cache/"):null,Cg="/models/",sL=vd?er.join(fo,Cg):Cg,nL=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ot=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Sg=Ot.WARNING,me={version:WF,backends:{onnx:{}},get logLevel(){return Sg},set logLevel(e){Sg=e,me.backends.onnx?.setLogLevel?.(e);},allowRemoteModels:true,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(wd||yd||ko),localModelPath:sL,useFS:zs,useBrowserCache:ho,useFSCache:zs,cacheDir:rL,useCustomCache:false,customCache:null,useWasmCache:ho||zs,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:false,fetch:nL};function Sw(e){return Object.keys(e).length===0}var bt=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function Pr(e,t){e&&e(t);}var td=class extends bt{constructor(e,t){super(),this.callback=e,this.files_loading=t;}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((n,a)=>n+a.loaded,0),r=Object.values(this.files_loading).reduce((n,a)=>n+a.total,0),s=r>0?t/r*100:0;this.callback({status:"progress_total",name:e.name,progress:s,loaded:t,total:r,files:structuredClone(this.files_loading)});}this.callback(e);}};function aL(e){return Number.isInteger(e)||typeof e=="bigint"}function Pg(e){return e==null||e===-1}function Fg(e){let t=[],r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Gt(...e){return Array.prototype.concat.apply([],e)}function oL(...e){return e.reduce((t,r)=>t.flatMap(s=>r.map(n=>[s,n])))}function _o(e,t){return Math.abs((e+t)%(2*t)-t)}function at(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return {[r]:e[r]}}))}function iL(e,t){let r=0;for(let s of e)s===t&&++r;return r}var ce={error(...e){me.logLevel<=Ot.ERROR&&console.error(...e);},warn(...e){me.logLevel<=Ot.WARNING&&console.warn(...e);},info(...e){me.logLevel<=Ot.INFO&&console.log(...e);},debug(...e){me.logLevel<=Ot.DEBUG&&console.log(...e);},log(...e){this.info(...e);}},lL=class{constructor(e){this.trie=this._build_trie(e);}_build_trie(e){let t=Object.create(null);for(let r of e){let s=t;for(let n=0;n<r.length;++n){let a=r[n];s=s[a]??(s[a]=Object.create(null));}s.end=r;}return t}split(e){let t=[],r=e.length,s=0,n=0;for(;n<r;){let a=this.trie,o=null,i=n;for(;i<r&&(a=a[e[i]]);)a.end&&(o=a.end),++i;o?(n>s&&t.push(e.slice(s,n)),t.push(o),n+=o.length,s=n):++n;}return s<r&&t.push(e.slice(s)),t}},Lg=lL,cL=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??false,this.lstrip=e.lstrip??false,this.rstrip=e.rstrip??false,this.special=e.special??false,this.normalized=e.normalized??!this.special;}},uL=cL,Pw=(()=>{let e=[...Array.from({length:94},(n,a)=>a+33),...Array.from({length:12},(n,a)=>a+161),...Array.from({length:82},(n,a)=>a+174)],t=e.slice(),r=0;for(let n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+r),r+=1);let s=t.map(n=>String.fromCharCode(n));return Object.fromEntries(e.map((n,a)=>[n,s[a]]))})(),dL=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),hL=dL(Pw),Ig=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",fL=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|[${Ig}])]+`,` ?[^\\s${Ig}]+`]]),po="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",bd=e=>e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),To=(e,t=true)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of fL)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=false,a=r.replace(/(\\[pP])\{([^}=]+)\}/g,(o,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=true,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(a,"gu")}catch{throw s}}}else if(e.String!==void 0){let r=_L(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},_L=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pL=(e,t,r)=>{let s=[],n=0;for(;n<e.length;){if(s.push(e[n]),(t.get(e[n])??r)!==r){++n;continue}for(;++n<e.length&&(t.get(e[n])??r)===r;)t.get(s.at(-1))!==r&&(s[s.length-1]+=e[n]);}return s},mL=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,gL=e=>Number.isInteger(e)||typeof e=="bigint",wL=e=>{let t=0;for(let r of e)++t;return t},yL=e=>Fw(e.toLowerCase()),$t=(...e)=>Array.prototype.concat.apply([],e),Md=e=>new Map(Object.entries(e)),vL=(e,t)=>{let r=[],s=0;for(let n of e.matchAll(t)){let a=n[0];s<n.index&&r.push(e.slice(s,n.index)),a.length>0&&r.push(a),s=n.index+a.length;}return s<e.length&&r.push(e.slice(s)),r},Fw=e=>e.replace(/\p{M}/gu,""),Og=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return `${t} must be a valid object`;for(let s of r)if(!(s in e))return `${t} must contain a "${s}" property`;return null},bL=e=>e.match(/\S+/g)||[],ML=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Gn=ML,xL=class extends Gn{constructor(e){super(),this.config=e;}_call(e){return this.normalize(e)}},mr=xL,kL=class extends mr{tokenize_chinese_chars(e){let t=[];for(let r=0;r<e.length;++r){let s=e[r],n=s.charCodeAt(0);mL(n)?(t.push(" "),t.push(s),t.push(" ")):t.push(s);}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(e){switch(e){case " ":case `
|
|
5
|
+
`:case "\r":return false;default:return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}clean_text(e){let t=[];for(let r of e){let s=r.charCodeAt(0);s===0||s===65533||this.is_control(r)||(/^\s$/.test(r)?t.push(" "):t.push(r));}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),this.config.strip_accents!==false&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},TL=kL,EL=class extends mr{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null;}normalize(e){return e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),e=e.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),e.includes("\uFF5E")?e=e.split("\uFF5E").map(r=>r.normalize("NFKC")).join("\uFF5E"):e=e.normalize("NFKC"),e}},AL=EL,CL=class extends mr{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>Lw(t));}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},SL=CL,PL=class extends mr{normalize(e){let t=To(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},FL=PL,LL=class extends mr{constructor(){super(...arguments),this.form="NFC";}normalize(e){return e=e.normalize(this.form),e}},Eo=LL,IL=class extends Eo{constructor(){super(...arguments),this.form="NFC";}},OL=IL,NL=class extends Eo{constructor(){super(...arguments),this.form="NFD";}},zL=NL,DL=class extends Eo{constructor(){super(...arguments),this.form="NFKC";}},BL=DL,RL=class extends Eo{constructor(){super(...arguments),this.form="NFKD";}},GL=RL,$L=class extends mr{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},VL=$L,UL=class extends mr{normalize(e){return Fw(e)}},jL=UL,qL=class extends mr{normalize(e){return e.toLowerCase()}},WL=qL,HL=class extends mr{normalize(e){return e=this.config.prepend+e,e}},QL=HL;function XL(e){if(e===null)return null;switch(e.type){case "BertNormalizer":return new TL(e);case "Precompiled":return new AL(e);case "Sequence":return new SL(e);case "Replace":return new FL(e);case "NFC":return new OL(e);case "NFD":return new zL(e);case "NFKC":return new BL(e);case "NFKD":return new GL(e);case "Strip":return new VL(e);case "StripAccents":return new jL(e);case "Lowercase":return new WL(e);case "Prepend":return new QL(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var Lw=XL,YL=class extends Gn{pre_tokenize(e,t){return (Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},Ut=YL,JL=class extends Ut{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??false,this.trim_offsets=this.config.trim_offsets??false,this.use_regex=this.config.use_regex??true,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=Pw,this.text_encoder=new TextEncoder;}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},KL=JL,ZL=class extends Ut{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},eI=ZL,tI=class extends Ut{constructor(e){super(),this.replacement=e.replacement??"\u2581",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always";}pre_tokenize_text(e,t){let{section_index:r=void 0}=t??{},s=e.replaceAll(" ",this.str_rep);return !s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},rI=tI,sI=class extends Ut{constructor(e){super(),this.config=e,this.pattern=To(this.config.pattern??{},this.config.invert??true);}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):vL(e,this.pattern)}},nI=sI,aI=class extends Ut{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${po}]+|[${po}]+`,"gu");}pre_tokenize_text(e){return e.match(this.pattern)||[]}},oI=aI,iI=class extends Ut{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu");}pre_tokenize_text(e){return e.match(this.pattern)||[]}},lI=iI,cI=class extends Ut{constructor(){super(),this.pattern=new RegExp(`[^\\s${po}]+|[${po}]`,"gu");}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},uI=cI,dI=class extends Ut{constructor(e){super(),this.config=e,this.pattern=To(this.config.pattern??{}),this.content=this.config.content??"";}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},hI=dI,fI=class extends Ut{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>Iw(t));}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,t):r,[e])}},_I=fI,pI=class extends Ut{pre_tokenize_text(e){return bL(e)}},mI=pI,gI=class extends Ut{constructor(e){super(),this.config=e,this._length=e.length;}pre_tokenize_text(e){let t=[];for(let r=0;r<e.length;r+=this._length)t.push(e.slice(r,r+this._length));return t}},wI=gI;function yI(e){if(e===null)return null;switch(e.type){case "BertPreTokenizer":return new uI;case "Sequence":return new _I(e);case "Whitespace":return new eI;case "WhitespaceSplit":return new mI;case "Metaspace":return new rI(e);case "ByteLevel":return new KL(e);case "Split":return new nI(e);case "Punctuation":return new oI(e);case "Digits":return new lI(e);case "Replace":return new hI(e);case "FixedLength":return new wI(e);default:throw new Error(`Unknown PreTokenizer type: ${e.type}`)}}var Iw=yI,vI=class extends Gn{constructor(e){super(),this.config=e,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??false;}_call(e){let t=this.encode(e);return this.fuse_unk&&(t=pL(t,this.tokens_to_ids,this.unk_token_id)),t}},Ao=vI,bI=class extends Ao{constructor(e){super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=Md(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[t,r]of this.tokens_to_ids)this.vocab[r]=t;}encode(e){let t=[];for(let r of e){let s=[...r];if(s.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let n=false,a=0,o=[];for(;a<s.length;){let i=s.length,l=null;for(;a<i;){let c=s.slice(a,i).join("");if(a>0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i;}if(l===null){n=true;break}o.push(l),a=i;}n?t.push(this.unk_token):t.push(...o);}return t}},Ng=bI,zg=class Ow{constructor(t,r){this.is_leaf=t,this.children=r;}static default(){return new Ow(false,new Map)}},MI=class{constructor(){this.root=zg.default();}extend(e){for(let t of e)this.push(t);}push(e){let t=this.root;for(let r of e){let s=t.children.get(r);s===void 0&&(s=zg.default(),t.children.set(r,s)),t=s;}t.is_leaf=true;}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(let s of e){if(r+=s,t=t.children.get(s),t===void 0)return;t.is_leaf&&(yield r);}}},xI=MI,du=class Nw{constructor(t,r,s,n,a){this.token_id=t,this.node_id=r,this.pos=s,this.length=n,this.score=a,this.prev=null,this.backtrace_score=0;}clone(){let t=new Nw(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},kI=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new du(this.bos_token_id??0,0,0,0,0),n=new du(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s);}insert(e,t,r,s){let n=this.nodes.length,a=new du(s,n,e,t,r);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a);}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return [];for(let o of this.begin_nodes[t]){o.prev=null;let i=0,l=null;for(let c of this.end_nodes[t]){let d=c.backtrace_score+o.score;(l===null||d>i)&&(l=c.clone(),i=d);}if(l!==null)o.prev=l,o.backtrace_score=i;else return []}++t;}let r=[],n=this.begin_nodes[e][0].prev;if(n===null)return [];let a=n.clone();for(;a.prev!==null;)r.push(a.clone()),a=a.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},TI=kI;function EI(e){if(e.length===0)throw new Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]<t&&(t=e[s],r=s);return [t,r]}var AI=class extends Ao{constructor(e,t){super(e);let r=e.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=e.vocab[s];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=EI(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new xI,this.trie.extend(this.vocab),this.fuse_unk=true;}populate_nodes(e){let t=e.chars,r=1,s=0;for(;s<t.length;){let n=false,o=t.slice(s).join(""),i=this.trie.common_prefix_search(o);for(let l of i){let c=this.tokens_to_ids.get(l),d=this.scores[c],h=wL(l);e.insert(s,h,d,c),!n&&h===r&&(n=true);}n||e.insert(s,r,this.unk_score,this.unk_token_id),s+=r;}}tokenize(e){let t=new TI(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let r of e){let s=this.tokenize(r);t.push(...s);}return t}},Dg=AI,CI=class{constructor(e=(r,s)=>r>s,t=1/0){this._heap=[],this._comparator=e,this._max_size=t;}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else {let r=this._smallest();this._comparator(t,this._heap[r])&&(this._heap[r]=t,this._sift_up_from(r));}return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return (e+1>>>1)-1}_left(e){return (e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=r;}_sift_up(){this._sift_up_from(this.size-1);}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e);}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t;}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},SI=CI,PI=class{constructor(e){this.capacity=e,this.cache=new Map;}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value);}clear(){this.cache.clear();}},FI=PI,LI=class extends Ao{constructor(e){super(e),this.tokens_to_ids=Md(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??false,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??false,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new FI(this.cache_capacity);}clear_cache(){this.cache.clear();}bpe(e){if(e.length===0)return [];let t=this.cache.get(e);if(t!==void 0)return t;let r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new SI((i,l)=>i.score<l.score),a={token:r[0],bias:0,prev:null,next:null},o=a;for(let i=1;i<r.length;++i){let l={bias:i/r.length,token:r[i],prev:o,next:null};o.next=l,this.add_node(n,o),o=l;}for(;!n.is_empty();){let i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=true,i.next.deleted=true,i.prev){let c={...i.prev};i.prev.deleted=true,i.prev=c,c.prev?c.prev.next=c:a=c;}let l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):a=l,l.next&&(l.next.prev=l,this.add_node(n,l));}for(let i=a;i!==null;i=i.next)s.push(i.token);}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,s),s}add_node(e,t){let r=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));r!==void 0&&(t.score=r+t.bias,e.push(t));}encode(e){let t=[];for(let r of e){if(this.ignore_merges&&this.tokens_to_ids.has(r)){t.push(r);continue}let s=this.bpe(r);for(let n of s)if(this.tokens_to_ids.has(n))t.push(n);else if(this.byte_fallback){let a=Array.from(this.text_encoder.encode(n)).map(o=>`<0x${o.toString(16).toUpperCase().padStart(2,"0")}>`);a.every(o=>this.tokens_to_ids.has(o))?t.push(...a):this.unk_token!=null&&t.push(this.unk_token);}else this.unk_token!=null&&t.push(this.unk_token);}return t}},Bg=LI,II=class extends Ao{constructor(e,t){super(e);let r=e.vocab;this.tokens_to_ids=Md(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s;}encode(e){return e}},OI=II;function NI(e,t){switch(e.type){case "WordPiece":return new Ng(e);case "Unigram":return new Dg(e,t.eos_token);case "BPE":return new Bg(e);default:if(e.vocab)return Array.isArray(e.vocab)?new Dg(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Bg(e):new Ng(e):new OI(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}var zI=NI,DI=class extends Gn{constructor(e){super(),this.config=e;}_call(e,...t){return this.post_process(e,...t)}},$n=DI,BI=class extends $n{post_process(e,t=null,r=true){let s=t===null?this.config.single:this.config.pair,n=[],a=[];for(let o of s)"SpecialToken"in o?r&&(n.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(n=$t(n,e),a=$t(a,new Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(n=$t(n,t),a=$t(a,new Array(t.length).fill(o.Sequence.type_id))));return {tokens:n,token_type_ids:a}}},RI=BI,GI=class extends $n{post_process(e,t=null){return {tokens:e,tokens_pair:t}}},$I=GI,VI=class extends $n{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls;}post_process(e,t=null,r=true){r&&(e=$t([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){let n=[],a=r?[this.sep[0]]:[];e=$t(e,n,t,a),s=$t(s,new Array(t.length+n.length+a.length).fill(1));}return {tokens:e,token_type_ids:s}}},UI=VI,jI=class extends $n{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls;}post_process(e,t,r=true){r&&(e=$t([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){let n=r?[this.sep[0]]:[],a=r?[this.sep[0]]:[];e=$t(e,n,t,a),s=$t(s,new Array(t.length+n.length+a.length).fill(1));}return {tokens:e,token_type_ids:s}}},qI=jI,WI=class extends $n{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>zw(t));}post_process(e,t=null,r=true){let s={tokens:e,tokens_pair:t};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},HI=WI;function QI(e){if(e===null)return null;switch(e.type){case "TemplateProcessing":return new RI(e);case "ByteLevel":return new $I(e);case "BertProcessing":return new UI(e);case "RobertaProcessing":return new qI(e);case "Sequence":return new HI(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var zw=QI,XI=class extends Gn{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in e?e.trim_offsets:false;}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}},jt=XI,YI=class extends jt{constructor(e){super(e),this.byte_decoder=hL,this.text_decoder=new TextDecoder("utf-8",{fatal:false,ignoreBOM:true}),this.end_of_word_suffix=null;}convert_tokens_to_string(e){let t=e.join(""),r=new Uint8Array([...t].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(e){let t=[],r=[];for(let s of e)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(s)):r.push(s);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},JI=YI,KI=class extends jt{constructor(e){super(e),this.cleanup=e.cleanup;}decode_chain(e){return e.map((t,r)=>{if(r!==0){let s=this.config.prefix;s&&t.startsWith(s)?t=t.replace(s,""):t=" "+t;}return this.cleanup&&(t=bd(t)),t})}},ZI=KI,eO=class extends jt{constructor(e){super(e),this.replacement=e.replacement??"\u2581";}decode_chain(e){let t=[];for(let r=0;r<e.length;++r){let s=e[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),t.push(s);}return t}},tO=eO,rO=class extends jt{constructor(e){super(e),this.suffix=e.suffix??"";}decode_chain(e){return e.map((t,r)=>t.replaceAll(this.suffix,r===e.length-1?"":" "))}},sO=rO,nO=class extends jt{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup;}convert_tokens_to_string(e){if(e.length===0)return "";let t=[e[0]];for(let n=1;n<e.length;++n)e[n]!==t.at(-1)&&t.push(e[n]);let s=t.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=bd(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return [this.convert_tokens_to_string(e)]}},aO=nO,oO=class extends jt{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>Dw(t));}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},iO=oO,lO=class extends jt{decode_chain(e){let t=To(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(s=>s.replaceAll(t,r))}},cO=lO,uO=class extends jt{decode_chain(e){return [e.join("")]}},dO=uO,hO=class extends jt{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0;}decode_chain(e){return e.map(t=>{let r=0;for(let n=0;n<this.start&&t[n]===this.content;++n){r=n+1;continue}let s=t.length;for(let n=0;n<this.stop;++n){let a=t.length-n-1;if(t[a]===this.content){s=a;continue}else break}return t.slice(r,s)})}},fO=hO,_O=class extends jt{constructor(e){super(e),this.text_decoder=new TextDecoder;}decode_chain(e){let t=[],r=[];for(let s of e){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){let a=parseInt(s.slice(3,5),16);isNaN(a)||(n=a);}if(n!==null)r.push(n);else {if(r.length>0){let a=this.text_decoder.decode(Uint8Array.from(r));t.push(a),r=[];}t.push(s);}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));t.push(s),r=[];}return t}},pO=_O;function mO(e){if(e===null)return null;switch(e.type){case "ByteLevel":return new JI(e);case "WordPiece":return new ZI(e);case "Metaspace":return new tO(e);case "BPEDecoder":return new sO(e);case "CTC":return new aO(e);case "Sequence":return new iO(e);case "Replace":return new cO(e);case "Fuse":return new dO(e);case "Strip":return new fO(e);case "ByteFallback":return new pO(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var Dw=mO,gO=class{constructor(e,t){let r=Og(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=Og(t,"Config");if(s)throw new Error(s);this.tokenizer=e,this.config=t,this.normalizer=Lw(this.tokenizer.normalizer),this.pre_tokenizer=Iw(this.tokenizer.pre_tokenizer),this.model=zI(this.tokenizer.model,this.config),this.post_processor=zw(this.tokenizer.post_processor),this.decoder=Dw(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],a=[];this.added_tokens_map=new Map;for(let o of this.tokenizer.added_tokens){let i=new uL(o);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);a.push(l),this.added_tokens_map.set(l,i);}else n.push(i.content);}(this.config.additional_special_tokens??[]).forEach(o=>{this.special_tokens.includes(o)||this.special_tokens.push(o);}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new Lg(n),this.splitter_normalized=new Lg(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??true,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??false;}encode(e,{text_pair:t=null,add_special_tokens:r=true,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),o=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:o,tokens:n,attention_mask:new Array(o.length).fill(1)};return s&&a&&(i.token_type_ids=a),i}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!gL(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);t.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(s=s.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=bd(s)),s}tokenize(e,{text_pair:t=null,add_special_tokens:r=false}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(t[s-1]=t[s-1].trimEnd()),n.rstrip&&s<t.length-1&&(t[s+1]=t[s+1].trimStart()));}),t.flatMap((r,s)=>{if(r.length===0)return [];if(this.added_tokens_map.has(r))return [r];if(this.remove_space===true&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=yL(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return [];let n=this.splitter_normalized.split(r);return n.forEach((a,o)=>{let i=this.added_tokens_map.get(a);i&&(i.lstrip&&o>0&&(n[o-1]=n[o-1].trimEnd()),i.rstrip&&o<n.length-1&&(n[o+1]=n[o+1].trimStart()));}),n.flatMap(a=>{if(a.length===0)return [];if(this.added_tokens_map.has(a))return [a];let o=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:s}):[a];return this.model(o)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=true}){let s=this.encode_text(e),n=this.encode_text(t||null);return this.post_processor?this.post_processor(s,n,r):{tokens:$t(s??[],n??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=true){let t=new Map;for(let r=0;r<this.model.vocab.length;++r){let s=this.model.vocab[r];(e||!this.added_tokens_map.has(s))&&t.set(s,r);}return t}},wO=gO,B=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Lt=class{constructor(e,t){this.value=e,this.type=t;}};function Rg(e){return /\w/.test(e)}function gn(e){return /[0-9]/.test(e)}function Gg(e){return /\s/.test(e)}var yO=[["{%",B.OpenStatement],["%}",B.CloseStatement],["{{",B.OpenExpression],["}}",B.CloseExpression],["(",B.OpenParen],[")",B.CloseParen],["{",B.OpenCurlyBracket],["}",B.CloseCurlyBracket],["[",B.OpenSquareBracket],["]",B.CloseSquareBracket],[",",B.Comma],[".",B.Dot],[":",B.Colon],["|",B.Pipe],["<=",B.ComparisonBinaryOperator],[">=",B.ComparisonBinaryOperator],["==",B.ComparisonBinaryOperator],["!=",B.ComparisonBinaryOperator],["<",B.ComparisonBinaryOperator],[">",B.ComparisonBinaryOperator],["+",B.AdditiveBinaryOperator],["-",B.AdditiveBinaryOperator],["~",B.AdditiveBinaryOperator],["*",B.MultiplicativeBinaryOperator],["/",B.MultiplicativeBinaryOperator],["%",B.MultiplicativeBinaryOperator],["=",B.Equals]],vO=new Map([["n",`
|
|
6
|
+
`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function bO(e,t={}){return e.endsWith(`
|
|
7
|
+
`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function MO(e,t={}){let r=[],s=bO(e,t),n=0,a=0,o=c=>{let d="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let h=s[n++],_=vO.get(h);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${h}`);d+=_;continue}if(d+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return d},i=()=>{let c=r.at(-1);c&&c.type===B.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop());},l=()=>{for(;n<s.length&&Gg(s[n]);)++n;};e:for(;n<s.length;){let c=r.at(-1)?.type;if(c===void 0||c===B.CloseStatement||c===B.CloseExpression||c===B.Comment){let h="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)h+=s[n++];if(h.length>0){r.push(new Lt(h,B.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let h=s[n]==="-";h&&++n;let _="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");_+=s[n++];}let p=_.endsWith("-");p&&(_=_.slice(0,-1)),h&&i(),r.push(new Lt(_,B.Comment)),n+=2,p&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Lt("{%",B.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Lt("{{",B.OpenExpression)),a=0,n+=3;continue}if(o(Gg),s.slice(n,n+3)==="-%}"){r.push(new Lt("%}",B.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Lt("}}",B.CloseExpression)),n+=3,l();continue}let d=s[n];if(d==="-"||d==="+"){let h=r.at(-1)?.type;if(h===B.Text||h===void 0)throw new SyntaxError(`Unexpected character: ${d}`);switch(h){case B.Identifier:case B.NumericLiteral:case B.StringLiteral:case B.CloseParen:case B.CloseSquareBracket:break;default:{++n;let _=o(gn);r.push(new Lt(`${d}${_}`,_.length>0?B.NumericLiteral:B.UnaryOperator));continue}}}for(let[h,_]of yO){if(h==="}}"&&a>0)continue;if(s.slice(n,n+h.length)===h){r.push(new Lt(h,_)),_===B.OpenExpression?a=0:_===B.OpenCurlyBracket?++a:_===B.CloseCurlyBracket&&--a,n+=h.length;continue e}}if(d==="'"||d==='"'){++n;let h=o(_=>_!==d);r.push(new Lt(h,B.StringLiteral)),++n;continue}if(gn(d)){let h=o(gn);if(s[n]==="."&&gn(s[n+1])){++n;let _=o(gn);h=`${h}.${_}`;}r.push(new Lt(h,B.NumericLiteral));continue}if(Rg(d)){let h=o(Rg);r.push(new Lt(h,B.Identifier));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return r}var qt=class{constructor(){k(this,"type","Statement");}},xO=class extends qt{constructor(t){super();k(this,"type","Program");this.body=t;}},kO=class extends qt{constructor(t,r,s){super();k(this,"type","If");this.test=t,this.body=r,this.alternate=s;}},TO=class extends qt{constructor(t,r,s,n){super();k(this,"type","For");this.loopvar=t,this.iterable=r,this.body=s,this.defaultBlock=n;}},EO=class extends qt{constructor(){super(...arguments);k(this,"type","Break");}},AO=class extends qt{constructor(){super(...arguments);k(this,"type","Continue");}},CO=class extends qt{constructor(t,r,s){super();k(this,"type","Set");this.assignee=t,this.value=r,this.body=s;}},SO=class extends qt{constructor(t,r,s){super();k(this,"type","Macro");this.name=t,this.args=r,this.body=s;}},PO=class extends qt{constructor(t){super();k(this,"type","Comment");this.value=t;}},Ct=class extends qt{constructor(){super(...arguments);k(this,"type","Expression");}},FO=class extends Ct{constructor(t,r,s){super();k(this,"type","MemberExpression");this.object=t,this.property=r,this.computed=s;}},$g=class extends Ct{constructor(t,r){super();k(this,"type","CallExpression");this.callee=t,this.args=r;}},Es=class extends Ct{constructor(t){super();k(this,"type","Identifier");this.value=t;}},Vs=class extends Ct{constructor(t){super();k(this,"type","Literal");this.value=t;}},LO=class extends Vs{constructor(){super(...arguments);k(this,"type","IntegerLiteral");}},IO=class extends Vs{constructor(){super(...arguments);k(this,"type","FloatLiteral");}},Vg=class extends Vs{constructor(){super(...arguments);k(this,"type","StringLiteral");}},OO=class extends Vs{constructor(){super(...arguments);k(this,"type","ArrayLiteral");}},Ug=class extends Vs{constructor(){super(...arguments);k(this,"type","TupleLiteral");}},NO=class extends Vs{constructor(){super(...arguments);k(this,"type","ObjectLiteral");}},wn=class extends Ct{constructor(t,r,s){super();k(this,"type","BinaryExpression");this.operator=t,this.left=r,this.right=s;}},zO=class extends Ct{constructor(t,r){super();k(this,"type","FilterExpression");this.operand=t,this.filter=r;}},DO=class extends qt{constructor(t,r){super();k(this,"type","FilterStatement");this.filter=t,this.body=r;}},BO=class extends Ct{constructor(t,r){super();k(this,"type","SelectExpression");this.lhs=t,this.test=r;}},RO=class extends Ct{constructor(t,r,s){super();k(this,"type","TestExpression");this.operand=t,this.negate=r,this.test=s;}},GO=class extends Ct{constructor(t,r){super();k(this,"type","UnaryExpression");this.operator=t,this.argument=r;}},$O=class extends Ct{constructor(t=void 0,r=void 0,s=void 0){super();k(this,"type","SliceExpression");this.start=t,this.stop=r,this.step=s;}},VO=class extends Ct{constructor(t,r){super();k(this,"type","KeywordArgumentExpression");this.key=t,this.value=r;}},UO=class extends Ct{constructor(t){super();k(this,"type","SpreadExpression");this.argument=t;}},jO=class extends qt{constructor(t,r,s){super();k(this,"type","CallStatement");this.call=t,this.callerArgs=r,this.body=s;}},qO=class extends Ct{constructor(t,r,s){super();k(this,"type","Ternary");this.condition=t,this.trueExpr=r,this.falseExpr=s;}};function WO(e){let t=new xO([]),r=0;function s(I,z){let R=e[r++];if(!R||R.type!==I)throw new Error(`Parser Error: ${z}. ${R.type} !== ${I}.`);return R}function n(I){if(!l(I))throw new SyntaxError(`Expected ${I}`);++r;}function a(){switch(e[r].type){case B.Comment:return new PO(e[r++].value);case B.Text:return c();case B.OpenStatement:return d();case B.OpenExpression:return h();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function o(...I){return r+I.length<=e.length&&I.every((z,R)=>z===e[r+R].type)}function i(...I){return e[r]?.type===B.OpenStatement&&e[r+1]?.type===B.Identifier&&I.includes(e[r+1]?.value)}function l(...I){return r+I.length<=e.length&&I.every((z,R)=>e[r+R].type==="Identifier"&&z===e[r+R].value)}function c(){return new Vg(s(B.Text,"Expected text token").value)}function d(){if(s(B.OpenStatement,"Expected opening statement token"),e[r].type!==B.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);let I=e[r].value,z;switch(I){case "set":++r,z=_();break;case "if":++r,z=p(),s(B.OpenStatement,"Expected {% token"),n("endif"),s(B.CloseStatement,"Expected %} token");break;case "macro":++r,z=w(),s(B.OpenStatement,"Expected {% token"),n("endmacro"),s(B.CloseStatement,"Expected %} token");break;case "for":++r,z=b(),s(B.OpenStatement,"Expected {% token"),n("endfor"),s(B.CloseStatement,"Expected %} token");break;case "call":{++r;let R=null;o(B.OpenParen)&&(R=j());let H=te();if(H.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let re=j();s(B.CloseStatement,"Expected closing statement token");let Ie=[];for(;!i("endcall");)Ie.push(a());s(B.OpenStatement,"Expected '{%'"),n("endcall"),s(B.CloseStatement,"Expected closing statement token");let se=new $g(H,re);z=new jO(se,R,Ie);break}case "break":++r,s(B.CloseStatement,"Expected closing statement token"),z=new EO;break;case "continue":++r,s(B.CloseStatement,"Expected closing statement token"),z=new AO;break;case "filter":{++r;let R=te();R instanceof Es&&o(B.OpenParen)&&(R=G(R)),s(B.CloseStatement,"Expected closing statement token");let H=[];for(;!i("endfilter");)H.push(a());s(B.OpenStatement,"Expected '{%'"),n("endfilter"),s(B.CloseStatement,"Expected '%}'"),z=new DO(R,H);break}default:throw new SyntaxError(`Unknown statement type: ${I}`)}return z}function h(){s(B.OpenExpression,"Expected opening expression token");let I=x();return s(B.CloseExpression,"Expected closing expression token"),I}function _(){let I=y(),z=null,R=[];if(o(B.Equals))++r,z=y();else {for(s(B.CloseStatement,"Expected %} token");!i("endset");)R.push(a());s(B.OpenStatement,"Expected {% token"),n("endset");}return s(B.CloseStatement,"Expected closing statement token"),new CO(I,z,R)}function p(){let I=x();s(B.CloseStatement,"Expected closing statement token");let z=[],R=[];for(;!i("elif","else","endif");)z.push(a());if(i("elif")){++r,++r;let H=p();R.push(H);}else if(i("else"))for(++r,++r,s(B.CloseStatement,"Expected closing statement token");!i("endif");)R.push(a());return new kO(I,z,R)}function w(){let I=te();if(I.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let z=j();s(B.CloseStatement,"Expected closing statement token");let R=[];for(;!i("endmacro");)R.push(a());return new SO(I,z,R)}function y(I=false){let z=I?te:x,R=[z()],H=o(B.Comma);for(;H&&(++r,R.push(z()),!!o(B.Comma)););return H?new Ug(R):R[0]}function b(){let I=y(true);if(!(I instanceof Es||I instanceof Ug))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${I.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let z=x();s(B.CloseStatement,"Expected closing statement token");let R=[];for(;!i("endfor","else");)R.push(a());let H=[];if(i("else"))for(++r,++r,s(B.CloseStatement,"Expected closing statement token");!i("endfor");)H.push(a());return new TO(I,z,R,H)}function x(){return T()}function T(){let I=C();if(l("if")){++r;let z=C();if(l("else")){++r;let R=T();return new qO(z,I,R)}else return new BO(I,z)}return I}function C(){let I=A();for(;l("or");){let z=e[r];++r;let R=A();I=new wn(z,I,R);}return I}function A(){let I=S();for(;l("and");){let z=e[r];++r;let R=S();I=new wn(z,I,R);}return I}function S(){let I;for(;l("not");){let z=e[r];++r;let R=S();I=new GO(z,R);}return I??N()}function N(){let I=M();for(;;){let z;if(l("not","in"))z=new Lt("not in",B.Identifier),r+=2;else if(l("in"))z=e[r++];else if(o(B.ComparisonBinaryOperator))z=e[r++];else break;let R=M();I=new wn(z,I,R);}return I}function M(){let I=D();for(;o(B.AdditiveBinaryOperator);){let z=e[r];++r;let R=D();I=new wn(z,I,R);}return I}function $(){let I=X(te());return o(B.OpenParen)?G(I):I}function G(I){let z=new $g(I,j());return z=X(z),o(B.OpenParen)&&(z=G(z)),z}function j(){s(B.OpenParen,"Expected opening parenthesis for arguments list");let I=Q();return s(B.CloseParen,"Expected closing parenthesis for arguments list"),I}function Q(){let I=[];for(;!o(B.CloseParen);){let z;if(e[r].type===B.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;let R=x();z=new UO(R);}else if(z=x(),o(B.Equals)){if(++r,!(z instanceof Es))throw new SyntaxError("Expected identifier for keyword argument");let R=x();z=new VO(z,R);}I.push(z),o(B.Comma)&&++r;}return I}function q(){let I=[],z=false;for(;!o(B.CloseSquareBracket);)o(B.Colon)?(I.push(void 0),++r,z=true):(I.push(x()),o(B.Colon)&&(++r,z=true));if(I.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(z){if(I.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new $O(...I)}return I[0]}function X(I){for(;o(B.Dot)||o(B.OpenSquareBracket);){let z=e[r];++r;let R,H=z.type===B.OpenSquareBracket;if(H)R=q(),s(B.CloseSquareBracket,"Expected closing square bracket");else if(R=te(),R.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");I=new FO(I,R,H);}return I}function D(){let I=L();for(;o(B.MultiplicativeBinaryOperator);){let z=e[r++],R=L();I=new wn(z,I,R);}return I}function L(){let I=Y();for(;l("is");){++r;let z=l("not");z&&++r;let R=te();if(!(R instanceof Es))throw new SyntaxError("Expected identifier for the test");I=new RO(I,z,R);}return I}function Y(){let I=$();for(;o(B.Pipe);){++r;let z=te();if(!(z instanceof Es))throw new SyntaxError("Expected identifier for the filter");o(B.OpenParen)&&(z=G(z)),I=new zO(I,z);}return I}function te(){let I=e[r++];switch(I.type){case B.NumericLiteral:{let z=I.value;return z.includes(".")?new IO(Number(z)):new LO(Number(z))}case B.StringLiteral:{let z=I.value;for(;o(B.StringLiteral);)z+=e[r++].value;return new Vg(z)}case B.Identifier:return new Es(I.value);case B.OpenParen:{let z=y();return s(B.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),z}case B.OpenSquareBracket:{let z=[];for(;!o(B.CloseSquareBracket);)z.push(x()),o(B.Comma)&&++r;return ++r,new OO(z)}case B.OpenCurlyBracket:{let z=new Map;for(;!o(B.CloseCurlyBracket);){let R=x();s(B.Colon,"Expected colon between key and value in object literal");let H=x();z.set(R,H),o(B.Comma)&&++r;}return ++r,new NO(z)}default:throw new SyntaxError(`Unexpected token: ${I.type}`)}}for(;r<e.length;)t.body.push(a());return t}function HO(e,t,r=1){if(t===void 0&&(t=e,e=0),r===0)throw new Error("range() step must not be zero");let s=[];if(r>0)for(let n=e;n<t;n+=r)s.push(n);else for(let n=e;n>t;n+=r)s.push(n);return s}function jg(e,t,r,s=1){let n=Math.sign(s);n>=0?(t=(t??(t=0))<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??(r=e.length))<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??(t=e.length-1))<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??(r=-1))<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));let a=[];for(let o=t;n*o<n*r;o+=s)a.push(e[o]);return a}function QO(e){return e.replace(/\b\w/g,t=>t.toUpperCase())}function XO(e){return YO(new Date,e)}function YO(e,t){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=a=>a<10?"0"+a:a.toString();return t.replace(/%[YmdbBHM%]/g,a=>{switch(a){case "%Y":return e.getFullYear().toString();case "%m":return n(e.getMonth()+1);case "%d":return n(e.getDate());case "%b":return s.format(e);case "%B":return r.format(e);case "%H":return n(e.getHours());case "%M":return n(e.getMinutes());case "%%":return "%";default:return a}})}function JO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KO(e,t,r,s){if(s===0)return e;let n=s==null||s<0?1/0:s,a=t.length===0?new RegExp("(?=)","gu"):new RegExp(JO(t),"gu");return e.replaceAll(a,o=>n>0?(--n,r):o)}var qg=class extends Error{},Wg=class extends Error{},nr=class{constructor(e=void 0){k(this,"type","RuntimeValue");k(this,"value");k(this,"builtins",new Map);this.value=e;}__bool__(){return new oe(!!this.value)}toString(){return String(this.value)}},de=class extends nr{constructor(){super(...arguments);k(this,"type","IntegerValue");}},Ge=class extends nr{constructor(){super(...arguments);k(this,"type","FloatValue");}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},K=class extends nr{constructor(){super(...arguments);k(this,"type","StringValue");k(this,"builtins",new Map([["upper",new ze(()=>new K(this.value.toUpperCase()))],["lower",new ze(()=>new K(this.value.toLowerCase()))],["strip",new ze(()=>new K(this.value.trim()))],["title",new ze(()=>new K(QO(this.value)))],["capitalize",new ze(()=>new K(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new de(this.value.length)],["rstrip",new ze(()=>new K(this.value.trimEnd()))],["lstrip",new ze(()=>new K(this.value.trimStart()))],["startswith",new ze(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let r=t[0];if(r instanceof K)return new oe(this.value.startsWith(r.value));if(r instanceof pe){for(let s of r.value){if(!(s instanceof K))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(s.value))return new oe(true)}return new oe(false)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new ze(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let r=t[0];if(r instanceof K)return new oe(this.value.endsWith(r.value));if(r instanceof pe){for(let s of r.value){if(!(s instanceof K))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(s.value))return new oe(true)}return new oe(false)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new ze(t=>{let r=t[0]??new Be;if(!(r instanceof K||r instanceof Be))throw new Error("sep argument must be a string or null");let s=t[1]??new de(-1);if(!(s instanceof de))throw new Error("maxsplit argument must be a number");let n=[];if(r instanceof Be){let a=this.value.trimStart();for(let{0:o,index:i}of a.matchAll(/\S+/g)){if(s.value!==-1&&n.length>=s.value&&i!==void 0){n.push(o+a.slice(i+o.length));break}n.push(o);}}else {if(r.value==="")throw new Error("empty separator");n=this.value.split(r.value),s.value!==-1&&n.length>s.value&&n.push(n.splice(s.value).join(r.value));}return new pe(n.map(a=>new K(a)))})],["replace",new ze(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let r=t[0],s=t[1];if(!(r instanceof K&&s instanceof K))throw new Error("replace() arguments must be strings");let n;if(t.length>2?t[2].type==="KeywordArgumentsValue"?n=t[2].value.get("count")??new Be:n=t[2]:n=new Be,!(n instanceof de||n instanceof Be))throw new Error("replace() count argument must be a number or null");return new K(KO(this.value,r.value,s.value,n.value))})]]));}},oe=class extends nr{constructor(){super(...arguments);k(this,"type","BooleanValue");}},ZO=/[\x7f-\uffff]/g;function Hg(e){return e.replace(ZO,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Kr(e,t={},r=0,s=true){let{indent:n=null,ensureAscii:a=false,separators:o=null,sortKeys:i=false}=t,l,c;switch(o?[l,c]=o:n?(l=",",c=": "):(l=", ",c=": "),e.type){case "NullValue":return "null";case "UndefinedValue":return s?"null":"undefined";case "IntegerValue":case "FloatValue":case "BooleanValue":return JSON.stringify(e.value);case "StringValue":{let d=JSON.stringify(e.value);return a&&(d=Hg(d)),d}case "ArrayValue":case "ObjectValue":{let d=n?" ".repeat(n):"",h=`
|
|
8
|
+
`+d.repeat(r),_=h+d;if(e.type==="ArrayValue"){let p=e.value.map(w=>Kr(w,t,r+1,s));return n?`[${_}${p.join(`${l}${_}`)}${h}]`:`[${p.join(l)}]`}else {let p=Array.from(e.value.entries());i&&(p=p.sort(([y],[b])=>y.localeCompare(b)));let w=p.map(([y,b])=>{let x=JSON.stringify(y);a&&(x=Hg(x));let T=`${x}${c}${Kr(b,t,r+1,s)}`;return n?`${_}${T}`:T});return n?`{${w.join(l)}${h}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var et=class extends nr{constructor(){super(...arguments);k(this,"type","ObjectValue");k(this,"builtins",new Map([["get",new ze(([t,r])=>{if(!(t instanceof K))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??r??new Be})],["items",new ze(()=>this.items())],["keys",new ze(()=>this.keys())],["values",new ze(()=>this.values())],["dictsort",new ze(t=>{let r=new Map,s=t.filter(l=>l instanceof Fn?(r=l.value,false):true),n=s.at(0)??r.get("case_sensitive")??new oe(false);if(!(n instanceof oe))throw new Error("case_sensitive must be a boolean");let a=s.at(1)??r.get("by")??new K("key");if(!(a instanceof K))throw new Error("by must be a string");if(!["key","value"].includes(a.value))throw new Error("by must be either 'key' or 'value'");let o=s.at(2)??r.get("reverse")??new oe(false);if(!(o instanceof oe))throw new Error("reverse must be a boolean");let i=Array.from(this.value.entries()).map(([l,c])=>new pe([new K(l),c])).sort((l,c)=>{let d=a.value==="key"?0:1,h=l.value[d],_=c.value[d],p=rd(h,_,n.value);return o.value?-p:p});return new pe(i)})]]));}__bool__(){return new oe(this.value.size>0)}items(){return new pe(Array.from(this.value.entries()).map(([t,r])=>new pe([new K(t),r])))}keys(){return new pe(Array.from(this.value.keys()).map(t=>new K(t)))}values(){return new pe(Array.from(this.value.values()))}toString(){return Kr(this,{},0,false)}},Fn=class extends et{constructor(){super(...arguments);k(this,"type","KeywordArgumentsValue");}},pe=class extends nr{constructor(){super(...arguments);k(this,"type","ArrayValue");k(this,"builtins",new Map([["length",new de(this.value.length)]]));}__bool__(){return new oe(this.value.length>0)}toString(){return Kr(this,{},0,false)}},Qg=class extends pe{constructor(){super(...arguments);k(this,"type","TupleValue");}},ze=class extends nr{constructor(){super(...arguments);k(this,"type","FunctionValue");}},Be=class extends nr{constructor(){super(...arguments);k(this,"type","NullValue");}},Ne=class extends nr{constructor(){super(...arguments);k(this,"type","UndefinedValue");}},Yr=class{constructor(e){k(this,"variables",new Map([["namespace",new ze(e=>{if(e.length===0)return new et(new Map);if(e.length!==1||!(e[0]instanceof et))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]));k(this,"tests",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof ze],["odd",e=>{if(!(e instanceof de))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof de))throw new Error(`cannot even on ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["none",e=>e.type==="NullValue"],["string",e=>e.type==="StringValue"],["number",e=>e instanceof de||e instanceof Ge],["integer",e=>e instanceof de],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof et],["sequence",e=>e instanceof pe||e instanceof et||e instanceof K],["lower",e=>{let t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{let t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]));this.parent=e;}set(e,t){return this.declareVariable(e,io(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new Ne}catch{return new Ne}}};function eN(e){e.set("false",false),e.set("true",true),e.set("none",null),e.set("raise_exception",t=>{throw new Error(t)}),e.set("range",HO),e.set("strftime_now",XO),e.set("True",true),e.set("False",false),e.set("None",null);}function Xg(e,t){let r=t.split("."),s=e;for(let n of r)if(s instanceof et)s=s.value.get(n)??new Ne;else if(s instanceof pe){let a=parseInt(n,10);if(!isNaN(a)&&a>=0&&a<s.value.length)s=s.value[a];else return new Ne}else return new Ne;return s}function rd(e,t,r=false){if(e instanceof Be&&t instanceof Be)return 0;if(e instanceof Be||t instanceof Be)throw new Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof Ne&&t instanceof Ne)return 0;if(e instanceof Ne||t instanceof Ne)throw new Error(`Cannot compare ${e.type} with ${t.type}`);let s=a=>a instanceof de||a instanceof Ge||a instanceof oe,n=a=>a instanceof oe?a.value?1:0:a.value;if(s(e)&&s(t)){let a=n(e),o=n(t);return a<o?-1:a>o?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);if(e.type==="StringValue"){let a=e.value,o=t.value;return r||(a=a.toLowerCase(),o=o.toLowerCase()),a<o?-1:a>o?1:0}else throw new Error(`Cannot compare type: ${e.type}`)}var tN=class{constructor(e){k(this,"global");this.global=e??new Yr;}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let r=this.evaluate(e.left,t);switch(e.operator.value){case "and":return r.__bool__().value?this.evaluate(e.right,t):r;case "or":return r.__bool__().value?r:this.evaluate(e.right,t)}let s=this.evaluate(e.right,t);switch(e.operator.value){case "==":return new oe(r.value==s.value);case "!=":return new oe(r.value!=s.value)}if(r instanceof Ne||s instanceof Ne){if(s instanceof Ne&&["in","not in"].includes(e.operator.value))return new oe(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else {if(r instanceof Be||s instanceof Be)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new K(r.value.toString()+s.value.toString());if((r instanceof de||r instanceof Ge)&&(s instanceof de||s instanceof Ge)){let n=r.value,a=s.value;switch(e.operator.value){case "+":case "-":case "*":{let o=e.operator.value==="+"?n+a:e.operator.value==="-"?n-a:n*a;return r instanceof Ge||s instanceof Ge?new Ge(o):new de(o)}case "/":return new Ge(n/a);case "%":{let o=n%a;return r instanceof Ge||s instanceof Ge?new Ge(o):new de(o)}case "<":return new oe(n<a);case ">":return new oe(n>a);case ">=":return new oe(n>=a);case "<=":return new oe(n<=a)}}else if(r instanceof pe&&s instanceof pe){if(e.operator.value==="+")return new pe(r.value.concat(s.value))}else if(s instanceof pe){let n=s.value.find(a=>a.value===r.value)!==void 0;switch(e.operator.value){case "in":return new oe(n);case "not in":return new oe(!n)}}}if((r instanceof K||s instanceof K)&&e.operator.value==="+")return new K(r.value.toString()+s.value.toString());if(r instanceof K&&s instanceof K)switch(e.operator.value){case "in":return new oe(s.value.includes(r.value));case "not in":return new oe(!s.value.includes(r.value))}if(r instanceof K&&s instanceof et)switch(e.operator.value){case "in":return new oe(s.value.has(r.value));case "not in":return new oe(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(e,t){let r=[],s=new Map;for(let n of e)if(n.type==="SpreadExpression"){let a=n,o=this.evaluate(a.argument,t);if(!(o instanceof pe))throw new Error(`Cannot unpack non-iterable type: ${o.type}`);for(let i of o.value)r.push(i);}else if(n.type==="KeywordArgumentExpression"){let a=n;s.set(a.key.value,this.evaluate(a.value,t));}else {if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,t));}return [r,s]}applyFilter(e,t,r){if(t.type==="Identifier"){let s=t;if(s.value==="safe")return e;if(s.value==="tojson")return new K(Kr(e,{}));if(e instanceof pe)switch(s.value){case "list":return e;case "first":return e.value[0];case "last":return e.value[e.value.length-1];case "length":return new de(e.value.length);case "reverse":return new pe(e.value.slice().reverse());case "sort":return new pe(e.value.slice().sort((n,a)=>rd(n,a,false)));case "join":return new K(e.value.map(n=>n.value).join(""));case "string":return new K(Kr(e,{},0,false));case "unique":{let n=new Set,a=[];for(let o of e.value)n.has(o.value)||(n.add(o.value),a.push(o));return new pe(a)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(e instanceof K)switch(s.value){case "length":case "upper":case "lower":case "title":case "capitalize":{let n=e.builtins.get(s.value);if(n instanceof ze)return n.value([],r);if(n instanceof de)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case "trim":return new K(e.value.trim());case "indent":return new K(e.value.split(`
|
|
9
|
+
`).map((n,a)=>a===0||n.length===0?n:" "+n).join(`
|
|
10
|
+
`));case "join":case "string":return e;case "int":{let n=parseInt(e.value,10);return new de(isNaN(n)?0:n)}case "float":{let n=parseFloat(e.value);return new Ge(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(e instanceof de||e instanceof Ge)switch(s.value){case "abs":return e instanceof de?new de(Math.abs(e.value)):new Ge(Math.abs(e.value));case "int":return new de(Math.floor(e.value));case "float":return new Ge(e.value);case "string":return new K(e.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(e instanceof et)switch(s.value){case "items":return new pe(Array.from(e.value.entries()).map(([n,a])=>new pe([new K(n),a])));case "length":return new de(e.value.size);default:{let n=e.builtins.get(s.value);if(n)return n instanceof ze?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(e instanceof oe)switch(s.value){case "bool":return new oe(e.value);case "int":return new de(e.value?1:0);case "float":return new Ge(e.value?1:0);case "string":return new K(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${e.type}`)}else if(t.type==="CallExpression"){let s=t;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,a]=this.evaluateArguments(s.args,r),o=a.get("indent")??new Be;if(!(o instanceof de||o instanceof Be))throw new Error("If set, indent must be a number");let i=a.get("ensure_ascii")??new oe(false);if(!(i instanceof oe))throw new Error("If set, ensure_ascii must be a boolean");let l=a.get("sort_keys")??new oe(false);if(!(l instanceof oe))throw new Error("If set, sort_keys must be a boolean");let c=a.get("separators")??new Be,d=null;if(c instanceof pe||c instanceof Qg){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[h,_]=c.value;if(!(h instanceof K)||!(_ instanceof K))throw new Error("separators must be a tuple of two strings");d=[h.value,_.value];}else if(!(c instanceof Be))throw new Error("If set, separators must be a tuple of two strings");return new K(Kr(e,{indent:o.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(n==="join"){let a;if(e instanceof K)a=Array.from(e.value);else if(e instanceof pe)a=e.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`);let[o,i]=this.evaluateArguments(s.args,r),l=o.at(0)??i.get("separator")??new K("");if(!(l instanceof K))throw new Error("separator must be a string");return new K(a.join(l.value))}else if(n==="int"||n==="float"){let[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("default")??(n==="int"?new de(0):new Ge(0));if(e instanceof K){let l=n==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(l)?i:n==="int"?new de(l):new Ge(l)}else {if(e instanceof de||e instanceof Ge)return e;if(e instanceof oe)return n==="int"?new de(e.value?1:0):new Ge(e.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}}else if(n==="default"){let[a,o]=this.evaluateArguments(s.args,r),i=a[0]??new K(""),l=a[1]??o.get("boolean")??new oe(false);if(!(l instanceof oe))throw new Error("`default` filter flag must be a boolean");return e instanceof Ne||l.value&&!e.__bool__().value?i:e}if(e instanceof pe){switch(n){case "sort":{let[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("reverse")??new oe(false);if(!(i instanceof oe))throw new Error("reverse must be a boolean");let l=a.at(1)??o.get("case_sensitive")??new oe(false);if(!(l instanceof oe))throw new Error("case_sensitive must be a boolean");let c=a.at(2)??o.get("attribute")??new Be;if(!(c instanceof K||c instanceof de||c instanceof Be))throw new Error("attribute must be a string, integer, or null");let d=h=>{if(c instanceof Be)return h;let _=c instanceof de?String(c.value):c.value;return Xg(h,_)};return new pe(e.value.slice().sort((h,_)=>{let p=d(h),w=d(_),y=rd(p,w,l.value);return i.value?-y:y}))}case "selectattr":case "rejectattr":{let a=n==="selectattr";if(e.value.some(h=>!(h instanceof et)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(h=>h.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[o,i,l]=s.args.map(h=>this.evaluate(h,r)),c;if(i){let h=r.tests.get(i.value);if(!h)throw new Error(`Unknown test: ${i.value}`);c=h;}else c=(...h)=>h[0].__bool__().value;let d=e.value.filter(h=>{let _=h.value.get(o.value),p=_?c(_,l):false;return a?p:!p});return new pe(d)}case "map":{let[,a]=this.evaluateArguments(s.args,r);if(a.has("attribute")){let o=a.get("attribute");if(!(o instanceof K))throw new Error("attribute must be a string");let i=a.get("default"),l=e.value.map(c=>{if(!(c instanceof et))throw new Error("items in map must be an object");let d=Xg(c,o.value);return d instanceof Ne?i??new Ne:d});return new pe(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(e instanceof K){switch(n){case "indent":{let[a,o]=this.evaluateArguments(s.args,r),i=a.at(0)??o.get("width")??new de(4);if(!(i instanceof de))throw new Error("width must be a number");let l=a.at(1)??o.get("first")??new oe(false),c=a.at(2)??o.get("blank")??new oe(false),d=e.value.split(`
|
|
11
|
+
`),h=" ".repeat(i.value),_=d.map((p,w)=>!l.value&&w===0||!c.value&&p.length===0?p:h+p);return new K(_.join(`
|
|
12
|
+
`))}case "replace":{let a=e.builtins.get("replace");if(!(a instanceof ze))throw new Error("replace filter not available");let[o,i]=this.evaluateArguments(s.args,r);return a.value([...o,new Fn(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(e instanceof et){let a=e.builtins.get(n);if(a&&a instanceof ze){let[o,i]=this.evaluateArguments(s.args,r);return i.size>0&&o.push(new Fn(i)),a.value(o,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){let r=this.evaluate(e.operand,t),s=t.tests.get(e.test.value);if(!s)throw new Error(`Unknown test: ${e.test.value}`);let n=s(r);return new oe(e.negate?!n:n)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new Ne}evaluateUnaryExpression(e,t){let r=this.evaluate(e.argument,t);if(e.operator.value==="not")return new oe(!r.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(let s of e){let n=this.evaluate(s,t);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString());}return new K(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[r,s]=this.evaluateArguments(e.args,t);s.size>0&&r.push(new Fn(s));let n=this.evaluate(e.callee,t);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof pe||e instanceof K))throw new Error("Slice object must be an array or string");let s=this.evaluate(t.start,r),n=this.evaluate(t.stop,r),a=this.evaluate(t.step,r);if(!(s instanceof de||s instanceof Ne))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof de||n instanceof Ne))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof de||a instanceof Ne))throw new Error("Slice step must be numeric or undefined");return e instanceof pe?new pe(jg(e.value,s.value,n.value,a.value)):new K(jg(Array.from(e.value),s.value,n.value,a.value).join(""))}evaluateMemberExpression(e,t){let r=this.evaluate(e.object,t),s;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);s=this.evaluate(e.property,t);}else s=new K(e.property.value);let n;if(r instanceof et){if(!(s instanceof K))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 pe||r instanceof K)if(s instanceof de)n=r.value.at(s.value),r instanceof K&&(n=new K(r.value.at(s.value)));else if(s instanceof K)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 K))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value);}return n instanceof nr?n:new Ne}evaluateSet(e,t){let r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){let s=e.assignee.value;t.setVariable(s,r);}else if(e.assignee.type==="TupleLiteral"){let s=e.assignee;if(!(r instanceof pe))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 a=0;a<s.value.length;++a){let o=s.value[a];if(o.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${o.type}`);t.setVariable(o.value,n[a]);}}else if(e.assignee.type==="MemberExpression"){let s=e.assignee,n=this.evaluate(s.object,t);if(!(n instanceof et))throw new Error("Cannot assign to member of non-object");if(s.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(s.property.value,r);}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new Be}evaluateIf(e,t){let r=this.evaluate(e.test,t);return this.evaluateBlock(r.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let r=new Yr(t),s,n;if(e.iterable.type==="SelectExpression"){let c=e.iterable;n=this.evaluate(c.lhs,r),s=c.test;}else n=this.evaluate(e.iterable,r);if(!(n instanceof pe||n instanceof et))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof et&&(n=n.keys());let a=[],o=[];for(let c=0;c<n.value.length;++c){let d=new Yr(r),h=n.value[c],_;if(e.loopvar.type==="Identifier")_=p=>p.setVariable(e.loopvar.value,h);else if(e.loopvar.type==="TupleLiteral"){let p=e.loopvar;if(h.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${h.type}`);let w=h;if(p.value.length!==w.value.length)throw new Error(`Too ${p.value.length>w.value.length?"few":"many"} items to unpack`);_=y=>{for(let b=0;b<p.value.length;++b){if(p.value[b].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${p.value[b].type}`);y.setVariable(p.value[b].value,w.value[b]);}};}else throw new Error(`Invalid loop variable(s): ${e.loopvar.type}`);s&&(_(d),!this.evaluate(s,d).__bool__().value)||(a.push(h),o.push(_));}let i="",l=true;for(let c=0;c<a.length;++c){let d=new Map([["index",new de(c+1)],["index0",new de(c)],["revindex",new de(a.length-c)],["revindex0",new de(a.length-c-1)],["first",new oe(c===0)],["last",new oe(c===a.length-1)],["length",new de(a.length)],["previtem",c>0?a[c-1]:new Ne],["nextitem",c<a.length-1?a[c+1]:new Ne]]);r.setVariable("loop",new et(d)),o[c](r);try{let h=this.evaluateBlock(e.body,r);i+=h.value;}catch(h){if(h instanceof Wg)continue;if(h instanceof qg)break;throw h}l=false;}if(l){let c=this.evaluateBlock(e.defaultBlock,r);i+=c.value;}return new K(i)}evaluateMacro(e,t){return t.setVariable(e.name.value,new ze((r,s)=>{let n=new Yr(s);r=r.slice();let a;r.at(-1)?.type==="KeywordArgumentsValue"&&(a=r.pop());for(let o=0;o<e.args.length;++o){let i=e.args[o],l=r[o];if(i.type==="Identifier"){let c=i;if(!l)throw new Error(`Missing positional argument: ${c.value}`);n.setVariable(c.value,l);}else if(i.type==="KeywordArgumentExpression"){let c=i,d=l??a?.value.get(c.key.value)??this.evaluate(c.value,n);n.setVariable(c.key.value,d);}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(e.body,n)})),new Be}evaluateCallStatement(e,t){let r=new ze((i,l)=>{let c=new Yr(l);if(e.callerArgs)for(let d=0;d<e.callerArgs.length;++d){let h=e.callerArgs[d];if(h.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${h.type}`);c.setVariable(h.value,i[d]??new Ne);}return this.evaluateBlock(e.body,c)}),[s,n]=this.evaluateArguments(e.call.args,t);s.push(new Fn(n));let a=this.evaluate(e.call.callee,t);if(a.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${a.type}`);let o=new Yr(t);return o.setVariable("caller",r),a.value(s,o)}evaluateFilterStatement(e,t){let r=this.evaluateBlock(e.body,t);return this.applyFilter(r,e.filter,t)}evaluate(e,t){if(!e)return new Ne;switch(e.type){case "Program":return this.evalProgram(e,t);case "Set":return this.evaluateSet(e,t);case "If":return this.evaluateIf(e,t);case "For":return this.evaluateFor(e,t);case "Macro":return this.evaluateMacro(e,t);case "CallStatement":return this.evaluateCallStatement(e,t);case "Break":throw new qg;case "Continue":throw new Wg;case "IntegerLiteral":return new de(e.value);case "FloatLiteral":return new Ge(e.value);case "StringLiteral":return new K(e.value);case "ArrayLiteral":return new pe(e.value.map(r=>this.evaluate(r,t)));case "TupleLiteral":return new Qg(e.value.map(r=>this.evaluate(r,t)));case "ObjectLiteral":{let r=new Map;for(let[s,n]of e.value){let a=this.evaluate(s,t);if(!(a instanceof K))throw new Error(`Object keys must be strings: got ${a.type}`);r.set(a.value,this.evaluate(n,t));}return new et(r)}case "Identifier":return this.evaluateIdentifier(e,t);case "CallExpression":return this.evaluateCallExpression(e,t);case "MemberExpression":return this.evaluateMemberExpression(e,t);case "UnaryExpression":return this.evaluateUnaryExpression(e,t);case "BinaryExpression":return this.evaluateBinaryExpression(e,t);case "FilterExpression":return this.evaluateFilterExpression(e,t);case "FilterStatement":return this.evaluateFilterStatement(e,t);case "TestExpression":return this.evaluateTestExpression(e,t);case "SelectExpression":return this.evaluateSelectExpression(e,t);case "Ternary":return this.evaluateTernaryExpression(e,t);case "Comment":return new Be;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function io(e){switch(typeof e){case "number":return Number.isInteger(e)?new de(e):new Ge(e);case "string":return new K(e);case "boolean":return new oe(e);case "undefined":return new Ne;case "object":return e===null?new Be:Array.isArray(e)?new pe(e.map(io)):new et(new Map(Object.entries(e).map(([t,r])=>[t,io(r)])));case "function":return new ze((t,r)=>{let s=e(...t.map(n=>n.value))??null;return io(s)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var Qe=`
|
|
13
|
+
`,rN="{%- ",sN=" -%}";function nN(e){switch(e.operator.type){case "MultiplicativeBinaryOperator":return 4;case "AdditiveBinaryOperator":return 3;case "ComparisonBinaryOperator":return 2;case "Identifier":return e.operator.value==="and"?1:e.operator.value==="in"||e.operator.value==="not in"?2:0}return 0}function aN(e,t=" "){let r=typeof t=="number"?" ".repeat(t):t;return Vt(e.body,0,r).replace(/\n$/,"")}function ot(...e){return rN+e.join(" ")+sN}function Vt(e,t,r){return e.map(s=>oN(s,t,r)).join(Qe)}function oN(e,t,r){let s=r.repeat(t);switch(e.type){case "Program":return Vt(e.body,t,r);case "If":return iN(e,t,r);case "For":return lN(e,t,r);case "Set":return cN(e,t,r);case "Macro":return uN(e,t,r);case "Break":return s+ot("break");case "Continue":return s+ot("continue");case "CallStatement":return dN(e,t,r);case "FilterStatement":return hN(e,t,r);case "Comment":return s+"{# "+e.value+" #}";default:return s+"{{- "+ge(e)+" -}}"}}function iN(e,t,r){let s=r.repeat(t),n=[],a=e;for(;a&&(n.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type==="If");)a=a.alternate[0];let o=s+ot("if",ge(n[0].test))+Qe+Vt(n[0].body,t+1,r);for(let i=1;i<n.length;++i)o+=Qe+s+ot("elif",ge(n[i].test))+Qe+Vt(n[i].body,t+1,r);return a&&a.alternate.length>0&&(o+=Qe+s+ot("else")+Qe+Vt(a.alternate,t+1,r)),o+=Qe+s+ot("endif"),o}function lN(e,t,r){let s=r.repeat(t),n="";if(e.iterable.type==="SelectExpression"){let o=e.iterable;n=`${ge(o.lhs)} if ${ge(o.test)}`;}else n=ge(e.iterable);let a=s+ot("for",ge(e.loopvar),"in",n)+Qe+Vt(e.body,t+1,r);return e.defaultBlock.length>0&&(a+=Qe+s+ot("else")+Qe+Vt(e.defaultBlock,t+1,r)),a+=Qe+s+ot("endfor"),a}function cN(e,t,r){let s=r.repeat(t),n=ge(e.assignee),a=e.value?ge(e.value):"",o=s+ot("set",`${n}${e.value?" = "+a:""}`);return e.body.length===0?o:o+Qe+Vt(e.body,t+1,r)+Qe+s+ot("endset")}function uN(e,t,r){let s=r.repeat(t),n=e.args.map(ge).join(", ");return s+ot("macro",`${e.name.value}(${n})`)+Qe+Vt(e.body,t+1,r)+Qe+s+ot("endmacro")}function dN(e,t,r){let s=r.repeat(t),n=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(ge).join(", ")})`:"",a=ge(e.call),o=s+ot(`call${n}`,a)+Qe;return o+=Vt(e.body,t+1,r)+Qe,o+=s+ot("endcall"),o}function hN(e,t,r){let s=r.repeat(t),n=e.filter.type==="Identifier"?e.filter.value:ge(e.filter),a=s+ot("filter",n)+Qe;return a+=Vt(e.body,t+1,r)+Qe,a+=s+ot("endfilter"),a}function ge(e,t=-1){switch(e.type){case "SpreadExpression":return `*${ge(e.argument)}`;case "Identifier":return e.value;case "IntegerLiteral":return `${e.value}`;case "FloatLiteral":return `${e.value}`;case "StringLiteral":return JSON.stringify(e.value);case "BinaryExpression":{let r=e,s=nN(r),n=ge(r.left,s),a=ge(r.right,s+1),o=`${n} ${r.operator.value} ${a}`;return s<t?`(${o})`:o}case "UnaryExpression":{let r=e;return r.operator.value+(r.operator.value==="not"?" ":"")+ge(r.argument,1/0)}case "CallExpression":{let r=e,s=r.args.map(ge).join(", ");return `${ge(r.callee)}(${s})`}case "MemberExpression":{let r=e,s=ge(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ge(r.property);return !r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case "FilterExpression":{let r=e,s=ge(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ge(r.filter)}`:`${s} | ${r.filter.value}`}case "SelectExpression":{let r=e;return `${ge(r.lhs)} if ${ge(r.test)}`}case "TestExpression":{let r=e;return `${ge(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case "ArrayLiteral":case "TupleLiteral":{let r=e.value.map(ge),s=e.type==="ArrayLiteral"?"[]":"()";return `${s[0]}${r.join(", ")}${s[1]}`}case "ObjectLiteral":return `{${Array.from(e.value.entries()).map(([s,n])=>`${ge(s)}: ${ge(n)}`).join(", ")}}`;case "SliceExpression":{let r=e,s=r.start?ge(r.start):"",n=r.stop?ge(r.stop):"",a=r.step?`:${ge(r.step)}`:"";return `${s}:${n}${a}`}case "KeywordArgumentExpression":{let r=e;return `${r.key.value}=${ge(r.value)}`}case "Ternary":{let r=e,s=`${ge(r.trueExpr)} if ${ge(r.condition,0)} else ${ge(r.falseExpr)}`;return t>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${e.type}`)}}var fN=class{constructor(e){k(this,"parsed");let t=MO(e,{lstrip_blocks:true,trim_blocks:true});this.parsed=WO(t);}render(e){let t=new Yr;if(eN(t),e)for(let[n,a]of Object.entries(e))t.set(n,a);return new tN(t).run(this.parsed).value}format(e){return aN(this.parsed,e?.indent||" ")}},_N={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"},mo=class Bw{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=At.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=At.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=At.createReadStream(t);this.body=new ReadableStream({start(n){s.on("data",a=>n.enqueue(a)),s.on("end",()=>n.close()),s.on("error",a=>n.error(a));},cancel(){s.destroy();}});}else this.status=404,this.statusText="Not Found",this.body=null;}updateContentType(){let t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",_N[t]??"application/octet-stream");}clone(){let t=new Bw(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return (await At.promises.readFile(this.filePath)).buffer}async blob(){let t=await At.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await At.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Co=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(he.IS_CRYPTO_AVAILABLE){let o=new Uint32Array(1);crypto.getRandomValues(o),e=o[0];}else e=Date.now()>>>0;let t=this._mt,r=(o,i)=>Math.imul(o,i)>>>0,s=[];for(let o=e||0;o>0;o=Math.floor(o/4294967296))s.push(o&4294967295);s.length||s.push(0),t[0]=19650218;for(let o=1;o<624;++o)t[o]=r(1812433253,t[o-1]^t[o-1]>>>30)+o>>>0;let n=1,a=0;for(let o=Math.max(624,s.length);o>0;--o,++n,++a)n>=624&&(t[0]=t[623],n=1),a>=s.length&&(a=0),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1664525))+s[a]+a>>>0;for(let o=623;o>0;--o,++n)n>=624&&(t[0]=t[623],n=1),t[n]=(t[n]^r(t[n-1]^t[n-1]>>>30,1566083941))-n>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null;}_int32(){let e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){let s=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^s>>>1^(s&1?2567483615:0))>>>0;}this._idx=0;}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return ((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){let s=this.random()*2*Math.PI,n=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(s)*n,this._gauss_next=Math.sin(s)*n;}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){let r=32-Math.clz32(t+1),s=this._int32()>>>32-r;for(;s>t;)s=this._int32()>>>32-r;let n=e[t];e[t]=e[s],e[s]=n;}}choices(e,t){return e[Rw(this._random_fn,t)]}};function Rw(e,t){let r=0;for(let n=0;n<t.length;++n)r+=t[n];let s=e()*r;for(let n=0;n<t.length;++n)if(s-=t[n],s<0)return n;return t.length-1}var Jt=new Co,Vn=Object.freeze({Random:Co,seed:Jt.seed.bind(Jt),random:Jt.random.bind(Jt),gauss:Jt.gauss.bind(Jt),shuffle:Jt.shuffle.bind(Jt),choices:Jt.choices.bind(Jt)}),pN=e=>Rw(Vn.random,e),mN=new Co,Gw=class{constructor(e){this.path=e;}async match(e){let t=er.join(this.path,e),r=new mo(t);if(r.exists)return r}async put(e,t,r=void 0){let s=er.join(this.path,e),n=he.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=mN._int32().toString(36),o=s+`.tmp.${n}.${a}`;try{let i=t.headers.get("Content-Length"),l=parseInt(i??"0"),c=0;await At.promises.mkdir(er.dirname(s),{recursive:!0});let d=At.createWriteStream(o),h=t.body.getReader();for(;;){let{done:_,value:p}=await h.read();if(_)break;await new Promise((y,b)=>{d.write(p,x=>{if(x){b(x);return}y();});}),c+=p.length;let w=l?c/l*100:0;r?.({progress:w,loaded:c,total:l});}await new Promise((_,p)=>{d.close(w=>w?p(w):_());}),await At.promises.rename(o,s);}catch(i){try{await At.promises.unlink(o);}catch{}throw i}}async delete(e){let t=er.join(this.path,e);try{return await At.promises.unlink(t),!0}catch{return false}}},gN={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"},Yg=100,wN=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Da(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function Us(e,t=null,r=null){let s;try{s=new URL(e);}catch{return false}return !(t&&!t.includes(s.protocol)||r&&!r.includes(s.hostname))}function yN(e){return !(!wN.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function vN(e,t,r){if(!r)return null;let s=gN[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${s}: "${t}".`)}async function bN(e,t,r){let s=e.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ce.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(n),o=0,i=e.body.getReader();async function l(){let{done:c,value:d}=await i.read();if(c)return;let h=o+d.length;if(h>n){n=h;let p=new Uint8Array(n);p.set(a),a=p;}a.set(d,o),o=h;let _=o/n*100;return t({progress:_,loaded:o,total:n}),l()}return await l(),a}function Jg(e){return Us(e,["blob:"])}function Kg(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof import.meta<"u"&&import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var $w="SHA-256",MN="experimental_transformers-hash-cache",Zg=e=>({algorithm:$w,value:e}),Bn,vu,ew=(vu=class{constructor(){xa(this,Bn,null);k(this,"_getHashCache",()=>(dt(this,Bn)??ka(this,Bn,caches.open(MN)),dt(this,Bn)));k(this,"match",async e=>{let t=await this._getFileHash(e);if(t)try{let[r]=await navigator.crossOriginStorage.requestFileHandles([Zg(t)]),s=await r.getFile();return new Response(s,{headers:{"Content-Length":String(s.size)}})}catch{return}});k(this,"put",async(e,t)=>{let r=await this._getFileHash(e);if(r){let s=await t.blob();await this._storeBlobInCOS(s,r);}else this._processAndStore(e,t.body);});k(this,"_storeBlobInCOS",async(e,t)=>{let[r]=await navigator.crossOriginStorage.requestFileHandles([Zg(t)],{create:true}),s=await r.createWritable();await s.write(e),await s.close();});k(this,"_processAndStore",async(e,t)=>{try{let r=[];for await(let a of t)r.push(a);let s=new Blob(r),n=await this._getBlobHash(s);await this._storeBlobInCOS(s,n);try{await(await this._getHashCache()).put(e,new Response(n));}catch{}}catch{}});k(this,"delete",async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return false}});k(this,"_getFileHash",async e=>{try{let t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();let s=await this._getLfsFileHash(e);return s?(await t.put(e,new Response(s)),s):null}catch{return null}});k(this,"_getLfsFileHash",async e=>{if(!e.includes("/resolve/"))return null;let t=e.replace("/resolve/","/raw/");try{let s=(await fetch(t).then(n=>n.text())).match(/^oid sha256:([0-9a-f]+)$/m);return s?s[1]:null}catch{return null}});k(this,"_getBlobHash",async e=>{let t=await e.arrayBuffer(),r=await crypto.subtle.digest($w,t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")});}},Bn=new WeakMap,k(vu,"isAvailable",()=>typeof navigator<"u"&&"crossOriginStorage"in navigator),vu);async function js(e=null){let t=null;if(me.useCustomCache){if(!me.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!me.customCache.match||!me.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=me.customCache;}if(!t&&me.experimental_useCrossOriginStorage&&ew.isAvailable()&&(t=new ew),!t&&me.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(me.cacheKey);}catch(r){ce.warn("An error occurred while opening the browser cache:",r);}}if(!t&&me.useFSCache){if(!he.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new Gw(e??me.cacheDir);}return t}async function xN(e,...t){for(let r of t)try{let s=await e.match(r);if(s)return s}catch{continue}}var Rn,ft,Tw,kN=(Tw=class{constructor(e){xa(this,Rn);xa(this,ft);ka(this,Rn,e),ka(this,ft,new Map);}get(e){if(!dt(this,ft).has(e))return;let t=dt(this,ft).get(e);return dt(this,ft).delete(e),dt(this,ft).set(e,t),t}put(e,t){dt(this,ft).has(e)&&dt(this,ft).delete(e),dt(this,ft).set(e,t),dt(this,ft).size>dt(this,Rn)&&dt(this,ft).delete(dt(this,ft).keys().next().value);}delete(e){return dt(this,ft).delete(e)}clear(){dt(this,ft).clear();}},Rn=new WeakMap,ft=new WeakMap,Tw),TN=100,hu=new kN(TN);function Vw(e,t){let r=hu.get(e);if(r!==void 0)return r;let s=t().then(n=>n,n=>(hu.delete(e),Promise.reject(n)));return hu.put(e,s),s}async function EN(e){if(!Us(e,["http:","https:"]))return null;let t=Uw(e);return t.set("Range","bytes=0-0"),me.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function es(e,t,r={}){let s=JSON.stringify([e,t,r?.revision,r?.cache_dir,r?.local_files_only]);return Vw(s,()=>AN(e,t,r))}async function AN(e,t,r){let s=await js(r?.cache_dir),{localPath:n,remoteURL:a,proposedCacheKey:o,validModelId:i}=Un(e,t,r,s),l=await jn(s,n,o);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),d=l.headers.get("content-type");return {exists:true,size:c?parseInt(c,10):void 0,contentType:d||void 0,fromCache:true}}if(me.allowLocalModels&&!Us(n,["http:","https:"]))try{let d=await Nn(n);if(typeof d!="string"&&d.status!==404){let h=d.headers.get("content-length"),_=d.headers.get("content-type");return {exists:!0,size:h?parseInt(h,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(me.allowRemoteModels&&!r.local_files_only&&i)try{let c=await EN(a);if(c&&c.status>=200&&c.status<300){let d,h=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let p=_.match(/bytes \d+-\d+\/(\d+)/);p&&(d=parseInt(p[1],10));}}else if(c.status===200)try{await c.body?.cancel();}catch{}if(d===void 0){let _=c.headers.get("content-length");d=_?parseInt(_,10):void 0;}return {exists:!0,size:d,contentType:h||void 0,fromCache:!1}}}catch(c){ce.warn(`Unable to fetch file metadata for "${a}": ${c}`);}return {exists:false,fromCache:false}}async function Nn(e){return me.useFS&&!Us(e,["http:","https:","blob:"])?new mo(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):me.fetch(e,{headers:Uw(e)})}function Uw(e){let t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){let s=!!process.env?.TESTING_REMOTELY,n=me.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Us(e,["http:","https:"],["huggingface.co","hf.co"])){let o=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;o&&r.set("Authorization",`Bearer ${o}`);}}return r}function Un(e,t,r={},s=null){let n=r.revision??"main",a=Da(e,t),o=yN(e),i=o?Da(me.localModelPath,a):a,l=Da(me.remoteHost,me.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(n)),t),c=s instanceof Gw?n==="main"?a:Da(e,n,t):l;return {requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:o}}async function jn(e,t,r){if(e)return await xN(e,t,r)}async function CN(e,t,r,s,n,a,o={}){if(await r.match(s)===void 0)if(a){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",a.byteLength.toString()),await r.put(s,new Response(a,{headers:i})).catch(l=>{ce.warn(`Unable to add response to browser cache: ${l}.`);});}}else {let i=o.progress_callback?l=>Pr(o.progress_callback,{status:"progress",name:e,file:t,...l}):void 0;await r.put(s,n,i);}}async function SN(e,t,r=true,s={},n=false,a=null){let{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:d}=Un(e,t,s,a),h,_=false,p;p=await jn(a,i,c);let w=p!==void 0;if(w)h=c;else {if(me.allowLocalModels)if(Us(o,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);if(!me.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}else try{p=await Nn(i),h=i;}catch(T){ce.warn(`Unable to load from local path "${i}": "${T}"`);}if(p===void 0||typeof p!="string"&&p.status===404){if(s.local_files_only||!me.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${e}".`);if(p=await Nn(l),p.status!==200)return vN(p.status,l,r);h=c;}_=a&&typeof Response<"u"&&p instanceof Response&&p.status===200;}Pr(s.progress_callback,{status:"download",name:e,file:t});let y;if(!(he.IS_NODE_ENV&&n)){let x;if(typeof p!="string")if(!s.progress_callback)x=new Uint8Array(await p.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))x=new Uint8Array(await p.arrayBuffer()),Pr(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:x.length,total:x.length});else {let T,C=p.headers.get("content-length");if(C)T=parseInt(C,10);else try{let A=await es(e,t,s);A.size&&(T=A.size);}catch{}x=await bN(p,A=>{Pr(s.progress_callback,{status:"progress",name:e,file:t,...A});},T);}y=x;}if(_&&h&&typeof p!="string"&&await CN(e,t,a,h,p,y,s),he.IS_NODE_ENV&&n&&s.progress_callback&&typeof p!="string"){let x=parseInt(p.headers.get("content-length"),10)||0;Pr(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:x,total:x});}if(Pr(s.progress_callback,{status:"done",name:e,file:t}),y){if(!he.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return y}if(p instanceof mo)return p.filePath;let b=await a?.match(h);if(b instanceof mo)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}var Ba=new Map;async function go(e,t,r=true,s={},n=false){if(!me.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(!me.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}Pr(s.progress_callback,{status:"initiate",name:e,file:t});let a=`${e}::${t}`,o=Ba.get(a);if(!o){let i=await js(s?.cache_dir);o=SN(e,t,r,s,n,i).then(l=>(Ba.delete(a),l),l=>{throw Ba.delete(a),l}),Ba.set(a,o);}return await o}async function xd(e,t,r=true,s={}){let n=await go(e,t,r,s,false);return n===null?null:new TextDecoder("utf-8").decode(n)}async function ar(e,t,r=true,s={}){let n=await xd(e,t,r,s);return n===null?{}:JSON.parse(n)}function PN(e,[t,r,s],[n,a],o="bilinear",i=false){let l=a/s,c=n/r,d=new e.constructor(n*a*t),h=r*s,_=n*a;for(let p=0;p<n;++p)for(let w=0;w<a;++w){let y=p*a+w,b=(w+.5)/l-.5,x=(p+.5)/c-.5,T=Math.floor(b),C=Math.floor(x),A=Math.min(T+1,s-1),S=Math.min(C+1,r-1);T=Math.max(T,0),C=Math.max(C,0);let N=b-T,M=x-C,$=(1-N)*(1-M),G=N*(1-M),j=(1-N)*M,Q=N*M,q=C*s,X=S*s,D=q+T,L=q+A,Y=X+T,te=X+A;for(let I=0;I<t;++I){let z=I*h;d[I*_+y]=$*e[z+D]+G*e[z+L]+j*e[z+Y]+Q*e[z+te];}}return d}function FN(e,t,r){let s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=t[r[i]],l*=s[i];let a=r.map((i,l)=>n[r.indexOf(l)]),o=new e.constructor(e.length);for(let i=0;i<e.length;++i){let l=0;for(let c=t.length-1,d=i;c>=0;--c)l+=d%t[c]*a[c],d=Math.floor(d/t[c]);o[l]=e[i];}return [o,s]}function tt(e){let t=Ve(e)[0],r=e.map(a=>Math.exp(a-t)),s=r.reduce((a,o)=>a+o,0);return r.map(a=>a/s)}function jw(e){let t=Ve(e)[0],r=0;for(let a=0;a<e.length;++a)r+=Math.exp(e[a]-t);let s=Math.log(r);return e.map(a=>a-t-s)}function qw(e,t){let r=0;for(let s=0;s<e.length;++s)r+=e[s]*t[s];return r}function LN(e,t){let r=qw(e,t),s=tw(e),n=tw(t);return r/(s*n)}function tw(e){return Math.sqrt(e.reduce((t,r)=>t+r*r,0))}function sd(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]<t&&(t=e[s],r=s);return [t,r]}function Ve(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;s<e.length;++s)e[s]>t&&(t=e[s],r=s);return [t,r]}function Ww(e){return e>0&&(e&e-1)===0}var Hw=class{constructor(e){if(this.size=e|0,this.size<=1||!Ww(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let r=0;r<this.table.length;r+=2){let s=Math.PI*r/this.size;this.table[r]=Math.cos(s),this.table[r+1]=-Math.sin(s);}let t=0;for(let r=1;this.size>r;r<<=1)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let r=0;r<this._bitrev.length;++r){this._bitrev[r]=0;for(let s=0;s<this._width;s+=2){let n=this._width-s-2;this._bitrev[r]|=(r>>>s&3)<<n;}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let r=t||new Array(e.length>>>1);for(let s=0;s<e.length;s+=2)r[s>>>1]=e[s];return r}toComplexArray(e,t){let r=t||this.createComplexArray();for(let s=0;s<r.length;s+=2)r[s]=e[s>>>1],r[s+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1);}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1);}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r<e.length;++r)e[r]/=this.size;}_transform4(e,t,r){let s=this._csize,a=1<<this._width,o=s/a<<1,i,l,c=this._bitrev;if(o===4)for(i=0,l=0;i<s;i+=o,++l){let h=c[l];this._singleTransform2(t,e,i,h,a);}else for(i=0,l=0;i<s;i+=o,++l){let h=c[l];this._singleTransform4(t,e,i,h,a,r);}let d=this.table;for(a>>=2;a>=2;a>>=2){o=s/a<<1;let h=o>>>2;for(i=0;i<s;i+=o){let _=i+h-1;for(let p=i,w=0;p<_;p+=2,w+=a){let y=p,b=y+h,x=b+h,T=x+h,C=e[y],A=e[y+1],S=e[b],N=e[b+1],M=e[x],$=e[x+1],G=e[T],j=e[T+1],Q=d[w],q=r*d[w+1],X=S*Q-N*q,D=S*q+N*Q,L=d[2*w],Y=r*d[2*w+1],te=M*L-$*Y,I=M*Y+$*L,z=d[3*w],R=r*d[3*w+1],H=G*z-j*R,re=G*R+j*z,Ie=C+te,se=A+I,pt=C-te,Oe=A-I,qe=X+H,mt=D+re,Pe=r*(X-H),ye=r*(D-re);e[y]=Ie+qe,e[y+1]=se+mt,e[b]=pt+ye,e[b+1]=Oe-Pe,e[x]=Ie-qe,e[x+1]=se-mt,e[T]=pt-ye,e[T+1]=Oe+Pe;}}}}_singleTransform2(e,t,r,s,n){let a=e[s],o=e[s+1],i=e[s+n],l=e[s+n+1];t[r]=a+i,t[r+1]=o+l,t[r+2]=a-i,t[r+3]=o-l;}_singleTransform4(e,t,r,s,n,a){let o=n*2,i=n*3,l=e[s],c=e[s+1],d=e[s+n],h=e[s+n+1],_=e[s+o],p=e[s+o+1],w=e[s+i],y=e[s+i+1],b=l+_,x=c+p,T=l-_,C=c-p,A=d+w,S=h+y,N=a*(d-w),M=a*(h-y);t[r]=b+A,t[r+1]=x+S,t[r+2]=T+M,t[r+3]=C-N,t[r+4]=b-A,t[r+5]=x-S,t[r+6]=T-M,t[r+7]=C+N;}_realTransform4(e,t,r){let s=this._csize,a=1<<this._width,o=s/a<<1,i,l,c=this._bitrev;if(o===4)for(i=0,l=0;i<s;i+=o,++l){let _=c[l];this._singleRealTransform2(t,e,i,_>>>1,a>>>1);}else for(i=0,l=0;i<s;i+=o,++l){let _=c[l];this._singleRealTransform4(t,e,i,_>>>1,a>>>1,r);}let d=this.table;for(a>>=2;a>=2;a>>=2){o=s/a<<1;let _=o>>>1,p=_>>>1,w=p>>>1;for(i=0;i<s;i+=o)for(let y=0,b=0;y<=w;y+=2,b+=a){let x=i+y,T=x+p,C=T+p,A=C+p,S=e[x],N=e[x+1],M=e[T],$=e[T+1],G=e[C],j=e[C+1],Q=e[A],q=e[A+1],X=S,D=N,L=d[b],Y=r*d[b+1],te=M*L-$*Y,I=M*Y+$*L,z=d[2*b],R=r*d[2*b+1],H=G*z-j*R,re=G*R+j*z,Ie=d[3*b],se=r*d[3*b+1],pt=Q*Ie-q*se,Oe=Q*se+q*Ie,qe=X+H,mt=D+re,Pe=X-H,ye=D-re,We=te+pt,Ht=I+Oe,be=r*(te-pt),Se=r*(I-Oe);if(e[x]=qe+We,e[x+1]=mt+Ht,e[T]=Pe+Se,e[T+1]=ye-be,y===0){e[C]=qe-We,e[C+1]=mt-Ht;continue}if(y===w)continue;let gs=i+p-y,tn=i+_-y;e[gs]=Pe-r*Se,e[gs+1]=-ye-r*be,e[tn]=qe-r*We,e[tn+1]=-mt+r*Ht;}}let h=s>>>1;for(let _=2;_<h;_+=2)e[s-_]=e[_],e[s-_+1]=-e[_+1];}_singleRealTransform2(e,t,r,s,n){let a=e[s],o=e[s+n];t[r]=a+o,t[r+1]=0,t[r+2]=a-o,t[r+3]=0;}_singleRealTransform4(e,t,r,s,n,a){let o=n*2,i=n*3,l=e[s],c=e[s+n],d=e[s+o],h=e[s+i],_=l+d,p=l-d,w=c+h,y=a*(c-h);t[r]=_+w,t[r+1]=0,t[r+2]=p,t[r+3]=-y,t[r+4]=_-w,t[r+5]=0,t[r+6]=p,t[r+7]=y;}},IN=class{constructor(e){let t=2*(e-1),r=2*(2*e-1),s=2**Math.ceil(Math.log2(r));this.bufferSize=s,this._a=t;let n=new Float64Array(r),a=new Float64Array(s);this._chirpBuffer=new Float64Array(s),this._buffer1=new Float64Array(s),this._buffer2=new Float64Array(s),this._outBuffer1=new Float64Array(s),this._outBuffer2=new Float64Array(s);let o=-2*Math.PI/e,i=Math.cos(o),l=Math.sin(o);for(let c=0;c<r>>1;++c){let d=(c+1-e)**2/2,h=Math.sqrt(i**2+l**2)**d,_=d*Math.atan2(l,i),p=2*c;n[p]=h*Math.cos(_),n[p+1]=h*Math.sin(_),a[p]=n[p],a[p+1]=-n[p+1];}this._slicedChirpBuffer=n.subarray(t,r),this._f=new Hw(s>>1),this._f.transform(this._chirpBuffer,a);}_transform(e,t,r){let s=this._buffer1,n=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,i=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(r)for(let d=0;d<l.length;d+=2){let h=d+1,_=d>>1,p=t[_];s[d]=p*l[d],s[h]=p*l[h];}else for(let d=0;d<l.length;d+=2){let h=d+1;s[d]=t[d]*l[d]-t[h]*l[h],s[h]=t[d]*l[h]+t[h]*l[d];}this._f.transform(a,s);for(let d=0;d<i.length;d+=2){let h=d+1;n[d]=a[d]*i[d]-a[h]*i[h],n[h]=a[d]*i[h]+a[h]*i[d];}this._f.inverseTransform(o,n);for(let d=0;d<o.length;d+=2){let h=o[d+c],_=o[d+c+1],p=l[d],w=l[d+1];e[d]=h*p-_*w,e[d+1]=h*w+_*p;}}transform(e,t){this._transform(e,t,false);}realTransform(e,t){this._transform(e,t,true);}},ON=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Ww(e),this.isPowerOfTwo?(this.fft=new Hw(e),this.outputBufferSize=2*e):(this.fft=new IN(e),this.outputBufferSize=this.fft.bufferSize);}realTransform(e,t){this.fft.realTransform(e,t);}transform(e,t){this.fft.transform(e,t);}};function NN(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");let r=new e.constructor(e.length),s=new e.constructor(t),n=Math.floor(t/2);for(let a=0;a<e.length;++a){let o=0;for(let i=-n;i<=n;++i){let l=a+i;l<0?l=Math.abs(l):l>=e.length&&(l=2*(e.length-1)-l),s[o++]=e[l];}s.sort(),r[a]=s[n];}return r}function Ln(e,t){let r=Math.pow(10,t);return Math.round(e*r)/r}function zN(e){let t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function DN(e){let t=e.length,r=e[0].length,s=[t+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let a=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let d=1;d<s[1];++d)for(let h=1;h<s[0];++h){let _=n[h-1][d-1],p=n[h-1][d],w=n[h][d-1],y,b;_<p&&_<w?(y=_,b=0):p<_&&p<w?(y=p,b=1):(y=w,b=2),n[h][d]=e[h-1][d-1]+y,a[h][d]=b;}for(let d=0;d<s[1];++d)a[0][d]=2;for(let d=0;d<s[0];++d)a[d][0]=1;let o=t,i=r,l=[],c=[];for(;o>0||i>0;)switch(l.push(o-1),c.push(i-1),a[o][i]){case 0:--o,--i;break;case 1:--o;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var BN=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let a=new ArrayBuffer(4),o=new Uint32Array(a),i=new Float32Array(a);for(let l=0;l<e.length;++l){let c=0,d=(l&32768)<<16,h=(l&31744)>>10,_=l&1023;if(h===31)c=d|2139095040|_<<13;else if(h===0)if(_===0)c=d;else {let p=113;for(;(_&1024)===0;)_<<=1,--p;_&=-1025,c=d|p<<23|_<<13;}else c=d|h+112<<23|_<<13;o[0]=c,e[l]=i[0];}}let r=t.length,s=e,n=new Float32Array(r);for(let a=0;a<r;++a)n[a]=s[t[a]];return n}})(),Qw={};$s(Qw,{default:()=>RN});var RN={};async function Xw(e){let t=e.split("/").pop(),r;try{if(r=await js(),r){let n=await r.match(e);if(n)return n}}catch(n){ce.warn(`Failed to load ${t} from cache:`,n);}let s=await me.fetch(e);if(!s.ok)throw new Error(`Failed to fetch ${t}: ${s.status} ${s.statusText}`);if(r)try{await r.put(e,s.clone());}catch(n){ce.warn(`Failed to cache ${t}:`,n);}return s}async function GN(e){let t=await Xw(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return ce.warn("Failed to read WASM binary:",r),null}}async function $N(e){if(he.IS_SERVICE_WORKER_ENV||he.IS_CHROME_AVAILABLE)return e;let t=await Xw(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ce.warn("Failed to read WASM factory:",r),null}}var VN=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 Yw(e){return e<=Ot.DEBUG?0:e<=Ot.INFO?2:e<=Ot.WARNING||e<=Ot.ERROR?3:4}var UN={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},It=[],nd,Ds,rw=Symbol.for("onnxruntime");if(rw in globalThis)Ds=globalThis[rw];else if(he.IS_NODE_ENV){switch(Ds=Qw,process.platform){case "win32":It.push("dml");break;case "linux":process.arch==="x64"&&It.push("cuda");break;case "darwin":It.push("coreml");break}It.push("webgpu"),It.push("cpu"),nd=["cpu"];}else Ds=iu,he.IS_WEBNN_AVAILABLE&&It.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),he.IS_WEBGPU_AVAILABLE&&It.push("webgpu"),It.push("wasm"),nd=["wasm"];var jN=Ds.InferenceSession;function qN(e=null){if(!e)return nd;switch(e){case "auto":return It;case "gpu":return It.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(It.includes(e))return [VN[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${It.join(", ")}.`)}var sw=Promise.resolve(),As=null;async function WN(){if(As)return As;if(!(me.useWasmCache&&typeof He?.wasm?.wasmPaths=="object"&&He?.wasm?.wasmPaths?.wasm&&He?.wasm?.wasmPaths?.mjs)){if(he.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return As=Promise.resolve(),As}return As=(async()=>{let t=He.wasm.wasmPaths,r=false;await Promise.all([t.wasm&&!Jg(t.wasm)?(async()=>{try{let s=await GN(Kg(t.wasm));s&&(He.wasm.wasmBinary=s,r=!0);}catch(s){ce.warn("Failed to pre-load WASM binary:",s);}})():Promise.resolve(),t.mjs&&!Jg(t.mjs)?(async()=>{try{let s=await $N(Kg(t.mjs));s&&(He.wasm.wasmPaths.mjs=s);}catch(s){ce.warn("Failed to pre-load WASM factory:",s);}})():Promise.resolve()]),r||(He.wasm.wasmPaths.mjs=t.mjs);})(),As}async function Jw(e,t,r){await WN();let s=Yw(me.logLevel??Ot.WARNING),n=()=>jN.create(e,{logSeverityLevel:s,...t}),a=await(he.IS_WEB_ENV?sw=sw.then(n):n());return a.config=r,a}var nw=Promise.resolve();async function Kw(e,t){let r=()=>e.run(t);return he.IS_WEB_ENV?nw=nw.then(r):r()}function Zw(e){return e instanceof Ds.Tensor}var He=Ds?.env;function kd(){return He?.wasm?.proxy}if(He){let e=function(t){let r=Yw(t);He.logLevel=UN[r];};if(He.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&He.versions?.web&&!He.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${He.versions.web}/dist/`;He.wasm.wasmPaths=he.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`};}He.wasm.proxy=false;}He.webgpu&&(He.webgpu.powerPreference="high-performance"),e(me.logLevel??Ot.WARNING),me.backends.onnx={...He,setLogLevel:e};}var Cr=async(e,t,r)=>{let s=await Jw(new Uint8Array(e),t);return(async n=>{let a=kd(),o=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(a?c.clone():c).ort_tensor])),i=await Kw(s,o);return Array.isArray(r)?r.map(l=>new V(i[l])):new V(i[r])})},bu,Zr=(bu=class{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Cr([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=Cr([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=Cr([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=Cr([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=Cr([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=Cr([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=Cr([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=Cr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}},k(bu,"session_options",{}),bu),HN=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"}),fu=he.IS_NODE_ENV?"cpu":"wasm";function ey(e,t,{warn:r}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(r&&r(`device not specified for "${t}". Using the default device (${fu}).`),fu):fu}var QN=(function(){let e;return async function(){if(e===void 0)if(!he.IS_WEBGPU_AVAILABLE)e=false;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16");}catch{e=false;}return e}})(),Ue=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"}),aw=Ue.fp32,ow=Object.freeze({[HN.wasm]:Ue.q8}),zn=Object.freeze({[Ue.fp32]:"",[Ue.fp16]:"_fp16",[Ue.int8]:"_int8",[Ue.uint8]:"_uint8",[Ue.q8]:"_quantized",[Ue.q4]:"_q4",[Ue.q2]:"_q2",[Ue.q1]:"_q1",[Ue.q4f16]:"_q4f16",[Ue.q2f16]:"_q2f16",[Ue.q1f16]:"_q1f16",[Ue.bnb4]:"_bnb4"});function ty(e,t,r,{configDtype:s=null,warn:n}={}){let a,o=false;e&&typeof e!="string"?e.hasOwnProperty(t)?a=e[t]:(a=null,o=true):a=e;let i;if(a===Ue.auto){if(s){let l=typeof s=="string"?s:s?.[t];if(l&&l!==Ue.auto&&Ue.hasOwnProperty(l))return l}i=ow[r]??aw;}else a&&Ue.hasOwnProperty(a)?i=a:i=ow[r]??aw;return o&&n&&n(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${r}).`),i}var Rs=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}),V=class Re{constructor(...t){k(this,"ort_tensor");return Zw(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new uu(t[0],t[1],t[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t;}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose();}*[Symbol.iterator](){let[t,...r]=this.dims;if(r.length>0){let s=r.reduce((n,a)=>n*a);for(let n=0;n<t;++n)yield this._subarray(n,s,r);}else yield*this.data;}_getitem(t){let[r,...s]=this.dims;if(t=Zt(t,r),s.length>0){let n=s.reduce((a,o)=>a*o);return this._subarray(t,n,s)}else return new Re(this.type,[this.data[t]],s)}indexOf(t){let r=this.data;for(let s=0;s<r.length;++s)if(r[s]==t)return s;return -1}_subarray(t,r,s){let n=t*r,a=(t+1)*r,o="subarray"in this.data?this.data.subarray(n,a):this.data.slice(n,a);return new Re(this.type,o,s)}item(){let t=this.data;if(t.length!==1)throw new Error(`a Tensor with ${t.length} elements cannot be converted to Scalar`);return t[0]}tolist(){return XN(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=1/(1+Math.exp(-t[r]));return this}map(t){return this.clone().map_(t)}map_(t){let r=this.data;for(let s=0;s<r.length;++s)r[s]=t(r[s],s,r);return this}mul(t){return this.clone().mul_(t)}mul_(t){let r=this.data;for(let s=0;s<r.length;++s)r[s]*=t;return this}div(t){return this.clone().div_(t)}div_(t){let r=this.data;for(let s=0;s<r.length;++s)r[s]/=t;return this}add(t){return this.clone().add_(t)}add_(t){let r=this.data;for(let s=0;s<r.length;++s)r[s]+=t;return this}sub(t){return this.clone().sub_(t)}sub_(t){let r=this.data;for(let s=0;s<r.length;++s)r[s]-=t;return this}clone(){return new Re(this.type,this.data.slice(),this.dims.slice())}slice(...t){let r=[],s=[];for(let d=0;d<this.dims.length;++d){let h=t[d];if(h==null)s.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof h=="number")h=Zt(h,this.dims[d],d),s.push([h,h+1]);else if(Array.isArray(h)&&h.length===2){let[_,p]=h;if(_=_===null?0:Zt(_,this.dims[d],d,false),p=p===null?this.dims[d]:Zt(p,this.dims[d],d,false),_>p)throw new Error(`Invalid slice: ${h}`);let w=[Math.max(_,0),Math.min(p,this.dims[d])];s.push(w),r.push(w[1]-w[0]);}else throw new Error(`Invalid slice: ${h}`)}let n=s.map(([d,h])=>h-d),a=n.reduce((d,h)=>d*h),o=this.data,i=new o.constructor(a),l=this.stride(),c=true;for(let d=1;d<n.length;++d)if(s[d][0]!==0||s[d][1]!==this.dims[d]){c=false;break}if(c){let d=s[0][0]*l[0],h=s[0][1]*l[0];if(ArrayBuffer.isView(o))i.set(o.subarray(d,h));else if(Array.isArray(o)){let _=o.slice(d,h);for(let p=0;p<_.length;++p)i[p]=_[p];}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<a;++d){let h=0;for(let _=n.length-1,p=d;_>=0;--_){let w=n[_];h+=(p%w+s[_][0])*l[_],p=Math.floor(p/w);}i[d]=o[h];}return new Re(this.type,i,r)}permute(...t){return ry(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=false){return this.norm(1,t,r)}norm(t="fro",r=null,s=false){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);let n=this.data,a=n instanceof BigInt64Array||n instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,i;if(a?(o=(h,_)=>h+_,i=0n):(o=(h,_)=>h+_**t,i=0),r===null){let h=n.reduce(o,i);return t!==1&&(h=h**(1/t)),new Re(this.type,[h],[])}let[l,c,d]=In(o,this,r,s);if(t!==1)for(let h=0;h<c.length;++h)c[h]=c[h]**(1/t);return new Re(l,c,d)}normalize_(t=2,r=1){r=Zt(r,this.dims.length);let s=this.norm(t,r,true),n=this.data,a=s.data;for(let o=0;o<n.length;++o){let i=0;for(let l=this.dims.length-1,c=o,d=1;l>=0;--l){let h=this.dims[l];if(l!==r){let _=c%h;i+=_*d,d*=this.dims[l];}c=Math.floor(c/h);}n[o]/=a[i];}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return _u(this.dims)}squeeze(t=null){return new Re(this.type,this.data,iw(this.dims,t))}squeeze_(t=null){return this.dims=iw(this.dims,t),this}unsqueeze(t){return new Re(this.type,this.data,lw(this.dims,t))}unsqueeze_(t){return this.dims=lw(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,t),n=this.dims.slice(t,r+1),a=this.dims.slice(r+1);return this.dims=[...s,n.reduce((o,i)=>o*i,1),...a],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let n=0;n<t.length;++n)if(t[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n;}let s=this.data;if(r!==-1){let n=t.reduce((a,o,i)=>i!==r?a*o:a,1);t[r]=s.length/n;}return new Re(this.type,s,t)}neg_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=-t[r];return this}neg(){return this.clone().neg_()}gt(t){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>t?1:0;return new Re("bool",r,this.dims)}lt(t){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]<t?1:0;return new Re("bool",r,this.dims)}clamp_(t,r){let s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],t),r);return this}clamp(t,r){return this.clone().clamp_(t,r)}round_(){let t=this.data;for(let r=0;r<t.length;++r)t[r]=Math.round(t[r]);return this}round(){return this.clone().round_()}mean(t=null,r=false){return So(this,t,r)}min(t=null,r=false){if(t===null){let o=sd(this.data)[0];return new Re(this.type,[o],[])}let[s,n,a]=In((o,i)=>Math.min(o,i),this,t,r,1/0);return new Re(s,n,a)}max(t=null,r=false){if(t===null){let o=Ve(this.data)[0];return new Re(this.type,[o],[])}let[s,n,a]=In((o,i)=>Math.max(o,i),this,t,r,-1/0);return new Re(s,n,a)}argmin(t=null,r=false){if(t!==null)throw new Error("`dim !== null` not yet implemented.");let s=sd(this.data)[1];return new Re("int64",[BigInt(s)],[])}argmax(t=null,r=false){if(t!==null)throw new Error("`dim !== null` not yet implemented.");let s=Ve(this.data)[1];return new Re("int64",[BigInt(s)],[])}repeat(...t){if(t.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(d=>d===1)){if(t.length===this.dims.length)return this.clone();let d=t.length-this.dims.length,h=Array(d).fill(1).concat(this.dims);return new Re(this.type,this.data.slice(),h)}let r=t.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((d,h)=>d*t[h]),a=n.reduce((d,h)=>d*h,1),o=this.data,i=new o.constructor(a),l=_u(s),c=_u(n);for(let d=0;d<a;++d){let h=d,_=0;for(let p=0;p<n.length;++p){let w=Math.floor(h/c[p]);h=h%c[p];let y=w%s[p];_+=y*l[p];}i[d]=o[_];}return new Re(this.type,i,n)}tile(...t){if(t.length<this.dims.length){let r=this.dims.length-t.length;t=Array(r).fill(1).concat(t);}return this.repeat(...t)}to(t){if(this.type===t)return this;if(!Rs.hasOwnProperty(t))throw new Error(`Unsupported type: ${t}`);let r,s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(t);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=a=>BigInt(Math.floor(a)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new Re(t,BN(this.data),this.dims);return new Re(t,Rs[t].from(this.data,r),this.dims)}};function XN(e,t){let r=e.length,s=t.reduce((a,o)=>a*o);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let n=e;for(let a=t.length-1;a>=0;a--)n=n.reduce((o,i)=>{let l=o[o.length-1];return l.length<t[a]?l.push(i):o.push([i]),o},[[]]);return n[0]}function ry(e,t){let[r,s]=FN(e.data,e.dims,t);return new V(e.type,r,s)}function Td(e,[t,r],s="bilinear",n=false){let a=e.dims.at(-3)??1,o=e.dims.at(-2),i=e.dims.at(-1),l=PN(e.data,[a,o,i],[t,r],s,n);return new V(e.type,l,[a,t,r])}async function Nt(e,{size:t=null,mode:r="bilinear"}={}){if(e.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(t.length===2)s=[...e.dims.slice(0,2),...t];else if(t.length===3)s=[e.dims[0],...t];else if(t.length===4)s=t;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await Zr.nearest_interpolate_4d;else if(r==="bilinear")n=await Zr.bilinear_interpolate_4d;else if(r==="bicubic")n=await Zr.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let a=new V("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:e,s:a})}async function sy(e,t){return await(await Zr.matmul)({a:e,b:t})}async function YN(e,t){return await(await Zr.rfft)({x:e,a:t})}async function ts(e,t){let r=await Zr.top_k;return t==null?t=e.dims.at(-1):t=Math.min(t,e.dims.at(-1)),await r({x:e,k:new V("int64",[BigInt(t)],[1])})}var Ra=e=>new V("int64",e,[e.length]);async function Ed(e,t,r,s,n){return await(await Zr.slice)({x:e,s:Ra(t),e:Ra(r),a:Ra(s),t:Ra(n??new Array(s.length).fill(1))})}function ny(e,t){let r=e.data,s=t.data,n=[e.dims[0],e.dims[2]],a=new r.constructor(n[0]*n[1]),[o,i,l]=e.dims,c=0;for(let d=0;d<o;++d){let h=d*l*i;for(let _=0;_<l;++_){let p=0,w=0,y=d*i,b=h+_;for(let T=0;T<i;++T){let C=Number(s[y+T]);w+=C,p+=r[b+T*l]*C;}let x=p/w;a[c++]=x;}}return new V(e.type,a,n)}function JN(e,t,{eps:r=1e-5}={}){if(e.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[s,n]=e.dims;if(t.length!==1&&t[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[a,o]=Ad(e,1,0,true),i=a.data,l=o.data,c=e.data,d=new c.constructor(c.length);for(let h=0;h<s;++h){let _=h*n;for(let p=0;p<n;++p){let w=_+p;d[w]=(c[w]-l[h])/(i[h]+r);}}return new V(e.type,d,e.dims)}function iw(e,t){return e=e.slice(),t===null?e=e.filter(r=>r!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,s)=>r!==1||!t.includes(s))),e}function lw(e,t){return t=Zt(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Zt(e,t,r=null,s=true){if(e<-t||e>=t){if(s)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function Le(e,t=0){t=Zt(t,e[0].dims.length);let r=e[0].dims.slice();r[t]=e.reduce((o,i)=>o+i.dims[t],0);let s=r.reduce((o,i)=>o*i,1),n=new e[0].data.constructor(s),a=e[0].type;if(t===0){let o=0;for(let i of e){let l=i.data;n.set(l,o),o+=l.length;}}else {let o=0;for(let i=0;i<e.length;++i){let{data:l,dims:c}=e[i];for(let d=0;d<l.length;++d){let h=0;for(let _=c.length-1,p=d,w=1;_>=0;--_){let y=c[_],b=p%y;_===t&&(b+=o),h+=b*w,w*=r[_],p=Math.floor(p/y);}n[h]=l[d];}o+=c[t];}}return new V(a,n,r)}function tr(e,t=0){return Le(e.map(r=>r.unsqueeze(t)),t)}function In(e,t,r,s=false,n=null){let a=t.data,o=t.dims;r=Zt(r,o.length);let i=o.slice();i[r]=1;let l=new a.constructor(a.length/o[r]);n!==null&&l.fill(n);for(let c=0;c<a.length;++c){let d=0;for(let h=o.length-1,_=c,p=1;h>=0;--h){let w=o[h];if(h!==r){let y=_%w;d+=y*p,p*=i[h];}_=Math.floor(_/w);}l[d]=e(l[d],a[c],c,d);}return s||i.splice(r,1),[t.type,l,i]}function Ad(e,t=null,r=1,s=false){let n=e.data,a=e.dims;if(t===null){let p=n.reduce((x,T)=>x+T,0)/n.length,w=Math.sqrt(n.reduce((x,T)=>x+(T-p)**2,0)/(n.length-r)),y=new V(e.type,[p],[]);return [new V(e.type,[w],[]),y]}t=Zt(t,a.length);let o=So(e,t,s),i=o.data,[l,c,d]=In((_,p,w,y)=>_+(p-i[y])**2,e,t,s);for(let _=0;_<c.length;++_)c[_]=Math.sqrt(c[_]/(a[t]-r));return [new V(l,c,d),o]}function So(e,t=null,r=false){let s=e.dims,n=e.data;if(t===null){let l=n.reduce((c,d)=>c+d,0);return new V(e.type,[l/n.length],[])}t=Zt(t,s.length);let[a,o,i]=In((l,c)=>l+c,e,t,r);if(s[t]!==1)for(let l=0;l<o.length;++l)o[l]/=s[t];return new V(a,o,i)}function _u(e){let t=new Array(e.length);for(let r=e.length-1,s=1;r>=0;--r)t[r]=s,s*=e[r];return t}function Cd(e,t,r,s){let n=e.reduce((a,o)=>a*o,1);return new V(r,new s(n).fill(t),e)}function it(e,t){let r,s;if(typeof t=="number")r="float32",s=Float32Array;else if(typeof t=="bigint")r="int64",s=BigInt64Array;else if(typeof t=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return Cd(e,t,r,s)}function wo(e,t){return it(e.dims,t)}function yt(e){return Cd(e,1n,"int64",BigInt64Array)}function Sd(e){return yt(e.dims)}function Pd(e){return Cd(e,0n,"int64",BigInt64Array)}function Fd(e){return Pd(e.dims)}function KN(e){let t=e.reduce((r,s)=>r*s,1);return new V("float32",Float32Array.from({length:t},()=>Vn.random()),e)}function ay(e){let t=e.reduce((r,s)=>r*s,1);return new V("float32",Float32Array.from({length:t},()=>Vn.gauss()),e)}function oy(e,t){if(e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=t==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,a=e.data,o=new n(a.length/8);for(let i=0;i<a.length;++i){let l=a[i]>0?1:0,c=Math.floor(i/8),d=i%8;o[c]|=l<<7-d,r&&d===0&&(o[c]-=128);}return new V(s,o,[e.dims[0],e.dims[1]/8])}async function Ld(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return (await es(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function iy(e,t){let r=await Ld(e);return await Promise.all(r.map(s=>ar(e,s,true,t)))}function Id(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var ZN=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function e3(e,t,r,s){for(let n of Object.keys(e)){let a=t-e[n].length,o=r(n),i=new Array(a).fill(o);e[n]=s==="right"?Gt(e[n],i):Gt(i,e[n]);}}function t3(e,t){for(let r of Object.keys(e))e[r].length=t;}function Qr(e,...t){for(let r of t){if(!Object.hasOwn(e,r))continue;let s=e[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function r3(e){let t=[];for(let r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var ie=class extends bt{constructor(t,r){super();k(this,"return_token_type_ids",false);k(this,"padding_side","right");if(this._tokenizerJSON=t,this._tokenizerConfig=r,this._tokenizer=new wO(t,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Qr(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Qr(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Qr(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Qr(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Qr(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Qr(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:a,template:o}of this.chat_template){if(typeof a!="string"||typeof o!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[a]=o;}this.chat_template=n;}this._compiled_template_cache=new Map;let s=r3(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content);}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=false,revision:o="main"}={}){let i=await iy(t,{progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(t){return typeof t=="string"?this._tokenizer.token_to_id(t):t.map(r=>this._tokenizer.token_to_id(r))}_call(t,r={}){let{text_pair:s=null,add_special_tokens:n=true,padding:a=false,return_token_type_ids:o=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??true,d=Array.isArray(t),h;if(d){if(t.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(t.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");h=t.map((p,w)=>this._encode_plus(p,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:o}));}else h=t.map(p=>this._encode_plus(p,{add_special_tokens:n,return_token_type_ids:o}));}else {if(t==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");h=[this._encode_plus(t,{text_pair:s,add_special_tokens:n,return_token_type_ids:o})];}if(l===null?l=this.model_max_length:i===null&&(a===true?(ce.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):a===false&&(ce.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=true)),a===true&&(l=Math.min(Ve(h.map(p=>p.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),a||i)for(let p=0;p<h.length;++p)h[p].input_ids.length!==l&&(h[p].input_ids.length>l?i&&t3(h[p],l):a&&e3(h[p],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let _={};if(c){if(!(a&&i)&&h.some(w=>{for(let y of Object.keys(w))if(w[y].length!==h[0][y]?.length)return true;return false}))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 p=[h.length,h[0].input_ids.length];for(let w of Object.keys(h[0]))_[w]=new V("int64",BigInt64Array.from(h.flatMap(y=>y[w]).map(BigInt)),p);}else {for(let p of Object.keys(h[0]))_[p]=h.map(w=>w[p]);if(!d)for(let p of Object.keys(_))_[p]=_[p][0];}return _}_encode_text(t){return t===null?null:this._tokenizer.encode(t).tokens}_encode_plus(t,{text_pair:r=null,add_special_tokens:s=true,return_token_type_ids:n=null}={}){let{ids:a,attention_mask:o,token_type_ids:i}=this._tokenizer.encode(t,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return {input_ids:a,attention_mask:o,...i?{token_type_ids:i}:{}}}tokenize(t,{pair:r=null,add_special_tokens:s=false}={}){return this._tokenizer.tokenize(t,{text_pair:r,add_special_tokens:s})}encode(t,{text_pair:r=null,add_special_tokens:s=true,return_token_type_ids:n=null}={}){return this._tokenizer.encode(t,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(t,r={}){return t instanceof V&&(t=t.tolist()),t.map(s=>this.decode(s,r))}decode(t,r={}){if(t instanceof V&&(t=Id(t)),!Array.isArray(t)||t.length===0||!aL(t[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(t,r)}decode_single(t,{skip_special_tokens:r=false,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(t,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:t=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(t!==null&&Object.hasOwn(s,t))t=s[t];else if(t===null)if(r!==null&&"tool_use"in s)t=s.tool_use;else if("default"in s)t=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(t===null)if(this.chat_template)t=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return t}apply_chat_template(t,r={}){let{tools:s=null,documents:n=null,chat_template:a=null,add_generation_prompt:o=false,tokenize:i=true,padding:l=false,truncation:c=false,max_length:d=null,return_tensor:h=true,return_dict:_=true,tokenizer_kwargs:p={},...w}=r;if(a=this.get_chat_template({chat_template:a,tools:s}),typeof a!="string")throw Error(`chat_template must be a string, but got ${typeof a}`);let y=this._compiled_template_cache.get(a);y===void 0&&(y=new fN(a),this._compiled_template_cache.set(a,y));let b=Object.create(null);for(let T of ZN){let C=Qr(this.config,T);C&&(b[T]=C);}let x=y.render({messages:t,add_generation_prompt:o,tools:s,documents:n,...b,...w});if(i){let T=this._call(x,{add_special_tokens:false,padding:l,truncation:c,max_length:d,return_tensor:h,...p});return _?T:T.input_ids}return x}};function Od(e,t,r,s){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,a=s.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(n!==void 0){if(!e.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(let o of e._tokenizer.post_processor.config.single)if("SpecialToken"in o&&e.languageRegex.test(o.SpecialToken.id)){o.SpecialToken.id=e.lang_to_token(n);break}}return s.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,r)}var ly={};$s(ly,{AlbertTokenizer:()=>cy,AutoTokenizer:()=>xe,BartTokenizer:()=>uy,BertTokenizer:()=>dy,BlenderbotSmallTokenizer:()=>hy,BlenderbotTokenizer:()=>fy,BloomTokenizer:()=>_y,CLIPTokenizer:()=>my,CamembertTokenizer:()=>py,CodeGenTokenizer:()=>wy,CodeLlamaTokenizer:()=>gy,CohereAsrTokenizer:()=>vy,CohereTokenizer:()=>yy,ConvBertTokenizer:()=>by,DebertaTokenizer:()=>xy,DebertaV2Tokenizer:()=>My,DistilBertTokenizer:()=>ky,ElectraTokenizer:()=>Ty,EsmTokenizer:()=>Ey,FalconTokenizer:()=>Ay,GPT2Tokenizer:()=>Py,GPTNeoXTokenizer:()=>Sy,GemmaTokenizer:()=>Cy,HerbertTokenizer:()=>Fy,LlamaTokenizer:()=>Ly,M2M100Tokenizer:()=>Iy,MBart50Tokenizer:()=>Ny,MBartTokenizer:()=>Nd,MPNetTokenizer:()=>By,MarianTokenizer:()=>Oy,MgpstrTokenizer:()=>zy,MobileBertTokenizer:()=>Dy,NllbTokenizer:()=>Ry,NougatTokenizer:()=>Gy,PreTrainedTokenizer:()=>ie,Qwen2Tokenizer:()=>$y,RoFormerTokenizer:()=>Uy,RobertaTokenizer:()=>Vy,SiglipTokenizer:()=>jy,SpeechT5Tokenizer:()=>qy,SqueezeBertTokenizer:()=>Wy,T5Tokenizer:()=>Hy,TokenizersBackend:()=>ie,VitsTokenizer:()=>Qy,Wav2Vec2CTCTokenizer:()=>Xy,WhisperTokenizer:()=>Jy,XLMRobertaTokenizer:()=>Ky,XLMTokenizer:()=>Zy});var cy=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},uy=class extends ie{},dy=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},hy=class extends ie{},fy=class extends ie{},_y=class extends ie{},py=class extends ie{},my=class extends ie{},gy=class extends ie{},wy=class extends ie{},yy=class extends ie{},vy=class extends ie{},by=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},My=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},xy=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},ky=class extends ie{},Ty=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},Ey=class extends ie{},Ay=class extends ie{},Cy=class extends ie{},Sy=class extends ie{},Py=class extends ie{},Fy=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},Ly=class extends ie{constructor(){super(...arguments);k(this,"padding_side","left");}},Iy=class extends ie{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`;}_build_translation_inputs(e,t,r){return Od(this,e,t,r)}},Oy=class extends ie{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),ce.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.');}_encode_text(e){if(e===null)return null;let[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){let[s,n]=r;return this.supported_language_codes.includes(s)||ce.warn(`Unsupported language code "${s}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Gt([s],super._encode_text(n))}}},Nd=class extends ie{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r;}_build_translation_inputs(e,t,r){return Od(this,e,t,r)}},Ny=class extends Nd{},zy=class extends ie{},Dy=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},By=class extends ie{},Ry=class extends ie{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r;}_build_translation_inputs(e,t,r){return Od(this,e,t,r)}},Gy=class extends ie{},$y=class extends ie{},Vy=class extends ie{},Uy=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},jy=class extends ie{},qy=class extends ie{},Wy=class extends ie{constructor(){super(...arguments);k(this,"return_token_type_ids",true);}},Hy=class extends ie{},s3=class extends jt{decode_chain(e){let t="";for(let r=1;r<e.length;r+=2)t+=e[r];return [t]}},Qy=class extends ie{constructor(e,t){super(e,t),this._tokenizer.decoder=new s3({type:"VitsDecoder"});}},Xy=class extends ie{},Yy=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],lo=new Map(Yy),n3=new Map([...Yy.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function a3(e){e=e.toLowerCase();let t=n3.get(e);if(t===void 0){let r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),lo.has(e))t=e;else {let n=e.length===2?lo.keys():lo.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return t}var o3="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",cw=new RegExp(`^[${o3}]+$`,"gu"),i3=.1,Jy=class extends ie{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=false,return_language:r=false,time_precision:s=null,force_full_sequences:n=true}={}){if(s===null)throw Error("Must specify time_precision");let a=null,o=t==="word";function i(){return {language:a,timestamp:[null,null],text:""}}let l=[],c=i(),d=0,h=this.timestamp_begin,p=h+1500,w=[],y=[],b=false,x=null,T=new Set(this.all_special_ids);for(let S of e){let N=S.tokens,M=o?S.token_timestamps:null,$=null,G=h;if("stride"in S){let[q,X,D]=S.stride;if(d-=X,x=q-D,X&&(G=X/s+h),D)for(let L=N.length-1;L>=0;--L){let Y=Number(N[L]);if(Y>=h){if($!==null&&(Y-h)*s<x)break;$=Y;}}}let j=[],Q=[];for(let q=0;q<N.length;++q){let X=Number(N[q]);if(T.has(X)){let D=this.decode([X]),L=lo.get(D.slice(2,-2));if(L!==void 0){if(a!==null&&L!==a&&!t){w.push(j);let Y=this.findLongestCommonSequence(w)[0],te=this.decode(Y);c.text=te,l.push(c),w=[],j=[],c=i();}a=c.language=L;}}else if(X>=h&&X<=p){let D=(X-h)*s+d,L=Ln(D,2);if($!==null&&X>=$)b=true;else if(b||w.length>0&&X<G)b=false;else if(c.timestamp[0]===null)c.timestamp[0]=L;else if(L!==c.timestamp[0]){c.timestamp[1]=L,w.push(j),o&&y.push(Q);let[Y,te]=this.findLongestCommonSequence(w,y),I=this.decode(Y);if(c.text=I,o&&(c.words=this.collateWordTimestamps(Y,te,a),c.words.length>0&&c.timestamp[1]!==null))for(let z of c.words)z.timestamp[1]>c.timestamp[1]&&c.timestamp[1]>=z.timestamp[0]&&(z.timestamp[1]=c.timestamp[1]);l.push(c),w=[],j=[],y=[],Q=[],c=i();}}else if(j.push(X),o){let D=Ln(M[q]+d,2),L;if(q+1<M.length){L=Ln(M[q+1]+d,2);let Y=this.decode([X]);cw.test(Y)&&(L=Ln(Math.min(D+s,L),2));}else L=null;Q.push([D,L]);}}if("stride"in S){let[q,X,D]=S.stride;d+=q-D;}j.length>0?(w.push(j),o&&y.push(Q)):w.every(q=>q.length===0)&&(c=i(),w=[],j=[],y=[],Q=[]);}if(w.length>0){if(n&&t)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[S,N]=this.findLongestCommonSequence(w,y),M=this.decode(S);c.text=M,o&&(c.words=this.collateWordTimestamps(S,N,a)),l.push(c);}let C=Object.create(null),A=l.map(S=>S.text).join("");if(t||r){for(let S=0;S<l.length;++S){let N=l[S];t||delete N.timestamp,r||delete N.language;}if(o){let S=[];for(let N of l)for(let M of N.words)S.push(M);C={chunks:S};}else C={chunks:l};}return [A,C]}findLongestCommonSequence(e,t=null){let r=e[0],s=r.length,n=[],a=Array.isArray(t)&&t.length>0,o=a?[]:null,i=a?t[0]:null;for(let l=1;l<e.length;++l){let c=e[l],d=0,h=[s,s,0,0],_=c.length;for(let C=1;C<s+_;++C){let A=Math.max(0,s-C),S=Math.min(s,s+_-C),N=r.slice(A,S),M=Math.max(0,C-s),$=Math.min(_,C),G=c.slice(M,$);if(N.length!==G.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let j;a?j=N.filter((X,D)=>X===G[D]&&i[A+D][0]-i3<=t[l][M+D][0]).length:j=N.filter((X,D)=>X===G[D]).length;let Q=C/1e4,q=j/C+Q;j>1&&q>d&&(d=q,h=[A,S,M,$]);}let[p,w,y,b]=h,x=Math.floor((w+p)/2),T=Math.floor((b+y)/2);if(a&&d===0&&s>0){let C=i[s-1][0],A=t[l].findIndex(S=>S[0]>=C);T=A===-1?c.length:A;}n.push(...r.slice(0,x)),r=c.slice(T),s=r.length,a&&(o.push(...i.slice(0,x)),i=t[l].slice(T));}return n.push(...r),a?(o.push(...i),[n,o]):[n,[]]}collateWordTimestamps(e,t,r){let[s,n,a]=this.combineTokensIntoWords(e,r),o=[];for(let i=0;i<s.length;++i){let l=a[i];o.push({text:s[i],timestamp:[t[l.at(0)][0],t[l.at(-1)][1]]});}return o}combineTokensIntoWords(e,t,r=`"'\u201C\xA1\xBF([{-`,s=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){t=t??"english";let n,a,o;return ["chinese","japanese","thai","lao","myanmar"].includes(t)?[n,a,o]=this.splitTokensOnUnicode(e):[n,a,o]=this.splitTokensOnSpaces(e),this.mergePunctuations(n,a,o,r,s)}decode(e,t){let r;return t?.decode_with_timestamps?(e instanceof V&&(e=Id(e)),r=this.decodeWithTimestamps(e,t)):r=super.decode(e,t),r}decodeWithTimestamps(e,t){let r=t?.time_precision??.02,s=this.all_special_ids.at(-1)+1,n=[[]];for(let a of e)if(a=Number(a),a>=s){let o=((a-s)*r).toFixed(2);n.push(`<|${o}|>`),n.push([]);}else n[n.length-1].push(a);return n=n.map(a=>typeof a=="string"?a:super.decode(a,t)),n.join("")}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:true}),r="\uFFFD",s=[],n=[],a=[],o=[],i=[],l=0;for(let c=0;c<e.length;++c){let d=e[c];o.push(d),i.push(c);let h=this.decode(o,{decode_with_timestamps:true});(!h.includes(r)||t[l+h.indexOf(r)]===r)&&(s.push(h),n.push(o),a.push(i),o=[],i=[],l+=h.length);}return [s,n,a]}splitTokensOnSpaces(e){let[t,r,s]=this.splitTokensOnUnicode(e),n=[],a=[],o=[];for(let i=0;i<t.length;++i){let l=t[i],c=r[i],d=s[i],h=c[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=l.startsWith(" "),p=l.trim(),w=cw.test(p);if(h||_||w||n.length===0)n.push(l),a.push(c),o.push(d);else {let y=n.length-1;n[y]+=l,a[y].push(...c),o[y].push(...d);}}return [n,a,o]}mergePunctuations(e,t,r,s,n){let a=structuredClone(e),o=structuredClone(t),i=structuredClone(r),l=a.length-2,c=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&s.includes(a[l].trim())?(a[c]=a[l]+a[c],o[c]=Gt(o[l],o[c]),i[c]=Gt(i[l],i[c]),a[l]="",o[l]=[],i[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&n.includes(a[c])?(a[l]+=a[c],o[l]=Gt(o[l],o[c]),i[l]=Gt(i[l],i[c]),a[c]="",o[c]=[],i[c]=[]):l=c,++c;return [a.filter(d=>d),o.filter(d=>d.length>0),i.filter(d=>d.length>0)]}},Ky=class extends ie{},Zy=class extends ie{constructor(t,r){super(t,r);k(this,"return_token_type_ids",true);ce.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.');}},xe=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=false,revision:a="main"}={}){let[o,i]=await iy(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:a}),l=i.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",c=ly[l];return c||(ce.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=ie),new c(o,i)}},Po="https://github.com/huggingface/transformers.js/issues/new/choose",zd="preprocessor_config.json",Dn=zd,ev="processor_config.json",tv="chat_template.jinja",yn,ke=(yn=class extends bt{constructor(e,t,r){super(),this.config=e,this.components=t,this.chat_template=r;}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:false,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(let r of [this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){let[r,s,n]=await Promise.all([this.uses_processor_config?ar(e,ev,true,t):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let o=await this[a].from_pretrained(e,t);return [a.replace(/_class$/,""),o]})).then(Object.fromEntries),this.uses_chat_template_file?xd(e,tv,true,t):null]);return new this(r,s,n)}},k(yn,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),k(yn,"uses_processor_config",false),k(yn,"uses_chat_template_file",false),yn),ad={};$s(ad,{ChatterboxProcessor:()=>bv,CohereAsrProcessor:()=>Mv,Florence2Processor:()=>mb,Gemma3Processor:()=>gb,Gemma3nProcessor:()=>wb,Gemma4Processor:()=>yb,Glm46VProcessor:()=>vb,GraniteSpeechProcessor:()=>bb,GroundingDinoProcessor:()=>Mb,Idefics3Processor:()=>ld,JinaCLIPProcessor:()=>kb,Lfm2VlProcessor:()=>Tb,LlavaProcessor:()=>Eb,MgpstrProcessor:()=>Ab,MoonshineProcessor:()=>Cb,OwlViTProcessor:()=>Sb,PaliGemmaProcessor:()=>Pb,Phi3VProcessor:()=>Fb,PixtralProcessor:()=>Lb,Processor:()=>ke,PyAnnoteProcessor:()=>Ib,Qwen2VLProcessor:()=>No,Qwen2_5_VLProcessor:()=>ih,Qwen3VLProcessor:()=>Ob,Sam2Processor:()=>ch,Sam2VideoProcessor:()=>Nb,SamProcessor:()=>lh,SmolVLMProcessor:()=>ld,SpeechT5Processor:()=>zb,UltravoxProcessor:()=>Db,VLChatProcessor:()=>xb,VoxtralProcessor:()=>Bb,VoxtralRealtimeProcessor:()=>Rb,Wav2Vec2Processor:()=>Gb,Wav2Vec2ProcessorWithLM:()=>$b,WhisperProcessor:()=>Vb});var lt=class extends bt{constructor(e){super(),this.config=e;}static async from_pretrained(e,t={}){let r=await ar(e,zd,true,t);return new this(r)}};function ct(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Dd={};$s(Dd,{ASTFeatureExtractor:()=>lv,ChatterboxFeatureExtractor:()=>cv,ClapFeatureExtractor:()=>uv,CohereAsrFeatureExtractor:()=>dv,DacFeatureExtractor:()=>Gd,EncodecFeatureExtractor:()=>Bd,FeatureExtractor:()=>lt,Gemma3nAudioFeatureExtractor:()=>$d,Gemma4AudioFeatureExtractor:()=>Vd,GraniteSpeechFeatureExtractor:()=>hv,MoonshineFeatureExtractor:()=>fv,ParakeetFeatureExtractor:()=>Rd,PyAnnoteFeatureExtractor:()=>Ud,SeamlessM4TFeatureExtractor:()=>_v,SnacFeatureExtractor:()=>pv,SpeechT5FeatureExtractor:()=>mv,VoxtralRealtimeFeatureExtractor:()=>yv,Wav2Vec2FeatureExtractor:()=>gv,WeSpeakerFeatureExtractor:()=>wv,WhisperFeatureExtractor:()=>vv});var u3=()=>{},d3=u3;async function rv(e,t){if(he.IS_BROWSER_ENV){if(he.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(t),s=document.createElement("a");s.href=r,s.download=e,s.click(),s.remove(),URL.revokeObjectURL(r);}else if(he.IS_FS_AVAILABLE){t.stream();At.createWriteStream(e);await d3();}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function sv(e,t){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Nn(e)).arrayBuffer(),s=new AudioContext({sampleRate:t});typeof t>"u"&&ce.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),a;if(n.numberOfChannels===2){let o=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);a=new Float32Array(i.length);for(let c=0;c<n.length;++c)a[c]=o*(i[c]+l[c])/2;}else a=n.getChannelData(0);return a}var nv=sv;function av(e,t){if(e<1)return new Float64Array;if(e===1)return new Float64Array([1]);let r=1-t,s=2*Math.PI/(e-1),n=new Float64Array(e);for(let a=0;a<e;++a)n[a]=t-r*Math.cos(a*s);return n}function uw(e){return av(e,.5)}function h3(e){return av(e,.54)}var f3={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,s=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*s:3*e/200};function pu(e,t="htk"){let r=f3[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(s=>r(s))}var _3={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,s=Math.log(6.4)/27)=>e>=r?t*Math.exp(s*(e-r)):200*e/3};function p3(e,t="htk"){let r=_3[t];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(s=>r(s))}function m3(e,t){let r=Float64Array.from({length:t.length-1},(o,i)=>t[i+1]-t[i]),s=Array.from({length:e.length},()=>new Array(t.length));for(let o=0;o<e.length;++o){let i=s[o];for(let l=0;l<t.length;++l)i[l]=t[l]-e[o];}let n=t.length-2,a=Array.from({length:n},()=>new Array(e.length));for(let o=0;o<e.length;++o){let i=s[o];for(let l=0;l<n;++l){let c=-i[l]/r[l],d=i[l+2]/r[l+1];a[l][o]=Math.max(0,Math.min(c,d));}}return a}function dw(e,t,r){let s=(t-e)/(r-1);return Float64Array.from({length:r},(n,a)=>e+s*a)}function rr(e,t,r,s,n,a=null,o="htk",i=false){if(a!==null&&a!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=pu(r,o),c=pu(s,o),d=dw(l,c,t+2),h=p3(d,o),_;if(i){let w=n/((e-1)*2);_=pu(Float64Array.from({length:e},(y,b)=>b*w),o),h=d;}else _=dw(0,Math.floor(n/2),e);let p=m3(_,h);if(a!==null&&a==="slaney")for(let w=0;w<t;++w){let y=p[w],b=2/(h[w+2]-h[w]);for(let x=0;x<e;++x)y[x]*=b;}return p}function g3(e,t,r){let s=new e.constructor(e.length+t+r),n=e.length-1;for(let a=0;a<e.length;++a)s[t+a]=e[a];for(let a=1;a<=t;++a)s[t-a]=e[_o(a,n)];for(let a=1;a<=r;++a)s[n+t+a]=e[_o(n-a,n)];return s}function ov(e,t,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);let a=Math.log10(r);for(let o=0;o<e.length;++o)e[o]=t*Math.log10(Math.max(s,e[o])-a);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");let o=Ve(e)[0]-n;for(let i=0;i<e.length;++i)e[i]=Math.max(e[i],o);}return e}function w3(e,t=1,r=1e-5,s=null){return ov(e,20,t,r,s)}function y3(e,t=1,r=1e-10,s=null){return ov(e,10,t,r,s)}async function or(e,t,r,s,{fft_length:n=null,power:a=1,center:o=true,pad_mode:i="reflect",onesided:l=true,preemphasis:c=null,preemphasis_htk_flavor:d=true,mel_filters:h=null,mel_floor:_=1e-10,log_mel:p=null,max_log_mel:w=null,reference:y=1,min_value:b=1e-10,db_range:x=null,remove_dc_offset:T=null,min_num_frames:C=null,max_num_frames:A=null,do_pad:S=true,transpose:N=false,mel_offset:M=0,mel_floor_mode:$="clamp"}={}){let G=t.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(G!==r)throw new Error(`Length of the window (${G}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(a===null&&h!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o){let H=Math.floor(r/2);switch(i){case "reflect":{e=g3(e,H,H);break}case "constant":{let re=new e.constructor(e.length+2*H);re.set(e,H),e=re;break}case "semicausal":{let re=new e.constructor(e.length+H);re.set(e,H),e=re;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let j=Math.floor(1+Math.floor((e.length-r)/s));C!==null&&j<C&&(j=C);let Q=l?Math.floor(n/2)+1:n,q=j,X=j;A!==null&&(A>j?S&&(X=A):X=q=A);let D=new ON(n),L=new Float64Array(n),Y=new Float64Array(D.outputBufferSize),te=new Float32Array(Q*X);for(let H=0;H<q;++H){let re=H*s,Ie=Math.min(e.length-re,r);Ie!==r&&L.fill(0,0,r);for(let se=0;se<Ie;++se)L[se]=e[re+se];if(T){let se=0;for(let Oe=0;Oe<Ie;++Oe)se+=L[Oe];let pt=se/Ie;for(let Oe=0;Oe<Ie;++Oe)L[Oe]-=pt;}if(c!==null){for(let se=Ie-1;se>=1;--se)L[se]-=c*L[se-1];L[0]*=1-c;}for(let se=0;se<t.length;++se)L[se]*=t[se];D.realTransform(Y,L);for(let se=0;se<Q;++se){let pt=se<<1;te[se*X+H]=Y[pt]**2+Y[pt+1]**2;}}if(a!==null&&a!==2){let H=a/2;for(let re=0;re<te.length;++re)te[re]**=H;}let I=h.length,z=await sy(new V("float32",h.flat(),[I,Q]),new V("float32",te,[Q,X]));N&&(z=z.transpose(1,0));let R=z.data;if($==="add")for(let H=0;H<R.length;++H)R[H]=M+R[H]+_;else for(let H=0;H<R.length;++H)R[H]=M+Math.max(_,R[H]);if(a!==null&&p!==null){let H=Math.min(R.length,q*I);switch(p){case "log":for(let re=0;re<H;++re)R[re]=Math.log(R[re]);break;case "log10":for(let re=0;re<H;++re)R[re]=Math.log10(R[re]);break;case "log10_max_norm":{for(let se=0;se<H;++se)R[se]=Math.log10(R[se]);let Ie=(w??Ve(R)[0])-8;for(let se=0;se<H;++se)R[se]=(Math.max(R[se],Ie)+4)/4;break}case "dB":if(a===1)w3(R,y,b,x);else if(a===2)y3(R,y,b,x);else throw new Error(`Cannot use log_mel option '${p}' with power ${a}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${p}'`)}}return z}function gr(e,t,{periodic:r=true,frame_length:s=null,center:n=true}={}){let a=r?e+1:e,o;switch(t){case "boxcar":o=new Float64Array(a).fill(1);break;case "hann":case "hann_window":o=uw(a);break;case "hamming":o=h3(a);break;case "povey":o=uw(a).map(c=>Math.pow(c,.85));break;default:throw new Error(`Unknown window type ${t}.`)}if(r&&(o=o.subarray(0,e)),s===null||e===s)return o;if(e>s)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-e)/2):0;return i.set(o,l),i}function v3(e,t){let r=e.reduce((a,o)=>a+o.length,0),s=new ArrayBuffer(44),n=new DataView(s);return Ga(n,0,"RIFF"),n.setUint32(4,36+r*4,true),Ga(n,8,"WAVE"),Ga(n,12,"fmt "),n.setUint32(16,16,true),n.setUint16(20,3,true),n.setUint16(22,1,true),n.setUint32(24,t,true),n.setUint32(28,t*4,true),n.setUint16(32,4,true),n.setUint16(34,32,true),Ga(n,36,"data"),n.setUint32(40,r*4,true),new Blob([s,...e.map(a=>a.buffer)],{type:"audio/wav"})}function Ga(e,t,r){for(let s=0;s<r.length;++s)e.setUint8(t+s,r.charCodeAt(s));}var iv=class{constructor(e,t){this.audio=e,this.sampling_rate=t;}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((s,n)=>s+n.length,0),t=new Float32Array(e),r=0;for(let s of this.audio)t.set(s,r),r+=s.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),v3(e,this.sampling_rate)}async save(e){return rv(e,this.toBlob())}},lv=class extends lt{constructor(e){super(e);let t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",true);this.mel_filters=r,this.window=gr(400,"hann",{periodic:false}),this.mean=this.config.mean,this.std=this.config.std;}async _extract_fbank_features(e,t){return or(e,this.window,400,160,{fft_length:512,power:2,center:false,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:true,max_num_frames:t,transpose:true})}async _call(e){ct(e,"ASTFeatureExtractor");let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let r=this.std*2,s=t.data;for(let n=0;n<s.length;++n)s[n]=(s[n]-this.mean)/r;}return {input_values:t.unsqueeze_(0)}}},Bd=class extends lt{async _call(e){ct(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=this.config.feature_size;if(e.length%t!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);let r=[1,t,e.length/t];return {input_values:new V("float32",e,r)}}},cv=class extends lt{async _call(e){ct(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return {input_values:new V("float32",e,t)}}},uv=class extends lt{constructor(e){super(e),this.mel_filters=rr(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=rr(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=gr(this.config.fft_window_size,"hann");}async _get_input_mel(e,t,r,s){let n,o=e.length-t;if(o>0)if(r==="rand_trunc"){let i=Math.floor(Vn.random()*(o+1));e=e.subarray(i,i+t),n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples);}else throw new Error(`Truncation strategy "${r}" not implemented`);else {if(o<0){let i=new Float64Array(t);if(i.set(e),s==="repeat")for(let l=e.length;l<t;l+=e.length)i.set(e.subarray(0,Math.min(e.length,t-l)),l);else if(s==="repeatpad")for(let l=e.length;l<-o;l+=e.length)i.set(e,l);e=i;}if(r==="fusion")throw new Error(`Truncation strategy "${r}" not implemented`);n=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples);}return n.unsqueeze_(0)}async _extract_fbank_features(e,t,r=null){return or(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:r,do_pad:false,transpose:true})}async _call(e,{max_length:t=null}={}){return ct(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},b3=1e-5,Rd=class extends lt{constructor(e){var s;super(e),(s=this.config).mel_filters??(s.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney"));let t=gr(this.config.win_length,"hann",{periodic:false});this.window=new Float64Array(this.config.n_fft);let r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,r);}async _extract_fbank_features(e){let t=this.config.preemphasis;e=new Float64Array(e);for(let s=e.length-1;s>=1;--s)e[s]-=t*e[s-1];return await or(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:true,transpose:true,mel_offset:2**-24})}async _call(e){ct(e,"ParakeetFeatureExtractor");let t=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),s=t.data;s.fill(0,r*t.dims[1]);let[n,a]=t.dims,o=new Float64Array(a),i=new Float64Array(a);for(let d=0;d<r;++d){let h=d*a;for(let _=0;_<a;++_){let p=s[h+_];o[_]+=p,i[_]+=p*p;}}let l=r>1?r-1:1;for(let d=0;d<a;++d){let h=o[d]/r,_=(i[d]-r*h*h)/l,w=1/(Math.sqrt(_)+b3);for(let y=0;y<r;++y){let b=y*a+d;s[b]=(s[b]-h)*w;}}let c=new BigInt64Array(n);return c.fill(1n,0,r),{input_features:t.unsqueeze_(0),attention_mask:new V("int64",c,[1,n])}}},dv=class extends Rd{_apply_dither(e){let t=this.config.dither??0;if(t<=0)return e;let r=new Co(e.length);for(let s=0;s<e.length;++s)e[s]+=t*r.gauss();return e}split_audio(e){let t=this.config.max_audio_clip_s??35,r=this.config.overlap_chunk_second??5,s=this.config.min_energy_window_samples??1600,n=this.config.sampling_rate,a=Math.max(1,Math.round(t*n)),o=Math.max(1,Math.round(r*n));if(e.length<=a)return [e];let i=[],l=0,c=e.length;for(;l<c;){if(l+a>=c){i.push(e.slice(l,c));break}let d=Math.max(l,l+a-o),h=Math.min(l+a,c),_;h<=d?_=l+a:_=this._find_split_point_energy(e,d,h,s),_=Math.max(l+1,Math.min(_,c)),i.push(e.slice(l,_)),l=_;}return i}_find_split_point_energy(e,t,r,s){let n=r-t;if(n<=s)return Math.floor((t+r)/2);let a=1/0,o=t,i=n-s;for(let l=0;l<=i;l+=s){let c=0;for(let d=0;d<s;++d){let h=e[t+l+d];c+=h*h;}c=Math.sqrt(c/s),c<a&&(a=c,o=t+l);}return o}async _call(e){ct(e,"CohereAsrFeatureExtractor");let t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},Gd=class extends Bd{},$d=class extends lt{constructor(e){super(e);let{fft_length:t,feature_size:r,min_frequency:s,max_frequency:n,sampling_rate:a,frame_length:o}=this.config,i=rr(Math.floor(1+t/2),r,s,n,a,null,"htk",false);this.mel_filters=i,this.window=gr(o,"hann");}async _extract_fbank_features(e,t){return or(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:false,onesided:true,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:false,transpose:true})}async _call(e,{max_length:t=48e4,truncation:r=true,padding:s=true,pad_to_multiple_of:n=128}={}){if(ct(e,"Gemma3nAudioFeatureExtractor"),r&&e.length>t&&(e=e.slice(0,t)),s&&e.length%n!==0){let i=n-e.length%n,l=new Float64Array(e.length+i);l.set(e),this.config.padding_value!==0&&l.fill(this.config.padding_value,e.length),e=l;}let a=await this._extract_fbank_features(e,this.config.max_length),o=it([1,a.dims[0]],true);return {input_features:a.unsqueeze_(0),input_features_mask:o}}},Vd=class extends $d{async _extract_fbank_features(e,t){let{frame_length:r,hop_length:s,fft_length:n}=this.config,a=Math.floor(r/2),o=Math.floor((e.length+a-(r+1))/s)+1;return or(e,this.window,r,s,{fft_length:n,center:true,pad_mode:"semicausal",onesided:true,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:false,transpose:true,max_num_frames:o})}async _call(e,t={}){ct(e,"Gemma4AudioFeatureExtractor");let r=e.length,s=await super._call(e,t),{input_features:n}=s,[,a,o]=n.dims,{frame_length:i,hop_length:l}=this.config,c=Math.floor(i/2),d=i+1,h=new Uint8Array(r+c+(t.pad_to_multiple_of??128));h.fill(1,c,c+r);let _=new Uint8Array(a);for(let w=0;w<a;++w)_[w]=h[w*l+d-1]?1:0;let p=n.data;for(let w=0;w<a;++w)_[w]||p.fill(0,w*o,(w+1)*o);return s.input_features_mask=new V("bool",_,[1,a]),s}},hv=class extends lt{constructor(e){super(e);let{n_fft:t,win_length:r,n_mels:s,sample_rate:n}=e.melspec_kwargs;this.mel_filters=rr(Math.floor(1+t/2),s,0,n/2,n,null,"htk");let a=gr(r,"hann");this.window=new Float64Array(t);let o=Math.floor((t-r)/2);this.window.set(a,o);}async _call(e){ct(e,"GraniteSpeechFeatureExtractor");let{n_fft:t,hop_length:r,n_mels:s}=this.config.melspec_kwargs,n=1+Math.floor((e.length-1)/r),a=n-n%2;return {input_features:(await or(e,this.window,t,r,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:true,max_num_frames:a,do_pad:false})).view(-1,2*s).unsqueeze_(0)}}},fv=class extends lt{async _call(e){ct(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return {input_values:new V("float32",e,t)}}},Ud=class extends lt{async _call(e){ct(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,1,e.length];return {input_values:new V("float32",e,t)}}samples_to_frames(e){return (e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let r=t/this.samples_to_frames(t)/this.config.sampling_rate,s=[];for(let n of e.tolist()){let a=[],o=-1;for(let i=0;i<n.length;++i){let l=tt(n[i]),[c,d]=Ve(l),[h,_]=[i,i+1];d!==o?(o=d,a.push({id:d,start:h,end:_,score:c})):(a.at(-1).end=_,a.at(-1).score+=c);}s.push(a.map(({id:i,start:l,end:c,score:d})=>({id:i,start:l*r,end:c*r,confidence:d/(c-l)})));}return s}},_v=class extends lt{constructor(e){super(e);let t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",true);this.mel_filters=r,this.window=gr(400,"povey",{periodic:false});}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),or(e,this.window,400,160,{fft_length:512,power:2,center:false,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:true,max_num_frames:t,transpose:true})}async _call(e,{padding:t=true,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:s=true,return_attention_mask:n=true}={}){ct(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(s){let[p,w]=a.dims,y=a.data;for(let b=0;b<w;++b){let x=0;for(let S=0;S<p;++S)x+=y[S*w+b];let T=x/p,C=0;for(let S=0;S<p;++S)C+=(y[S*w+b]-T)**2;C/=p-1;let A=Math.sqrt(C+1e-7);for(let S=0;S<p;++S){let N=S*w+b;y[N]=(y[N]-T)/A;}}}let o;if(t){let[p,w]=a.dims,y=a.data,b=p%r;if(b>0){let x=new Float32Array(w*(p+b));x.set(y),x.fill(this.config.padding_value,y.length);let T=p+b;a=new V(a.type,x,[T,w]),n&&(o=new V("int64",new BigInt64Array(T),[1,T]),o.data.fill(1n,0,p));}}let[i,l]=a.dims,c=this.config.stride;if(i%c!==0)throw new Error(`The number of frames (${i}) must be a multiple of the stride (${c}).`);let h=a.view(1,Math.floor(i/c),l*c),_={input_features:h};if(n){let p=h.dims[1],w=new BigInt64Array(p);if(o){let y=o.data;for(let b=1,x=0;b<i;b+=c,++x)w[x]=y[b];}else w.fill(1n);_.attention_mask=new V("int64",w,[1,p]);}return _}},pv=class extends Gd{},mv=class extends lt{},gv=class extends lt{_zero_mean_unit_var_norm(e){let r=e.reduce((n,a)=>n+a,0)/e.length,s=e.reduce((n,a)=>n+(a-r)**2,0)/e.length;return e.map(n=>(n-r)/Math.sqrt(s+1e-7))}async _call(e){ct(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let r=[1,t.length];return {input_values:new V("float32",t,r),attention_mask:new V("int64",new BigInt64Array(t.length).fill(1n),r)}}},wv=class extends lt{constructor(e){super(e);let t=this.config.sampling_rate,r=rr(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",true);this.mel_filters=r,this.window=gr(400,"hamming",{periodic:false}),this.min_num_frames=this.config.min_num_frames;}async _extract_fbank_features(e){return e=e.map(t=>t*32768),or(e,this.window,400,160,{fft_length:512,power:2,center:false,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:true,transpose:true,min_num_frames:this.min_num_frames})}async _call(e){ct(e,"WeSpeakerFeatureExtractor");let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let r=t.mean(1).data,s=t.data,[n,a,o]=t.dims;for(let i=0;i<n;++i){let l=i*a*o,c=i*o;for(let d=0;d<a;++d){let h=l+d*o;for(let _=0;_<o;++_)s[h+_]-=r[c+_];}}}return {input_features:t}}},yv=class extends lt{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=gr(this.config.n_fft,"hann");}async _extract_fbank_features(e,{center:t=true}={}){let{n_fft:r,hop_length:s,mel_filters:n,global_log_mel_max:a}=this.config,o=Math.floor(t?e.length/s:(e.length-r)/s);return await or(e,this.window,r,s,{power:2,mel_filters:n,log_mel:"log10_max_norm",max_log_mel:a,center:t,max_num_frames:o,do_pad:false})}async _call(e,{center:t=true}={}){return ct(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},vv=class extends lt{constructor(e){var t;super(e),(t=this.config).mel_filters??(t.mel_filters=rr(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=gr(this.config.n_fft,"hann");}async _extract_fbank_features(e){return await or(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){ct(e,"WhisperFeatureExtractor");let r,s=t??this.config.n_samples;return e.length>s?(e.length>this.config.n_samples&&ce.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),r=e.slice(0,s)):(r=new Float32Array(s),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},St=class{static async from_pretrained(e,t={}){let r=await ar(e,zd,true,t),s=r.feature_extractor_type,n=Dd[s];if(!n)throw new Error(`Unknown feature_extractor_type: '${s}'. Please report this at ${Po}.`);return new n(r)}},qa,bv=(qa=class extends ke{async _call(e,t=null){let r=this.tokenizer(e),s=t?await this.feature_extractor(t):{};return {...r,...s}}},k(qa,"tokenizer_class",xe),k(qa,"feature_extractor_class",St),qa),M3=new Set(["ja","zh"]),vn,Mv=(vn=class extends ke{get_decoder_prompt_ids(e="en"){let t=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t="en"){let r=e.filter(a=>a&&a.trim());if(r.length===0)return "";let s=M3.has(t)?"":" ";return [r[0].trimEnd(),...r.slice(1).map(a=>a.trim())].join(s)}async _call(e){return await this.feature_extractor(e)}},k(vn,"tokenizer_class",xe),k(vn,"feature_extractor_class",St),k(vn,"uses_processor_config",true),vn),od={},Jr,xv,Sr;if(he.IS_WEB_ENV)Jr=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},Sr=self.createImageBitmap,xv=self.ImageData;else if(od)Sr=async e=>{let r=(await e.metadata()).channels,{data:s,info:n}=await e.rotate().raw().toBuffer({resolveWithObject:true}),a=new vt(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&a.convert(r),a};else throw new Error("Unable to load image processing library.");var x3={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},k3=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),vt=class Kt{constructor(t,r,s,n){this.data=t,this.width=r,this.height=s,this.channels=n;}get size(){return [this.width,this.height]}static async read(t){if(t instanceof Kt)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!he.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new Kt(s,t.width,t.height,4)}static async fromURL(t){let r=await Nn(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(t){if(he.IS_WEB_ENV){let r=await Sr(t),s=Jr(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=od(await t.arrayBuffer());return await Sr(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new Kt(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r<this.data.length;r+=this.channels){let n=this.data[r],a=this.data[r+1],o=this.data[r+2];t[s++]=Math.round(.2989*n+.587*a+.114*o);}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let t=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)t[s++]=this.data[r],t[s++]=this.data[r+1],t[s++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let t=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=this.data[r],t[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)t[s++]=this.data[r],t[s++]=this.data[r+1],t[s++]=this.data[r+2],t[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(t,this.width,this.height,4)}putAlpha(t){if(t.width!==this.width||t.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${t.width}x${t.height}`);if(t.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${t.channels}`);let r=this.data,s=t.data,n=this.width*this.height;if(this.channels===3){let a=new Uint8ClampedArray(n*4);for(let o=0,i=0,l=0;o<n;++o)a[l++]=r[i++],a[l++]=r[i++],a[l++]=r[i++],a[l++]=s[o];return this._update(a,this.width,this.height,4)}else if(this.channels===4){for(let a=0;a<n;++a)r[4*a+3]=s[a];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,r,{resample:s=2}={}){if(this.width===t&&this.height===r)return this;let n=x3[s]??s,a=Pg(t),o=Pg(r);if(a&&o)return this;if(a?t=r/this.height*this.width:o&&(r=t/this.width*this.height),he.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=Jr(t,r).getContext("2d");return c.drawImage(l,0,0,t,r),new Kt(c.getImageData(0,0,t,r).data,t,r,4).convert(i)}else {let i=this.toSharp();switch(n){case "box":case "hamming":(n==="box"||n==="hamming")&&(ce.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case "nearest":case "bilinear":case "bicubic":i=i.affine([t/this.width,0,0,r/this.height],{interpolator:n});break;case "lanczos":i=i.resize({width:t,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await Sr(i)}}async pad([t,r,s,n]){if(t=Math.max(t,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),t===0&&r===0&&s===0&&n===0)return this;if(he.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),i=this.width+t+r,l=this.height+s+n,c=Jr(i,l).getContext("2d");return c.drawImage(o,0,0,this.width,this.height,t,s,this.width,this.height),new Kt(c.getImageData(0,0,i,l).data,i,l,4).convert(a)}else {let a=this.toSharp().extend({left:t,right:r,top:s,bottom:n});return await Sr(a)}}async crop([t,r,s,n]){if(t=Math.max(t,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),t===0&&r===0&&s===this.width-1&&n===this.height-1)return this;let a=s-t+1,o=n-r+1;if(he.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=Jr(a,o).getContext("2d");return c.drawImage(l,t,r,a,o,0,0,a,o),new Kt(c.getImageData(0,0,a,o).data,a,o,4).convert(i)}else {let i=this.toSharp().extract({left:t,top:r,width:a,height:o});return await Sr(i)}}async center_crop(t,r){if(this.width===t&&this.height===r)return this;let s=(this.width-t)/2,n=(this.height-r)/2;if(he.IS_WEB_ENV){let a=this.channels,o=this.toCanvas(),i=Jr(t,r).getContext("2d"),l=0,c=0,d=0,h=0;return s>=0?l=s:d=-s,n>=0?c=n:h=-n,i.drawImage(o,l,c,t,r,d,h,t,r),new Kt(i.getImageData(0,0,t,r).data,t,r,4).convert(a)}else {let a=this.toSharp();if(s>=0&&n>=0)a=a.extract({left:Math.floor(s),top:Math.floor(n),width:t,height:r});else if(s<=0&&n<=0){let o=Math.floor(-n),i=Math.floor(-s);a=a.extend({top:o,left:i,right:t-this.width-i,bottom:r-this.height-o});}else {let o=[0,0],i=0;n<0?(o[0]=Math.floor(-n),o[1]=r-this.height-o[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=t-this.width-l[0]):c=Math.floor(s),a=a.extend({top:o[0],bottom:o[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:t,height:r});}return await Sr(a)}}async toBlob(t="image/png",r=1){if(!he.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new V("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!he.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let t=this.clone().rgba(),r=Jr(t.width,t.height),s=new xv(t.data,t.width,t.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:t,width:r,height:s,channels:n}=this,a=t.constructor,o=t.length/n,i=Array.from({length:n},()=>new a(o));for(let l=0;l<o;++l){let c=n*l;for(let d=0;d<n;++d)i[d][l]=t[c+d];}return i.map(l=>new Kt(l,r,s,1))}_update(t,r,s,n=null){return this.data=t,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new Kt(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(t){if(he.IS_WEB_ENV){if(he.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=t.split(".").pop().toLowerCase(),s=k3.get(r)??"image/png",n=await this.toBlob(s);return rv(t,n)}else if(he.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(he.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return od(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},T3=vt.read.bind(vt);function hw(e,t,r=0,s=null){let n=e/t,a=zN(n)*t;return s!==null&&a>s&&(a=Math.floor(n)*t),a<r&&(a=Math.ceil(n)*t),a}function fw([e,t],r){return [Math.max(Math.floor(e/r),1)*r,Math.max(Math.floor(t/r),1)*r]}function kv([e,t,r,s]){return [e-r/2,t-s/2,e+r/2,t+s/2]}function Fo(e,t=.5,r=null,s=false){let n=e.logits,a=e.pred_boxes,[o,i,l]=n.dims;if(r!==null&&r.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let d=0;d<o;++d){let h=r!==null?r[d]:null,_={boxes:[],classes:[],scores:[]},p=n[d],w=a[d];for(let y=0;y<i;++y){let b=p[y],x=[],T;if(s){T=b.sigmoid().data;for(let C=0;C<T.length;++C)T[C]>t&&x.push(C);}else {let C=Ve(b.data)[1];if(C===l-1||(T=tt(b.data),T[C]<t))continue;x.push(C);}for(let C of x){let A=w[y].data;A=kv(A),h!==null&&(A=A.map((S,N)=>S*h[(N+1)%2])),_.boxes.push(A),_.classes.push(C),_.scores.push(T[C]);}}c.push(_);}return c}function Tv(e,t=null){let r=e.logits,s=r.dims[0];if(t!==null&&t.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let a=0;a<s;++a){let o=t!==null?t[a]:null,i=r[a];o!==null&&(i=Td(i,o,"bilinear",false));let[l,c]=o??i.dims.slice(-2),d=new V("int32",new Int32Array(l*c),[l,c]),h=i[0].data,_=d.data;for(let y=1;y<i.dims[0];++y){let b=i[y].data;for(let x=0;x<b.length;++x)b[x]>h[x]&&(h[x]=b[x],_[x]=y);}let p=new Array(i.dims[0]);for(let y=0;y<_.length;++y){let b=_[y];p[b]=b;}let w=p.filter(y=>y!==void 0);n.push({segmentation:d,labels:w});}return n}function E3(e,t,r,s){let n=[],a=[],o=[];for(let i=0;i<e.dims[0];++i){let l=e[i],c=t[i],d=Ve(l.data)[1];if(d===s)continue;let _=tt(l.data)[d];_>r&&(n.push(c),a.push(_),o.push(d));}return [n,a,o]}function A3(e,t,r,s=.5,n=.8){let a=[],o=0,i=0,l=t[r].data;for(let d=0;d<e.length;++d)e[d]===r&&(a.push(d),++o),l[d]>=s&&++i;let c=o>0&&i>0;return c&&(c=o/i>n),[c,a]}function C3(e,t,r,s,n,a=null,o=null){let[i,l]=o??e[0].dims,c=new V("int32",new Int32Array(i*l),[i,l]),d=[];if(o!==null)for(let y=0;y<e.length;++y)e[y]=Td(e[y],o,"bilinear",false);let h=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let y=0;y<e.length;++y){let b=t[y],x=e[y].data;for(let T=0;T<x.length;++T)x[T]*=b,x[T]>_[T]&&(h[T]=y,_[T]=x[T]);}let p=0,w=c.data;for(let y=0;y<r.length;++y){let b=r[y],[x,T]=A3(h,e,y,s,n);if(x){++p;for(let C of T)w[C]=p;d.push({id:p,label_id:b,score:t[y]});}}return [c,d]}function jd(e,t,r=28,s=3136,n=784*1280,a=1){if(e<r||t<r){let l=Math.max(r/e,r/t);e=Math.round(e*l),t=Math.round(t*l);}if(Math.max(e,t)/Math.min(e,t)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let o=Math.round(e/r)*r,i=Math.round(t/r)*r;if(a*o*i>n){let l=Math.sqrt(a*e*t/n);o=Math.max(r,Math.floor(e/l/r)*r),i=Math.max(r,Math.floor(t/l/r)*r);}else if(a*o*i<s){let l=Math.sqrt(s/(a*e*t));o=Math.ceil(e*l/r)*r,i=Math.ceil(t*l/r)*r;}return [i,o]}function Ev(e,t=.5,r=.5,s=.8,n=null,a=null){n===null&&(ce.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);let o=e.class_queries_logits??e.logits,l=(e.masks_queries_logits??e.pred_masks).sigmoid(),[c,d,h]=o.dims;if(h-=1,a!==null&&a.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let _=[];for(let p=0;p<c;++p){let w=a!==null?a[p]:null,y=o[p],b=l[p],[x,T,C]=E3(y,b,t,h);if(C.length===0){let[N,M]=w??b.dims.slice(-2),$=new V("int32",new Int32Array(N*M).fill(-1),[N,M]);_.push({segmentation:$,segments_info:[]});continue}let[A,S]=C3(x,T,C,r,s,n,w);_.push({segmentation:A,segments_info:S});}return _}function Av(e,t=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var ue=class extends bt{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??true,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??true,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??false,this.config=e;}async thumbnail(e,t,r=2){let s=e.height,n=e.width,a=t.height,o=t.width,i=Math.min(s,a),l=Math.min(n,o);return i===s&&l===n?e:(s>n?l=Math.floor(n*i/s):n>s&&(i=Math.floor(s*l/n)),await e.resize(l,i,{resample:r}))}async crop_margin(e,t=200){let r=e.clone().grayscale(),s=sd(r.data)[0],a=Ve(r.data)[0]-s;if(a===0)return e;let o=t/255,i=r.width,l=r.height,c=0,d=0,h=r.data;for(let _=0;_<r.height;++_){let p=_*r.width;for(let w=0;w<r.width;++w)(h[p+w]-s)/a<o&&(i=Math.min(i,w),l=Math.min(l,_),c=Math.max(c,w),d=Math.max(d,_));}return e=await e.crop([i,l,c,d]),e}pad_image(e,t,r,{mode:s="constant",center:n=false,constant_values:a=0}={}){let[o,i,l]=t,c,d;if(typeof r=="number"?(c=r,d=r):r==="square"?c=d=Math.max(o,i):(c=r.width,d=r.height),c!==i||d!==o){let h=new Float32Array(c*d*l);if(Array.isArray(a))for(let w=0;w<h.length;++w)h[w]=a[w%l];else a!==0&&h.fill(a);let[_,p]=n?[Math.floor((c-i)/2),Math.floor((d-o)/2)]:[0,0];for(let w=0;w<o;++w){let y=(w+p)*c,b=w*i;for(let x=0;x<i;++x){let T=(y+x+_)*l,C=(b+x)*l;for(let A=0;A<l;++A)h[T+A]=e[C+A];}}if(s==="symmetric"){if(n)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let w=o-1,y=i-1;for(let b=0;b<d;++b){let x=b*c,T=_o(b,w)*i;for(let C=0;C<c;++C){if(b<o&&C<i)continue;let A=(x+C)*l,S=(T+_o(C,y))*l;for(let N=0;N<l;++N)h[A+N]=e[S+N];}}}e=h,t=[d,c,l];}return [e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t];}get_resize_output_image_size(e,t){let[r,s]=e.size,n,a;if(this.do_thumbnail){let{height:o,width:i}=t;n=Math.min(o,i);}else Number.isInteger(t)?(n=t,a=this.config.max_size??n):t!==void 0&&(n=t.shortest_edge,a=t.longest_edge);if(n!==void 0||a!==void 0){let o=n===void 0?1:Math.max(n/r,n/s),i=r*o,l=s*o,c=a===void 0?1:Math.min(a/i,a/l),d=Math.floor(Number((i*c).toFixed(2))),h=Math.floor(Number((l*c).toFixed(2)));return this.size_divisibility!==void 0&&([d,h]=fw([d,h],this.size_divisibility)),[d,h]}else if(t!==void 0&&t.width!==void 0&&t.height!==void 0){let o=t.width,i=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let l=i/s,c=o/r;Math.abs(1-c)<Math.abs(1-l)?l=c:c=l,i=hw(l*s,this.config.ensure_multiple_of),o=hw(c*r,this.config.ensure_multiple_of);}return [o,i]}else {if(this.size_divisibility!==void 0)return fw([r,s],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}}async resize(e){let[t,r]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,r,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:r=null,do_convert_rgb:s=null,do_convert_grayscale:n=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[o,i]=e.size;if(s??this.do_convert_rgb?e=e.rgb():n&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,p;Number.isInteger(this.crop_size)?(_=this.crop_size,p=this.crop_size):(_=this.crop_size.width,p=this.crop_size.height),e=await e.center_crop(_,p);}let l=[e.height,e.width],c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),t??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let p=this.image_std;if(Array.isArray(this.image_std)||(p=new Array(e.channels).fill(p)),_.length!==e.channels||p.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${p.length}) must match the number of channels in the image (${e.channels}).`);for(let w=0;w<c.length;w+=e.channels)for(let y=0;y<e.channels;++y)c[w+y]=(c[w+y]-_[y])/p[y];}if(r??this.do_pad){if(this.pad_size)[c,d]=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let _=Math.ceil(d[1]/this.size_divisibility)*this.size_divisibility,p=Math.ceil(d[0]/this.size_divisibility)*this.size_divisibility;[c,d]=this.pad_image(c,d,{width:_,height:p});}}if(a??this.do_flip_channel_order){if(d[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<c.length;_+=3){let p=c[_];c[_]=c[_+2],c[_+2]=p;}}let h=new V("float32",c,d).permute(2,0,1);return {original_size:[i,o],reshaped_input_size:l,pixel_values:h}}async _call(e,...t){Array.isArray(e)||(e=[e]);let r=await Promise.all(e.map(n=>this.preprocess(n)));return {pixel_values:tr(r.map(n=>n.pixel_values),0),original_sizes:r.map(n=>n.original_size),reshaped_input_sizes:r.map(n=>n.reshaped_input_size)}}static async from_pretrained(e,t={}){let r=await ar(e,Dn,true,t);return new this(r)}},yo={};$s(yo,{BeitFeatureExtractor:()=>Cv,BitImageProcessor:()=>Sv,CHMv2ImageProcessor:()=>Fv,CLIPFeatureExtractor:()=>Lv,CLIPImageProcessor:()=>qd,ChineseCLIPFeatureExtractor:()=>Pv,ConvNextFeatureExtractor:()=>Iv,ConvNextImageProcessor:()=>Wd,DINOv3ViTImageProcessor:()=>zv,DPTFeatureExtractor:()=>Bv,DPTImageProcessor:()=>Xd,DeiTFeatureExtractor:()=>Ov,DeiTImageProcessor:()=>Hd,DetrFeatureExtractor:()=>Nv,DetrImageProcessor:()=>Qd,DonutFeatureExtractor:()=>Dv,DonutImageProcessor:()=>Lo,EfficientNetImageProcessor:()=>Rv,GLPNFeatureExtractor:()=>Vv,Gemma3ImageProcessor:()=>Gv,Gemma4ImageProcessor:()=>Yd,Glm46VImageProcessor:()=>$v,GroundingDinoImageProcessor:()=>Uv,Idefics3ImageProcessor:()=>id,ImageFeatureExtractor:()=>ue,ImageProcessor:()=>ue,JinaCLIPImageProcessor:()=>qv,Lfm2VlImageProcessor:()=>Wv,LlavaOnevisionImageProcessor:()=>Hv,Mask2FormerImageProcessor:()=>Xv,MaskFormerFeatureExtractor:()=>Qv,MaskFormerImageProcessor:()=>Io,MobileNetV1FeatureExtractor:()=>Yv,MobileNetV1ImageProcessor:()=>Kd,MobileNetV2FeatureExtractor:()=>Jv,MobileNetV2ImageProcessor:()=>Zd,MobileNetV3FeatureExtractor:()=>Kv,MobileNetV3ImageProcessor:()=>eh,MobileNetV4FeatureExtractor:()=>Zv,MobileNetV4ImageProcessor:()=>th,MobileViTFeatureExtractor:()=>eb,MobileViTImageProcessor:()=>rh,NougatImageProcessor:()=>tb,OwlViTFeatureExtractor:()=>rb,OwlViTImageProcessor:()=>Oo,Owlv2ImageProcessor:()=>sb,Phi3VImageProcessor:()=>nb,PixtralImageProcessor:()=>ab,PvtImageProcessor:()=>ob,Qwen2VLImageProcessor:()=>Jd,RTDetrImageProcessor:()=>ib,Sam2ImageProcessor:()=>co,Sam3ImageProcessor:()=>co,SamImageProcessor:()=>co,SapiensFeatureExtractor:()=>lb,SapiensImageProcessor:()=>sh,SegformerFeatureExtractor:()=>cb,SegformerImageProcessor:()=>nh,SiglipImageProcessor:()=>ub,SmolVLMImageProcessor:()=>id,Swin2SRImageProcessor:()=>db,VLMImageProcessor:()=>jv,ViTFeatureExtractor:()=>hb,ViTImageProcessor:()=>ah,VitMatteImageProcessor:()=>fb,VitPoseImageProcessor:()=>_b,YolosFeatureExtractor:()=>pb,YolosImageProcessor:()=>oh});var Cv=class extends ue{},Sv=class extends ue{},Pv=class extends ue{},Fv=class extends ue{},qd=class extends ue{},Lv=class extends qd{},Wd=class extends ue{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256;}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){let r=Math.floor(t/this.crop_pct),[s,n]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(s,n,{resample:this.resample}),e=await e.center_crop(t,t);}else e=await e.resize(t,t,{resample:this.resample});return e}},Iv=class extends Wd{},Hd=class extends ue{},Ov=class extends Hd{},Qd=class extends ue{async _call(e){let t=await super._call(e),r=[t.pixel_values.dims[0],64,64],s=it(r,1n);return {...t,pixel_mask:s}}post_process_object_detection(...e){return Fo(...e)}post_process_panoptic_segmentation(...e){return Ev(...e)}post_process_instance_segmentation(...e){return Av(...e)}},Nv=class extends Qd{},zv=class extends ue{},Lo=class extends ue{pad_image(e,t,r,s={}){let[n,a,o]=t,i=this.image_mean;Array.isArray(this.image_mean)||(i=new Array(o).fill(i));let l=this.image_std;Array.isArray(l)||(l=new Array(o).fill(i));let c=i.map((d,h)=>-d/l[h]);return super.pad_image(e,t,r,{center:true,constant_values:c,...s})}},Dv=class extends Lo{},Xd=class extends ue{},Bv=class extends Xd{},Rv=class extends ue{constructor(e){super(e),this.include_top=this.config.include_top??true,this.include_top&&(this.image_std=this.image_std.map(t=>t*t));}},Gv=class extends ue{};function S3(e,t,r,s,n){let a=s*r**2,o=Math.sqrt(a/(e*t)),i=n*r,l=Math.floor(o*e/i)*i,c=Math.floor(o*t/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let d=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(t/e)*i,d)):c===0&&(c=i,l=Math.min(Math.floor(e/t)*i,d)),[l,c]}function P3(e,t,r,s,n,a,o){let i=Math.floor(t/n),l=Math.floor(r/n),c=i*l,d=n*n*s,h=new Float32Array(a*d),_=0;for(let y=0;y<i;++y)for(let b=0;b<l;++b)for(let x=0;x<n;++x){let T=(y*n+x)*r*s+b*n*s;for(let C=0;C<n;++C){let A=T+C*s;for(let S=0;S<s;++S)h[_++]=e[A+S];}}let p=new BigInt64Array(a*2).fill(-1n),w=0;for(let y=0;y<i;++y)for(let b=0;b<l;++b)p[w++]=BigInt(b),p[w++]=BigInt(y);return {patches:new V("float32",h,[a,d]),positions:new V("int64",p,[a,2]),num_soft_tokens:Math.floor(c/o**2)}}var Yd=class extends bt{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??true,this.do_resize=e.do_resize??true,this.do_convert_rgb=e.do_convert_rgb??true;}async _call(e){Array.isArray(e)||(e=[e]);let{patch_size:t,pooling_kernel_size:r}=this,s=this.max_soft_tokens*r**2,n=[],a=[],o=[];for(let i of e){if(this.do_convert_rgb&&(i=i.rgb()),this.do_resize){let[_,p]=S3(i.height,i.width,t,s,r);(_!==i.height||p!==i.width)&&(i=await i.resize(p,_,{resample:this.resample}));}let l=Float32Array.from(i.data);if(this.do_rescale)for(let _=0;_<l.length;++_)l[_]*=this.rescale_factor;let{patches:c,positions:d,num_soft_tokens:h}=P3(l,i.height,i.width,i.channels,t,s,r);n.push(c),a.push(d),o.push(h);}return {pixel_values:tr(n,0),image_position_ids:tr(a,0),num_soft_tokens_per_image:o}}},Jd=class extends ue{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size;}get_resize_output_image_size(e,t){let r=this.patch_size*this.merge_size;return jd(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){let{pixel_values:r,original_sizes:s,reshaped_input_sizes:n}=await super._call(e,...t),a=r,{temporal_patch_size:o,merge_size:i,patch_size:l}=this.config;a.dims[0]===1&&(a=Le(Array.from({length:o},()=>a),0));let c=a.dims[0]/o,d=a.dims[1],h=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l),p=a.view(c,o,d,Math.floor(h/i),i,l,Math.floor(_/i),i,l).permute(0,3,6,4,7,2,1,5,8).view(c*h*_,d*o*l*l),w=new V("int64",[c,h,_],[1,3]);return {pixel_values:p,image_grid_thw:w,original_sizes:s,reshaped_input_sizes:n}}},$v=class extends Jd{get_resize_output_image_size(e,t){let r=this.patch_size*this.merge_size,s=this.config.temporal_patch_size??2;return jd(e.height,e.width,r,this.min_pixels,this.max_pixels,s)}},Vv=class extends ue{},Uv=class extends ue{async _call(e){let t=await super._call(e),r=t.pixel_values.dims,s=yt([r[0],r[2],r[3]]);return {...t,pixel_mask:s}}},id=class extends ue{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??true,this.max_image_size=e.max_image_size;}get_resize_for_vision_encoder(e,t){let[r,s]=e.dims.slice(-2),n=s/r;return s>=r?(s=Math.ceil(s/t)*t,r=Math.floor(s/n),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,s=Math.floor(r*n),s=Math.ceil(s/t)*t),{height:r,width:s}}async _call(e,{do_image_splitting:t=null,return_row_col_info:r=false}={}){let s;if(!Array.isArray(e))s=[[e]];else {if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?s=e:s=[e];}let n=[],a=[],o=[],i=[],l=[];for(let b of s){let x=await Promise.all(b.map(A=>this.preprocess(A)));i.push(...x.map(A=>A.original_size)),l.push(...x.map(A=>A.reshaped_input_size)),x.forEach(A=>A.pixel_values.unsqueeze_(0));let{longest_edge:T}=this.max_image_size,C;if(t??this.do_image_splitting){let A=new Array(x.length),S=new Array(x.length);C=await Promise.all(x.map(async(N,M)=>{let $=this.get_resize_for_vision_encoder(N.pixel_values,T),G=await Nt(N.pixel_values,{size:[$.height,$.width]}),{frames:j,num_splits_h:Q,num_splits_w:q}=await this.split_image(G,this.max_image_size);return A[M]=Q,S[M]=q,Le(j,0)})),a.push(A),o.push(S);}else {let A=[T,T];C=await Promise.all(x.map(S=>Nt(S.pixel_values,{size:A}))),a.push(new Array(x.length).fill(0)),o.push(new Array(x.length).fill(0));}n.push(Le(C,0));}let c=n.length,[d,h,_,p]=n[0].dims,w,y;if(c===1)w=n[0].unsqueeze_(0),y=it([c,d,_,p],true);else {let b=Math.max(...n.map(C=>C.dims.at(0)));y=it([c,b,_,p],true);let x=y.data,T=b*_*p;for(let C=0;C<c;++C){let A=n[C].dims[0];if(A<b){n[C]=Le([n[C],it([b-A,h,_,p],0)],0);let S=C*T+A*_*p,N=(C+1)*T;x.fill(false,S,N);}}w=tr(n,0);}return {pixel_values:w,pixel_attention_mask:y,original_sizes:i,reshaped_input_sizes:l,...r?{rows:a,cols:o}:{}}}async split_image(e,{longest_edge:t}){let r=t,s=t,n=[],[a,o]=e.dims.slice(-2),i=0,l=0;if(a>r||o>s){i=Math.ceil(a/r),l=Math.ceil(o/s);let c=Math.ceil(a/i),d=Math.ceil(o/l);for(let p=0;p<i;++p)for(let w=0;w<l;++w){let y,b,x,T;p===i-1?(b=a-c,T=a):(b=p*c,T=(p+1)*c),w===l-1?(y=o-d,x=o):(y=w*d,x=(w+1)*d);let S=await Ed(e,[b,y],[T,x],[2,3]);n.push(S);}let h=r,_=s;(a!==h||o!==_)&&(e=await Nt(e,{size:[h,_]}));}return n.push(e),{frames:n,num_splits_h:i,num_splits_w:l}}},jv=class extends ue{constructor(e){super({do_pad:true,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(t=>t*this.rescale_factor);}pad_image(e,t,r,s){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:true,...s})}},qv=class extends ue{constructor(e){let{resize_mode:t,fill_color:r,interpolation:s,size:n,...a}=e,o=t==="squash"?{width:n,height:n}:t==="shortest"?{shortest_edge:n}:{longest_edge:n},i=s==="bicubic"?3:2;super({...a,size:o,resample:i,do_center_crop:true,crop_size:n,do_normalize:true});}};function _w(e,t){return Math.round(e/t)*t}function F3(e,t,r,s,n){let a=1/0,o=[1,1],i=r*s;for(let l of t){let c=Math.abs(e-l[0]/l[1]);c<a?(a=c,o=l):c===a&&i>.5*n*n*l[0]*l[1]&&(o=l);}return o}function L3(e,t){let r=[],s=new Set;for(let n=e;n<=t;++n)for(let a=1;a<=n;++a)for(let o=1;o<=n;++o){let i=a*o;if(i>=e&&i<=t){let l=a<<16|o;s.has(l)||(s.add(l),r.push([a,o]));}}return r.sort((n,a)=>n[0]*n[1]-a[0]*a[1])}function I3(e,t){let[r,s,n,a]=e.dims,o=Math.floor(n/t),i=Math.floor(a/t),l=t*t*s,c=e.data,d=new Float32Array(r*o*i*l),h=n*a;for(let _=0;_<r;++_){let p=_*s*h,w=_*o*i*l;for(let y=0;y<o;++y)for(let b=0;b<i;++b){let x=w+(y*i+b)*l;for(let T=0;T<t;++T){let C=(y*t+T)*a+b*t;for(let A=0;A<t;++A){let S=C+A;for(let N=0;N<s;++N)d[x++]=c[p+N*h+S];}}}}return new V("float32",d,[r,o*i,l])}function O3(e,t){let[,r,s]=e.dims,n=new BigInt64Array(t);n.fill(1n,0,r);let a=e;if(r<t){let o=new Float32Array(t*s);o.set(e.data),a=new V("float32",o,[1,t,s]);}return {padded:a,mask:new V("int64",n,[t])}}var Wv=class extends ue{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??true,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??true,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??false;let t=this.max_image_tokens*this.downsample_factor**2,r=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,r);}_is_image_too_large(e,t){let r=this.encoder_patch_size*this.downsample_factor,s=Math.max(this.encoder_patch_size,_w(e,r)),n=Math.max(this.encoder_patch_size,_w(t,r));return s*n>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let r=L3(this.min_tiles,this.max_tiles),[s,n]=F3(t/e,r,t,e,this.tile_size);return {grid_width:s,grid_height:n,target_width:this.tile_size*s,target_height:this.tile_size*n}}async _call(e,{return_row_col_info:t=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];let s=[],n=[],a=[],o=[],i=[],l=[];for(let d of r){let h=await Promise.all(d.map(_=>this.preprocess(_,{do_pad:false})));for(let{pixel_values:_}of h){let[,p,w]=_.dims,y=_.unsqueeze_(0),b=this.encoder_patch_size*this.downsample_factor,x=b**2,[T,C]=jd(Math.max(b,p),Math.max(b,w),b,this.min_image_tokens*x,this.max_image_tokens*x).map(G=>Math.max(b,G)),A,S=1,N=1,M=this._is_image_too_large(p,w),$=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(M&&$){let{grid_width:G,grid_height:j,target_width:Q,target_height:q}=this._get_grid_layout(p,w);S=j,N=G;let X=await Nt(y,{size:[q,Q]});A=[];for(let D=0;D<j;++D)for(let L=0;L<G;++L){let Y=D*this.tile_size,te=L*this.tile_size;A.push(X.slice(null,null,[Y,Y+this.tile_size],[te,te+this.tile_size]));}this.use_thumbnail&&G*j!==1&&A.push(await Nt(y,{size:[C,T]}));}else A=[await Nt(y,{size:[C,T]})];for(let G of A){let[,,j,Q]=G.dims,q=I3(G,this.encoder_patch_size),{padded:X,mask:D}=O3(q,this.max_num_patches);s.push(X),n.push(D),a.push([Math.floor(j/this.encoder_patch_size),Math.floor(Q/this.encoder_patch_size)]);}o.push(S),i.push(N),l.push([C,T]);}}let c={pixel_values:Le(s,0),pixel_attention_mask:tr(n,0),spatial_shapes:new V("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return (t??this.return_row_col_info)&&(c.image_rows=o,c.image_cols=i,c.image_sizes=l),c}},Hv=class extends ue{},Io=class extends ue{post_process_panoptic_segmentation(...e){return Ev(...e)}post_process_instance_segmentation(...e){return Av(...e)}},Qv=class extends Io{},Xv=class extends Io{},Kd=class extends ue{},Yv=class extends Kd{},Zd=class extends ue{},Jv=class extends Zd{},eh=class extends ue{},Kv=class extends eh{},th=class extends ue{},Zv=class extends th{},rh=class extends ue{},eb=class extends rh{},tb=class extends Lo{},Oo=class extends ue{post_process_object_detection(...e){return Fo(...e)}},rb=class extends Oo{},sb=class extends Oo{},Et=336,N3=[2,3],{ceil:mu,floor:Cs,sqrt:gu}=Math,nb=class extends ue{constructor(e){super({...e,do_normalize:true,do_pad:true,pad_size:"custom",do_convert_rgb:true,do_resize:true}),this._num_crops=e.num_crops;}calc_num_image_tokens_from_image_size(e,t){let{num_img_tokens:r}=this.config;return Cs((Cs(t/Et)*Cs(e/Et)+1)*r+1+(Cs(t/Et)+1)*gu(r))}get_resize_output_image_size(e,t){let r=this._num_crops,[s,n]=e.size,a=s/n,o=1;for(;o*Math.ceil(o/a)<=r;)o+=1;o-=1;let i=Math.floor(o*336),l=Math.floor(i/a);return [i,l]}pad_image(e,t,r,s={}){let[n,a]=t,o=Et*mu(n/Et),i=Et*mu(a/Et),l=[1,1,1].map((c,d)=>(c-this.image_mean[d])/this.image_std[d]);return super.pad_image(e,t,{width:i,height:o},{center:true,constant_values:l,...s})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??(t=this.config.num_crops),t<4||gu(t)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let r=e.length,s=await Promise.all(e.map(h=>this.preprocess(h))),n=s.map(h=>h.original_size),a=s.map(h=>h.reshaped_input_size),o=[];for(let{pixel_values:h}of s){h.unsqueeze_(0);let[_,p]=h.dims.slice(-2),w=await Nt(h,{size:[Et,Et],mode:"bicubic"});if(t>0){let y=[],b=gu(t),x=Cs(p/b),T=Cs(_/b);for(let A=0;A<b;++A)for(let S=0;S<b;++S){let N,M,$,G;A===b-1?(M=_-T,G=_):(M=A*T,G=(A+1)*T),S===b-1?(N=p-x,$=p):(N=S*x,$=(S+1)*x);let q=await Ed(h,[M,N],[G,$],N3);y.push(q);}let C=await Nt(Le(y,0),{size:[Et,Et],mode:"bicubic"});o.push(Le([w,C],0));}else o.push(w);}let i=tr(o,0),l=a.map(h=>h.map(_=>Et*mu(_/Et))),c=new V("int64",l.flat(),[r,2]),d=l.map(([h,_])=>this.calc_num_image_tokens_from_image_size(_,h));return {pixel_values:i,original_sizes:n,reshaped_input_sizes:a,image_sizes:c,num_img_tokens:d}}},ab=class extends ue{get_resize_output_image_size(e,t){let{longest_edge:r}=t;if(r===void 0)throw new Error("size must contain 'longest_edge'");let[s,n]=e.size,a=Math.max(s,n)/r,o=s,i=n;a>1&&(o=Math.floor(s/a),i=Math.floor(n/a));let{patch_size:l,spatial_merge_size:c}=this.config;if(!c)throw new Error("config must contain 'spatial_merge_size'");let d=l*c,h=Math.floor((o-1)/d)+1,_=Math.floor((i-1)/d)+1;return [h*d,_*d]}},ob=class extends ue{},ib=class extends ue{post_process_object_detection(...e){return Fo(...e)}},co=class extends ue{reshape_input_points(e,t,r,s=false){e=structuredClone(e);let n=Fg(e);if(n.length===3)s||(n=[1,...n]),e=[e];else if(n.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){let[o,i]=t[a],[l,c]=r[a],d=[c/i,l/o];for(let h=0;h<e[a].length;++h)for(let _=0;_<e[a][h].length;++_)for(let p=0;p<e[a][h][_].length;++p)e[a][h][_][p]*=d[p%2];}return new V("float32",Float32Array.from(e.flat(1/0)),n)}add_input_labels(e,t){let r=Fg(e);if(r.length===2)r=[1,...r],e=[e];else if(r.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(r.some((s,n)=>s!==t.dims[n]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new V("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:s=null}={}){let n=await super._call(e);if(t&&(n.input_points=this.reshape_input_points(t,n.original_sizes,n.reshaped_input_sizes)),r){if(!n.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");n.input_labels=this.add_input_labels(r,n.input_points);}return s&&(n.input_boxes=this.reshape_input_points(s,n.original_sizes,n.reshaped_input_sizes,true)),n}async post_process_masks(e,t,r,{mask_threshold:s=0,binarize:n=true,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let i=[a.height,a.width];for(let l=0;l<t.length;++l){let c=t[l],d=r[l],h=await Nt(e[l],{mode:"bilinear",size:i});if(h=h.slice(null,null,[0,d[0]],[0,d[1]]),h=await Nt(h,{mode:"bilinear",size:c}),n){let _=h.data,p=new Uint8Array(_.length);for(let w=0;w<_.length;++w)_[w]>s&&(p[w]=1);h=new V("bool",p,h.dims);}o.push(h);}return o}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:s=512/1500,points_per_crop:n=32,crop_n_points_downscale_factor:a=1}={}){}},sh=class extends ue{post_process_semantic_segmentation(...e){return Tv(...e)}},lb=class extends sh{},nh=class extends ue{post_process_semantic_segmentation(...e){return Tv(...e)}},cb=class extends nh{},ub=class extends ue{},db=class extends ue{pad_image(e,t,r,s={}){let[n,a,o]=t;return super.pad_image(e,t,{width:a+(r-a%r)%r,height:n+(r-n%r)%r},{mode:"symmetric",center:false,constant_values:-1,...s})}},ah=class extends ue{},hb=class extends ah{},fb=class extends ue{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=await Promise.all(e.map(a=>this.preprocess(a))),s=await Promise.all(t.map(a=>this.preprocess(a,{do_normalize:false,do_convert_rgb:false,do_convert_grayscale:true})));return {pixel_values:tr(r.map((a,o)=>Le([a.pixel_values,s[o].pixel_values],0)),0),original_sizes:r.map(a=>a.original_size),reshaped_input_sizes:r.map(a=>a.reshaped_input_size)}}},_b=class extends ue{post_process_pose_estimation(e,t,{threshold:r=null}={}){let s=e.tolist(),[n,a,o,i]=e.dims,l=[];for(let c=0;c<n;++c){let d=s[c],h=t[c],_=[];for(let p=0;p<h.length;++p){let w=h[p],y=[],b=[],x=[],T=w.at(-2)/i,C=w.at(-1)/o;for(let A=0;A<d.length;++A){let[S,N]=[0,0],M=0,$=-1/0,G=d[A];for(let Q=0;Q<G.length;++Q){let q=G[Q];for(let X=0;X<q.length;++X){let D=q[X];M+=D,$=Math.max($,D),S+=(X+.5)*D,N+=Q*D;}}if(r!=null&&$<r)continue;let j=[T*S/M,C*N/M];y.push(j),x.push(A),b.push($);}_.push({bbox:w,scores:b,labels:x,keypoints:y});}l.push(_);}return l}},oh=class extends ue{post_process_object_detection(...e){return Fo(...e)}},pb=class extends oh{},ut=class{static async from_pretrained(e,t={}){let r=await ar(e,Dn,true,t),s=r.image_processor_type??r.feature_extractor_type,n=yo[s?.replace(/Fast$/,"")];return n||(s!==void 0&&ce.warn(`Image processor type '${s}' not found, assuming base ImageProcessor. Please report this at ${Po}.`),n=ue),new n(r)}},Wa,mb=(Wa=class extends ke{constructor(e,t,r){super(e,t,r);let{tasks_answer_post_processing_type:s,task_prompts_without_inputs:n,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(s??{})),this.task_prompts_without_inputs=new Map(Object.entries(n??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3;}construct_prompts(e){typeof e=="string"&&(e=[e]);let t=[];for(let r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else {for(let[s,n]of this.task_prompts_with_input)if(r.includes(s)){t.push(n.replaceAll("{input}",r).replaceAll(s,""));break}t.length!==e.length&&t.push(r);}return t}post_process_generation(e,t,r){let s=this.tasks_answer_post_processing_type.get(t)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let n;switch(s){case "pure_text":n=e;break;case "description_with_bboxes":case "bboxes":case "phrase_grounding":case "ocr":let a=s==="ocr"?"quad_boxes":"bboxes",o=e.matchAll(this.regexes[a]),i=[],l=[];for(let[c,d,...h]of o)i.push(d?d.trim():i.at(-1)??""),l.push(h.map((_,p)=>(Number(_)+.5)/this.size_per_bin*r[p%2]));n={labels:i,[a]:l};break;default:throw new Error(`Task "${t}" (of type "${s}") not yet implemented.`)}return {[t]:n}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");let s=await this.image_processor(e,r),n=t?this.tokenizer(this.construct_prompts(t),r):{};return {...s,...n}}},k(Wa,"tokenizer_class",xe),k(Wa,"image_processor_class",ut),Wa),Ps,gb=(Ps=class extends ke{constructor(e,t,r){super(e,t,r),this.image_seq_length=this.config.image_seq_length;let{boi_token:s,image_token:n,eoi_token:a}=this.tokenizer.config;this.boi_token=s,this.image_token=n,this.eoi_token=a;let o=n.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
14
|
+
|
|
15
|
+
${s}${o}${a}
|
|
16
|
+
|
|
17
|
+
`;}async _call(e,t=null,r={}){typeof e=="string"&&(e=[e]);let s;return t&&(s=await this.image_processor(t,r),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,r),...s}}},k(Ps,"tokenizer_class",xe),k(Ps,"image_processor_class",ut),k(Ps,"uses_processor_config",true),k(Ps,"uses_chat_template_file",true),Ps),Xr,wb=(Xr=class extends ke{constructor(e,t,r){super(e,t,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:s,boa_token:n,audio_token:a,eoa_token:o,image_token_id:i,boi_token:l,image_token:c,eoi_token:d}=this.tokenizer.config;this.audio_token_id=s,this.boa_token=n,this.audio_token=a;let h=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
|
|
18
|
+
|
|
19
|
+
${n}${h}${o}
|
|
20
|
+
|
|
21
|
+
`,this.image_token_id=i,this.boi_token=l,this.image_token=c;let _=c.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
22
|
+
|
|
23
|
+
${l}${_}${d}
|
|
24
|
+
|
|
25
|
+
`;}async _call(e,t=null,r=null,s={}){typeof e=="string"&&(e=[e]);let n;r&&(n=await this.feature_extractor(r,s),e=e.map(i=>i.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,s),e=e.map(i=>i.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,s),...a,...n}}},k(Xr,"image_processor_class",ut),k(Xr,"feature_extractor_class",St),k(Xr,"tokenizer_class",xe),k(Xr,"uses_processor_config",true),k(Xr,"uses_chat_template_file",true),Xr),Ha,yb=(Ha=class extends ke{constructor(e,t,r){super(e,t,r),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:s,boa_token:n,eoa_token:a,image_token:o,boi_token:i,eoi_token:l}=this.tokenizer.config;this.audio_token=s,this.boa_token=n,this.eoa_token=a,this.image_token=o,this.boi_token=i,this.eoi_token=l;}static async from_pretrained(e,t={}){let[r,s,n]=await Promise.all([ar(e,ev,true,t),xe.from_pretrained(e,t),xd(e,tv,false,t)]),a={tokenizer:s};return r.image_processor&&(a.image_processor=new Yd(r.image_processor)),r.feature_extractor&&(a.feature_extractor=new Vd(r.feature_extractor)),new this(r,a,n)}_compute_audio_num_tokens(e,t){let r=Math.round(t*20/1e3),s=Math.round(t*10/1e3),n=Math.floor(r/2),a=Math.floor((e+n-r-1)/s)+1;if(a<=0)return 0;for(let o=0;o<2;++o)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,t=null,r=null,s={}){typeof e=="string"&&(e=[e]);let n;if(t){n=await this.image_processor(t,s);let o=n.num_soft_tokens_per_image,i=0;e=e.map(l=>l.replaceAll(this.image_token,()=>`
|
|
26
|
+
|
|
27
|
+
${this.boi_token}${this.image_token.repeat(o[i++])}${this.eoi_token}
|
|
28
|
+
|
|
29
|
+
`));}let a;if(r){let o=Array.isArray(r)?r:[r];a=await this.feature_extractor(o[0],s);let i=this.feature_extractor.config.sampling_rate??16e3,l=0;e=e.map(c=>c.replaceAll(this.audio_token,()=>`
|
|
30
|
+
|
|
31
|
+
${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(o[l++].length,i))}${this.eoa_token}
|
|
32
|
+
|
|
33
|
+
`));}return {...this.tokenizer(e,s),...n,...a}}},k(Ha,"uses_processor_config",true),k(Ha,"uses_chat_template_file",true),Ha),bn,No=(bn=class extends ke{async _call(e,t=null,...r){Array.isArray(e)||(e=[e]);let s,n;if(t&&(s=await this.image_processor(t),n=s.image_grid_thw),n){let o=this.image_processor.config.merge_size**2,i=0,l=this.constructor.image_token,c=n.tolist();e=e.map(d=>{for(;d.includes(l);){let h=Number(c[i++].reduce((_,p)=>_*p,1n));d=d.replace(l,"<|placeholder|>".repeat(Math.floor(h/o)));}return d.replaceAll("<|placeholder|>",l)});}return {...this.tokenizer(e),...s}}},k(bn,"image_processor_class",ut),k(bn,"tokenizer_class",xe),k(bn,"image_token","<|image_pad|>"),bn),Mu,vb=(Mu=class extends No{},k(Mu,"image_token","<|image|>"),Mu),Mn,bb=(Mn=class extends ke{_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:s}=this.feature_extractor.config,n=Math.floor(r/s),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/r)*n}async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){let{input_features:a}=await this.feature_extractor(t);s.input_features=a;let o=this._get_num_audio_features(t.length),i=new Uint8Array(o).fill(1);s.input_features_mask=new V("bool",i,[1,o]);let l=this.config.audio_token??"<|audio|>";if(!e.includes(l))throw new Error(`The input text does not contain the audio token ${l}.`);e=e.replaceAll(l,l.repeat(o));}return {...this.tokenizer(e,{add_special_tokens:false,...r}),...s}}},k(Mn,"tokenizer_class",xe),k(Mn,"feature_extractor_class",St),k(Mn,"uses_processor_config",true),Mn);function z3(e,t){let s=e.dims.at(-1)-1,n=e.tolist();n.fill(false,0,1),n.fill(false,s);let a=t.tolist();return n.map((o,i)=>o?i:null).filter(o=>o!==null).map(o=>a[o])}var Qa,Mb=(Qa=class extends ke{async _call(e,t,r={}){let s=e?await this.image_processor(e,r):{};return {...t?this.tokenizer(t,r):{},...s}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:s=.25,target_sizes:n=null}={}){let{logits:a,pred_boxes:o}=e,i=a.dims[0];if(n!==null&&n.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let l=a.dims.at(1),c=a.sigmoid(),d=c.max(-1).tolist(),h=o.tolist().map(p=>p.map(w=>kv(w))),_=[];for(let p=0;p<i;++p){let w=n!==null?n[p]:null;w!==null&&(h[p]=h[p].map(C=>C.map((A,S)=>A*w[(S+1)%2])));let y=d[p],b=[],x=[],T=[];for(let C=0;C<l;++C){let A=y[C];if(A<=r)continue;let S=h[p][C],N=c[p][C];b.push(A),T.push(S);let M=z3(N.gt(s),t[p]);x.push(M);}_.push({scores:b,boxes:T,labels:this.batch_decode(x)});}return _}},k(Qa,"tokenizer_class",xe),k(Qa,"image_processor_class",ut),Qa);function D3(e,t,r,s,n,a){let o="";for(let i=0;i<t;++i){for(let l=0;l<r;++l)o+=s+`<row_${i+1}_col_${l+1}>`+n.repeat(e);o+=`
|
|
34
|
+
`;}return o+=`
|
|
35
|
+
${s}${a}`+n.repeat(e)+`${s}`,o}function B3(e,t,r,s){return `${t}${s}`+r.repeat(e)+`${t}`}function R3(e,t,r,s,n,a){return e===0&&t===0?B3(r,s,n,a):D3(r,e,t,s,n,a)}var xn,ld=(xn=class extends ke{constructor(){super(...arguments);k(this,"fake_image_token","<fake_token_around_image>");k(this,"image_token","<image>");k(this,"global_img_token","<global-img>");}async _call(t,r=null,s={}){s.return_row_col_info??(s.return_row_col_info=true);let n;r&&(n=await this.image_processor(r,s)),Array.isArray(t)||(t=[t]);let a=n.rows??[new Array(t.length).fill(0)],o=n.cols??[new Array(t.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let h=0;h<t.length;++h){let _=t[h],p=a[h],w=o[h];l.push(iL(_,this.image_token));let y=p.map((T,C)=>R3(T,w[C],i,this.fake_image_token,this.image_token,this.global_img_token)),b=_.split(this.image_token);if(b.length===0)throw new Error("The image token should be present in the text.");let x=b[0];for(let T=0;T<y.length;++T)x+=y[T]+b[T+1];c.push(x);}return {...this.tokenizer(c),...n}}},k(xn,"image_processor_class",ut),k(xn,"tokenizer_class",xe),k(xn,"uses_processor_config",true),xn),kn,xb=(kn=class extends ke{constructor(e,t,r){super(e,t,r),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens;}async _call(e,{images:t=null,chat_template:r="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(y=>y.images).flatMap(y=>y.images).map(y=>vt.read(y)));let s=this.tokenizer,n=s.apply_chat_template(e,{tokenize:false,add_generation_prompt:true,chat_template:r}),a=y=>s.encode(y,{add_special_tokens:false}),o=n.split(this.image_tag),i=o.length-1;if(t.length!==i)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${i})`);let[l,c,d]=s.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),h=a(o[0]),_=new Array(h.length).fill(false);for(let y=1;y<o.length;++y){let b=new Array(this.num_image_tokens).fill(l),x=a(o[y]);h=Gt(h,[c],b,[d],x);let T=new Array(this.num_image_tokens).fill(true);_=Gt(_,[false],T,[false],new Array(x.length).fill(false));}let p=[1,h.length],w={input_ids:new V("int64",h,p),attention_mask:new V("int64",new Array(h.length).fill(1),p),images_seq_mask:new V("bool",_,p),images_emb_mask:new V("bool",new Array(i*this.num_image_tokens).fill(true),[1,i,this.num_image_tokens])};if(t&&t.length>0){let y=await this.image_processor(t);return y.pixel_values.unsqueeze_(0),{...w,...y}}return w}},k(kn,"image_processor_class",ut),k(kn,"tokenizer_class",xe),k(kn,"uses_processor_config",true),kn),Xa,kb=(Xa=class extends ke{async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");let s=e?this.tokenizer(e,r):{},n=t?await this.image_processor(t,r):{};return {...s,...n}}},k(Xa,"tokenizer_class",xe),k(Xa,"image_processor_class",ut),Xa),Ya,Tb=(Ya=class extends ke{async _call(e,t=null,r={}){let{image_rows:s,image_cols:n,image_sizes:a,...o}=await this.image_processor(e,{...r,return_row_col_info:true});if(t){let i=this.config.image_token??"<image>",{tile_size:l=512,downsample_factor:c=2,encoder_patch_size:d=16,use_thumbnail:h=true}=this.image_processor.config,_=T=>Math.ceil(Math.floor(T/d)/c),p=_(l)**2,w=this.config.image_start_token??"<|image_start|>",y=this.config.image_end_token??"<|image_end|>",b=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let x=0;t=t.map(T=>{let C=T.split(i);return C[0]+C.slice(1).map(A=>{let S=x++,[N,M]=a[S],$=s[S],G=n[S],j=_(N)*_(M),Q=w;if($>1||G>1){let q=i.repeat(p);for(let X=0;X<$;++X)for(let D=0;D<G;++D)Q+=`<|img_row_${X+1}_col_${D+1}|>`+q;h&&(Q+=b+i.repeat(j));}else Q+=i.repeat(j);return Q+y+A}).join("")});}return {...o,...t?this.tokenizer(t,r):{}}}},k(Ya,"tokenizer_class",xe),k(Ya,"image_processor_class",ut),Ya),Tn,Eb=(Tn=class extends ke{async _call(e,t=null,r={}){let s=await this.image_processor(e,r);if(t){let[a,o]=s.pixel_values.dims.slice(-2),{image_token:i,patch_size:l,num_additional_image_tokens:c}=this.config,d=Math.floor(a/l)*Math.floor(o/l)+c;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let h=0;h<t.length;++h)t[h]=t[h].replace(i,i.repeat(d));}let n=t?this.tokenizer(t,r):{};return {...s,...n}}},k(Tn,"tokenizer_class",xe),k(Tn,"image_processor_class",ut),k(Tn,"uses_processor_config",true),Tn),pw={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},Ja,Ab=(Ja=class extends ke{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,t){if(!pw.hasOwnProperty(t))throw new Error(`Format ${t} is not supported.`);let[r,s]=pw[t],n=this[r].bind(this),[a,o]=e.dims,i=[],l=[],c=e.tolist();for(let h=0;h<a;++h){let _=c[h],p=[],w=[];for(let b=1;b<o;++b){let[x,T]=Ve(tt(_[b]));if(w.push(x),T==s)break;p.push(T);}let y=w.length>0?w.reduce((b,x)=>b*x,1):0;l.push(p),i.push(y);}return [n(l),i]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){let[s,n]=this._decode_helper(e,"char"),[a,o]=this._decode_helper(t,"bpe"),[i,l]=this._decode_helper(r,"wp"),c=[],d=[];for(let h=0;h<s.length;++h){let[_,p]=Ve([n[h],o[h],l[h]]);c.push([s[h],a[h],i[h]][p]),d.push(_);}return {generated_text:c,scores:d,char_preds:s,bpe_preds:a,wp_preds:i}}static async from_pretrained(...e){let t=await super.from_pretrained(...e),r=await xe.from_pretrained("Xenova/gpt2"),s=await xe.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:r,wp_tokenizer:s},t}async _call(e,t=null){let r=await this.image_processor(e);return t&&(r.labels=this.tokenizer(t).input_ids),r}},k(Ja,"tokenizer_class",xe),k(Ja,"image_processor_class",ut),Ja),Ka,Cb=(Ka=class extends ke{async _call(e){return await this.feature_extractor(e)}},k(Ka,"tokenizer_class",xe),k(Ka,"feature_extractor_class",St),Ka),Za,Sb=(Za=class extends ke{},k(Za,"tokenizer_class",xe),k(Za,"image_processor_class",ut),Za),Ss="<image>";function G3(e,t,r,s,n){return `${s.repeat(r*n)}${t}${e}
|
|
36
|
+
`}var En,Pb=(En=class extends ke{async _call(e,t=null,r={}){t||(ce.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let s=this.tokenizer.bos_token,n=this.image_processor.config.image_seq_length,a;t.some(l=>l.includes(Ss))?a=t.map(l=>{let c=l.replaceAll(Ss,Ss.repeat(n)),d=c.lastIndexOf(Ss),h=d===-1?0:d+Ss.length;return c.slice(0,h)+s+c.slice(h)+`
|
|
37
|
+
`}):(ce.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(l=>G3(l,s,n,Ss,e.length)));let o=this.tokenizer(a,r);return {...await this.image_processor(e,r),...o}}},k(En,"tokenizer_class",xe),k(En,"image_processor_class",ut),k(En,"uses_processor_config",false),En),mw="<|image|>",$3=/<\|image_\d+\|>/g,eo,Fb=(eo=class extends ke{async _call(e,t=null,{padding:r=true,truncation:s=true,num_crops:n=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:n});let{num_img_tokens:i}=o,l=e.map((d,h)=>d.split($3).join(mw.repeat(i[h])));a=this.tokenizer(l,{padding:r,truncation:s});let c=this.tokenizer._tokenizer.token_to_id(mw);a.input_ids.map_(d=>d==c?-d:d);}else a=this.tokenizer(e);return {...a,...o}}},k(eo,"image_processor_class",ut),k(eo,"tokenizer_class",xe),eo),An,Lb=(An=class extends ke{async _call(e,t=null,r={}){let s=await this.image_processor(e,r);if(t){let[a,o]=s.pixel_values.dims.slice(-2),{image_token:i,image_break_token:l,image_end_token:c,patch_size:d,spatial_merge_size:h}=this.config,_=d*h,p=Math.floor(a/_),w=Math.floor(o/_);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let y=0;y<t.length;++y){let b=i.repeat(w),x=b+l,T=b+c,C=x.repeat(p-1)+T;t[y]=t[y].replace(i,C);}}let n=t?this.tokenizer(t,r):{};return {...s,...n}}},k(An,"tokenizer_class",xe),k(An,"image_processor_class",ut),k(An,"uses_processor_config",true),An),xu,Ib=(xu=class extends ke{async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}},k(xu,"feature_extractor_class",Ud),xu),ih=class extends No{},Ob=class extends ih{},ku,lh=(ku=class extends ke{async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}},k(ku,"image_processor_class",ut),ku),ch=class extends lh{},Nb=class extends ch{},to,zb=(to=class extends ke{async _call(e){return await this.feature_extractor(e)}},k(to,"tokenizer_class",xe),k(to,"feature_extractor_class",St),to),Cn,Db=(Cn=class extends ke{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){let a=t.length,{input_features:o}=await this.feature_extractor(t,{...r,max_length:a}),i=Math.round(a/this.config.encoder_ds_factor+1e-4),l=1+Math.ceil(i/this.config.stack_factor);s.audio_token_len=[l],s.audio_values=o;let c=this.config.audio_placeholder;if(!e.includes(c))throw new Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(l));}return {...this.tokenizer(e,{add_special_tokens:false,...r}),...s}}},k(Cn,"tokenizer_class",xe),k(Cn,"feature_extractor_class",St),k(Cn,"uses_processor_config",true),Cn),$a="[AUDIO]",V3="[BEGIN_AUDIO]",U3=375;function j3(e,t){let r=[];for(let s=0;s<e.length;s+=t)r.push(e.subarray(s,Math.min(s+t,e.length)));return r}var Sn,Bb=(Sn=class extends ke{async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){if(!e.includes($a))throw new Error(`The input text does not contain the audio token ${$a}.`);Array.isArray(t)||(t=[t]);let a=e.split($a),o=a.length-1;if(o!==t.length)throw new Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${o}).`);let i=this.feature_extractor.config.n_samples,l=t.map(p=>j3(p,i)),c=l.map(p=>p.length),d=l.flat(),h=(await Promise.all(d.map(p=>this.feature_extractor(p,r)))).map(p=>p.input_features);s.audio_values=h.length>1?Le(h,0):h[0];let _=a[0];for(let p=0;p<c.length;++p){_+=V3;for(let w=0;w<c[p];++w)_+=$a.repeat(U3);_+=a[p+1];}e=_;}return {...this.tokenizer(e,{add_special_tokens:false,...r}),...s}}},k(Sn,"tokenizer_class",xe),k(Sn,"feature_extractor_class",St),k(Sn,"uses_processor_config",false),Sn),gw=32,wu=6,Va=8,q3=10,W3=32,Pn,Rb=(Pn=class extends ke{get num_mel_frames_first_audio_chunk(){return (wu+1)*Va}get num_samples_first_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return (this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return Va*e+t}get num_right_pad_tokens(){return wu+1+q3}get audio_length_per_tok(){return Va}get raw_audio_length_per_tok(){return Va*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=false,is_first_audio_chunk:r=true}={}){if(ct(e,"VoxtralRealtimeProcessor"),!t&&!r)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(r)if(t){let s=gw*this.raw_audio_length_per_tok,n=new Float32Array(s+e.length);n.set(e,s);let a=await this.feature_extractor(n,{center:true}),i=1+(gw+wu),l=new BigInt64Array(i).fill(BigInt(W3));return l[0]=1n,{input_ids:new V("int64",l,[1,i]),...a}}else {let s=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+s);return n.set(e),await this.feature_extractor(n,{center:true})}else return await this.feature_extractor(e,{center:false})}},k(Pn,"tokenizer_class",xe),k(Pn,"feature_extractor_class",St),k(Pn,"uses_processor_config",false),Pn),ro,Gb=(ro=class extends ke{async _call(e){return await this.feature_extractor(e)}},k(ro,"tokenizer_class",xe),k(ro,"feature_extractor_class",St),ro),so,$b=(so=class extends ke{async _call(e){return await this.feature_extractor(e)}},k(so,"tokenizer_class",xe),k(so,"feature_extractor_class",St),so),no,Vb=(no=class extends ke{async _call(e){return await this.feature_extractor(e)}},k(no,"tokenizer_class",xe),k(no,"feature_extractor_class",St),no),Ub=class{static async from_pretrained(e,t={}){let r=await ar(e,Dn,true,t),{image_processor_type:s,feature_extractor_type:n,processor_class:a}=r;if(a&&ad[a])return ad[a].from_pretrained(e,t);if(!s&&!n)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let o={};if(s){let l=yo[s.replace(/Fast$/,"")];if(!l)throw new Error(`Unknown image_processor_type: '${s}'.`);o.image_processor=new l(r);}if(n){let l=yo[n];if(l)o.image_processor=new l(r);else {let c=Dd[n];if(!c)throw new Error(`Unknown feature_extractor_type: '${n}'.`);o.feature_extractor=new c(r);}}let i={};return new ke(i,o,null)}};async function H3(e,t){return await ar(e,"config.json",true,t)}function Fs(e){let t={},r={};switch(e.model_type){case "llava":case "paligemma":case "gemma3":case "florence2":case "llava_onevision":case "idefics3":case "granite_speech":case "ultravox":case "voxtral":case "voxtral_realtime":case "smolvlm":case "gemma3n":case "gemma4":case "lfm2_vl":case "chatterbox":case "lighton_ocr":case "glm_ocr":case "mistral3":case "qwen2_5_vl":case "qwen3_vl":case "qwen3_vl_moe":r=Fs(e.text_config);break;case "moondream1":r=Fs(e.phi_config);break;case "musicgen":r=Fs(e.decoder);break;case "multi_modality":r=Fs(e.language_config);break;case "gpt2":case "gptj":case "jais":case "codegen":case "gpt_bigcode":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="n_embd";break;case "gpt_neox":case "stablelm":case "opt":case "falcon":case "modernbert-decoder":t.num_heads="num_attention_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size";break;case "gpt_oss":case "llama":case "llama4_text":case "nanochat":case "apertus":case "arcee":case "afmoe":case "lfm2":case "lfm2_moe":case "smollm3":case "olmo":case "olmo2":case "olmo3":case "mobilellm":case "granite":case "granitemoehybrid":case "cohere":case "cohere2":case "mistral":case "voxtral_realtime_text":case "voxtral_realtime_encoder":case "starcoder2":case "qwen2":case "qwen2_moe":case "qwen2_vl":case "qwen2_vl_text":case "qwen2_5_vl_text":case "qwen3_moe":case "qwen3_vl_text":case "qwen3_vl_moe_text":case "phi":case "phi3":case "phi3_v":case "llava_qwen2":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.hidden_size="hidden_size",t.num_attention_heads="num_attention_heads",t.dim_kv="head_dim";break;case "qwen3":case "solar_open":case "glm_ocr_text":case "gemma":case "gemma2":case "vaultgemma":case "gemma3_text":case "gemma3n_text":case "gemma4_text":case "glm":case "helium":case "ernie4_5":case "hunyuan_v1_dense":case "falcon_h1":case "nemotron_h":case "ministral":case "ministral3":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="head_dim";break;case "openelm":t.num_heads="num_kv_heads",t.num_layers="num_transformer_layers",t.dim_kv="head_dim";break;case "gpt_neo":case "donut-swin":t.num_heads="num_heads",t.num_layers="num_layers",t.hidden_size="hidden_size";break;case "bloom":t.num_heads="n_head",t.num_layers="n_layer",t.hidden_size="hidden_size";break;case "mpt":t.num_heads="n_heads",t.num_layers="n_layers",t.hidden_size="d_model";break;case "exaone":t.num_heads="num_key_value_heads",t.num_layers="num_layers",t.dim_kv="head_dim",t.num_attention_heads="num_attention_heads";break;case "youtu":case "deepseek_v3":case "glm_moe_dsa":case "mistral4":t.num_heads="num_key_value_heads",t.num_layers="num_hidden_layers",t.dim_kv="qk_head_dim",t.num_attention_heads="num_attention_heads";break;case "t5":case "mt5":case "longt5":t.num_decoder_layers="num_decoder_layers",t.num_decoder_heads="num_heads",t.decoder_dim_kv="d_kv",t.num_encoder_layers="num_layers",t.num_encoder_heads="num_heads",t.encoder_dim_kv="d_kv";break;case "bart":case "mbart":case "marian":case "whisper":case "lite-whisper":case "m2m_100":case "blenderbot":case "blenderbot-small":case "florence2_language":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="d_model",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="d_model";break;case "speecht5":t.num_decoder_layers="decoder_layers",t.num_decoder_heads="decoder_attention_heads",t.decoder_hidden_size="hidden_size",t.num_encoder_layers="encoder_layers",t.num_encoder_heads="encoder_attention_heads",t.encoder_hidden_size="hidden_size";break;case "trocr":t.num_encoder_layers=t.num_decoder_layers="decoder_layers",t.num_encoder_heads=t.num_decoder_heads="decoder_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="d_model";break;case "musicgen_decoder":t.num_encoder_layers=t.num_decoder_layers="num_hidden_layers",t.num_encoder_heads=t.num_decoder_heads="num_attention_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case "moonshine":t.num_decoder_layers="decoder_num_hidden_layers",t.num_decoder_heads="decoder_num_key_value_heads",t.num_encoder_layers="encoder_num_hidden_layers",t.num_encoder_heads="encoder_num_key_value_heads",t.encoder_hidden_size=t.decoder_hidden_size="hidden_size";break;case "cohere_asr":t.num_decoder_layers="num_hidden_layers",t.num_decoder_heads="num_key_value_heads",t.decoder_hidden_size="hidden_size",t.decoder_dim_kv="head_dim";let{num_hidden_layers:n,num_attention_heads:a,hidden_size:o}=e.encoder_config;r={num_encoder_layers:n,num_encoder_heads:a,encoder_hidden_size:o,encoder_dim_kv:e.head_dim};break;case "vision-encoder-decoder":let i=Fs(e.decoder),l="num_decoder_layers"in i,c=at(e,["model_type","is_encoder_decoder"]);return l?(c.num_decoder_layers=i.num_decoder_layers,c.num_decoder_heads=i.num_decoder_heads,c.decoder_hidden_size=i.decoder_hidden_size,c.num_encoder_layers=i.num_encoder_layers,c.num_encoder_heads=i.num_encoder_heads,c.encoder_hidden_size=i.encoder_hidden_size):(c.num_layers=i.num_layers,c.num_heads=i.num_heads,c.hidden_size=i.hidden_size),c}let s={...r,...at(e,["model_type","multi_query","is_encoder_decoder"])};for(let n in t)s[n]=e[t[n]];return s}function zo(e,t){e instanceof vo||(e=new vo(e));let r=t?.batch_size??1;if(["lfm2","lfm2_moe"].includes(e.model_type)){let s=t?.prefix??"past_key_values",n=s==="present"?"present":"past",a={},{layer_types:o,num_attention_heads:i,num_key_value_heads:l,hidden_size:c,conv_L_cache:d}=e,h=c/i;for(let _=0;_<o.length;++_)if(o[_]==="full_attention")for(let p of ["key","value"])a[`${s}.${_}.${p}`]=[r,l,0,h];else if(o[_]==="conv")a[`${n}_conv.${_}`]=[r,c,d];else throw new Error(`Unsupported layer type: ${o[_]}`);return a}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){let s=t?.prefix??"past_key_values",n=s==="present"?"present":"past",a=e,o=a.layer_types??a.layers_block_type,i=a.num_hidden_layers??o?.length,l=a.num_key_value_heads,c=a.head_dim??a.hidden_size/a.num_attention_heads,d=a.mamba_n_heads??a.mamba_num_heads,h=a.mamba_d_head??a.mamba_head_dim,_=a.mamba_d_state??a.ssm_state_size,p=a.mamba_n_groups??a.n_groups,w=a.mamba_d_conv??a.conv_kernel,b=(a.mamba_d_ssm??(a.mamba_expand?a.mamba_expand*a.hidden_size:d*h))+2*p*_,x={};for(let T=0;T<i;++T)if((!o||o[T]==="mamba")&&(x[`${n}_conv.${T}`]=[r,b,w],x[`${n}_ssm.${T}`]=[r,d,h,_]),!o||o[T]==="attention")for(let C of ["key","value"])x[`${s}.${T}.${C}`]=[r,l,0,c];return x}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){let s=t?.prefix??"past_key_values",n=s==="present"?"present":"past",a={},{head_dim:o,layer_types:i,num_attention_heads:l,num_key_value_heads:c,hidden_size:d,linear_num_value_heads:h,linear_num_key_heads:_,linear_key_head_dim:p,linear_value_head_dim:w,linear_conv_kernel_dim:y}=e,b=p*_,x=w*h,T=o??d/l;for(let C=0;C<i.length;++C)if(i[C]==="full_attention")for(let A of ["key","value"])a[`${s}.${C}.${A}`]=[r,c,0,T];else if(i[C]==="linear_attention"){if(e.model_type==="olmo_hybrid")a[`${n}_conv.${C}.key`]=[r,b,y],a[`${n}_conv.${C}.value`]=[r,x,y],a[`${n}_conv.${C}.query`]=[r,b,y];else {let A=b*2+x;a[`${n}_conv.${C}`]=[r,A,y];}a[`${n}_recurrent.${C}`]=[r,h,p,w];}else throw new Error(`Unsupported layer type: ${i[C]}`);return a}else if(["gemma4","gemma4_text"].includes(e.model_type)){let s=e.model_type==="gemma4"?e.text_config:e,n=t?.prefix??"past_key_values",a={},o=s.num_hidden_layers,i=s.num_kv_shared_layers??0,l=o-i,c=s.num_key_value_heads,d=s.head_dim,h=s.global_head_dim??d,_=s.layer_types??[];for(let p=0;p<l;++p){let w=_[p]==="full_attention"?h:d;for(let y of ["key","value"])a[`${n}.${p}.${y}`]=[r,c,0,w];}return a}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type)){let s;return e.model_type==="voxtral_realtime"&&t?.session_name==="audio_encoder"?s=e.audio_config:s=e.text_config,zo(s,t)}return Q3(e,t)}function Q3(e,{prefix:t="past_key_values",batch_size:r=1}={}){let s={},n=e.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){let a=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,o=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,i=[r,n.num_encoder_heads,0,a],l=[r,n.num_decoder_heads,0,o];for(let c=0;c<n.num_decoder_layers;++c)s[`${t}.${c}.encoder.key`]=i,s[`${t}.${c}.encoder.value`]=i,s[`${t}.${c}.decoder.key`]=l,s[`${t}.${c}.decoder.value`]=l;}else {let a=n.num_heads,o=n.num_layers,i=n.dim_kv??n.hidden_size/(n.num_attention_heads??a);if(n.model_type==="falcon"){let l=[r*a,0,i];for(let c=0;c<o;++c)s[`${t}.${c}.key`]=l,s[`${t}.${c}.value`]=l;}else if(n.multi_query){let l=[r*a,0,2*i];for(let c=0;c<o;++c)s[`${t}.${c}.key_value`]=l;}else if(n.model_type==="bloom"){let l=[r*a,i,0],c=[r*a,0,i];for(let d=0;d<o;++d)s[`${t}.${d}.key`]=l,s[`${t}.${d}.value`]=c;}else if(n.model_type==="openelm")for(let l=0;l<o;++l){let c=[r,a[l],0,i];s[`${t}.${l}.key`]=c,s[`${t}.${l}.value`]=c;}else {let l=[r,a,0,i];for(let c=0;c<o;++c)s[`${t}.${c}.key`]=l,s[`${t}.${c}.value`]=l;}}return s}var vo=class cd{constructor(t){k(this,"model_type",null);k(this,"is_encoder_decoder",false);k(this,"max_position_embeddings");k(this,"transformers.js_config");Object.assign(this,t),this.normalized_config=Fs(this);}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=false,revision:o="main"}={}){s&&!(s instanceof cd)&&(s=new cd(s));let i=s??await H3(t,{progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o});return new this(i)}},Gs=class{static async from_pretrained(...e){return vo.from_pretrained(...e)}};function jb(e,t,r){return e?typeof e=="object"&&e!==null?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(r)?+e[r]:0:+e:0}function qb(e,t){let r=[];for(let s=0;s<t;++s)r.push(`${e}_data${s===0?"":"_"+s}`);return r}async function X3(e,t,r,s){let n=`${t}${s}.onnx`,a=`${r.subfolder??""}/${n}`;return await go(e,a,true,r,he.IS_NODE_ENV)}async function Y3(e,t,r,s,n,a={}){let o=`${t}${r}.onnx`,i=he.IS_NODE_ENV,l=[],c=jb(n,o,t);if(c>0){if(c>Yg)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${Yg}).`);let d=qb(o,c);for(let h of d){let _=`${s.subfolder??""}/${h}`;l.push(new Promise(async(p,w)=>{let y=await go(e,_,true,s,i);p(y instanceof Uint8Array?{path:h,data:y}:h);}));}}else a.externalData!==void 0&&(l=a.externalData.map(async d=>{if(typeof d.data=="string"){let h=await go(e,d.data,true,s);return {...d,data:h}}return d}));return Promise.all(l)}async function J3(e,t,r,s=false,n=void 0){let a=r.config?.["transformers.js_config"]??{},o=ey(r.device??a.device,t,{warn:A=>ce.info(A)}),i=qN(o),l=a.device_config??{};l.hasOwnProperty(o)&&(a={...a,...l[o]});let c=ty(r.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:A=>ce.info(A)});if(zn.hasOwnProperty(c)){if(o==="webgpu"&&!he.IS_NODE_ENV&&c===Ue.fp16&&!await QN())throw new Error(`The device (${o}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(Ue).join(", ")}`);let d=a.kv_cache_dtype,h=d?typeof d=="string"?d:d[c]??"float32":void 0;if(h&&!["float32","float16"].includes(h))throw new Error(`Invalid kv_cache_dtype: ${h}. Should be one of: float32, float16`);let _=zn[c],p={...r.session_options};p.executionProviders??(p.executionProviders=i);let w=a.free_dimension_overrides;w?p.freeDimensionOverrides??(p.freeDimensionOverrides=w):o.startsWith("webnn")&&!p.freeDimensionOverrides&&ce.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let y=X3(e,t,r,_),b=r.use_external_data_format??a.use_external_data_format,x=await Y3(e,t,_,r,b,p);if(x.length>0&&(!he.IS_NODE_ENV||x.some(A=>typeof A!="string"))&&(p.externalData=x),s&&o==="webgpu"&&d!==false){let A=zo(r.config,{prefix:"present",session_name:n});if(Object.keys(A).length>0&&!kd()){let S={};for(let N in A)S[N]="gpu-buffer";p.preferredOutputLocation=S;}}return {buffer_or_path:await y,session_options:p,session_config:{dtype:c,kv_cache_dtype:h,device:o}}}async function K3(e,t,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{let a=s?.[n]??false,{buffer_or_path:o,session_options:i,session_config:l}=await J3(e,t[n],r,a,n),c=await Jw(o,i,l);return [n,c]})))}function Wb(e){for(let t in e)Zw(e[t])?e[t]=new V(e[t]):typeof e[t]=="object"&&Wb(e[t]);return e}async function we(e,t){let r=Z3(e,t);try{let s=Object.fromEntries(Object.entries(r).map(([a,o])=>{let i=o.ort_tensor;return he.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[a,i]})),n=await Kw(e,s);return Wb(n)}catch(s){let n=Object.fromEntries(Object.entries(r).map(([a,o])=>{let i={type:o.type,dims:o.dims,location:o.location};return i.location!=="gpu-buffer"&&(i.data=o.data),[a,i]}));throw ce.error(`An error occurred during model execution: "${s}".`),ce.error("Inputs given to model:",n),s}}function Z3(e,t){let r=Object.create(null),s=[];for(let o of e.inputNames){let i=t[o];if(!(i instanceof V)){s.push(o);continue}r[o]=kd()?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(t).length,a=e.inputNames.length;if(n>a){let o=Object.keys(t).filter(i=>!e.inputNames.includes(i));ce.warn(`WARNING: Too many inputs were provided (${n} > ${a}). The following inputs will be ignored: "${o.join(", ")}".`);}return r}var Xe=class{},le=class extends Xe{constructor({logits:e,...t}){super(),this.logits=e;let r=Object.values(t);r.length>0&&(this.attentions=r);}},je=class extends Xe{constructor({logits:e}){super(),this.logits=e;}},Ye=class extends Xe{constructor({logits:e}){super(),this.logits=e;}},_t=class extends Xe{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t;}},rs=class extends Xe{constructor({logits:e}){super(),this.logits=e;}},ez=class extends Xe{constructor({alphas:e}){super(),this.alphas=e;}},zt=class extends bt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},Do=class extends bt{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},bo=class extends bt{constructor(){super(),this.processors=[];}push(e){this.processors.push(e);}extend(e){this.processors.push(...e);}_call(e,t){let r=t;for(let s of this.processors)r=s(e,r);return r}[Symbol.iterator](){return this.processors.values()}},Hb=class extends zt{constructor(e){super(),this.bos_token_id=e;}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===1){let s=t[r].data;s.fill(-1/0),s[this.bos_token_id]=0;}return t}},Qb=class extends zt{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t];}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.max_length-1){let s=t[r].data;s.fill(-1/0);for(let n of this.eos_token_id)s[n]=0;}return t}},Xb=class extends zt{constructor(e){super(),this.suppress_tokens=e;}_call(e,t){for(let r=0;r<e.length;++r){let s=t[r].data;for(let n of this.suppress_tokens)s[n]=-1/0;}return t}},uh=class extends zt{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t;}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length===this.begin_index){let s=t[r].data;for(let n of this.begin_suppress_tokens)s[n]=-1/0;}return t}},Yb=class extends zt{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index;}_call(e,t){for(let r=0;r<e.length;++r){let s=t[r].data;if(s[this.no_timestamps_token_id]=-1/0,e[r].length===this.begin_index){s.subarray(0,this.timestamp_begin).fill(-1/0);continue}let n=e[r].slice(this.begin_index),a=n.length>=1&&n[n.length-1]>=this.timestamp_begin,o=n.length<2||n[n.length-2]>=this.timestamp_begin;if(a&&(o?s.subarray(this.timestamp_begin).fill(-1/0):s.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){let d=this.timestamp_begin+this.max_initial_timestamp_index;s.subarray(d+1).fill(-1/0);}let i=jw(s),l=Math.log(i.subarray(this.timestamp_begin).map(Math.exp).reduce((d,h)=>d+h)),c=Ve(i.subarray(0,this.timestamp_begin))[0];l>c&&s.subarray(0,this.timestamp_begin).fill(-1/0);}return t}},Jb=class extends zt{constructor(e){super(),this.no_repeat_ngram_size=e;}getNgrams(e){let t=e.length,r=[];for(let n=0;n<t+1-this.no_repeat_ngram_size;++n){let a=[];for(let o=0;o<this.no_repeat_ngram_size;++o)a.push(e[n+o]);r.push(a.map(Number));}let s=new Map;for(let n of r){let a=n.slice(0,n.length-1),o=JSON.stringify(a),i=s.get(o)??[];i.push(n[n.length-1]),s.set(o,i);}return s}getGeneratedNgrams(e,t){let r=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(r.map(Number)))??[]}calcBannedNgramTokens(e){let t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{let r=this.getNgrams(e);return this.getGeneratedNgrams(r,e)}}_call(e,t){for(let r=0;r<e.length;++r){let s=t[r].data,n=this.calcBannedNgramTokens(e[r]);for(let a of n)s[a]=-1/0;}return t}},Kb=class extends zt{constructor(e){super(),this.penalty=e;}_call(e,t){for(let r=0;r<e.length;++r){let s=t[r].data;for(let n of new Set(e[r])){let a=Number(n);s[a]<0?s[a]*=this.penalty:s[a]/=this.penalty;}}return t}},Zb=class extends zt{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t];}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length<this.min_length){let s=t[r].data;for(let n of this.eos_token_id)s[n]=-1/0;}return t}},e0=class extends zt{constructor(e,t,r){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(r)?r:[r];}_call(e,t){for(let r=0;r<e.length;++r)if(e[r].length-this.prompt_length_to_skip<this.min_new_tokens){let n=t[r].data;for(let a of this.eos_token_id)n[a]=-1/0;}return t}},t0=class extends zt{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t];}_call(e,t){for(let r=0;r<e.length;++r){let s=t[r].data,n=e[r];for(let a of this.bad_words_ids){if(n.length<a.length-1)continue;let o=true;for(let i=1;i<=a.length-1;++i)if(a.at(-i-1)!=n.at(-i)){o=false;break}o&&(s[a.at(-1)]=-1/0);}}return t}},r0=class extends zt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e;}_call(e,t){if(t.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let r=e.length,s=t.slice([0,r],null),n=t.slice([r,t.dims[0]],null);for(let a=0;a<n.data.length;++a)n.data[a]+=(s.data[a]-n.data[a])*this.guidance_scale;return n}},s0=class extends Do{constructor(e){if(super(),typeof e!="number"||e<=0);this.temperature=e;}_call(e,t){let r=t.data;for(let s=0;s<r.length;++s)r[s]/=this.temperature;return t}},tz=class extends Do{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(r)||r<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${r}`);this.top_p=e,this.filter_value=t,this.min_tokens_to_keep=r;}},rz=class extends Do{constructor(e,{filter_value:t=-1/0,min_tokens_to_keep:r=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,r),this.filter_value=t;}},n0=class{constructor(e){k(this,"max_length",20);k(this,"max_new_tokens",null);k(this,"min_length",0);k(this,"min_new_tokens",null);k(this,"early_stopping",false);k(this,"max_time",null);k(this,"do_sample",false);k(this,"num_beams",1);k(this,"num_beam_groups",1);k(this,"penalty_alpha",null);k(this,"use_cache",true);k(this,"temperature",1);k(this,"top_k",50);k(this,"top_p",1);k(this,"typical_p",1);k(this,"epsilon_cutoff",0);k(this,"eta_cutoff",0);k(this,"diversity_penalty",0);k(this,"repetition_penalty",1);k(this,"encoder_repetition_penalty",1);k(this,"length_penalty",1);k(this,"no_repeat_ngram_size",0);k(this,"bad_words_ids",null);k(this,"force_words_ids",null);k(this,"renormalize_logits",false);k(this,"constraints",null);k(this,"forced_bos_token_id",null);k(this,"forced_eos_token_id",null);k(this,"remove_invalid_values",false);k(this,"exponential_decay_length_penalty",null);k(this,"suppress_tokens",null);k(this,"streamer",null);k(this,"begin_suppress_tokens",null);k(this,"forced_decoder_ids",null);k(this,"guidance_scale",null);k(this,"num_return_sequences",1);k(this,"output_attentions",false);k(this,"output_hidden_states",false);k(this,"output_scores",false);k(this,"return_dict_in_generate",false);k(this,"pad_token_id",null);k(this,"bos_token_id",null);k(this,"eos_token_id",null);k(this,"encoder_no_repeat_ngram_size",0);k(this,"decoder_start_token_id",null);k(this,"generation_kwargs",{});Object.assign(this,at(e,Object.getOwnPropertyNames(this)));}},qs=class extends bt{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},dh=class a0 extends bt{constructor(){super(),this.criteria=[];}push(t){this.criteria.push(t);}extend(t){t instanceof a0?t=t.criteria:t instanceof qs&&(t=[t]),this.criteria.push(...t);}_call(t,r){let s=new Array(t.length).fill(false);for(let n of this.criteria){let a=n(t,r);for(let o=0;o<s.length;++o)s[o]||(s[o]=a[o]);}return s}[Symbol.iterator](){return this.criteria.values()}},o0=class extends qs{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t;}_call(e){return e.map(t=>t.length>=this.max_length)}},i0=class extends qs{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e;}_call(e,t){return e.map(r=>{let s=r.at(-1);return this.eos_token_id.some(n=>s==n)})}},sz=class extends qs{constructor(){super(),this.interrupted=false;}interrupt(){this.interrupted=true;}reset(){this.interrupted=false;}_call(e,t){return new Array(e.length).fill(this.interrupted)}},Bo=class extends bt{constructor(e){super(),this.generation_config=e;}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let r=e.dims.at(-1),s=e.data;if(t===-1)s=s.slice(-r);else {let n=t*r;s=s.slice(n,n+r);}return s}randomSelect(e){return pN(e)}static getSampler(e){if(e.do_sample)return new az(e);if(e.num_beams>1)return new oz(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 nz(e)}},nz=class extends Bo{async sample(e){let t=Ve(e.data)[1];return [[BigInt(t),0]]}},az=class extends Bo{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[r,s]=await ts(e,t),n=tt(r.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(n);return [s.data[a],Math.log(n[a])]})}},oz=class extends Bo{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[r,s]=await ts(e,t),n=tt(r.data);return Array.from({length:this.generation_config.num_beams},(a,o)=>[s.data[o],Math.log(n[o])])}},iz=class{constructor(e){if(e)for(let t in e){if(t in this)throw new TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let r=e[t];if(!(r instanceof V))throw new TypeError(`Expected a Tensor for key "${t}", got ${typeof r}`);this[t]=r;}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(let t in e){let r=this[t],s=e[t];r&&r!==s&&r.location==="gpu-buffer"&&r.dispose(),this[t]=s;}}async dispose(){let e=[];for(let t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e);}},Ro=iz,W={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},fr={[W.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:true},optional_configs:{generation_config:"generation_config.json"}},[W.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[W.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:true},optional_configs:{generation_config:"generation_config.json"}},[W.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:true},optional_configs:{generation_config:"generation_config.json"}},[W.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:true},optional_configs:{generation_config:"generation_config.json"}},[W.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:true}},[W.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[W.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let s={...fr[W.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),e.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:true},optional_configs:{generation_config:"generation_config.json"}},[W.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let s={...fr[W.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:true},optional_configs:{generation_config:"generation_config.json"}},[W.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let s={...fr[W.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},optional_configs:{generation_config:"generation_config.json"}},[W.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:true},optional_configs:{generation_config:"generation_config.json"}},[W.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:true},optional_configs:{generation_config:"generation_config.json"}},[W.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[W.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[W.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:true},optional_configs:{generation_config:"generation_config.json"}},[W.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,r)=>{let s={...fr[W.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:true,audio_encoder:true},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(e,t)=>({model:t.model_file_name??"model"})}};function lz(e){return fr[e]?.text_only_sessions??null}function l0(e,t,r={}){let s=fr[e]??fr.default;return {sessions:s.sessions(t,r,r.textOnly??false),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function hh(e,{warn:t=true}={}){let r=e.architectures||[];for(let s of r){let n=_r.get(s);if(n!==void 0)return n}if(e.model_type){let s=_r.get(e.model_type);if(s!==void 0)return s;for(let n of Object.values(Ls))if(n.has(e.model_type)){let a=_r.get(n.get(e.model_type));if(a!==void 0)return a}}if(t){let s=r.length>0?r.join(", "):"(none)";ce.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Po}`);}return W.EncoderOnly}function fh(e,{config:t=null,cache_dir:r=null,local_files_only:s=false,revision:n="main"}={}){if(t!==null)return Gs.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:n});let a=JSON.stringify([e,r,s,n]);return Vw(a,()=>Gs.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:n}))}async function _h(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){t=await fh(e,{config:t});let a=["config.json"],o=t["transformers.js_config"]??{},i=o.use_external_data_format,l="onnx",c=s??o.device,d=r??o.dtype,h=hh(t),_=(y,b=null)=>{b=b??y;let x=ey(c,y),T=ty(d,y,x),C=zn[T]??"",A=`${b}${C}.onnx`,S=`${l}/${A}`;a.push(S);let N=jb(i,A,y);for(let M of qb(A,N)){let $=`${l}/${M}`;a.push($);}},{sessions:p,optional_configs:w}=l0(h,t,{model_file_name:n});for(let[y,b]of Object.entries(p))_(y,b);if(w)for(let y of Object.values(w))a.push(y);return a}var Ls=null;function cz(e){Ls=e;}function ud(e){if(e instanceof V)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new V("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new V("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function c0(e){return new V("bool",[e],[1])}var ww={[W.DecoderOnly]:{can_generate:true,forward:pr,prepare_inputs:On},[W.DecoderOnlyWithoutHead]:{can_generate:false,forward:pr,prepare_inputs:On},[W.Seq2Seq]:{can_generate:true,forward:Ua,prepare_inputs:Mo},[W.Vision2Seq]:{can_generate:true,forward:Ua,prepare_inputs:Mo},[W.Musicgen]:{can_generate:true,forward:Ua},[W.EncoderDecoder]:{can_generate:false,forward:Ua},[W.ImageTextToText]:{can_generate:true,forward:fz,prepare_inputs:ja},[W.AudioTextToText]:{can_generate:true,forward:hz,prepare_inputs:ja},[W.ImageAudioTextToText]:{can_generate:true,prepare_inputs:ja},[W.Phi3V]:{can_generate:true,prepare_inputs:ja},[W.MultiModality]:{can_generate:true},[W.AutoEncoder]:{can_generate:false,forward:uz},[W.Chatterbox]:{can_generate:true,forward:Fr},[W.VoxtralRealtime]:{can_generate:true,prepare_inputs:On},default:{can_generate:false,forward:Fr}};function yw(e,t){let r=_r.get(e),s=false,n=t?.architectures?.[0];if(n&&n!==e&&e?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let i=_r.get(n);i!==void 0&&(r=i,s=true);}let a=ww[r]??ww.default,o=fr[r]??fr.default;return {typeConfig:{...a,...o},textOnly:s,modelType:r}}var _r=new Map,ph=new Map,Bs=new Map,P=class extends bt{constructor(t,r,s){super();k(this,"main_input_name","input_ids");k(this,"forward_params",["input_ids","attention_mask"]);k(this,"_return_dict_in_generate_keys",null);this.config=t,this.sessions=r,this.configs=s;let n=Bs.get(this.constructor),{typeConfig:a}=yw(n,t);this.can_generate=a.can_generate,this._forward=a.forward,this._prepare_inputs_for_generation=a.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{};}async dispose(){let t=[];for(let r of Object.values(this.sessions))t.push(r.release?.());return await Promise.all(t)}static async from_pretrained(t,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=false,revision:o="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:d=null,use_external_data_format:h=null,session_options:_={}}={}){let p={progress_callback:r,config:s,cache_dir:n,local_files_only:a,revision:o,model_file_name:i,subfolder:l,device:c,dtype:d,use_external_data_format:h,session_options:_},w=Bs.get(this);s=p.config=await Gs.from_pretrained(t,p);let{typeConfig:y,textOnly:b,modelType:x}=yw(w,s);if(x===void 0){let S=w??s?.model_type;S!=="custom"&&ce.warn(`Model type for '${S}' not found, assuming encoder-only architecture. Please report this at ${Po}.`);}if(r&&!(r instanceof td)){let S={};try{let N=await _h(t,{config:s,dtype:d,device:c,model_file_name:i});(await Promise.all(N.map($=>es(t,$,p)))).forEach(($,G)=>{if($.exists){let j=N[G]==="config.json";S[N[G]]={loaded:j?$.size??0:0,total:$.size??0};}});}catch(N){ce.warn(`Unable to fetch model file metadata for total progress tracking: ${N}`);}Object.keys(S).length>0&&(p.progress_callback=new td(r,S));}let T=y.sessions(s,p,b),C=[K3(t,T,p,y.cache_sessions)];y.optional_configs&&C.push(pz(t,y.optional_configs,p));let A=await Promise.all(C);return new this(s,...A)}async _call(t){return await this.forward(t)}async forward(t){return await this._forward(this,t)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(t,r,s=null){let n=new bo;if(t.repetition_penalty!==null&&t.repetition_penalty!==1&&n.push(new Kb(t.repetition_penalty)),t.no_repeat_ngram_size!==null&&t.no_repeat_ngram_size>0&&n.push(new Jb(t.no_repeat_ngram_size)),t.bad_words_ids!==null&&n.push(new t0(t.bad_words_ids,t.eos_token_id)),t.min_length!==null&&t.eos_token_id!==null&&t.min_length>0&&n.push(new Zb(t.min_length,t.eos_token_id)),t.min_new_tokens!==null&&t.eos_token_id!==null&&t.min_new_tokens>0&&n.push(new e0(r,t.min_new_tokens,t.eos_token_id)),t.forced_bos_token_id!==null&&n.push(new Hb(t.forced_bos_token_id)),t.forced_eos_token_id!==null&&n.push(new Qb(t.max_length,t.forced_eos_token_id)),t.suppress_tokens!==null&&n.push(new Xb(t.suppress_tokens)),t.begin_suppress_tokens!==null){let a=r>1||t.forced_bos_token_id===null?r:r+1;n.push(new uh(t.begin_suppress_tokens,a));}return t.guidance_scale!==null&&t.guidance_scale>1&&n.push(new r0(t.guidance_scale)),t.temperature===0&&t.do_sample&&(ce.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),t.do_sample=false),t.do_sample&&t.temperature!==null&&t.temperature!==1&&n.push(new s0(t.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(t,r,s=n0){let n={...this.config};for(let o of ["decoder","generator","text_config"])o in n&&Object.assign(n,n[o]);let a=new s(n);return Object.assign(a,this.generation_config??{}),t&&Object.assign(a,t),r&&Object.assign(a,at(r,Object.getOwnPropertyNames(a))),a}_get_stopping_criteria(t,r=null){let s=new dh;return t.max_length!==null&&s.push(new o0(t.max_length,this.config.max_position_embeddings??null)),t.eos_token_id!==null&&s.push(new i0(t.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let t=[Ls.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Ls.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Ls.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Ls.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Bs.get(this.constructor),s=new Set,n=this.config.model_type;for(let o of t){let i=o?.get(n);i&&s.add(i);}let a=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(a+=` Please use the following class instead: ${[...s].join(", ")}`),Error(a)}}prepare_inputs_for_generation(...t){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...t)}_update_model_kwargs_for_generation({generated_input_ids:t,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=dd(r,s.past_key_values),s.input_ids=new V("int64",t.flat(),[t.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=Le([s.decoder_attention_mask,yt([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=Le([s.attention_mask,yt([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:t,bos_token_id:r,model_kwargs:s}){let n=at(s,this.forward_params),a=this.main_input_name;if(a in n){if(t)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[a]=t;return {inputs_tensor:n[a],model_inputs:n,model_input_name:a}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:t,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:o,pixel_values:i,attention_mask:l,...c}=r,d=await this._prepare_inputs_embeds(r);r={...c,...at(d,["inputs_embeds","attention_mask"])};}let{last_hidden_state:a}=await Fr(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)a=Le([a,wo(a,0)],0),"attention_mask"in r&&(r.attention_mask=Le([r.attention_mask,Fd(r.attention_mask)],0));else if(r.decoder_input_ids){let o=ud(r.decoder_input_ids).dims[0];if(o!==a.dims[0]){if(a.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${a.dims[0]}) than the decoder inputs (${o}).`);a=Le(Array.from({length:o},()=>a),0);}}return r.encoder_outputs=a,r}_prepare_decoder_input_ids_for_generation({batch_size:t,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:a,generation_config:o}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof V)){if(i)Array.isArray(i[0])||(i=Array.from({length:t},()=>i));else if(n??(n=a),this.config.model_type==="musicgen")i=Array.from({length:t*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==t)throw new Error(`\`decoder_start_token_id\` expcted to have length ${t} but got ${n.length}`);i=n;}else i=Array.from({length:t},()=>[n]);i=ud(i);}return l.decoder_attention_mask=Sd(i),{input_ids:i,model_inputs:l}}async generate({inputs:t=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:a=null,...o}){this._validate_model_class(),r=this._prepare_generation_config(r,o);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:t,model_kwargs:o}),d=this.config.is_encoder_decoder;d&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let h;d?{input_ids:h,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):h=l[c];let _=h.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=_+r.max_new_tokens);let p=this._get_logits_processor(r,_,s),w=this._get_stopping_criteria(r,n),y=l[c].dims.at(0),b=Bo.getSampler(r),x=new Array(y).fill(0),T=h.tolist();a&&a.put(T);let C,A={},S={};for(;;){if(l=this.prepare_inputs_for_generation(T,l,r),C=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let D=dz(C);for(let L in D)L in A||(A[L]=[]),A[L].push(D[L]);}else this._return_dict_in_generate_keys&&Object.assign(S,at(C,this._return_dict_in_generate_keys));let j=C.logits.slice(null,-1,null).to("float32"),Q=p(T,j),q=[];for(let D=0;D<Q.dims.at(0);++D){let L=Q[D],Y=await b(L);for(let[te,I]of Y){let z=BigInt(te);x[D]+=I,T[D].push(z),q.push([z]);break}}if(a&&a.put(q),w(T).every(D=>D))break;l=this._update_model_kwargs_for_generation({generated_input_ids:q,outputs:C,model_inputs:l,is_encoder_decoder:d});}a&&a.end();let N=new V("int64",T.flat(),[T.length,T[0].length]),M=dd(C,l.past_key_values),$=new Set(Object.values(M));for(let j of Object.values(C))j.location==="gpu-buffer"&&!$.has(j)&&j.dispose();return "past_key_values"in o||r.return_dict_in_generate||await M.dispose(),r.return_dict_in_generate?{sequences:N,past_key_values:M,...A,...S}:N}async _encode_input(t,r,s){if(!Object.hasOwn(this.sessions,t))throw new Error(`Model does not have a ${t} session.`);let n=this.sessions[t];return (await we(n,at(r,n.inputNames)))[s]}async encode_image(t){return this._encode_input("vision_encoder",t,"image_features")}async encode_text(t){return this._encode_input("embed_tokens",t,"inputs_embeds")}async encode_audio(t){return this._encode_input("audio_encoder",t,"audio_features")}};async function Ua(e,t){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:a,...o}=t;if(!r){let i=at(t,e.sessions.model.inputNames);r=(await Fr(e,i)).last_hidden_state;}return o.input_ids=n,o.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await pr(e,o,true)}async function Fr(e,t){let r=e.sessions.model,s=at(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!t.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await e.encode_text({input_ids:t.input_ids});}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Fd(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=yt([n[0],n[2],n[3]]);}return await we(r,s)}async function uz(e,t){let r=await e.encode(t);return await e.decode(r)}function dd(e,t){let r=Object.create(null);for(let s in e)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")&&t?r[n]=t[n]:r[n]=e[s];}return t?(t.update(r),t):new Ro(r)}function dz(e){let t={};for(let r of ["cross_attentions","encoder_attentions","decoder_attentions"])for(let s in e)s.startsWith(r)&&(r in t||(t[r]=[]),t[r].push(e[s]));return t}function mh(e,t,r){if(r&&Object.keys(r).length>0)return Object.assign(t,r),r;let s=e.sessions.decoder_model_merged??e.sessions.model,n=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=s?.config?.kv_cache_dtype??"float32",o=a==="float16"?Rs.float16:Rs.float32,i=zo(e.config,{batch_size:n}),l=Object.create(null);for(let c in i){let d=i[c].reduce((_,p)=>_*p,1),h=new V(a,new o(d),i[c]);t[c]=h,l[c]=h;}return r?(r.update(l),r):new Ro(l)}async function pr(e,t,r=false){let s=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...a}=t;if(s.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=c0(n!=null&&Object.keys(n).length>0)),s.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;a.position_ids=_z(a,n,i);}s.inputNames.includes("num_logits_to_keep")&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new V("int64",[0n],[])),mh(e,a,n);let o=at(a,s.inputNames);return await we(s,o)}async function u0(e,{encode_function:t,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:a=null,attention_mask:o=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:d=null,logits_processor:h=null,..._}){if(!l){l=await e.encode_text({input_ids:a,..._});let w=at(_,s);if(Object.keys(w).length>0){if(a.dims[1]!==1){let y=await t({...w,..._});({inputs_embeds:l,attention_mask:o}=r({[n]:y,inputs_embeds:l,input_ids:a,attention_mask:o}));}else if(c&&a.dims[1]===1){let y=a.dims[1],b=c.get_seq_length();o=Le([yt([a.dims[0],b]),o.slice(null,[o.dims[1]-y,o.dims[1]])],1);}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){let{image_grid_thw:w,video_grid_thw:y}=_;[i]=e.get_rope_index(a,w,y,o);}return await pr(e,{inputs_embeds:l,past_key_values:c,attention_mask:o,position_ids:i,generation_config:d,logits_processor:h},true)}async function hz(e,t){return await u0(e,{...t,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function fz(e,t){return await u0(e,{...t,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function d0(e,t=0){let[r,s]=e.dims,n=e.data,a=new BigInt64Array(n.length);for(let o=0;o<r;++o){let i=o*s,l=BigInt(t);for(let c=0;c<s;++c){let d=i+c;n[d]===0n?a[d]=BigInt(1):(a[d]=l,l+=n[d]);}}return {data:a,dims:e.dims}}function _z(e,t=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:a}=e,{data:o,dims:i}=d0(a,r),l=new V("int64",o,i);if(t){let c=-(s??n).dims.at(1);l=l.slice(null,[c,null]);}return l}function On(e,t,r,s){let n=r.past_key_values?r.past_key_values.get_seq_length():0;if((e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new V("int64",[1n],[])),!r.attention_mask){let o;for(let i of ["input_ids","inputs_embeds","position_ids"])if(r[i]){o=r[i].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=yt([o[0],n+o[1]]);}if(r.past_key_values){let{input_ids:o,attention_mask:i}=r;i&&i.dims[1]>o.dims[1]||n<o.dims[1]&&(r.input_ids=o.slice(null,[n,null]));}return r}function Mo(e,t,r,s){return r.past_key_values&&(t=t.map(n=>[n.at(-1)])),{...r,decoder_input_ids:ud(t)}}function ja(e,...t){return e.config.is_encoder_decoder?Mo(e,...t):On(e,...t)}function h0({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n}){let a=s.tolist().map(c=>c.reduce((d,h,_)=>(h==e&&d.push(_),d),[])),o=a.reduce((c,d)=>c+d.length,0),i=r.dims[0];if(o!==i)throw new Error(`Number of tokens and features do not match: tokens: ${o}, features ${i}`);let l=0;for(let c=0;c<a.length;++c){let d=a[c],h=t[c];for(let _=0;_<d.length;++_)h[d[_]].data.set(r[l++].data);}return {inputs_embeds:t,attention_mask:n}}function gh({image_token_id:e,inputs_embeds:t,image_features:r,input_ids:s,attention_mask:n}){return h0({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n})}function f0({audio_token_id:e,inputs_embeds:t,audio_features:r,input_ids:s,attention_mask:n}){return h0({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:n})}async function pz(e,t,r){return Object.fromEntries(await Promise.all(Object.keys(t).map(async s=>{let n=await ar(e,t[s],false,r);return [s,n]})))}var wh={};$s(wh,{ASTForAudioClassification:()=>T0,ASTModel:()=>k0,ASTPreTrainedModel:()=>Uo,AfmoeForCausalLM:()=>b0,AfmoeModel:()=>v0,AfmoePreTrainedModel:()=>$o,AlbertForMaskedLM:()=>g0,AlbertForQuestionAnswering:()=>m0,AlbertForSequenceClassification:()=>p0,AlbertModel:()=>_0,AlbertPreTrainedModel:()=>Ws,ApertusForCausalLM:()=>y0,ApertusModel:()=>w0,ApertusPreTrainedModel:()=>Go,ArceeForCausalLM:()=>x0,ArceeModel:()=>M0,ArceePreTrainedModel:()=>Vo,BartForConditionalGeneration:()=>A0,BartForSequenceClassification:()=>C0,BartModel:()=>E0,BartPretrainedModel:()=>qn,BeitForImageClassification:()=>P0,BeitModel:()=>S0,BeitPreTrainedModel:()=>jo,BertForMaskedLM:()=>L0,BertForQuestionAnswering:()=>N0,BertForSequenceClassification:()=>I0,BertForTokenClassification:()=>O0,BertModel:()=>F0,BertPreTrainedModel:()=>ss,BlenderbotForConditionalGeneration:()=>D0,BlenderbotModel:()=>z0,BlenderbotPreTrainedModel:()=>qo,BlenderbotSmallForConditionalGeneration:()=>R0,BlenderbotSmallModel:()=>B0,BlenderbotSmallPreTrainedModel:()=>Wo,BloomForCausalLM:()=>$0,BloomModel:()=>G0,BloomPreTrainedModel:()=>Ho,CHMv2ForDepthEstimation:()=>Q0,CHMv2PreTrainedModel:()=>Mh,CLIPModel:()=>Y0,CLIPPreTrainedModel:()=>Lr,CLIPSegForImageSegmentation:()=>tM,CLIPSegModel:()=>eM,CLIPSegPreTrainedModel:()=>Qo,CLIPTextModel:()=>J0,CLIPTextModelWithProjection:()=>Th,CLIPVisionModel:()=>K0,CLIPVisionModelWithProjection:()=>Z0,CamembertForMaskedLM:()=>U0,CamembertForQuestionAnswering:()=>W0,CamembertForSequenceClassification:()=>j0,CamembertForTokenClassification:()=>q0,CamembertModel:()=>V0,CamembertPreTrainedModel:()=>ns,ChatterboxModel:()=>vh,ChatterboxPreTrainedModel:()=>yh,ChineseCLIPModel:()=>H0,ChineseCLIPPreTrainedModel:()=>bh,ClapAudioModelWithProjection:()=>kh,ClapModel:()=>X0,ClapPreTrainedModel:()=>Wn,ClapTextModelWithProjection:()=>xh,CodeGenForCausalLM:()=>sM,CodeGenModel:()=>rM,CodeGenPreTrainedModel:()=>Xo,Cohere2ForCausalLM:()=>iM,Cohere2Model:()=>oM,Cohere2PreTrainedModel:()=>Jo,CohereAsrForConditionalGeneration:()=>cM,CohereAsrModel:()=>lM,CohereAsrPreTrainedModel:()=>Ko,CohereForCausalLM:()=>aM,CohereModel:()=>nM,CoherePreTrainedModel:()=>Yo,ConvBertForMaskedLM:()=>dM,ConvBertForQuestionAnswering:()=>_M,ConvBertForSequenceClassification:()=>hM,ConvBertForTokenClassification:()=>fM,ConvBertModel:()=>uM,ConvBertPreTrainedModel:()=>as,ConvNextForImageClassification:()=>mM,ConvNextModel:()=>pM,ConvNextPreTrainedModel:()=>Zo,ConvNextV2ForImageClassification:()=>wM,ConvNextV2Model:()=>gM,ConvNextV2PreTrainedModel:()=>ei,DFineForObjectDetection:()=>MM,DFineModel:()=>bM,DFinePreTrainedModel:()=>ri,DINOv3ConvNextModel:()=>QM,DINOv3ConvNextPreTrainedModel:()=>Oh,DINOv3ViTModel:()=>XM,DINOv3ViTPreTrainedModel:()=>Nh,DPTForDepthEstimation:()=>sx,DPTModel:()=>rx,DPTPreTrainedModel:()=>li,DacDecoderModel:()=>Sh,DacDecoderOutput:()=>Ah,DacEncoderModel:()=>Ch,DacEncoderOutput:()=>Eh,DacModel:()=>xM,DacPreTrainedModel:()=>Hn,DebertaForMaskedLM:()=>TM,DebertaForQuestionAnswering:()=>CM,DebertaForSequenceClassification:()=>EM,DebertaForTokenClassification:()=>AM,DebertaModel:()=>kM,DebertaPreTrainedModel:()=>os,DebertaV2ForMaskedLM:()=>LM,DebertaV2ForQuestionAnswering:()=>NM,DebertaV2ForSequenceClassification:()=>IM,DebertaV2ForTokenClassification:()=>OM,DebertaV2Model:()=>FM,DebertaV2PreTrainedModel:()=>is,DecisionTransformerModel:()=>zM,DecisionTransformerPreTrainedModel:()=>Ph,DeepseekV3ForCausalLM:()=>PM,DeepseekV3Model:()=>SM,DeepseekV3PreTrainedModel:()=>si,DeiTForImageClassification:()=>BM,DeiTModel:()=>DM,DeiTPreTrainedModel:()=>ni,DepthAnythingForDepthEstimation:()=>RM,DepthAnythingPreTrainedModel:()=>Fh,DepthProForDepthEstimation:()=>GM,DepthProPreTrainedModel:()=>Lh,DetrForObjectDetection:()=>VM,DetrForSegmentation:()=>UM,DetrModel:()=>$M,DetrObjectDetectionOutput:()=>ai,DetrPreTrainedModel:()=>Qn,DetrSegmentationOutput:()=>Ih,Dinov2ForImageClassification:()=>qM,Dinov2Model:()=>jM,Dinov2PreTrainedModel:()=>oi,Dinov2WithRegistersForImageClassification:()=>HM,Dinov2WithRegistersModel:()=>WM,Dinov2WithRegistersPreTrainedModel:()=>ii,DistilBertForMaskedLM:()=>ex,DistilBertForQuestionAnswering:()=>ZM,DistilBertForSequenceClassification:()=>JM,DistilBertForTokenClassification:()=>KM,DistilBertModel:()=>YM,DistilBertPreTrainedModel:()=>ls,DonutSwinModel:()=>tx,DonutSwinPreTrainedModel:()=>zh,EdgeTamModel:()=>hE,EfficientNetForImageClassification:()=>ax,EfficientNetModel:()=>nx,EfficientNetPreTrainedModel:()=>ci,ElectraForMaskedLM:()=>ix,ElectraForQuestionAnswering:()=>ux,ElectraForSequenceClassification:()=>lx,ElectraForTokenClassification:()=>cx,ElectraModel:()=>ox,ElectraPreTrainedModel:()=>cs,Ernie4_5ForCausalLM:()=>hx,Ernie4_5Model:()=>dx,Ernie4_5PretrainedModel:()=>ui,EsmForMaskedLM:()=>_x,EsmForSequenceClassification:()=>px,EsmForTokenClassification:()=>mx,EsmModel:()=>fx,EsmPreTrainedModel:()=>Qs,EuroBertForMaskedLM:()=>wx,EuroBertForSequenceClassification:()=>yx,EuroBertForTokenClassification:()=>vx,EuroBertModel:()=>gx,EuroBertPreTrainedModel:()=>Xs,ExaoneForCausalLM:()=>Mx,ExaoneModel:()=>bx,ExaonePreTrainedModel:()=>di,FalconForCausalLM:()=>kx,FalconH1ForCausalLM:()=>Ex,FalconH1Model:()=>Tx,FalconH1PreTrainedModel:()=>fi,FalconModel:()=>xx,FalconPreTrainedModel:()=>hi,FastViTForImageClassification:()=>Cx,FastViTModel:()=>Ax,FastViTPreTrainedModel:()=>_i,Florence2ForConditionalGeneration:()=>Sx,Florence2PreTrainedModel:()=>Dh,GLPNForDepthEstimation:()=>Wx,GLPNModel:()=>qx,GLPNPreTrainedModel:()=>Mi,GPT2LMHeadModel:()=>r1,GPT2Model:()=>t1,GPT2PreTrainedModel:()=>Ai,GPTBigCodeForCausalLM:()=>Qx,GPTBigCodeModel:()=>Hx,GPTBigCodePreTrainedModel:()=>xi,GPTJForCausalLM:()=>n1,GPTJModel:()=>s1,GPTJPreTrainedModel:()=>Ci,GPTNeoForCausalLM:()=>Yx,GPTNeoModel:()=>Xx,GPTNeoPreTrainedModel:()=>ki,GPTNeoXForCausalLM:()=>Kx,GPTNeoXModel:()=>Jx,GPTNeoXPreTrainedModel:()=>Ti,Gemma2ForCausalLM:()=>Ix,Gemma2Model:()=>Lx,Gemma2PreTrainedModel:()=>mi,Gemma3ForCausalLM:()=>Dx,Gemma3ForConditionalGeneration:()=>Gh,Gemma3Model:()=>zx,Gemma3PreTrainedModel:()=>Rh,Gemma3nForCausalLM:()=>Bx,Gemma3nForConditionalGeneration:()=>Xn,Gemma3nPreTrainedModel:()=>$h,Gemma4ForCausalLM:()=>Rx,Gemma4ForConditionalGeneration:()=>gi,GemmaForCausalLM:()=>Fx,GemmaModel:()=>Px,GemmaPreTrainedModel:()=>pi,GlmForCausalLM:()=>$x,GlmModel:()=>Gx,GlmMoeDsaForCausalLM:()=>Ux,GlmMoeDsaModel:()=>Vx,GlmMoeDsaPreTrainedModel:()=>yi,GlmOcrForConditionalGeneration:()=>jx,GlmPreTrainedModel:()=>wi,GptOssForCausalLM:()=>e1,GptOssModel:()=>Zx,GptOssPreTrainedModel:()=>Ei,GraniteForCausalLM:()=>o1,GraniteModel:()=>a1,GraniteMoeHybridForCausalLM:()=>l1,GraniteMoeHybridModel:()=>i1,GraniteMoeHybridPreTrainedModel:()=>Pi,GranitePreTrainedModel:()=>Si,GraniteSpeechForConditionalGeneration:()=>c1,GroundingDinoForObjectDetection:()=>u1,GroundingDinoPreTrainedModel:()=>Wh,GroupViTModel:()=>d1,GroupViTPreTrainedModel:()=>Hh,HeliumForCausalLM:()=>f1,HeliumModel:()=>h1,HeliumPreTrainedModel:()=>Li,HieraForImageClassification:()=>p1,HieraModel:()=>_1,HieraPreTrainedModel:()=>Ii,HubertForCTC:()=>M1,HubertForSequenceClassification:()=>x1,HubertModel:()=>b1,HubertPreTrainedModel:()=>v1,HunYuanDenseV1ForCausalLM:()=>T1,HunYuanDenseV1Model:()=>k1,HunYuanDenseV1PreTrainedModel:()=>Oi,IJepaForImageClassification:()=>A1,IJepaModel:()=>E1,IJepaPreTrainedModel:()=>Ni,Idefics3ForConditionalGeneration:()=>Qh,JAISLMHeadModel:()=>S1,JAISModel:()=>C1,JAISPreTrainedModel:()=>zi,JinaCLIPModel:()=>P1,JinaCLIPPreTrainedModel:()=>Yn,JinaCLIPTextModel:()=>Xh,JinaCLIPVisionModel:()=>F1,Lfm2ForCausalLM:()=>I1,Lfm2Model:()=>L1,Lfm2MoeForCausalLM:()=>z1,Lfm2MoeModel:()=>N1,Lfm2MoePreTrainedModel:()=>Bi,Lfm2PreTrainedModel:()=>Di,Lfm2VlForConditionalGeneration:()=>D1,LightOnOcrForConditionalGeneration:()=>O1,LiteWhisperForConditionalGeneration:()=>E2,Llama4ForCausalLM:()=>G1,Llama4PreTrainedModel:()=>Yh,LlamaForCausalLM:()=>R1,LlamaModel:()=>B1,LlamaPreTrainedModel:()=>Ri,LlavaForConditionalGeneration:()=>sr,LlavaOnevisionForConditionalGeneration:()=>sr,LlavaPreTrainedModel:()=>Bh,LlavaQwen2ForCausalLM:()=>Nx,LongT5ForConditionalGeneration:()=>V1,LongT5Model:()=>$1,LongT5PreTrainedModel:()=>Gi,M2M100ForConditionalGeneration:()=>j1,M2M100Model:()=>U1,M2M100PreTrainedModel:()=>$i,MBartForCausalLM:()=>K1,MBartForConditionalGeneration:()=>Y1,MBartForSequenceClassification:()=>J1,MBartModel:()=>X1,MBartPreTrainedModel:()=>Ys,MPNetForMaskedLM:()=>Bk,MPNetForQuestionAnswering:()=>$k,MPNetForSequenceClassification:()=>Rk,MPNetForTokenClassification:()=>Gk,MPNetModel:()=>Dk,MPNetPreTrainedModel:()=>us,MT5ForConditionalGeneration:()=>qk,MT5Model:()=>jk,MT5PreTrainedModel:()=>Ki,MarianMTModel:()=>W1,MarianModel:()=>q1,MarianPreTrainedModel:()=>Vi,MaskFormerForInstanceSegmentation:()=>Q1,MaskFormerModel:()=>H1,MaskFormerPreTrainedModel:()=>Ui,Metric3DForDepthEstimation:()=>Z1,Metric3DPreTrainedModel:()=>Jh,Metric3Dv2ForDepthEstimation:()=>ek,Metric3Dv2PreTrainedModel:()=>Kh,MgpstrForSceneTextRecognition:()=>tk,MgpstrModelOutput:()=>Zh,MgpstrPreTrainedModel:()=>ef,MimiDecoderModel:()=>nf,MimiDecoderOutput:()=>rf,MimiEncoderModel:()=>sf,MimiEncoderOutput:()=>tf,MimiModel:()=>rk,MimiPreTrainedModel:()=>Jn,Mistral4ForCausalLM:()=>ok,Mistral4Model:()=>ak,Mistral4PreTrainedModel:()=>qi,MistralForCausalLM:()=>nk,MistralModel:()=>sk,MistralPreTrainedModel:()=>ji,MobileBertForMaskedLM:()=>lk,MobileBertForQuestionAnswering:()=>uk,MobileBertForSequenceClassification:()=>ck,MobileBertModel:()=>ik,MobileBertPreTrainedModel:()=>Js,MobileLLMForCausalLM:()=>hk,MobileLLMModel:()=>dk,MobileLLMPreTrainedModel:()=>Wi,MobileNetV1ForImageClassification:()=>_k,MobileNetV1ForSemanticSegmentation:()=>pk,MobileNetV1Model:()=>fk,MobileNetV1PreTrainedModel:()=>Kn,MobileNetV2ForImageClassification:()=>gk,MobileNetV2ForSemanticSegmentation:()=>wk,MobileNetV2Model:()=>mk,MobileNetV2PreTrainedModel:()=>Zn,MobileNetV3ForImageClassification:()=>vk,MobileNetV3ForSemanticSegmentation:()=>bk,MobileNetV3Model:()=>yk,MobileNetV3PreTrainedModel:()=>ea,MobileNetV4ForImageClassification:()=>xk,MobileNetV4ForSemanticSegmentation:()=>kk,MobileNetV4Model:()=>Mk,MobileNetV4PreTrainedModel:()=>ta,MobileViTForImageClassification:()=>Ek,MobileViTModel:()=>Tk,MobileViTPreTrainedModel:()=>Hi,MobileViTV2ForImageClassification:()=>Ck,MobileViTV2Model:()=>Ak,MobileViTV2PreTrainedModel:()=>Qi,ModernBertDecoderForCausalLM:()=>Ok,ModernBertDecoderModel:()=>Ik,ModernBertDecoderPreTrainedModel:()=>Xi,ModernBertForMaskedLM:()=>Pk,ModernBertForSequenceClassification:()=>Fk,ModernBertForTokenClassification:()=>Lk,ModernBertModel:()=>Sk,ModernBertPreTrainedModel:()=>Ks,Moondream1ForConditionalGeneration:()=>Ox,MoonshineForConditionalGeneration:()=>zk,MoonshineModel:()=>Nk,MoonshinePreTrainedModel:()=>Yi,MptForCausalLM:()=>Uk,MptModel:()=>Vk,MptPreTrainedModel:()=>Ji,MultiModalityCausalLM:()=>Wk,MultiModalityPreTrainedModel:()=>af,MusicgenForCausalLM:()=>Qk,MusicgenForConditionalGeneration:()=>of,MusicgenModel:()=>Hk,MusicgenPreTrainedModel:()=>Zi,NanoChatForCausalLM:()=>Yk,NanoChatModel:()=>Xk,NanoChatPreTrainedModel:()=>el,NemotronHForCausalLM:()=>Kk,NemotronHModel:()=>Jk,NemotronHPreTrainedModel:()=>tl,NeoBertForMaskedLM:()=>eT,NeoBertForQuestionAnswering:()=>sT,NeoBertForSequenceClassification:()=>tT,NeoBertForTokenClassification:()=>rT,NeoBertModel:()=>Zk,NeoBertPreTrainedModel:()=>ds,NomicBertModel:()=>nT,NomicBertPreTrainedModel:()=>lf,OPTForCausalLM:()=>mT,OPTModel:()=>pT,OPTPreTrainedModel:()=>il,Olmo2ForCausalLM:()=>lT,Olmo2Model:()=>iT,Olmo2PreTrainedModel:()=>sl,Olmo3ForCausalLM:()=>uT,Olmo3Model:()=>cT,Olmo3PreTrainedModel:()=>nl,OlmoForCausalLM:()=>oT,OlmoHybridForCausalLM:()=>hT,OlmoHybridModel:()=>dT,OlmoHybridPreTrainedModel:()=>al,OlmoModel:()=>aT,OlmoPreTrainedModel:()=>rl,OpenELMForCausalLM:()=>_T,OpenELMModel:()=>fT,OpenELMPreTrainedModel:()=>ol,OwlViTForObjectDetection:()=>vT,OwlViTModel:()=>yT,OwlViTPreTrainedModel:()=>cl,Owlv2ForObjectDetection:()=>wT,Owlv2Model:()=>gT,Owlv2PreTrainedModel:()=>ll,PaliGemmaForConditionalGeneration:()=>bT,ParakeetForCTC:()=>MT,ParakeetPreTrainedModel:()=>cf,PatchTSMixerForPrediction:()=>kT,PatchTSMixerModel:()=>xT,PatchTSMixerPreTrainedModel:()=>ul,PatchTSTForPrediction:()=>ET,PatchTSTModel:()=>TT,PatchTSTPreTrainedModel:()=>dl,Phi3ForCausalLM:()=>PT,Phi3Model:()=>ST,Phi3PreTrainedModel:()=>fl,Phi3VForCausalLM:()=>df,Phi3VPreTrainedModel:()=>uf,PhiForCausalLM:()=>CT,PhiModel:()=>AT,PhiPreTrainedModel:()=>hl,PreTrainedModel:()=>P,PvtForImageClassification:()=>LT,PvtModel:()=>FT,PvtPreTrainedModel:()=>_l,PyAnnoteForAudioFrameClassification:()=>OT,PyAnnoteModel:()=>IT,PyAnnotePreTrainedModel:()=>pl,Qwen2ForCausalLM:()=>zT,Qwen2Model:()=>NT,Qwen2MoeForCausalLM:()=>BT,Qwen2MoeModel:()=>DT,Qwen2MoePreTrainedModel:()=>gl,Qwen2PreTrainedModel:()=>ml,Qwen2VLForCausalLM:()=>Uh,Qwen2VLForConditionalGeneration:()=>vi,Qwen2VLPreTrainedModel:()=>Vh,Qwen2_5_VLForCausalLM:()=>jh,Qwen2_5_VLForConditionalGeneration:()=>bi,Qwen3ForCausalLM:()=>GT,Qwen3Model:()=>RT,Qwen3MoeForCausalLM:()=>VT,Qwen3MoeModel:()=>$T,Qwen3MoePreTrainedModel:()=>yl,Qwen3NextForCausalLM:()=>jT,Qwen3NextModel:()=>UT,Qwen3NextPreTrainedModel:()=>vl,Qwen3PreTrainedModel:()=>wl,Qwen3VLForCausalLM:()=>hf,Qwen3VLForConditionalGeneration:()=>bl,Qwen3VLMoeForCausalLM:()=>WT,Qwen3VLMoeForConditionalGeneration:()=>qT,Qwen3_5ForCausalLM:()=>ff,Qwen3_5ForConditionalGeneration:()=>Ml,Qwen3_5MoeForCausalLM:()=>QT,Qwen3_5MoeForConditionalGeneration:()=>HT,RFDetrForObjectDetection:()=>KT,RFDetrModel:()=>JT,RFDetrObjectDetectionOutput:()=>_f,RFDetrPreTrainedModel:()=>kl,RTDetrForObjectDetection:()=>vM,RTDetrModel:()=>yM,RTDetrObjectDetectionOutput:()=>Hs,RTDetrPreTrainedModel:()=>ti,RTDetrV2ForObjectDetection:()=>uE,RTDetrV2Model:()=>cE,RTDetrV2ObjectDetectionOutput:()=>pf,RTDetrV2PreTrainedModel:()=>Tl,ResNetForImageClassification:()=>YT,ResNetModel:()=>XT,ResNetPreTrainedModel:()=>xl,RoFormerForMaskedLM:()=>aE,RoFormerForQuestionAnswering:()=>lE,RoFormerForSequenceClassification:()=>oE,RoFormerForTokenClassification:()=>iE,RoFormerModel:()=>nE,RoFormerPreTrainedModel:()=>fs,RobertaForMaskedLM:()=>eE,RobertaForQuestionAnswering:()=>sE,RobertaForSequenceClassification:()=>tE,RobertaForTokenClassification:()=>rE,RobertaModel:()=>ZT,RobertaPreTrainedModel:()=>hs,Sam2ImageSegmentationOutput:()=>wf,Sam2Model:()=>El,Sam2PreTrainedModel:()=>yf,Sam3TrackerModel:()=>fE,SamImageSegmentationOutput:()=>mf,SamModel:()=>dE,SamPreTrainedModel:()=>gf,SapiensForDepthEstimation:()=>pE,SapiensForNormalEstimation:()=>mE,SapiensForSemanticSegmentation:()=>_E,SapiensPreTrainedModel:()=>ra,SegformerForImageClassification:()=>wE,SegformerForSemanticSegmentation:()=>yE,SegformerModel:()=>gE,SegformerPreTrainedModel:()=>sa,SiglipModel:()=>vE,SiglipPreTrainedModel:()=>Al,SiglipTextModel:()=>vf,SiglipVisionModel:()=>bE,SmolLM3ForCausalLM:()=>xE,SmolLM3Model:()=>ME,SmolLM3PreTrainedModel:()=>Cl,SmolVLMForConditionalGeneration:()=>kE,SnacDecoderModel:()=>Mf,SnacEncoderModel:()=>bf,SnacModel:()=>TE,SnacPreTrainedModel:()=>na,SolarOpenForCausalLM:()=>AE,SolarOpenModel:()=>EE,SolarOpenPreTrainedModel:()=>Sl,SpeechT5ForSpeechToText:()=>SE,SpeechT5ForTextToSpeech:()=>PE,SpeechT5HifiGan:()=>FE,SpeechT5Model:()=>CE,SpeechT5PreTrainedModel:()=>aa,SqueezeBertForMaskedLM:()=>IE,SqueezeBertForQuestionAnswering:()=>NE,SqueezeBertForSequenceClassification:()=>OE,SqueezeBertModel:()=>LE,SqueezeBertPreTrainedModel:()=>Zs,StableLmForCausalLM:()=>DE,StableLmModel:()=>zE,StableLmPreTrainedModel:()=>Pl,Starcoder2ForCausalLM:()=>RE,Starcoder2Model:()=>BE,Starcoder2PreTrainedModel:()=>Fl,StyleTextToSpeech2Model:()=>GE,StyleTextToSpeech2PreTrainedModel:()=>xf,SupertonicForConditionalGeneration:()=>Tf,SupertonicPreTrainedModel:()=>kf,Swin2SRForImageSuperResolution:()=>qE,Swin2SRModel:()=>jE,Swin2SRPreTrainedModel:()=>Ll,SwinForImageClassification:()=>VE,SwinForSemanticSegmentation:()=>UE,SwinModel:()=>$E,SwinPreTrainedModel:()=>oa,T5ForConditionalGeneration:()=>HE,T5Model:()=>WE,T5PreTrainedModel:()=>Il,TableTransformerForObjectDetection:()=>XE,TableTransformerModel:()=>QE,TableTransformerObjectDetectionOutput:()=>Ef,TableTransformerPreTrainedModel:()=>Ol,TrOCRForCausalLM:()=>YE,TrOCRPreTrainedModel:()=>Af,UltravoxModel:()=>Fi,UltravoxPreTrainedModel:()=>qh,UniSpeechForCTC:()=>KE,UniSpeechForSequenceClassification:()=>ZE,UniSpeechModel:()=>JE,UniSpeechPreTrainedModel:()=>ia,UniSpeechSatForAudioFrameClassification:()=>s2,UniSpeechSatForCTC:()=>t2,UniSpeechSatForSequenceClassification:()=>r2,UniSpeechSatModel:()=>e2,UniSpeechSatPreTrainedModel:()=>en,VaultGemmaForCausalLM:()=>a2,VaultGemmaModel:()=>n2,VaultGemmaPreTrainedModel:()=>Nl,ViTForImageClassification:()=>l2,ViTMAEModel:()=>c2,ViTMAEPreTrainedModel:()=>Cf,ViTMSNForImageClassification:()=>d2,ViTMSNModel:()=>u2,ViTMSNPreTrainedModel:()=>Dl,ViTModel:()=>i2,ViTPreTrainedModel:()=>zl,VisionEncoderDecoderModel:()=>o2,VitMatteForImageMatting:()=>h2,VitMattePreTrainedModel:()=>Sf,VitPoseForPoseEstimation:()=>f2,VitPosePreTrainedModel:()=>Pf,VitsModel:()=>_2,VitsModelOutput:()=>Ff,VitsPreTrainedModel:()=>Lf,VoxtralForConditionalGeneration:()=>p2,VoxtralRealtimeForConditionalGeneration:()=>Of,VoxtralRealtimePreTrainedModel:()=>If,Wav2Vec2BertForCTC:()=>g2,Wav2Vec2BertForSequenceClassification:()=>w2,Wav2Vec2BertModel:()=>m2,Wav2Vec2BertPreTrainedModel:()=>la,Wav2Vec2ForAudioFrameClassification:()=>y1,Wav2Vec2ForCTC:()=>g1,Wav2Vec2ForSequenceClassification:()=>w1,Wav2Vec2Model:()=>m1,Wav2Vec2PreTrainedModel:()=>wr,WavLMForAudioFrameClassification:()=>x2,WavLMForCTC:()=>v2,WavLMForSequenceClassification:()=>b2,WavLMForXVector:()=>M2,WavLMModel:()=>y2,WavLMPreTrainedModel:()=>_s,WeSpeakerResNetModel:()=>k2,WeSpeakerResNetPreTrainedModel:()=>zf,WhisperForConditionalGeneration:()=>Df,WhisperModel:()=>T2,WhisperPreTrainedModel:()=>Bl,XLMForQuestionAnswering:()=>F2,XLMForSequenceClassification:()=>S2,XLMForTokenClassification:()=>P2,XLMModel:()=>A2,XLMPreTrainedModel:()=>ps,XLMRobertaForMaskedLM:()=>I2,XLMRobertaForQuestionAnswering:()=>z2,XLMRobertaForSequenceClassification:()=>O2,XLMRobertaForTokenClassification:()=>N2,XLMRobertaModel:()=>L2,XLMRobertaPreTrainedModel:()=>ms,XLMWithLMHeadModel:()=>C2,XVectorOutput:()=>Nf,YolosForObjectDetection:()=>B2,YolosModel:()=>D2,YolosObjectDetectionOutput:()=>Bf,YolosPreTrainedModel:()=>Rl,YoutuForCausalLM:()=>G2,YoutuModel:()=>R2,YoutuPreTrainedModel:()=>Gl});var Ws=class extends P{},_0=class extends Ws{},p0=class extends Ws{async _call(e){return new le(await super._call(e))}},m0=class extends Ws{async _call(e){return new _t(await super._call(e))}},g0=class extends Ws{async _call(e){return new Ye(await super._call(e))}},Go=class extends P{},w0=class extends Go{},y0=class extends Go{},$o=class extends P{},v0=class extends $o{},b0=class extends $o{},Vo=class extends P{},M0=class extends Vo{},x0=class extends Vo{},Uo=class extends P{},k0=class extends Uo{},T0=class extends Uo{},qn=class extends P{},E0=class extends qn{},A0=class extends qn{},C0=class extends qn{async _call(e){return new le(await super._call(e))}},jo=class extends P{},S0=class extends jo{},P0=class extends jo{async _call(e){return new le(await super._call(e))}},ss=class extends P{},F0=class extends ss{},L0=class extends ss{async _call(e){return new Ye(await super._call(e))}},I0=class extends ss{async _call(e){return new le(await super._call(e))}},O0=class extends ss{async _call(e){return new je(await super._call(e))}},N0=class extends ss{async _call(e){return new _t(await super._call(e))}},qo=class extends P{},z0=class extends qo{},D0=class extends qo{},Wo=class extends P{},B0=class extends Wo{},R0=class extends Wo{},Ho=class extends P{},G0=class extends Ho{},$0=class extends Ho{},ns=class extends P{},V0=class extends ns{},U0=class extends ns{async _call(e){return new Ye(await super._call(e))}},j0=class extends ns{async _call(e){return new le(await super._call(e))}},q0=class extends ns{async _call(e){return new je(await super._call(e))}},W0=class extends ns{async _call(e){return new _t(await super._call(e))}},mz=4299n,vw=6561n,yh=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"]);k(this,"main_input_name","input_ids");k(this,"_return_dict_in_generate_keys",["audio_tokens","speaker_embeddings","speaker_features"]);}},vh=class extends yh{async encode_speech(e){return we(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:s=null,position_ids:n=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,audio_features:c=null,audio_tokens:d=null,speaker_embeddings:h=null,speaker_features:_=null,...p}){let w;if(!a){let b=this.sessions.embed_tokens.inputNames,x={input_ids:e};if(b.includes("exaggeration")){if(!(s instanceof V)){let T=e.dims[0];if(s==null)s=it([T],.5);else if(typeof s=="number")s=it([T],s);else if(Array.isArray(s))s=new V("float32",s,[T]);else throw new Error("Unsupported type for `exaggeration` input")}x.exaggeration=s;}if(b.includes("position_ids")&&(x.position_ids=n),{inputs_embeds:a}=await we(this.sessions.embed_tokens,x),c&&d&&h&&_&&(w={audio_features:c,audio_tokens:d,speaker_embeddings:h,speaker_features:_}),w||r)w??(w=await this.encode_speech(r)),a=Le([w.audio_features,a],1),t=yt([a.dims[0],a.dims[1]]);else {let T=a.dims[1];if(!o||T!==1)throw new Error("Incorrect state encountered during generation.");let C=o.get_seq_length();t=yt([a.dims[0],C+T]);}}return {...await pr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:i,logits_processor:l},false),...w}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){let s=Array.from({length:e.length},(n,a)=>e[a].length-e[a].findLastIndex(o=>o==vw)-1);t.position_ids=new V("int64",s,[e.length,1]);}else {let n=t.input_ids.tolist().map(a=>{let o=0;return a.map(i=>i>=vw?0:o++)});t.position_ids=new V("int64",n.flat(),t.input_ids.dims);}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),On(this,e,t)}async generate(e){let{sequences:t,audio_tokens:r,speaker_embeddings:s,speaker_features:n}=await super.generate({...e,return_dict_in_generate:true}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=it([a.dims[0],3],mz),i=Le([r,a,o],1),{waveform:l}=await we(this.sessions.conditional_decoder,{speech_tokens:i,speaker_features:n,speaker_embeddings:s});return l}},bh=class extends P{},H0=class extends bh{},Mh=class extends P{},Q0=class extends Mh{},Wn=class extends P{},X0=class extends Wn{},xh=class extends Wn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},kh=class extends Wn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},Lr=class extends P{},Y0=class extends Lr{},J0=class extends Lr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},Th=class extends Lr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},K0=class extends Lr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Z0=class extends Lr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Qo=class extends P{},eM=class extends Qo{},tM=class extends Qo{},Xo=class extends P{},rM=class extends Xo{},sM=class extends Xo{},Yo=class extends P{},nM=class extends Yo{},aM=class extends Yo{},Jo=class extends P{},oM=class extends Jo{},iM=class extends Jo{},Ko=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",false);k(this,"main_input_name","input_features");k(this,"forward_params",["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]);}},lM=class extends Ko{},cM=class extends Ko{},as=class extends P{},uM=class extends as{},dM=class extends as{async _call(e){return new Ye(await super._call(e))}},hM=class extends as{async _call(e){return new le(await super._call(e))}},fM=class extends as{async _call(e){return new je(await super._call(e))}},_M=class extends as{async _call(e){return new _t(await super._call(e))}},Zo=class extends P{},pM=class extends Zo{},mM=class extends Zo{async _call(e){return new le(await super._call(e))}},ei=class extends P{},gM=class extends ei{},wM=class extends ei{async _call(e){return new le(await super._call(e))}},ti=class extends P{},yM=class extends ti{},vM=class extends ti{async _call(e){return new Hs(await super._call(e))}},Hs=class extends Xe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t;}},ri=class extends P{},bM=class extends ri{},MM=class extends ri{async _call(e){return new Hs(await super._call(e))}},Eh=class extends Xe{constructor({audio_codes:e}){super(),this.audio_codes=e;}},Ah=class extends Xe{constructor({audio_values:e}){super(),this.audio_values=e;}},Hn=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"]);}},xM=class extends Hn{async encode(e){return new Eh(await we(this.sessions.encoder_model,e))}async decode(e){return new Ah(await we(this.sessions.decoder_model,e))}},Ch=class extends Hn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Sh=class extends Hn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},os=class extends P{},kM=class extends os{},TM=class extends os{async _call(e){return new Ye(await super._call(e))}},EM=class extends os{async _call(e){return new le(await super._call(e))}},AM=class extends os{async _call(e){return new je(await super._call(e))}},CM=class extends os{async _call(e){return new _t(await super._call(e))}},si=class extends P{},SM=class extends si{},PM=class extends si{},is=class extends P{},FM=class extends is{},LM=class extends is{async _call(e){return new Ye(await super._call(e))}},IM=class extends is{async _call(e){return new le(await super._call(e))}},OM=class extends is{async _call(e){return new je(await super._call(e))}},NM=class extends is{async _call(e){return new _t(await super._call(e))}},Ph=class extends P{},zM=class extends Ph{},ni=class extends P{},DM=class extends ni{},BM=class extends ni{async _call(e){return new le(await super._call(e))}},Fh=class extends P{},RM=class extends Fh{},Lh=class extends P{},GM=class extends Lh{},Qn=class extends P{},$M=class extends Qn{},VM=class extends Qn{async _call(e){return new ai(await super._call(e))}},UM=class extends Qn{async _call(e){return new Ih(await super._call(e))}},ai=class extends Xe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t;}},Ih=class extends Xe{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r;}},oi=class extends P{},jM=class extends oi{},qM=class extends oi{async _call(e){return new le(await super._call(e))}},ii=class extends P{},WM=class extends ii{},HM=class extends ii{async _call(e){return new le(await super._call(e))}},Oh=class extends P{},QM=class extends Oh{},Nh=class extends P{},XM=class extends Nh{},ls=class extends P{},YM=class extends ls{},JM=class extends ls{async _call(e){return new le(await super._call(e))}},KM=class extends ls{async _call(e){return new je(await super._call(e))}},ZM=class extends ls{async _call(e){return new _t(await super._call(e))}},ex=class extends ls{async _call(e){return new Ye(await super._call(e))}},zh=class extends P{},tx=class extends zh{},li=class extends P{},rx=class extends li{},sx=class extends li{},ci=class extends P{},nx=class extends ci{},ax=class extends ci{async _call(e){return new le(await super._call(e))}},cs=class extends P{},ox=class extends cs{},ix=class extends cs{async _call(e){return new Ye(await super._call(e))}},lx=class extends cs{async _call(e){return new le(await super._call(e))}},cx=class extends cs{async _call(e){return new je(await super._call(e))}},ux=class extends cs{async _call(e){return new _t(await super._call(e))}},ui=class extends P{},dx=class extends ui{},hx=class extends ui{},Qs=class extends P{},fx=class extends Qs{},_x=class extends Qs{async _call(e){return new Ye(await super._call(e))}},px=class extends Qs{async _call(e){return new le(await super._call(e))}},mx=class extends Qs{async _call(e){return new je(await super._call(e))}},Xs=class extends P{},gx=class extends Xs{},wx=class extends Xs{async _call(e){return new Ye(await super._call(e))}},yx=class extends Xs{async _call(e){return new le(await super._call(e))}},vx=class extends Xs{async _call(e){return new je(await super._call(e))}},di=class extends P{},bx=class extends di{},Mx=class extends di{},hi=class extends P{},xx=class extends hi{},kx=class extends hi{},fi=class extends P{},Tx=class extends fi{},Ex=class extends fi{},_i=class extends P{},Ax=class extends _i{},Cx=class extends _i{async _call(e){return new le(await super._call(e))}},Dh=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);k(this,"main_input_name","inputs_embeds");}},Sx=class extends Dh{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:s}){return {inputs_embeds:Le([t,e],1),attention_mask:Le([yt(t.dims.slice(0,2)),s],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:s}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let n,a;return e&&(n=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),n&&a?{inputs_embeds:r,attention_mask:s}=this._merge_input_ids_with_image_features({inputs_embeds:n,image_features:a,input_ids:e,attention_mask:s}):r=n||a,{inputs_embeds:r,attention_mask:s}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:s,decoder_attention_mask:n,encoder_outputs:a,past_key_values:o,inputs_embeds:i,decoder_inputs_embeds:l}){if(i||({inputs_embeds:i,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:i,attention_mask:r})),!a){let{last_hidden_state:d}=await Fr(this,{inputs_embeds:i,attention_mask:r});a=d;}if(!l){if(!s)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:s});}return await pr(this,{inputs_embeds:l,attention_mask:n,encoder_attention_mask:r,encoder_hidden_states:a,past_key_values:o},true)}},pi=class extends P{},Px=class extends pi{},Fx=class extends pi{},mi=class extends P{},Lx=class extends mi{},Ix=class extends mi{},Bh=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]);}},sr=class extends Bh{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return gh({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},Ox=class extends sr{},Nx=class extends sr{},Rh=class extends P{},zx=class extends Rh{},Gh=class extends sr{},Dx=class extends Gh{},$h=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]);}},Xn=class extends $h{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:s=null,input_features_mask:n=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:i=null,past_key_values:l=null,generation_config:c=null,logits_processor:d=null,...h}){if((!o||!i)&&({inputs_embeds:o,per_layer_inputs:i}=await we(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){let{image_features:p}=await this._encode_vision({pixel_values:r,...h});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}));}if(s){let{audio_features:p}=await we(this.sessions.audio_encoder,{input_features:s,input_features_mask:n});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:p,inputs_embeds:o,input_ids:e,attention_mask:t}));}}return await pr(this,{inputs_embeds:o,per_layer_inputs:i,past_key_values:l,attention_mask:t,position_ids:a,generation_config:c,logits_processor:d},true)}_encode_vision(e){return we(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return gh({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return f0({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},Bx=class extends Xn{},gi=class extends Xn{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"]);}_encode_vision(t){return we(this.sessions.vision_encoder,{pixel_values:t.pixel_values,pixel_position_ids:t.image_position_ids})}},Rx=class extends gi{},wi=class extends P{},Gx=class extends wi{},$x=class extends wi{},yi=class extends P{},Vx=class extends yi{},Ux=class extends yi{},Vh=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]);}},vi=class extends Vh{constructor(){super(...arguments);k(this,"image_grid_thw_name","grid_thw");}_get_text_only_rope_index(t,r){if(r){let{data:s,dims:n}=d0(r),a=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),o=Array.from({length:n[0]},(i,l)=>Ve(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return [new V("int64",a,[3,...n]),new V("int64",o,[o.length,1])]}else {let[s,n]=t.dims,a=BigInt64Array.from({length:3*s*n},(o,i)=>BigInt(Math.floor(i%n/s)));return [new V("int64",a,[3,...t.dims]),Pd([s,1])]}}_reorder_and_write_positions(t,r,s,n){let a=t.reduce((c,d)=>c+d.length,0),o=new Array(a),i=0;for(let c=0;c<3;++c)for(let d of t){let h=d.length/3;for(let _=c*h;_<(c+1)*h;++_)o[i++]=d[_];}let l=0;for(let c=0;c<r.length;++c)if(r[c]==1){for(let d=0;d<3;++d)s[d][n][c]=o[d*a/3+l];++l;}return o}_get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:a}){let{image_token_id:o,video_token_id:i,vision_start_token_id:l}=this.config,c=t,h=c.reduce((T,C,A)=>(C==l&&T.push(A),T),[]).map(T=>c[T+1]),_=h.filter(T=>T==o).length,p=h.filter(T=>T==i).length,w=[],y=0,b=_,x=p;for(let T=0;T<h.length;++T){let C=c.findIndex((H,re)=>re>y&&H==o),A=c.findIndex((H,re)=>re>y&&H==i),S=b>0&&C!==-1?C:c.length+1,N=x>0&&A!==-1?A:c.length+1,M,$,G,j;S<N?([$,G,j]=r[a.image_index],++a.image_index,--b,M=S):([$,G,j]=s[a.video_index],++a.video_index,--x,M=N);let[Q,q,X]=[Number($),Math.floor(Number(G)/n),Math.floor(Number(j)/n)],D=M-y,L=w.length>0?Ve(w.at(-1))[0]+1:0;w.push(Array.from({length:3*D},(H,re)=>L+re%D));let Y=D+L,te=Q*q*X,I=Array.from({length:te},(H,re)=>Y+Math.floor(re/(q*X))),z=Array.from({length:te},(H,re)=>Y+Math.floor(re/X)%q),R=Array.from({length:te},(H,re)=>Y+re%X);w.push([I,z,R].flat()),y=M+te;}if(y<c.length){let T=w.length>0?Ve(w.at(-1))[0]+1:0,C=c.length-y;w.push(Array.from({length:3*C},(A,S)=>T+S%C));}return w}get_rope_index(t,r,s,n){let{vision_config:a}=this.config,o=a.spatial_merge_size??2;if(r||s){let i=t.tolist();n||(n=Sd(t));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:t.dims[0]},()=>Array.from({length:t.dims[1]},()=>0))),d=r?r.tolist():[],h=s?s.tolist():[],_={image_index:0,video_index:0},p=[];for(let w=0;w<i.length;++w){let y=i[w].filter((T,C)=>l[w][C]==1),b=this._get_multimodal_rope_positions({filtered_ids:y,image_grid_thw_list:d,video_grid_thw_list:h,spatial_merge_size:o,state:_}),x=this._reorder_and_write_positions(b,l[w],c,w);p.push(Ve(x)[0]+1-i[w].length);}return [new V("int64",c.flat(1/0),[3,t.dims[0],t.dims[1]]),new V("int64",p,[p.length,1])]}else return this._get_text_only_rope_index(t,n)}async encode_image({pixel_values:t,image_grid_thw:r}){return (await we(this.sessions.vision_encoder,{pixel_values:t,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(t){return gh({image_token_id:this.config.image_token_id,...t})}prepare_inputs_for_generation(t,r,s){if(!r.attention_mask||r.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return r;if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else {r.pixel_values=null;let a=r.past_key_values.get_seq_length();if(a<r.input_ids.dims[1]){let[o,i]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);r.rope_deltas=i,r.position_ids=o.slice(null,null,[a,null]),r.input_ids=r.input_ids.slice(null,[a,null]);}else {r.rope_deltas||([,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask));let o=BigInt(a),i=r.rope_deltas.map(l=>o+l);r.position_ids=tr([i,i,i],0);}}return r}},Uh=class extends vi{},bi=class extends vi{constructor(){super(...arguments);k(this,"image_grid_thw_name","image_grid_thw");}},jh=class extends Uh{constructor(){super(...arguments);k(this,"image_grid_thw_name","image_grid_thw");}},jx=class extends bi{get_vision_position_ids(e,t,r,s){let n=Math.floor(t[0]/r),a=Math.floor(t[1]/s),o=Math.floor(t[2]/s),i=a*o*n,l=Array.from({length:i},()=>e),c=Array.from({length:i},(h,_)=>e+Math.floor(_/(o*n))),d=Array.from({length:i},(h,_)=>e+_%o);return [...l,...c,...d]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:r,spatial_merge_size:s,state:n}){let{image_token_id:a}=this.config,o=[],i=0,l=e[0]==a?1:0;for(let h=1;h<=e.length;++h){let _=h<e.length?e[h]==a?1:0:-1;_!==l&&(o.push([l,i,h]),i=h,l=_);}let c=0,d=[];for(let[h,_,p]of o)if(h===0){let w=p-_;d.push(Array.from({length:3*w},(y,b)=>c+b%w)),c+=w;}else {let w=t[n.image_index++].map(Number),y=w[0];d.push(this.get_vision_position_ids(c,w,y,s)),c+=Math.max(w[1],w[2])/s;}return d}},Mi=class extends P{},qx=class extends Mi{},Wx=class extends Mi{},xi=class extends P{},Hx=class extends xi{},Qx=class extends xi{},ki=class extends P{},Xx=class extends ki{},Yx=class extends ki{},Ti=class extends P{},Jx=class extends Ti{},Kx=class extends Ti{},Ei=class extends P{},Zx=class extends Ei{},e1=class extends Ei{},Ai=class extends P{},t1=class extends Ai{},r1=class extends Ai{},Ci=class extends P{},s1=class extends Ci{},n1=class extends Ci{},Si=class extends P{},a1=class extends Si{},o1=class extends Si{},Pi=class extends P{},i1=class extends Pi{},l1=class extends Pi{},qh=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"]);}},Fi=class extends qh{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return f0({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},c1=class extends Fi{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","input_features","past_key_values"]);}},Wh=class extends P{},u1=class extends Wh{},Hh=class extends P{},d1=class extends Hh{},Li=class extends P{},h1=class extends Li{},f1=class extends Li{},Ii=class extends P{},_1=class extends Ii{},p1=class extends Ii{async _call(e){return new le(await super._call(e))}},wr=class extends P{},m1=class extends wr{},g1=class extends wr{async _call(e){return new rs(await super._call(e))}},w1=class extends wr{async _call(e){return new le(await super._call(e))}},y1=class extends wr{async _call(e){return new je(await super._call(e))}},v1=class extends P{},b1=class extends wr{},M1=class extends wr{async _call(e){return new rs(await super._call(e))}},x1=class extends wr{async _call(e){return new le(await super._call(e))}},Oi=class extends P{},k1=class extends Oi{},T1=class extends Oi{},Qh=class extends sr{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]);}},Ni=class extends P{},E1=class extends Ni{},A1=class extends Ni{async _call(e){return new le(await super._call(e))}},zi=class extends P{},C1=class extends zi{},S1=class extends zi{},Yn=class extends P{},P1=class extends Yn{async forward(e){let t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=yt([e.pixel_values.dims[0],1])),r){let{image_size:l}=this.config.vision_config;e.pixel_values=it([0,3,l,l],0);}let{text_embeddings:s,image_embeddings:n,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),i={};return t||(i.text_embeddings=s,i.l2norm_text_embeddings=a),r||(i.image_embeddings=n,i.l2norm_image_embeddings=o),i}},Xh=class extends Yn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},F1=class extends Yn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Di=class extends P{},L1=class extends Di{},I1=class extends Di{},O1=class extends sr{},Bi=class extends P{},N1=class extends Bi{},z1=class extends Bi{},D1=class extends sr{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]);}},Ri=class extends P{},B1=class extends Ri{},R1=class extends Ri{},Yh=class extends P{},G1=class extends Yh{},Gi=class extends P{},$1=class extends Gi{},V1=class extends Gi{},$i=class extends P{},U1=class extends $i{},j1=class extends $i{},Vi=class extends P{},q1=class extends Vi{},W1=class extends Vi{},Ui=class extends P{},H1=class extends Ui{},Q1=class extends Ui{},Ys=class extends P{},X1=class extends Ys{},Y1=class extends Ys{},J1=class extends Ys{async _call(e){return new le(await super._call(e))}},K1=class extends Ys{},Jh=class extends P{},Z1=class extends Jh{},Kh=class extends P{},ek=class extends Kh{},Zh=class extends Xe{constructor({char_logits:e,bpe_logits:t,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=r;}get logits(){return [this.char_logits,this.bpe_logits,this.wp_logits]}},ef=class extends P{},tk=class extends ef{async _call(e){return new Zh(await super._call(e))}},tf=class extends Xe{constructor({audio_codes:e}){super(),this.audio_codes=e;}},rf=class extends Xe{constructor({audio_values:e}){super(),this.audio_values=e;}},Jn=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"]);}},rk=class extends Jn{async encode(e){return new tf(await we(this.sessions.encoder_model,e))}async decode(e){return new rf(await we(this.sessions.decoder_model,e))}},sf=class extends Jn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},nf=class extends Jn{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},ji=class extends P{},sk=class extends ji{},nk=class extends ji{},qi=class extends P{},ak=class extends qi{},ok=class extends qi{},Js=class extends P{},ik=class extends Js{},lk=class extends Js{async _call(e){return new Ye(await super._call(e))}},ck=class extends Js{async _call(e){return new le(await super._call(e))}},uk=class extends Js{async _call(e){return new _t(await super._call(e))}},Wi=class extends P{},dk=class extends Wi{},hk=class extends Wi{},Kn=class extends P{},fk=class extends Kn{},_k=class extends Kn{async _call(e){return new le(await super._call(e))}},pk=class extends Kn{},Zn=class extends P{},mk=class extends Zn{},gk=class extends Zn{async _call(e){return new le(await super._call(e))}},wk=class extends Zn{},ea=class extends P{},yk=class extends ea{},vk=class extends ea{async _call(e){return new le(await super._call(e))}},bk=class extends ea{},ta=class extends P{},Mk=class extends ta{},xk=class extends ta{async _call(e){return new le(await super._call(e))}},kk=class extends ta{},Hi=class extends P{},Tk=class extends Hi{},Ek=class extends Hi{async _call(e){return new le(await super._call(e))}},Qi=class extends P{},Ak=class extends Qi{},Ck=class extends Qi{async _call(e){return new le(await super._call(e))}},Ks=class extends P{},Sk=class extends Ks{},Pk=class extends Ks{async _call(e){return new Ye(await super._call(e))}},Fk=class extends Ks{async _call(e){return new le(await super._call(e))}},Lk=class extends Ks{async _call(e){return new je(await super._call(e))}},Xi=class extends P{},Ik=class extends Xi{},Ok=class extends Xi{},Yi=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",false);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values","decoder_input_ids","past_key_values"]);}},Nk=class extends Yi{},zk=class extends Yi{},us=class extends P{},Dk=class extends us{},Bk=class extends us{async _call(e){return new Ye(await super._call(e))}},Rk=class extends us{async _call(e){return new le(await super._call(e))}},Gk=class extends us{async _call(e){return new je(await super._call(e))}},$k=class extends us{async _call(e){return new _t(await super._call(e))}},Ji=class extends P{},Vk=class extends Ji{},Uk=class extends Ji{},Ki=class extends P{},jk=class extends Ki{},qk=class extends Ki{},af=class extends P{},Wk=class extends af{constructor(...t){super(...t);k(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text";}async forward(t){let r=this._generation_mode??"text",s;if(r==="text"||!t.past_key_values){let l=this.sessions.prepare_inputs_embeds,c=at(t,l.inputNames);s=await we(l,c);}else {let l=this.sessions.gen_img_embeds,c=at({image_ids:t.input_ids},l.inputNames);s=await we(l,c);}let n={...t,...s},a=await pr(this,n),o=this.sessions[r==="text"?"lm_head":"gen_head"];if(!o)throw new Error(`Unable to find "${o}" generation head`);let i=await we(o,at(a,o.inputNames));return {...s,...a,...i}}prepare_inputs_for_generation(t,r,s){let n=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=Le([r.input_ids,r.input_ids],0):(r.input_ids=Le([r.input_ids,wo(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Le([r.attention_mask,wo(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=it([0,0,3,384,384],1)),n&&(r.images_seq_mask=new V("bool",new Array(1).fill(true).fill(false,0,1),[1,1]),r.images_emb_mask=new V("bool",new Array(0).fill(false),[1,1,0])),r}async generate(t){return this._generation_mode="text",super.generate(t)}async generate_images(t){this._generation_mode="image";let r=(t.inputs??t[this.main_input_name]).dims[1],n=(await super.generate(t)).slice(null,[r,null]),a=this.sessions.image_decode,{decoded_image:o}=await we(a,{generated_tokens:n}),i=o.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let d=vt.fromTensor(c);l.push(d);}return l}},Zi=class extends P{},Hk=class extends Zi{},Qk=class extends Zi{},of=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);}_apply_and_filter_by_delay_pattern_mask(t){let[r,s]=t.dims,n=this.config.decoder.num_codebooks,a=s-n,o=0;for(let c=0;c<t.size;++c){if(t.data[c]==this.config.decoder.pad_token_id)continue;let d=c%s,h=Math.floor(c/s)%n,_=d-h;_>0&&_<=a&&(t.data[o++]=t.data[c]);}let i=Math.floor(r/n),l=o/(i*n);return new V(t.type,t.data.slice(0,o),[i,n,l])}prepare_inputs_for_generation(t,r,s){let n=BigInt(this.config.decoder.pad_token_id),a=structuredClone(t);for(let o=0;o<a.length;++o)for(let i=0;i<a[o].length;++i)o%this.config.decoder.num_codebooks>=i&&(a[o][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(a=a.concat(a)),Mo(this,a,r)}async generate(t){let r=await super.generate(t),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await we(this.sessions.encodec_decode,{audio_codes:s});return n}},el=class extends P{},Xk=class extends el{},Yk=class extends el{},tl=class extends P{},Jk=class extends tl{},Kk=class extends tl{},ds=class extends P{},Zk=class extends ds{},eT=class extends ds{async _call(e){return new Ye(await super._call(e))}},tT=class extends ds{async _call(e){return new le(await super._call(e))}},rT=class extends ds{async _call(e){return new je(await super._call(e))}},sT=class extends ds{async _call(e){return new _t(await super._call(e))}},lf=class extends P{},nT=class extends lf{},rl=class extends P{},aT=class extends rl{},oT=class extends rl{},sl=class extends P{},iT=class extends sl{},lT=class extends sl{},nl=class extends P{},cT=class extends nl{},uT=class extends nl{},al=class extends P{},dT=class extends al{},hT=class extends al{},ol=class extends P{},fT=class extends ol{},_T=class extends ol{},il=class extends P{},pT=class extends il{},mT=class extends il{},ll=class extends P{},gT=class extends ll{},wT=class extends ll{},cl=class extends P{},yT=class extends cl{},vT=class extends cl{},bT=class extends sr{},cf=class extends P{},MT=class extends cf{async _call(e){return new rs(await super._call(e))}},ul=class extends P{},xT=class extends ul{},kT=class extends ul{},dl=class extends P{},TT=class extends dl{},ET=class extends dl{},hl=class extends P{},AT=class extends hl{},CT=class extends hl{},fl=class extends P{},ST=class extends fl{},PT=class extends fl{},uf=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]);}},df=class extends uf{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:s=null,position_ids:n=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:i=null,logits_processor:l=null,...c}){if(!a){let h;if(r&&e.dims[1]!==1){if(!s)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:h}=await we(this.sessions.vision_encoder,{pixel_values:r,image_sizes:s}));}else {let _=this.config.normalized_config.hidden_size;h=new V("float32",[],[0,_]);}({inputs_embeds:a}=await we(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:h}));}return await pr(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:n,generation_config:i,logits_processor:l},false)}},_l=class extends P{},FT=class extends _l{},LT=class extends _l{async _call(e){return new le(await super._call(e))}},pl=class extends P{},IT=class extends pl{},OT=class extends pl{async _call(e){return new je(await super._call(e))}},ml=class extends P{},NT=class extends ml{},zT=class extends ml{},gl=class extends P{},DT=class extends gl{},BT=class extends gl{},wl=class extends P{},RT=class extends wl{},GT=class extends wl{},yl=class extends P{},$T=class extends yl{},VT=class extends yl{},vl=class extends P{},UT=class extends vl{},jT=class extends vl{},bl=class extends bi{},hf=class extends jh{},qT=class extends bl{},WT=class extends hf{},Ml=class extends bl{},ff=class extends Ml{},HT=class extends Ml{},QT=class extends ff{},xl=class extends P{},XT=class extends xl{},YT=class extends xl{async _call(e){return new le(await super._call(e))}},kl=class extends P{},JT=class extends kl{},KT=class extends kl{async _call(e){return new _f(await super._call(e))}},_f=class extends Hs{},hs=class extends P{},ZT=class extends hs{},eE=class extends hs{async _call(e){return new Ye(await super._call(e))}},tE=class extends hs{async _call(e){return new le(await super._call(e))}},rE=class extends hs{async _call(e){return new je(await super._call(e))}},sE=class extends hs{async _call(e){return new _t(await super._call(e))}},fs=class extends P{},nE=class extends fs{},aE=class extends fs{async _call(e){return new Ye(await super._call(e))}},oE=class extends fs{async _call(e){return new le(await super._call(e))}},iE=class extends fs{async _call(e){return new je(await super._call(e))}},lE=class extends fs{async _call(e){return new _t(await super._call(e))}},Tl=class extends P{},cE=class extends Tl{},uE=class extends Tl{async _call(e){return new pf(await super._call(e))}},pf=class extends Hs{},mf=class extends Xe{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t;}},gf=class extends P{},dE=class extends gf{async get_image_embeddings({pixel_values:e}){return await Fr(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??(e.input_labels=yt(e.input_points.dims.slice(0,-1)));let t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await we(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new mf(await super._call(e))}},wf=class extends Xe{constructor({iou_scores:e,pred_masks:t,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=r;}},yf=class extends P{},El=class extends yf{async get_image_embeddings({pixel_values:e}){return await Fr(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(a,o)=>`image_embeddings.${o}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??(e.input_labels=yt(a.slice(0,-1))),e.input_boxes??(e.input_boxes=it([a[0],0,4],0));}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=it([a[0],a[1],0],-1n),e.input_points=it([a[0],1,0,2],0);}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let s=this.sessions.prompt_encoder_mask_decoder,n=at(e,s.inputNames);return await we(s,n)}async _call(e){return new wf(await super._call(e))}},hE=class extends El{},fE=class extends El{},ra=class extends P{},_E=class extends ra{},pE=class extends ra{},mE=class extends ra{},sa=class extends P{},gE=class extends sa{},wE=class extends sa{},yE=class extends sa{},Al=class extends P{},vE=class extends Al{},vf=class extends Al{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},bE=class extends Lr{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Cl=class extends P{},ME=class extends Cl{},xE=class extends Cl{},kE=class extends Qh{},na=class extends P{constructor(){super(...arguments);k(this,"main_input_name","input_values");k(this,"forward_params",["input_values"]);}},TE=class extends na{async encode(e){return await we(this.sessions.encoder_model,e)}async decode(e){return await we(this.sessions.decoder_model,e)}},bf=class extends na{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},Mf=class extends na{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Sl=class extends P{},EE=class extends Sl{},AE=class extends Sl{},aa=class extends P{},CE=class extends aa{},SE=class extends aa{},PE=class extends aa{async generate_speech(e,t,{threshold:r=.5,minlenratio:s=0,maxlenratio:n=20,vocoder:a=null}={}){let o={input_ids:e},{encoder_outputs:i,encoder_attention_mask:l}=await Fr(this,o),c=i.dims[1]/this.config.reduction_factor,d=Math.floor(c*n),h=Math.floor(c*s),_=this.config.num_mel_bins,p=[],w=null,y=null,b=0;for(;;){++b;let C=c0(!!y),A;y?A=y.output_sequence_out:A=new V("float32",new Float32Array(_),[1,1,_]);let S={use_cache_branch:C,output_sequence:A,encoder_attention_mask:l,speaker_embeddings:t,encoder_hidden_states:i};mh(this,S,w),y=await we(this.sessions.decoder_model_merged,S),w=dd(y,w);let{prob:N,spectrum:M}=y;if(p.push(M),b>=h&&(Array.from(N.data).filter($=>$>=r).length>0||b>=d))break}let x=Le(p),{waveform:T}=await we(a.sessions.model,{spectrogram:x});return {spectrogram:x,waveform:T}}},FE=class extends P{constructor(){super(...arguments);k(this,"main_input_name","spectrogram");}},Zs=class extends P{},LE=class extends Zs{},IE=class extends Zs{async _call(e){return new Ye(await super._call(e))}},OE=class extends Zs{async _call(e){return new le(await super._call(e))}},NE=class extends Zs{async _call(e){return new _t(await super._call(e))}},Pl=class extends P{},zE=class extends Pl{},DE=class extends Pl{},Fl=class extends P{},BE=class extends Fl{},RE=class extends Fl{},xf=class extends P{},GE=class extends xf{},kf=class extends P{},Tf=class extends kf{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:s=5,speed:n=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:i,latent_dim:l}=this.config,{last_hidden_state:c,durations:d}=await we(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),h=d.div(n).mul_(a),_=i*o,p=h.data,w=Int32Array.from(p,G=>Math.ceil(G/_)),y=Math.max(...w),b=e.dims[0],x=new BigInt64Array(b*y);for(let G=0;G<b;++G)x.fill(1n,G*y,G*y+w[G]);let T=new V("int64",x,[b,y]),C=l*o,A=C*y,S=ay([b,C,y]),N=S.data;for(let G=0;G<b;++G)if(w[G]!==y)for(let j=0;j<C;++j)N.fill(0,G*A+j*y+w[G],G*A+(j+1)*y);let M=it([b],s);for(let G=0;G<s;++G){let j=it([b],G);({denoised_latents:S}=await we(this.sessions.latent_denoiser,{style:r,noisy_latents:S,latent_mask:T,encoder_outputs:c,attention_mask:t,timestep:j,num_inference_steps:M}));}let{waveform:$}=await we(this.sessions.voice_decoder,{latents:S});return {waveform:$,durations:h}}},oa=class extends P{},$E=class extends oa{},VE=class extends oa{async _call(e){return new le(await super._call(e))}},UE=class extends oa{},Ll=class extends P{},jE=class extends Ll{},qE=class extends Ll{},Il=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);}},WE=class extends Il{},HE=class extends Il{},Ol=class extends P{},QE=class extends Ol{},XE=class extends Ol{async _call(e){return new Ef(await super._call(e))}},Ef=class extends ai{},Af=class extends P{},YE=class extends Af{},ia=class extends P{},JE=class extends ia{},KE=class extends ia{async _call(e){return new rs(await super._call(e))}},ZE=class extends ia{async _call(e){return new le(await super._call(e))}},en=class extends P{},e2=class extends en{},t2=class extends en{async _call(e){return new rs(await super._call(e))}},r2=class extends en{async _call(e){return new le(await super._call(e))}},s2=class extends en{async _call(e){return new je(await super._call(e))}},Nl=class extends P{},n2=class extends Nl{},a2=class extends Nl{},o2=class extends P{constructor(){super(...arguments);k(this,"main_input_name","pixel_values");k(this,"forward_params",["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]);}},zl=class extends P{},i2=class extends zl{},l2=class extends zl{async _call(e){return new le(await super._call(e))}},Cf=class extends P{},c2=class extends Cf{},Dl=class extends P{},u2=class extends Dl{},d2=class extends Dl{async _call(e){return new le(await super._call(e))}},Sf=class extends P{},h2=class extends Sf{async _call(e){return new ez(await super._call(e))}},Pf=class extends P{},f2=class extends Pf{},Ff=class extends Xe{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t;}},Lf=class extends P{},_2=class extends Lf{async _call(e){return new Ff(await super._call(e))}},p2=class extends Fi{},bw=2,gz=1,yu=new WeakMap;function wz(e,t){let{text_config:r,audio_config:s}=e.config,n=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=s,i=a+o,l=new Ro,c=n?.config?.kv_cache_dtype??"float32",d=c==="float16"?Rs.float16:Rs.float32,h=zo(s,{batch_size:1});for(let w in h){let y=h[w].reduce((b,x)=>b*x,1);l[w]=new V(c,new d(y),h[w]);}let _=new V(c,new d(i*bw),[1,i,bw]),p=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!p)throw new Error("input_features must be iterable or async iterable");return {encoder_session:n,enc_kv_cache:l,enc_padding_cache:_,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:false,chunks_iter:p,text_hidden_size:r.hidden_size}}async function yz(e,t){let r=t.dims[2],s=Math.floor((gz+r-3)/2)+1,n=new V("int64",BigInt64Array.from({length:s},(d,h)=>BigInt(e.enc_past_seq_len+h)),[1,s]),a=e.enc_past_seq_len+s,o=yt([1,a]),{audio_embeds:i,present_padding_cache:l,...c}=await we(e.encoder_session,{input_features:t,attention_mask:o,position_ids:n,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location==="gpu-buffer"&&e.enc_padding_cache.dispose(),e.enc_padding_cache=l;for(let d in c)if(d.startsWith("present.")){let h=d.replace("present","past_key_values"),_=e.enc_kv_cache[h];_?.location==="gpu-buffer"&&_.dispose(),e.enc_kv_cache[h]=c[d];}return e.enc_past_seq_len=a,i}async function vz(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){let r=await e.chunks_iter.next();if(r.done){e.stream_exhausted=true;break}let s=await yz(e,r.value);e.audio_embed_queue.push({data:s.data,tokens:s.dims[1]}),e.audio_embed_total_tokens+=s.dims[1];}}function bz(e,t,r){if(e.audio_embed_queue.length===0)return;let s=t.data,n=0,a=r;for(;a>0&&e.audio_embed_queue.length>0;){let o=e.audio_embed_queue[0],i=o.tokens-e.audio_queue_offset,l=Math.min(a,i),c=e.audio_queue_offset*e.text_hidden_size;for(let d=0;d<l*e.text_hidden_size;++d)s[n*e.text_hidden_size+d]+=o.data[c+d];n+=l,a-=l,e.audio_queue_offset+=l,e.audio_queue_offset>=o.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0);}e.audio_consumed+=r-a;}var Mz=class extends qs{constructor(e){super(),this._s=e;}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},If=class extends P{constructor(){super(...arguments);k(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values"]);}},Of=class extends If{async forward({input_ids:e,past_key_values:t,...r}){let s=e.dims[1],n=yu.get(this);n&&await vz(n,n.audio_consumed+s);let{inputs_embeds:a}=await we(this.sessions.embed_tokens,{input_ids:e});n&&bz(n,a,s);let o={inputs_embeds:a,...r};mh(this,o,t);let i=this.sessions.decoder_model_merged,l=at(o,i.inputNames);return await we(i,l)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let s=wz(this,e);yu.set(this,s);let n=new dh;n.push(new Mz(s)),t&&n.extend(t);try{return await super.generate({...r,stopping_criteria:n})}finally{s.enc_kv_cache.dispose(),yu.delete(this);}}},la=class extends P{},m2=class extends la{},g2=class extends la{async _call(e){return new rs(await super._call(e))}},w2=class extends la{async _call(e){return new le(await super._call(e))}},Nf=class extends Xe{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t;}},_s=class extends P{},y2=class extends _s{},v2=class extends _s{async _call(e){return new rs(await super._call(e))}},b2=class extends _s{async _call(e){return new le(await super._call(e))}},M2=class extends _s{async _call(e){return new Nf(await super._call(e))}},x2=class extends _s{async _call(e){return new je(await super._call(e))}},zf=class extends P{},k2=class extends zf{},xz=class extends n0{constructor(){super(...arguments);k(this,"return_timestamps",null);k(this,"return_token_timestamps",null);k(this,"num_frames",null);k(this,"alignment_heads",null);k(this,"task",null);k(this,"language",null);k(this,"no_timestamps_token_id",null);k(this,"prompt_ids",null);k(this,"is_multilingual",null);k(this,"lang_to_id",null);k(this,"task_to_id",null);k(this,"max_initial_timestamp_index",1);}},Bl=class extends P{constructor(){super(...arguments);k(this,"requires_attention_mask",false);k(this,"main_input_name","input_features");k(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);}},T2=class extends Bl{},Df=class extends Bl{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,xz)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],r=e.language,s=e.task;if(e.is_multilingual){r||(ce.warn("No language specified - defaulting to English (en)."),r="en");let a=`<|${a3(r)}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[s??"transcribe"]);}else if(r||s)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return !e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(ce.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(n=>n!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:s=null,...n}){t=this._prepare_generation_config(t,n);let a=n.decoder_input_ids instanceof V?Id(n.decoder_input_ids):n.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??(r=new bo),r.push(new Yb(t,a))),t.begin_suppress_tokens&&(r??(r=new bo),r.push(new uh(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task==="translate"&&ce.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=true,t.return_dict_in_generate=true;}if(t.return_timestamps&&!n.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:a,kwargs:n});let o=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:a,...n});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:r,init_tokens:s,kwargs:n}){let a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,i=t.return_token_timestamps,l=e,c=l.dims[2],d=2,h=this.config.max_source_positions,_=d*h,p=0,w=[],y=[];for(;p<c;){let x=Math.min(p+_,c),T=l.slice(null,null,[p,x]),C,A=T.dims[2];if(A<_){let Y=l.dims[1],te=new Float32Array(Y*_),I=T.data;for(let z=0;z<Y;++z)te.set(I.subarray(z*A,(z+1)*A),z*_);C=new V("float32",te,[1,Y,_]);}else C=T;if(r)for(let Y of r)"begin_index"in Y&&(Y.begin_index=s.length);let S=await super.generate({inputs:C,generation_config:t,logits_processor:r,decoder_input_ids:s,...n}),M=(i?S.sequences:S)[0].tolist().map(Number).slice(s.length),$;if(i){S.token_timestamps=this._extract_token_timestamps(S,t.alignment_heads,Math.floor((x-p)/d),.02,s.length);let Y=p/d*.02;$=S.token_timestamps[0].tolist().slice(s.length).map(te=>te+Y);}if(M.length>0&&M.at(-1)===o&&M.pop(),M.length===0)break;let G=M.map(Y=>Y>=a),j=M.length>=2&&G[M.length-1]&&!G[M.length-2],Q=[];for(let Y=0;Y<M.length-1;++Y)G[Y]&&G[Y+1]&&Q.push(Y+1);let q,X=M.length;if(Q.length>0)if(j)q=x-p;else {let Y=Q.at(-1);q=(M[Y-1]-a)*d,X=Y;}else q=x-p;let D=Math.floor(p/d),L=a+1500;for(let Y=0;Y<X;++Y)M[Y]>=a&&(M[Y]=Math.min(M[Y]+D,L));w.push(...M.slice(0,X)),$&&y.push(...$.slice(0,X)),p+=q;}w.push(o);let b=[...s,...w];if(i){let x=new V("int64",b.map(BigInt),[1,b.length]),T=[...new Array(s.length).fill(0),...y,0],C=new V("float32",new Float32Array(T),[1,T.length]);return {sequences:x,token_timestamps:C}}return new V("int64",b.map(BigInt),[1,b.length])}_extract_token_timestamps(e,t,r=null,s=.02,n=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");r==null&&ce.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&&(ce.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let o=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(b,x)=>Le(o.map(T=>T[x]),2)),l=tr(t.map(([b,x])=>{if(b>=i.length)throw new Error(`Layer index ${b} is out of bounds for cross attentions (length ${i.length}).`);return r?i[b].slice(null,x,null,[0,r]):i[b].slice(null,x)})).transpose(1,0,2,3),[c,d]=Ad(l,-2,0,true),h=l.clone();for(let b=0;b<h.dims[0];++b){let x=h[b];for(let T=0;T<x.dims[0];++T){let C=x[T],A=c[b][T][0].data,S=d[b][T][0].data;for(let N=0;N<C.dims[0];++N){let M=C[N].data;for(let $=0;$<M.length;++$)M[$]=(M[$]-S[$])/A[$];M.set(NN(M,a));}}}let _=n>0?h.slice(null,null,[n,h.dims[2]],null):h,p=[So(_,1)],w=e.sequences.dims,y=new V("float32",new Float32Array(w[0]*w[1]),w);for(let b=0;b<w[0];++b){let x=p[b].neg().squeeze_(0),[T,C]=DN(x.tolist()),A=Array.from({length:T.length-1},($,G)=>T[G+1]-T[G]),S=Gt([1],A).map($=>!!$),N=[];for(let $=0;$<S.length;++$)S[$]&&N.push(C[$]*s);let M=new Array(n).fill(0);M.push(...N),N.length>0&&M.push(N.at(-1)),y[b].data.set(M);}return y}},E2=class extends Df{},ps=class extends P{},A2=class extends ps{},C2=class extends ps{async _call(e){return new Ye(await super._call(e))}},S2=class extends ps{async _call(e){return new le(await super._call(e))}},P2=class extends ps{async _call(e){return new je(await super._call(e))}},F2=class extends ps{async _call(e){return new _t(await super._call(e))}},ms=class extends P{},L2=class extends ms{},I2=class extends ms{async _call(e){return new Ye(await super._call(e))}},O2=class extends ms{async _call(e){return new le(await super._call(e))}},N2=class extends ms{async _call(e){return new je(await super._call(e))}},z2=class extends ms{async _call(e){return new _t(await super._call(e))}},Rl=class extends P{},D2=class extends Rl{},B2=class extends Rl{async _call(e){return new Bf(await super._call(e))}},Bf=class extends Xe{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t;}},Gl=class extends P{},R2=class extends Gl{},G2=class extends Gl{},kz=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"]]),Tz=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"]]),Ez=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),Az=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"]]),$2=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),V2=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),U2=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),j2=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"]]),q2=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"]]),W2=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),H2=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"]]),Cz=new Map([["multi_modality","MultiModalityCausalLM"]]),Q2=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"]]),X2=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"]]),Y2=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),J2=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"]]),K2=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),Sz=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),Z2=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"]]),eA=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),tA=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Is=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),rA=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),sA=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),nA=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),aA=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),oA=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),iA=new Map([["wavlm","WavLMForXVector"]]),lA=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),cA=new Map([["vitmatte","VitMatteForImageMatting"]]),Pz=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),uA=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),dA=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),hA=new Map([["sapiens","SapiensForNormalEstimation"]]),fA=new Map([["vitpose","VitPoseForPoseEstimation"]]),_A=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),pA=[[kz,W.EncoderOnly],[Tz,W.EncoderDecoder],[Az,W.DecoderOnlyWithoutHead],[Ez,W.AutoEncoder],[j2,W.EncoderOnly],[q2,W.EncoderOnly],[W2,W.Seq2Seq],[$2,W.Seq2Seq],[H2,W.DecoderOnly],[Cz,W.MultiModality],[Q2,W.EncoderOnly],[X2,W.EncoderOnly],[Y2,W.Vision2Seq],[J2,W.ImageTextToText],[K2,W.AudioTextToText],[Z2,W.EncoderOnly],[Is,W.EncoderOnly],[sA,W.EncoderOnly],[rA,W.EncoderOnly],[cA,W.EncoderOnly],[Pz,W.EncoderOnly],[uA,W.EncoderOnly],[dA,W.EncoderOnly],[hA,W.EncoderOnly],[fA,W.EncoderOnly],[eA,W.EncoderOnly],[tA,W.EncoderOnly],[nA,W.MaskGeneration],[aA,W.EncoderOnly],[oA,W.EncoderOnly],[V2,W.Seq2Seq],[U2,W.EncoderOnly],[iA,W.EncoderOnly],[lA,W.EncoderOnly],[_A,W.EncoderOnly]];for(let[e,t]of pA)for(let r of e.values()){_r.set(r,t);let s=wh[r];Bs.set(s,r),ph.set(r,s);}var Fz=[["MusicgenForConditionalGeneration",of,W.Musicgen],["Phi3VForCausalLM",df,W.Phi3V],["CLIPTextModelWithProjection",Th,W.EncoderOnly],["SiglipTextModel",vf,W.EncoderOnly],["JinaCLIPTextModel",Xh,W.EncoderOnly],["ClapTextModelWithProjection",xh,W.EncoderOnly],["ClapAudioModelWithProjection",kh,W.EncoderOnly],["DacEncoderModel",Ch,W.EncoderOnly],["DacDecoderModel",Sh,W.EncoderOnly],["MimiEncoderModel",sf,W.EncoderOnly],["MimiDecoderModel",nf,W.EncoderOnly],["SnacEncoderModel",bf,W.EncoderOnly],["SnacDecoderModel",Mf,W.EncoderOnly],["Gemma3nForConditionalGeneration",Xn,W.ImageAudioTextToText],["Gemma4ForConditionalGeneration",gi,W.ImageAudioTextToText],["SupertonicForConditionalGeneration",Tf,W.Supertonic],["ChatterboxModel",vh,W.Chatterbox],["VoxtralRealtimeForConditionalGeneration",Of,W.VoxtralRealtime]];for(let[e,t,r]of Fz)_r.set(e,r),Bs.set(t,e),ph.set(e,t);var mA=new Map([["modnet",Is],["birefnet",Is],["isnet",Is],["ben",Is]]);for(let[e,t]of mA.entries())t.set(e,"PreTrainedModel"),_r.set(e,W.EncoderOnly),ph.set(e,P);var Lz=new Set(mA.keys());_r.set("PreTrainedModel",W.EncoderOnly);Bs.set(P,"PreTrainedModel");var Ee={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:j2,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:q2,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:V2,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:U2,MODEL_FOR_MASKED_LM_MAPPING_NAMES:Q2,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:X2,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:Z2,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Is,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:rA,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:sA,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:eA,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:tA,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:nA,MODEL_FOR_CTC_MAPPING_NAMES:aA,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:oA,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:iA,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:lA,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:Sz,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:cA,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:uA,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:dA,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:hA,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:fA,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:_A,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:J2,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:K2,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:W2,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:$2,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:H2,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:Y2};cz(Ee);var ao,Ae=(ao=class{static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return false;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return true;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:n=false,revision:a="main",model_file_name:o=null,subfolder:i="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,session_options:h={}}={}){let _={progress_callback:t,config:r,cache_dir:s,local_files_only:n,revision:a,model_file_name:o,subfolder:i,device:l,dtype:c,use_external_data_format:d,session_options:h};if(_.config=await Gs.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:p}=_.config;for(let w of this.MODEL_CLASS_MAPPINGS){let y=w.get(p);if(!y){for(let b of w.values())if(b[0]===p){y=b;break}if(!y)continue}return await wh[y].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return Lz.has(p)||ce.warn(`Unknown model class "${p}", attempting to construct from base class.`),await P.from_pretrained(e,_);throw Error(`Unsupported model type: ${p}`)}},k(ao,"MODEL_CLASS_MAPPINGS",null),k(ao,"BASE_IF_FAIL",false),ao),oo,Os=(oo=class extends Ae{},k(oo,"MODEL_CLASS_MAPPINGS",pA.map(e=>e[0])),k(oo,"BASE_IF_FAIL",true),oo),Tu,hd=(Tu=class extends Ae{},k(Tu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]),Tu),Eu,gA=(Eu=class extends Ae{},k(Eu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]),Eu),Au,uo=(Au=class extends Ae{},k(Au,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]),Au),Cu,wA=(Cu=class extends Ae{},k(Cu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]),Cu),Su,yA=(Su=class extends Ae{},k(Su,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]),Su),Pu,vA=(Pu=class extends Ae{},k(Pu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]),Pu),Fu,bA=(Fu=class extends Ae{},k(Fu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]),Fu),Lu,MA=(Lu=class extends Ae{},k(Lu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_MASKED_LM_MAPPING_NAMES]),Lu),Iu,xA=(Iu=class extends Ae{},k(Iu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]),Iu),Ou,kA=(Ou=class extends Ae{},k(Ou,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]),Ou),Nu,TA=(Nu=class extends Ae{},k(Nu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]),Nu),zu,fd=(zu=class extends Ae{},k(zu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]),zu),Du,_d=(Du=class extends Ae{},k(Du,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]),Du),Bu,pd=(Bu=class extends Ae{},k(Bu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]),Bu),Ru,EA=(Ru=class extends Ae{},k(Ru,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]),Ru),Gu,AA=(Gu=class extends Ae{},k(Gu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]),Gu),$u,Iz=($u=class extends Ae{},k($u,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]),$u),Vu,CA=(Vu=class extends Ae{},k(Vu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_CTC_MAPPING_NAMES]),Vu),Uu,SA=(Uu=class extends Ae{},k(Uu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]),Uu),ju,Oz=(ju=class extends Ae{},k(ju,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]),ju),qu,Nz=(qu=class extends Ae{},k(qu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]),qu),Wu,PA=(Wu=class extends Ae{},k(Wu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]),Wu),Hu,zz=(Hu=class extends Ae{},k(Hu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]),Hu),Qu,FA=(Qu=class extends Ae{},k(Qu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]),Qu),Xu,LA=(Xu=class extends Ae{},k(Xu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]),Xu),Yu,Dz=(Yu=class extends Ae{},k(Yu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]),Yu),Ju,Bz=(Ju=class extends Ae{},k(Ju,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]),Ju),Ku,IA=(Ku=class extends Ae{},k(Ku,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]),Ku),Zu,Rz=(Zu=class extends Ae{},k(Zu,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]),Zu),ed,Gz=(ed=class extends Ae{},k(ed,"MODEL_CLASS_MAPPINGS",[Ee.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]),ed);async function Wt(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>vt.read(t)))}async function Ns(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?nv(r,t):r instanceof Float64Array?new Float32Array(r):r))}function md(e,t){t&&(e=e.map(o=>o|0));let[r,s,n,a]=e;return {xmin:r,ymin:s,xmax:n,ymax:a}}var $e=class extends bt{constructor({task:e,model:t,tokenizer:r=null,processor:s=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=s;}async dispose(){await this.model.dispose();}},OA=class extends $e{async _call(e,{top_k:t=1}={}){let r=this.tokenizer(e,{padding:true,truncation:true}),s=await this.model(r),{problem_type:n,id2label:a}=this.model.config,o=n==="multi_label_classification"?l=>l.sigmoid():l=>new V("float32",tt(l.data),l.dims),i=[];for(let l of s.logits){let c=o(l),d=await ts(c,t),h=d[0].tolist(),p=d[1].tolist().map((w,y)=>({label:a?a[w]:`LABEL_${w}`,score:h[y]}));t===1?i.push(...p):i.push(p);}return Array.isArray(e)||t===1?i:i[0]}},NA=class extends $e{async _call(e,{ignore_labels:t=["O"]}={}){let r=Array.isArray(e),s=this.tokenizer(r?e:[e],{padding:true,truncation:true}),a=(await this.model(s)).logits,o=this.model.config.id2label,i=[];for(let l=0;l<a.dims[0];++l){let c=s.input_ids[l],d=a[l],h=[];for(let _=0;_<d.dims[0];++_){let p=d[_],w=Ve(p.data)[1],y=o?o[w]:`LABEL_${w}`;if(t.includes(y))continue;let b=this.tokenizer.decode([c[_].item()],{skip_special_tokens:true});if(b==="")continue;let x=tt(p.data);h.push({entity:y,score:x[w],index:_,word:b});}i.push(h);}return r?i:i[0]}},zA=class extends $e{async _call(e,t,{top_k:r=1}={}){let s=this.tokenizer(e,{text_pair:t,padding:true,truncation:true}),n=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(s),i=s.input_ids.tolist(),l=s.attention_mask.tolist(),{all_special_ids:c,sep_token_id:d}=this.tokenizer,h=[];for(let _=0;_<a.dims[0];++_){let p=i[_],w=p.findIndex(S=>S==d),y=a[_].tolist(),b=o[_].tolist();for(let S=1;S<y.length;++S)(l[_]==0||S<=w||c.findIndex(N=>N==p[S])!==-1)&&(y[S]=-1/0,b[S]=-1/0);let x=tt(y).map((S,N)=>[S,N]),T=tt(b).map((S,N)=>[S,N]);x[0][0]=0,T[0][0]=0;let C=oL(x,T).filter(S=>S[0][1]<=S[1][1]).map(S=>[S[0][1],S[1][1],S[0][0]*S[1][0]]).sort((S,N)=>N[2]-S[2]),A=[];for(let S=0;S<Math.min(C.length,r);++S){let[N,M,$]=C[S],G=p.slice(N,M+1),j=this.tokenizer.decode(G,{skip_special_tokens:true});A.push({answer:j,score:$});}r===1?h.push(...A):h.push(A);}return n?h:h[0]}},DA=class extends $e{async _call(e,{top_k:t=5}={}){let{mask_token_id:r,mask_token:s}=this.tokenizer,n=this.tokenizer(e,{padding:true,truncation:true}),{logits:a}=await this.model(n),o=[],i=n.input_ids.tolist();for(let l=0;l<i.length;++l){let c=i[l],d=c.findIndex(y=>y==r);if(d===-1)throw Error(`Mask token (${s}) not found in text.`);let h=a[l][d],_=await ts(new V("float32",tt(h.data),h.dims),t),p=_[0].tolist(),w=_[1].tolist();o.push(w.map((y,b)=>{let x=c.slice();return x[d]=y,{score:p[b],token:Number(y),token_str:this.tokenizer.decode([y]),sequence:this.tokenizer.decode(x,{skip_special_tokens:true})}}));}return Array.isArray(e)?o:o[0]}},$l=class extends $e{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256});k(this,"_key","generated_text");}async _call(t,r={}){Array.isArray(t)||(t=[t]),this.model.config.prefix&&(t=t.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(t=t.map(l=>s[this.task].prefix+l));let n=this.tokenizer,a={padding:true,truncation:true},o;this.task==="translation"&&"_build_translation_inputs"in n?o=n._build_translation_inputs(t,a,r):o=n(t,a);let i=await this.model.generate({...o,...this._default_generation_config,...r});return n.batch_decode(i,{skip_special_tokens:true}).map(l=>({[this._key]:l}))}},BA=class extends $l{constructor(){super(...arguments);k(this,"_key","summary_text");}},RA=class extends $l{constructor(){super(...arguments);k(this,"_key","translation_text");}};function Mw(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var GA=class extends $e{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256});}async _call(t,r={}){let s=false,n=false,a=r.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??false,o=r.tokenizer_encode_kwargs,i;if(typeof t=="string")i=t=[t];else if(Array.isArray(t)&&t.every(w=>typeof w=="string"))s=true,i=t;else {if(Mw(t))t=[t];else if(Array.isArray(t)&&t.every(Mw))s=true;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=true,i=t.map(w=>this.tokenizer.apply_chat_template(w,{tokenize:false,add_generation_prompt:true,...o})),a=false,o=void 0;}let l=n?false:r.return_full_text??true;this.tokenizer.padding_side="left";let c=this.tokenizer(i,{add_special_tokens:a,padding:true,truncation:true,...o}),d=await this.model.generate({...c,...this._default_generation_config,...r}),h=this.tokenizer.batch_decode(d,{skip_special_tokens:true}),_;!l&&c.input_ids.dims.at(-1)>0&&(_=this.tokenizer.batch_decode(c.input_ids,{skip_special_tokens:true}).map(w=>w.length));let p=Array.from({length:t.length},w=>[]);for(let w=0;w<h.length;++w){let y=Math.floor(w/d.dims[0]*t.length);_&&(h[w]=h[w].slice(_[y])),p[y].push({generated_text:n?[...t[y],{role:"assistant",content:h[w]}]:h[w]});}return !s&&p.length===1?p[0]:p}},$A=class extends $e{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([t,r])=>[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(ce.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&&(ce.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0);}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:s=false}={}){let n=Array.isArray(e);n||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(l=>r.replace("{}",l)),o=s||t.length===1,i=[];for(let l of e){let c=[];for(let _ of a){let p=this.tokenizer(l,{text_pair:_,padding:true,truncation:true}),w=await this.model(p);o?c.push([w.logits.data[this.contradiction_id],w.logits.data[this.entailment_id]]):c.push(w.logits.data[this.entailment_id]);}let h=(o?c.map(_=>tt(_)[1]):tt(c)).map((_,p)=>[_,p]).sort((_,p)=>p[0]-_[0]);i.push({sequence:l,labels:h.map(_=>t[_[1]]),scores:h.map(_=>_[0])});}return n?i:i[0]}},VA=class extends $e{async _call(e,{top_k:t=5}={}){let r=this.processor.feature_extractor.config.sampling_rate,s=await Ns(e,r),n=this.model.config.id2label,a=[];for(let o of s){let i=await this.processor(o),c=(await this.model(i)).logits[0],d=await ts(new V("float32",tt(c.data),c.dims),t),h=d[0].tolist(),p=d[1].tolist().map((w,y)=>({label:n?n[w]:`LABEL_${w}`,score:h[y]}));a.push(p);}return Array.isArray(e)?a:a[0]}},UA=class extends $e{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){let s=!Array.isArray(e);s&&(e=[e]);let n=t.map(c=>r.replace("{}",c)),a=this.tokenizer(n,{padding:true,truncation:true}),o=this.processor.feature_extractor.config.sampling_rate,i=await Ns(e,o),l=[];for(let c of i){let d=await this.processor(c),h=await this.model({...a,...d}),_=tt(h.logits_per_audio.data);l.push([..._].map((p,w)=>({score:p,label:t[w]})));}return s?l[0]:l}},jA=class extends $e{constructor(){super(...arguments);k(this,"_default_generation_config",{});}async _call(t,r={}){switch(r={...this._default_generation_config,...r},this.model.config.model_type){case "whisper":case "lite-whisper":return this._call_whisper(t,r);case "wav2vec2":case "wav2vec2-bert":case "unispeech":case "unispeech-sat":case "hubert":case "parakeet_ctc":return this._call_wav2vec2(t,r);case "moonshine":return this._call_moonshine(t,r);case "cohere_asr":return this._call_cohere_asr(t,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(t,r){r.language&&ce.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&ce.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor.config.sampling_rate,o=await Ns(n,a),i=[];for(let l of o){let c=await this.processor(l),h=(await this.model(c)).logits[0],_=[];for(let w of h)_.push(Ve(w.data)[1]);let p=this.tokenizer.decode(_,{skip_special_tokens:true}).trim();i.push({text:p});}return s?i[0]:i}async _call_whisper(t,r){let s=r.return_timestamps??false,n=r.chunk_length_s??0,a=r.force_full_sequences??false,o=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=true,i.return_timestamps=true);let l=!Array.isArray(t),c=l?[t]:t,d=this.processor.feature_extractor.config,h=d.chunk_length/this.model.config.max_source_positions,_=d.hop_length,p=d.sampling_rate,w=await Ns(c,p),y=[];for(let b of w){let x=[];if(n>0){if(o===null)o=n/6;else if(n<=o)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let A=p*n,S=p*o,N=A-2*S,M=0;for(;;){let $=M+A,G=b.subarray(M,$),j=await this.processor(G),Q=M===0,q=$>=b.length;if(x.push({stride:[G.length,Q?0:S,q?0:S],input_features:j.input_features,is_last:q}),q)break;M+=N;}}else x=[{stride:[b.length,0,0],input_features:(await this.processor(b)).input_features,is_last:true}];for(let A of x){i.num_frames=Math.floor(A.stride[0]/_);let S=await this.model.generate({inputs:A.input_features,...i});if(s==="word"){let N=S.sequences.tolist()[0],M=S.token_timestamps.tolist()[0],$=this.tokenizer.timestamp_begin,G=Math.max(N.findIndex(j=>Number(j)>=$),0);A.tokens=N.slice(G),A.token_timestamps=M.slice(G).map(j=>Ln(j,2));}else A.tokens=S[0].tolist();A.stride=A.stride.map(N=>N/p);}let[T,C]=this.tokenizer._decode_asr(x,{time_precision:h,return_timestamps:s,force_full_sequences:a});y.push({text:T,...C});}return l?y[0]:y}async _call_moonshine(t,r){let s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor.config.sampling_rate,o=await Ns(n,a),i=[];for(let l of o){let c=await this.processor(l),d=Math.floor(l.length/a)*6,h=await this.model.generate({max_new_tokens:d,...r,...c}),_=this.processor.batch_decode(h,{skip_special_tokens:true})[0];i.push({text:_});}return s?i[0]:i}async _call_cohere_asr(t,r){let s=!Array.isArray(t),n=s?[t]:t,a=this.processor.feature_extractor,o=a.config.sampling_rate,i=await Ns(n,o),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),d=[];for(let h of i){let _=a.split_audio(h),p=[];for(let y of _){let b=await this.processor(y),x=await this.model.generate({...b,decoder_input_ids:c,...r}),T=this.tokenizer.decode(x[0].tolist(),{skip_special_tokens:true}).trim();p.push(T);}let w=this.processor.constructor.join_chunks(p,l);d.push({text:w});}return s?d[0]:d}},qA=class extends $e{constructor(t){super(t);k(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=t.vocoder??null;}async _prepare_speaker_embeddings(t,r){if((typeof t=="string"||t instanceof URL)&&(t=new Float32Array(await(await me.fetch(t)).arrayBuffer())),t instanceof Float32Array)t=new V("float32",t,[t.length]);else if(!(t instanceof V))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(t.dims[0]===1)t=t.repeat(r,1);else if(t.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${t.dims[0]}.`)}return t}_postprocess_waveform(t,r,s,n=null){let a=r.data,[o,i]=r.dims,l=n?n.data:null,c=[];for(let d=0;d<o;++d){let h=l?Math.min(Math.ceil(l[d]),i):i,_=d*i;c.push(new iv(a.slice(_,_+h),s));}return Array.isArray(t)?c:c[0]}async _call(t,r){return this.processor?this._call_text_to_spectrogram(t,r):this.model.config.model_type==="supertonic"?this._call_supertonic(t,r):this._call_text_to_waveform(t)}async _call_supertonic(t,{speaker_embeddings:r,num_inference_steps:s,speed:n}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:a,style_dim:o}=this.model.config,i=this.tokenizer(t,{padding:true,truncation:true}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,o);let{waveform:c,durations:d}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(t,c,a,d)}async _call_text_to_waveform(t){let r=this.tokenizer(t,{padding:true,truncation:true}),{waveform:s}=await this.model(r),n=this.model.config.sampling_rate;return this._postprocess_waveform(t,s,n)}async _call_text_to_spectrogram(t,{speaker_embeddings:r}){this.vocoder||(ce.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Os.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:s}=this.tokenizer(t,{padding:true,truncation:true}),n=s.dims[0];r=await this._prepare_speaker_embeddings(r,n),r=r.view(n,-1);let{waveform:a}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),o=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(t,a,o)}},WA=class extends $e{async _call(e,t={}){let r=Array.isArray(e),s=await Wt(e),{pixel_values:n}=await this.processor(s),a=[];for(let o of n){o.dims=[1,...o.dims];let i=await this.model.generate({inputs:o,...t}),l=this.tokenizer.batch_decode(i,{skip_special_tokens:true}).map(c=>({generated_text:c.trim()}));a.push(l);}return r?a:a[0]}},HA=class extends $e{async _call(e,{top_k:t=5}={}){let r=await Wt(e),{pixel_values:s}=await this.processor(r),n=await this.model({pixel_values:s}),{id2label:a}=this.model.config,o=[];for(let i of n.logits){let l=await ts(new V("float32",tt(i.data),i.dims),t),c=l[0].tolist(),h=l[1].tolist().map((_,p)=>({label:a?a[_]:`LABEL_${_}`,score:c[p]}));o.push(h);}return Array.isArray(e)?o:o[0]}},xw={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Rf=class extends $e{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:s=.8,label_ids_to_fuse:n=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let l=await Wt(e),c=l.map(x=>[x.height,x.width]),d=await this.processor(l),{inputNames:h,outputNames:_}=this.model.sessions.model;if(!h.includes("pixel_values")){if(h.length!==1)throw Error(`Expected a single input name, but got ${h.length} inputs: ${h}.`);let x=h[0];if(x in d)throw Error(`Input name ${x} already exists in the inputs.`);d[x]=d.pixel_values;}let p=await this.model(d),w=null;if(o!==null)w=xw[o];else if(this.processor.image_processor){for(let[x,T]of Object.entries(xw))if(T in this.processor.image_processor){w=this.processor.image_processor[T].bind(this.processor.image_processor),o=x;break}}let y=this.model.config.id2label,b=[];if(o)if(o==="panoptic"||o==="instance"){let x=w(p,t,r,s,n,a??c)[0],T=x.segmentation;for(let C of x.segments_info){let A=new Uint8ClampedArray(T.data.length);for(let N=0;N<T.data.length;++N)T.data[N]===C.id&&(A[N]=255);let S=new vt(A,T.dims[1],T.dims[0],1);b.push({score:C.score,label:y[C.label_id],mask:S});}}else if(o==="semantic"){let{segmentation:x,labels:T}=w(p,a??c)[0];for(let C of T){let A=new Uint8ClampedArray(x.data.length);for(let N=0;N<x.data.length;++N)x.data[N]===C&&(A[N]=255);let S=new vt(A,x.dims[1],x.dims[0],1);b.push({score:null,label:y[C],mask:S});}}else throw Error(`Subtask ${o} not supported.`);else {let T=p[_[0]];for(let C=0;C<c.length;++C){let A=c[C],S=T[C];S.data.some(M=>M<-1e-5||M>1+1e-5)&&S.sigmoid_();let N=await vt.fromTensor(S.mul_(255).to("uint8")).resize(A[1],A[0]);b.push({label:null,score:null,mask:N});}}return b}},QA=class extends Rf{async _call(e,t={}){let r=await Wt(e),s=await super._call(e,t),n=r.map((a,o)=>{let i=a.clone();return i.putAlpha(s[o].mask),i});return Array.isArray(e)?n:n[0]}},XA=class extends $e{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){let s=Array.isArray(e),n=await Wt(e),a=t.map(h=>r.replace("{}",h)),o=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":true,truncation:true}),{pixel_values:i}=await this.processor(n),l=await this.model({...o,pixel_values:i}),c=this.model.config.model_type==="siglip"?h=>h.sigmoid().data:h=>tt(h.data),d=[];for(let h of l.logits_per_image){let p=[...c(h)].map((w,y)=>({score:w,label:t[y]}));p.sort((w,y)=>y.score-w.score),d.push(p);}return s?d:d[0]}},YA=class extends $e{async _call(e,{threshold:t=.9,percentage:r=false}={}){let s=Array.isArray(e);if(s&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let n=await Wt(e),a=r?null:n.map(_=>[_.height,_.width]),{pixel_values:o,pixel_mask:i}=await this.processor(n),l=await this.model({pixel_values:o,pixel_mask:i}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,h=c.map(_=>_.boxes.map((p,w)=>({score:_.scores[w],label:d[_.classes[w]],box:md(p,!r)})));return s?h:h[0]}},JA=class extends $e{async _call(e,t,{threshold:r=.1,top_k:s=null,percentage:n=false}={}){let a=Array.isArray(e),o=await Wt(e),i=this.tokenizer(t,{padding:true,truncation:true}),l=await this.processor(o),c=[];for(let d=0;d<o.length;++d){let h=o[d],_=n?null:[[h.height,h.width]],p=l.pixel_values[d].unsqueeze_(0),w=await this.model({...i,pixel_values:p}),y;if("post_process_grounded_object_detection"in this.processor){let b=this.processor.post_process_grounded_object_detection(w,i.input_ids,{box_threshold:r,text_threshold:r,target_sizes:_})[0];y=b.boxes.map((x,T)=>({score:b.scores[T],label:b.labels[T],box:md(x,!n)}));}else {let b=this.processor.image_processor.post_process_object_detection(w,r,_,true)[0];y=b.boxes.map((x,T)=>({score:b.scores[T],label:t[b.classes[T]],box:md(x,!n)}));}y.sort((b,x)=>x.score-b.score),s!==null&&(y=y.slice(0,s)),c.push(y);}return a?c:c[0]}},KA=class extends $e{constructor(){super(...arguments);k(this,"_default_generation_config",{max_new_tokens:256});}async _call(t,r,s={}){if(Array.isArray(t)){if(t.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");t=t[0];}let n=(await Wt(t))[0],{pixel_values:a}=await this.processor(n),o=`<s_docvqa><s_question>${r}</s_question><s_answer>`,i=this.tokenizer(o,{add_special_tokens:false,padding:true,truncation:true}).input_ids,l=await this.model.generate({inputs:a,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...s}),d=this.tokenizer.batch_decode(l)[0].match(/<s_answer>(.*?)<\/s_answer>/),h=null;return d&&d.length>=2&&(h=d[1].trim()),[{answer:h}]}},ZA=class extends $e{async _call(e){let t=await Wt(e),r=await this.processor(t),s=await this.model(r),n=[];for(let a of s.reconstruction){let o=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");n.push(vt.fromTensor(o));}return Array.isArray(e)?n:n[0]}},eC=class extends $e{async _call(e){let t=await Wt(e),r=await this.processor(t),{predicted_depth:s}=await this.model(r),n=[];for(let a=0;a<t.length;++a){let o=s[a],[i,l]=o.dims.slice(-2),[c,d]=t[a].size,h=(await Nt(o.view(1,1,i,l),{size:[d,c],mode:"bilinear"})).view(d,c),_=h.min().item(),p=h.max().item(),w=h.sub(_).div_(p-_).mul_(255).to("uint8").unsqueeze(0),y=vt.fromTensor(w);n.push({predicted_depth:h,depth:y});}return Array.isArray(e)?n:n[0]}},tC=class extends $e{async _call(e,{pooling:t="none",normalize:r=false,quantize:s=false,precision:n="binary"}={}){let a=this.tokenizer(e,{padding:true,truncation:true}),o=await this.model(a),i=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case "none":break;case "mean":i=ny(i,a.attention_mask);break;case "first_token":case "cls":i=i.slice(null,0);break;case "last_token":case "eos":i=i.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return r&&(i=i.normalize(2,-1)),s&&(i=oy(i,n)),i}},rC=class extends $e{async _call(e,{pool:t=null}={}){let r=await Wt(e),{pixel_values:s}=await this.processor(r),n=await this.model({pixel_values:s}),a;if(t){if(!("pooler_output"in n))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=n.pooler_output;}else a=n.last_hidden_state??n.logits??n.image_embeds;return a}},xo=Object.freeze({"text-classification":{pipeline:OA,model:hd,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:NA,model:gA,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:zA,model:xA,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:DA,model:MA,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:BA,model:uo,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:RA,model:uo,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:$l,model:uo,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:GA,model:bA,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:$A,model:hd,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:VA,model:SA,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:UA,model:Os,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:jA,model:[wA,CA],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:qA,model:[vA,yA],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:WA,model:kA,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:HA,model:TA,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Rf,model:[fd,_d,pd],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:QA,model:[fd,_d,pd],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:XA,model:Os,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:YA,model:EA,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:JA,model:AA,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:KA,model:PA,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ZA,model:FA,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:eC,model:LA,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:tC,model:Os,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:rC,model:[IA,Os],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),sC=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function nC(e){if(!e)throw new Error("modelId is required");return (await es(e,Dn,{})).exists?[Dn]:[]}async function ca(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:n=null,include_tokenizer:a=true,include_processor:o=true}={}){let i=await _h(e,{config:t,dtype:r,device:s,model_file_name:n});if(a){let l=await Ld(e);i.push(...l);}if(o){let l=await nC(e);i.push(...l);}return i}async function ua(e,t,r={}){e=sC[e]??e;let s=xo[e];if(!s)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(xo).join(", ")}]`);let{type:n}=s,i=await ca(t,{...r,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"});if(e==="text-generation"){let l=await fh(t,r),c=hh(l),d=lz(c);if(d){let h=Object.values(d).map(_=>`onnx/${_}`);return i.filter(_=>!_.startsWith("onnx/")||h.some(p=>_.startsWith(p)))}}return i}async function $z(e,t=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:a=false,revision:o="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:d=null,model_file_name:h=null,session_options:_={}}={}){e=sC[e]??e;let p=xo[e.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(xo)}]`);t||(t=p.default.model,ce.info(`No model specified. Using default model: "${t}".`),!l&&p.default.dtype&&(l=p.default.dtype));let w=await ua(e,t,{device:i,dtype:l}),y={};r&&(await Promise.all(w.map(async Q=>es(t,Q)))).forEach((Q,q)=>{Q.exists&&(y[w[q]]={loaded:0,total:Q.size??0});});let b={progress_callback:r?new td(r,y):void 0,config:s,cache_dir:n,local_files_only:a,revision:o,device:i,dtype:l,subfolder:c,use_external_data_format:d,model_file_name:h,session_options:_},x=w.includes("tokenizer.json"),T=w.includes("preprocessor_config.json"),C=p.model,A;if(Array.isArray(C)){let j=s??await Gs.from_pretrained(t,b),{model_type:Q}=j,q=C.find(X=>X.supports(Q));if(!q)throw Error(`Unsupported model type "${Q}" for task "${e}". None of the candidate model classes support this type.`);A=q.from_pretrained(t,{...b,config:j});}else A=C.from_pretrained(t,b);let[S,N,M]=await Promise.all([x?xe.from_pretrained(t,b):null,T?Ub.from_pretrained(t,b):null,A]),$={task:e,model:M};S&&($.tokenizer=S),N&&($.processor=N),Pr(r,{status:"ready",task:e,model:t});let G=p.pipeline;return new G($)}var Vz=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,aC=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},kw=he.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),oC=class extends aC{constructor(e,{skip_prompt:t=false,callback_function:r=null,token_callback_function:s=null,skip_special_tokens:n=true,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=r??kw,this.token_callback_function=s,this.decode_kwargs={skip_special_tokens:n,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=true,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt));}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=false,this.skip_prompt))return;let r=e[0];if(this.token_callback_function?.(r),r.length===1&&this.special_ids.has(r[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let i=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(i,false),this.token_cache=[],this.print_len=0;}let a=this.tokenizer.decode(r,this.decode_kwargs);this.on_finalized_text(a,false);return}this.token_cache=Gt(this.token_cache,r);let s=this.tokenizer.decode(this.token_cache,this.decode_kwargs),n;t||s.endsWith(`
|
|
38
|
+
`)?(n=s.slice(this.print_len),this.token_cache=[],this.print_len=0):s.length>0&&Vz(s.charCodeAt(s.length-1))?(n=s.slice(this.print_len),this.print_len+=n.length):(n=s.slice(this.print_len,s.lastIndexOf(" ")+1),this.print_len+=n.length),this.on_finalized_text(n,false);}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=true,this.on_finalized_text(e,true);}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===kw&&he.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
|
|
39
|
+
`);}},Uz=class extends oC{constructor(e,{skip_prompt:t=false,callback_function:r=null,token_callback_function:s=null,on_chunk_start:n=null,on_chunk_end:a=null,on_finalize:o=null,time_precision:i=.02,skip_special_tokens:l=true,decode_kwargs:c={}}={}){super(e,{skip_prompt:t,skip_special_tokens:l,callback_function:r,token_callback_function:s,decode_kwargs:c}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=n,this.on_chunk_end=a,this.on_finalize=o,this.time_precision=i,this.waiting_for_timestamp=false;}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let t=e[0];if(t.length===1){let r=Number(t[0])-this.timestamp_begin;if(r>=0){let s=r*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(s):this.on_chunk_start?.(s),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(t);return}}return super.put(e)}end(){super.end(),this.on_finalize?.();}},Gf=class{constructor(e,t){this.image=e,this.timestamp=t;}},iC=class{constructor(e,t){e.length>0&&e[0]instanceof vt&&(e=e.map((r,s)=>new Gf(r,(s+1)/(e.length+1)*t))),this.frames=e,this.duration=t;}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};async function jz(e,{num_frames:t=null,fps:r=null}={}){if(!he.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(t==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=true,typeof e=="string")n.src=e;else if(e instanceof Blob)n.src=URL.createObjectURL(e);else if(e instanceof HTMLVideoElement)n.src=e.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(h=>n.onloadedmetadata=h),n.seekable.start(0)===n.seekable.end(0)){let _=await(await me.fetch(n.src)).blob();n.src=URL.createObjectURL(_),await new Promise(p=>n.onloadedmetadata=p);}let a=n.duration,o,i;t!=null?(o=t,i=t===1?0:a/(t-1)):(i=1/r,o=Math.floor(a/i));let l=[];for(let h=0;h<o;++h)l.push(t===1?a/2:h*i);let c=document.createElement("canvas");c.width=n.videoWidth,c.height=n.videoHeight;let d=c.getContext("2d",{willReadFrequently:true});for(let h of l){n.currentTime=h,await new Promise(y=>{n.onseeked=y;}),d.drawImage(n,0,0,c.width,c.height);let _=d.getImageData(0,0,c.width,c.height),p=new vt(_.data,c.width,c.height,4),w=new Gf(p,h);s.push(w);}return n.remove(),new iC(s,a)}async function Vl(e,t,r={}){let s=await js(r?.cache_dir);if(!s)return {allCached:false,files:t.map(o=>({file:o,cached:false}))};let n=await Promise.all(t.map(async a=>{let{localPath:o,proposedCacheKey:i}=Un(e,a,r,s),l=await jn(s,o,i);return {file:a,cached:!!l}}));return {allCached:n.every(a=>a.cached),files:n}}async function lC(e,t,r={}){let s=await js(r?.cache_dir);if(!s)return false;let{localPath:n,proposedCacheKey:a}=Un(e,t,r,s);return !!await jn(s,n,a)}async function qz(e,t={}){if(!e)throw new Error("modelId is required");if(!await lC(e,"config.json",t))return false;let r=await ca(e,t);return (await Vl(e,r,t)).allCached}async function Wz(e,t={}){if(!e)throw new Error("modelId is required");let r=await ca(e,t);return await Vl(e,r,t)}async function Hz(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");if(!await lC(t,"config.json",r))return false;let s=await ua(e,t,r);return (await Vl(t,s,r)).allCached}async function Qz(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");let s=await ua(e,t,r);return await Vl(t,s,r)}async function cC(e,t,r={}){let s=await js(r?.cache_dir);if(!s)return {filesDeleted:0,filesCached:0,files:t.map(a=>({file:a,deleted:false,wasCached:false}))};if(!s.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(t.map(async a=>{let{localPath:o,proposedCacheKey:i}=Un(e,a,r,s),c=!!await jn(s,o,i),d=false;if(c){let h=await s.delete(i),_=!h&&i!==o?await s.delete(o):false;d=h||_;}return {file:a,deleted:d,wasCached:c}}));return {filesDeleted:n.filter(a=>a.deleted).length,filesCached:n.filter(a=>a.wasCached).length,files:n}}async function Xz(e,t={}){if(!e)throw new Error("modelId is required");let r=await ca(e,t);return await cC(e,r,t)}async function Yz(e,t,r={}){if(!e)throw new Error("task is required");if(!t)throw new Error("modelId is required");let s=await ua(e,t,r);return await cC(t,s,r)}var Jz=Object.keys(zn);async function Kz(e,{config:t=null,model_file_name:r=null,revision:s="main",cache_dir:n=null,local_files_only:a=false}={}){t=await fh(e,{config:t,cache_dir:n,local_files_only:a,revision:s});let o="onnx",i=hh(t),{sessions:l}=l0(i,t,{model_file_name:r}),c=Object.values(l),d={revision:s,cache_dir:n,local_files_only:a};return (await Promise.all(Jz.map(async _=>{let p=zn[_]??"",w=await Promise.all(c.map(async y=>{let b=`${o}/${y}${p}.onnx`;return (await es(e,b,d)).exists}));return {dtype:_,available:w.every(Boolean)}}))).filter(_=>_.available).map(_=>_.dtype)}var Zz=class{static async get_files(e,t={}){return ca(e,t)}static async get_pipeline_files(e,t,r={}){return ua(e,t,r)}static async get_model_files(e,t={}){return _h(e,t)}static async get_tokenizer_files(e){return Ld(e)}static async get_processor_files(e){return nC(e)}static async get_available_dtypes(e,t={}){return Kz(e,t)}static async is_cached(e,t={}){return qz(e,t)}static async is_cached_files(e,t={}){return Wz(e,t)}static async is_pipeline_cached(e,t,r={}){return Hz(e,t,r)}static async is_pipeline_cached_files(e,t,r={}){return Qz(e,t,r)}static async get_file_metadata(e,t,r={}){return es(e,t,r)}static async clear_cache(e,t={}){return Xz(e,t)}static async clear_pipeline_cache(e,t,r={}){return Yz(e,t,r)}};function eD(e){let t=e[e.length-1];if(!t||!Array.isArray(t.content))return {audio:null,images:null};let r=null,s=[];for(let n of t.content)n&&(n.type==="audio"&&n.data?r=n.data:n.type==="image"&&(n.image||n.data||n.url)&&s.push(n.image??n.data??n.url));return {audio:r,images:s.length>0?s:null}}function uC(e,t,r={}){let s=r.defaultMaxNewTokens??1024,n=async(a,o)=>{let i=t.apply_chat_template(a,{enable_thinking:false,add_generation_prompt:true}),{audio:l,images:c}=eD(a),d=await t(i,c,l,{add_special_tokens:false}),h={...d,max_new_tokens:o?.max_new_tokens??s,temperature:o?.temperature??0,do_sample:o?.do_sample??false,top_p:o?.top_p??1};o?.streamer&&(h.streamer=o.streamer);let _=await e.generate(h),p=d.input_ids.dims.at(-1),w=_.slice(null,[p,null]);return [{generated_text:t.batch_decode(w,{skip_special_tokens:true})[0]??""}]};return n.tokenizer=t.tokenizer,n.dispose=async()=>{try{await e.dispose?.();}catch{}},n}function dC(e,t){if(!(!t||t.length===0))for(let r of t)try{e&&e[r]&&(e[r]=null);}catch{}}var{pipeline:tD,env:Ir,TextStreamer:rD}=da;function fC(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>fC(t)).join(""):e&&typeof e=="object"?e.text||e.content||JSON.stringify(e):String(e||"")}try{Ir.backends?.onnx?.wasm&&(Ir.backends.onnx.wasm.proxy=!1,Ir.backends.onnx.wasm.numThreads=1);}catch{}try{let e=globalThis.ort??Ir.ort;e?.env?.wasm&&(e.env.wasm.proxy=!1,e.env.wasm.numThreads=1);}catch{}Ir.allowLocalModels=false;Ir.allowRemoteModels=true;Ir.remoteHost="https://huggingface.co";Ir.remotePathTemplate="{model}/resolve/{revision}/";var Mt=null,sD="",Ul="text-generation";function nD(e){if(!e)return [];if(Array.isArray(e))return e.length>0&&Array.isArray(e[0])?e:[e];if(typeof e.tolist=="function"){let t=e.tolist();return Array.isArray(t)&&t.length>0&&Array.isArray(t[0])?t:[t]}if(e.data&&e.dims){let[t,r]=e.dims.length===2?e.dims:[1,e.dims[e.dims.length-1]],s=Array.from(e.data),n=[];for(let a=0;a<t;a++)n.push(s.slice(a*r,(a+1)*r));return n}return []}self.onmessage=async e=>{let{type:t,id:r,...s}=e.data;try{switch(t){case "init":{Ul=s.pipelineTask||"text-generation",sD=s.modelId;let n=s.device==="cpu"?"wasm":s.device;if(s.modelClass){let a=da[s.modelClass];if(!a)throw new Error(`Worker init: transformers.js has no export named "${s.modelClass}". Check your modelClass config (case-sensitive).`);let o=s.processorClass||"AutoProcessor",i=da[o];if(!i)throw new Error(`Worker init: transformers.js has no export named "${o}". Check your processorClass config (default: AutoProcessor).`);let l=await i.from_pretrained(s.modelId,{progress_callback:d=>{self.postMessage({type:"progress",id:r,data:d});}}),c=await a.from_pretrained(s.modelId,{dtype:s.dtype,device:n,progress_callback:d=>{self.postMessage({type:"progress",id:r,data:d});}});dC(c,s.disableEncoders),Mt=uC(c,l),self.postMessage({type:"init_complete",id:r});break}Mt=await tD(Ul,s.modelId,{device:n,progress_callback:a=>{self.postMessage({type:"progress",id:r,data:a});},dtype:s.dtype}),self.postMessage({type:"init_complete",id:r});break}case "generate":{if(!Mt){self.postMessage({type:"error",id:r,error:"Pipeline not initialized"});return}let{requestBody:n}=s;if(n.raw){let l=await Mt(n.inputs,n.options);self.postMessage({type:"generate_complete",id:r,data:l});return}let{messages:a,options:o}=hC(n),i=await Mt(a,o);self.postMessage({type:"generate_complete",id:r,data:i});break}case "generate_stream":{if(!Mt){self.postMessage({type:"error",id:r,error:"Pipeline not initialized"});return}let{messages:n,options:a}=hC(s.requestBody),o=Mt.tokenizer;if(!o){self.postMessage({type:"error",id:r,error:"Streaming requires a tokenizer on the pipeline. Current task may not support streaming."});return}let i=new rD(o,{skip_prompt:!0,skip_special_tokens:!0,callback_function:l=>{l&&self.postMessage({type:"stream_chunk",id:r,text:l});}});await Mt(n,{...a,streamer:i}),self.postMessage({type:"stream_complete",id:r});break}case "embed":{if(!Mt){self.postMessage({type:"error",id:r,error:"Pipeline not initialized"});return}if(Ul!=="feature-extraction"){self.postMessage({type:"error",id:r,error:`Embeddings require pipelineTask="feature-extraction". Current task: "${Ul}".`});return}let n=s.inputs,a=await Mt(n,{pooling:s.pooling||"mean",normalize:s.normalize!==!1});self.postMessage({type:"embed_complete",id:r,data:nD(a)});break}case "unload":{Mt&&typeof Mt.dispose=="function"&&await Mt.dispose(),Mt=null,self.postMessage({type:"unload_complete",id:r});break}default:self.postMessage({type:"error",id:r,error:`Unknown message type: ${t}`});}}catch(n){self.postMessage({type:"error",id:r,error:n.message});}};function hC(e){let{messages:t,max_tokens:r,max_completion_tokens:s,temperature:n,top_p:a}=e,o=r??s??256,i=n??.7,l=a??1,c=(t||[]).map(h=>({...h,content:fC(h.content)})),d={max_new_tokens:o,temperature:i,top_p:l,do_sample:i>0,return_full_text:false};return {messages:c,options:d}}
|
|
40
|
+
/*! Bundled license information:
|
|
41
|
+
|
|
42
|
+
onnxruntime-web/dist/ort.webgpu.bundle.min.mjs:
|
|
43
|
+
(*!
|
|
44
|
+
* ONNX Runtime Web v1.26.0-dev.20260410-5e55544225
|
|
45
|
+
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
46
|
+
* Licensed under the MIT License.
|
|
47
|
+
*)
|
|
48
|
+
*/
|