var DI=Object.defineProperty;var _s=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var hs=(t,e)=>{for(var r in e)DI(t,r,{get:e[r],enumerable:!0})};var _t={};var Ut={};var pE={};var BI="4.0.1",Ef=typeof self<"u",on=!gE(_t),mE=!gE(Ut),tc=Ef&&"caches"in self,UI=typeof globalThis.Deno<"u",h3=typeof globalThis.Bun<"u",sc=UI&&tc&&!on,_E=typeof process<"u",hE=_E&&process?.release?.name==="node"&&!sc,Af=typeof window<"u"&&typeof window.document<"u",Tf=Ef&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),FI=Af||Tf||sc,GI=hE||typeof navigator<"u"&&"gpu"in navigator,jI=typeof navigator<"u"&&"ml"in navigator,qI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",WI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",VI=typeof ServiceWorkerGlobalScope<"u"&&Ef&&self instanceof ServiceWorkerGlobalScope,HI=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},XI=HI(),ie=Object.freeze({IS_BROWSER_ENV:Af,IS_WEBWORKER_ENV:Tf,IS_WEB_ENV:FI,IS_SERVICE_WORKER_ENV:VI,IS_DENO_WEB_RUNTIME:sc,IS_WEB_CACHE_AVAILABLE:tc,IS_WEBGPU_AVAILABLE:GI,IS_WEBNN_AVAILABLE:jI,IS_SAFARI:XI,IS_PROCESS_AVAILABLE:_E,IS_NODE_ENV:hE,IS_FS_AVAILABLE:on,IS_PATH_AVAILABLE:mE,IS_CRYPTO_AVAILABLE:qI,IS_CHROME_AVAILABLE:WI}),Mf=on&&mE,rc="./";if(Mf){let t=Object(import.meta).url;t?rc=Ut.dirname(Ut.dirname(pE.fileURLToPath(t))):typeof __dirname<"u"&&(rc=Ut.dirname(__dirname))}var KI=Mf?Ut.join(rc,"/.cache/"):null,fE="/models/",YI=Mf?Ut.join(rc,fE):fE,QI=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,It=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),dE=It.WARNING,_e={version:BI,backends:{onnx:{}},get logLevel(){return dE},set logLevel(t){dE=t,_e.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Af||Tf||sc),localModelPath:YI,useFS:on,useBrowserCache:tc,useFSCache:on,cacheDir:KI,useCustomCache:!1,customCache:null,useWasmCache:tc||on,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:QI};function gE(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function lr(t,e){t&&t(e)}var gs=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function wE(t){return Number.isInteger(t)||typeof t=="bigint"}function Sf(t){return t==null||t===-1}function Of(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function ht(...t){return Array.prototype.concat.apply([],t)}function xE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function an(t,e){return Math.abs((t+e)%(2*e)-e)}function Qe(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function yE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){_e.logLevel<=It.ERROR&&console.error(...t)},warn(...t){_e.logLevel<=It.WARNING&&console.warn(...t)},info(...t){_e.logLevel<=It.INFO&&console.log(...t)},debug(...t){_e.logLevel<=It.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var JI=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),tC=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),rC=tC(SE),vE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",sC=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|[${vE}])]+`,` ?[^\\s${vE}]+`]]),nc="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Cf=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),oc=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[s,n]of sC)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=nC(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},nC=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),oC=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,iC=t=>Number.isInteger(t)||typeof t=="bigint",lC=t=>{let e=0;for(let r of t)++e;return e},cC=t=>OE(t.toLowerCase()),Kt=(...t)=>Array.prototype.concat.apply([],t),Pf=t=>new Map(Object.entries(t)),uC=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),kE=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},pC=t=>t.match(/\S+/g)||[],fC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},uo=fC,dC=class extends uo{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},vr=dC,mC=class extends vr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},gC=hC,wC=class extends vr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>IE(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},xC=wC,yC=class extends vr{normalize(t){let e=oc(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},bC=yC,vC=class extends vr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},ac=vC,kC=class extends ac{constructor(){super(...arguments),this.form="NFC"}},EC=kC,AC=class extends ac{constructor(){super(...arguments),this.form="NFD"}},TC=AC,MC=class extends ac{constructor(){super(...arguments),this.form="NFKC"}},SC=MC,OC=class extends ac{constructor(){super(...arguments),this.form="NFKD"}},IC=OC,CC=class extends vr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},PC=CC,LC=class extends vr{normalize(t){return OE(t)}},zC=LC,NC=class extends vr{normalize(t){return t.toLowerCase()}},RC=NC,$C=class extends vr{normalize(t){return t=this.config.prepend+t,t}},DC=$C;function BC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new _C(t);case"Precompiled":return new gC(t);case"Sequence":return new xC(t);case"Replace":return new bC(t);case"NFC":return new EC(t);case"NFD":return new TC(t);case"NFKC":return new SC(t);case"NFKD":return new IC(t);case"Strip":return new PC(t);case"StripAccents":return new zC(t);case"Lowercase":return new RC(t);case"Prepend":return new DC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var IE=BC,UC=class extends uo{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Yt=UC,FC=class extends Yt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=SE,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},GC=FC,jC=class extends Yt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},qC=jC,WC=class extends Yt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},VC=WC,HC=class extends Yt{constructor(t){super(),this.config=t,this.pattern=oc(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):uC(t,this.pattern)}},XC=HC,KC=class extends Yt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${nc}]+|[${nc}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},YC=KC,QC=class extends Yt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},JC=QC,ZC=class extends Yt{constructor(){super(),this.pattern=new RegExp(`[^\\s${nc}]+|[${nc}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},eP=ZC,tP=class extends Yt{constructor(t){super(),this.config=t,this.pattern=oc(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},rP=tP,sP=class extends Yt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>CE(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},nP=sP,oP=class extends Yt{pre_tokenize_text(t){return pC(t)}},aP=oP,iP=class extends Yt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;rthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},EE=pP,AE=class PE{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new PE(!1,new Map)}},fP=class{constructor(){this.root=AE.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=AE.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let s of t){if(r+=s,e=e.children.get(s),e===void 0)return;e.is_leaf&&(yield r)}}},dP=fP,If=class LE{constructor(e,r,s,n,o){this.token_id=e,this.node_id=r,this.pos=s,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new LE(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},mP=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new If(this.bos_token_id??0,0,0,0,0),n=new If(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new If(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let u=c.backtrace_score+a.score;(l===null||u>i)&&(l=c.clone(),i=u)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},_P=mP;function hP(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=hP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new dP,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;sr>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},bP=yP,vP=class extends ic{constructor(t){super(t),this.tokens_to_ids=Pf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new bP(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new xP((i,l)=>i.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},ME=vP,kP=class extends ic{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Pf(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},EP=kP;function AP(t,e){switch(t.type){case"WordPiece":return new EE(t);case"Unigram":return new TE(t,e.eos_token);case"BPE":return new ME(t);default:if(t.vocab)return Array.isArray(t.vocab)?new TE(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new ME(t):new EE(t):new EP(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var TP=AP,MP=class extends uo{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},po=MP,SP=class extends po{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Kt(n,t),o=Kt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Kt(n,e),o=Kt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},OP=SP,IP=class extends po{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},CP=IP,PP=class extends po{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Kt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Kt(t,n,e,o),s=Kt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},LP=PP,zP=class extends po{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Kt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Kt(t,n,e,o),s=Kt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},NP=zP,RP=class extends po{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>zE(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},$P=RP;function DP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new OP(t);case"ByteLevel":return new CP(t);case"BertProcessing":return new LP(t);case"RobertaProcessing":return new NP(t);case"Sequence":return new $P(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var zE=DP,BP=class extends uo{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Ft=BP,UP=class extends Ft{constructor(t){super(t),this.byte_decoder=rC,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},FP=UP,GP=class extends Ft{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=Cf(e)),e})}},jP=GP,qP=class extends Ft{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;re.replaceAll(this.suffix,r===t.length-1?"":" "))}},HP=VP,XP=class extends Ft{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(s=Cf(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},KP=XP,YP=class extends Ft{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>NE(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},QP=YP,JP=class extends Ft{decode_chain(t){let e=oc(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},ZP=JP,eL=class extends Ft{decode_chain(t){return[t.join("")]}},tL=eL,rL=class extends Ft{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},oL=nL;function aL(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new FP(t);case"WordPiece":return new jP(t);case"Metaspace":return new WP(t);case"BPEDecoder":return new HP(t);case"CTC":return new KP(t);case"Sequence":return new QP(t);case"Replace":return new ZP(t);case"Fuse":return new tL(t);case"Strip":return new sL(t);case"ByteFallback":return new oL(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var NE=aL,iL=class{constructor(t,e){let r=kE(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=kE(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=IE(this.tokenizer.normalizer),this.pre_tokenizer=CE(this.tokenizer.pre_tokenizer),this.model=TP(this.tokenizer.model,this.config),this.post_processor=zE(this.tokenizer.post_processor),this.decoder=NE(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new eC(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new bE(n),this.splitter_normalized=new bE(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!iC(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=Cf(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=cC(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Kt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],cL=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function uL(t,e={}){return t.endsWith(` `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function pL(t,e={}){let r=[],s=uL(t,e),n=0,o=0,a=c=>{let u="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=cL.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);u+=m;continue}if(u+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return u},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new Gt(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let m="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");m+=s[n++]}let _=m.endsWith("-");_&&(m=m.slice(0,-1)),f&&i(),r.push(new Gt(m,D.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Gt("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Gt("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(DE),s.slice(n,n+3)==="-%}"){r.push(new Gt("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Gt("}}",D.CloseExpression)),n+=3,l();continue}let u=s[n];if(u==="-"||u==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${u}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let m=a(fo);r.push(new Gt(`${u}${m}`,m.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,m]of lL){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Gt(f,m)),m===D.OpenExpression?o=0:m===D.OpenCurlyBracket?++o:m===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(u==="'"||u==='"'){++n;let f=a(m=>m!==u);r.push(new Gt(f,D.StringLiteral)),++n;continue}if(fo(u)){let f=a(fo);if(s[n]==="."&&fo(s[n+1])){++n;let m=a(fo);f=`${f}.${m}`}r.push(new Gt(f,D.NumericLiteral));continue}if($E(u)){let f=a($E);r.push(new Gt(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${u}`)}return r}var Jt=class{type="Statement"},fL=class extends Jt{constructor(t){super(),this.body=t}type="Program"},dL=class extends Jt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},mL=class extends Jt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},_L=class extends Jt{type="Break"},hL=class extends Jt{type="Continue"},gL=class extends Jt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},wL=class extends Jt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},xL=class extends Jt{constructor(t){super(),this.value=t}type="Comment"},Lt=class extends Jt{type="Expression"},yL=class extends Lt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},BE=class extends Lt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},ln=class extends Lt{constructor(t){super(),this.value=t}type="Identifier"},cn=class extends Lt{constructor(t){super(),this.value=t}type="Literal"},bL=class extends cn{type="IntegerLiteral"},vL=class extends cn{type="FloatLiteral"},UE=class extends cn{type="StringLiteral"},kL=class extends cn{type="ArrayLiteral"},FE=class extends cn{type="TupleLiteral"},EL=class extends cn{type="ObjectLiteral"},mo=class extends Lt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},AL=class extends Lt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},TL=class extends Jt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},ML=class extends Lt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},SL=class extends Lt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},OL=class extends Lt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},IL=class extends Lt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},CL=class extends Lt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},PL=class extends Lt{constructor(t){super(),this.argument=t}type="SpreadExpression"},LL=class extends Jt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},zL=class extends Lt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function NL(t){let e=new fL([]),r=0;function s(L,$){let B=t[r++];if(!B||B.type!==L)throw new Error(`Parser Error: ${$}. ${B.type} !== ${L}.`);return B}function n(L){if(!l(L))throw new SyntaxError(`Expected ${L}`);++r}function o(){switch(t[r].type){case D.Comment:return new xL(t[r++].value);case D.Text:return c();case D.OpenStatement:return u();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...L){return r+L.length<=t.length&&L.every(($,B)=>$===t[r+B].type)}function i(...L){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&L.includes(t[r+1]?.value)}function l(...L){return r+L.length<=t.length&&L.every(($,B)=>t[r+B].type==="Identifier"&&$===t[r+B].value)}function c(){return new UE(s(D.Text,"Expected text token").value)}function u(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let L=t[r].value,$;switch(L){case"set":++r,$=m();break;case"if":++r,$=_(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,$=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,$=v(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let B=null;a(D.OpenParen)&&(B=F());let J=Y();if(J.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let le=F();s(D.CloseStatement,"Expected closing statement token");let je=[];for(;!i("endcall");)je.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let ce=new BE(J,le);$=new LL(ce,B,je);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),$=new _L;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),$=new hL;break;case"filter":{++r;let B=Y();B instanceof ln&&a(D.OpenParen)&&(B=G(B)),s(D.CloseStatement,"Expected closing statement token");let J=[];for(;!i("endfilter");)J.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),$=new TL(B,J);break}default:throw new SyntaxError(`Unknown statement type: ${L}`)}return $}function f(){s(D.OpenExpression,"Expected opening expression token");let L=b();return s(D.CloseExpression,"Expected closing expression token"),L}function m(){let L=x(),$=null,B=[];if(a(D.Equals))++r,$=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)B.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new gL(L,$,B)}function _(){let L=b();s(D.CloseStatement,"Expected closing statement token");let $=[],B=[];for(;!i("elif","else","endif");)$.push(o());if(i("elif")){++r,++r;let J=_();B.push(J)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)B.push(o());return new dL(L,$,B)}function w(){let L=Y();if(L.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let $=F();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endmacro");)B.push(o());return new wL(L,$,B)}function x(L=!1){let $=L?Y:b,B=[$()],J=a(D.Comma);for(;J&&(++r,B.push($()),!!a(D.Comma)););return J?new FE(B):B[0]}function v(){let L=x(!0);if(!(L instanceof ln||L instanceof FE))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${L.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let $=b();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endfor","else");)B.push(o());let J=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)J.push(o());return new mL(L,$,B,J)}function b(){return A()}function A(){let L=S();if(l("if")){++r;let $=S();if(l("else")){++r;let B=A();return new zL($,L,B)}else return new ML(L,$)}return L}function S(){let L=M();for(;l("or");){let $=t[r];++r;let B=M();L=new mo($,L,B)}return L}function M(){let L=I();for(;l("and");){let $=t[r];++r;let B=I();L=new mo($,L,B)}return L}function I(){let L;for(;l("not");){let $=t[r];++r;let B=I();L=new OL($,B)}return L??O()}function O(){let L=k();for(;;){let $;if(l("not","in"))$=new Gt("not in",D.Identifier),r+=2;else if(l("in"))$=t[r++];else if(a(D.ComparisonBinaryOperator))$=t[r++];else break;let B=k();L=new mo($,L,B)}return L}function k(){let L=U();for(;a(D.AdditiveBinaryOperator);){let $=t[r];++r;let B=U();L=new mo($,L,B)}return L}function R(){let L=Q(Y());return a(D.OpenParen)?G(L):L}function G(L){let $=new BE(L,F());return $=Q($),a(D.OpenParen)&&($=G($)),$}function F(){s(D.OpenParen,"Expected opening parenthesis for arguments list");let L=K();return s(D.CloseParen,"Expected closing parenthesis for arguments list"),L}function K(){let L=[];for(;!a(D.CloseParen);){let $;if(t[r].type===D.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let B=b();$=new PL(B)}else if($=b(),a(D.Equals)){if(++r,!($ instanceof ln))throw new SyntaxError("Expected identifier for keyword argument");let B=b();$=new CL($,B)}L.push($),a(D.Comma)&&++r}return L}function V(){let L=[],$=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(L.push(void 0),++r,$=!0):(L.push(b()),a(D.Colon)&&(++r,$=!0));if(L.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($){if(L.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new IL(...L)}return L[0]}function Q(L){for(;a(D.Dot)||a(D.OpenSquareBracket);){let $=t[r];++r;let B,J=$.type===D.OpenSquareBracket;if(J)B=V(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(B=Y(),B.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");L=new yL(L,B,J)}return L}function U(){let L=C();for(;a(D.MultiplicativeBinaryOperator);){let $=t[r++],B=C();L=new mo($,L,B)}return L}function C(){let L=se();for(;l("is");){++r;let $=l("not");$&&++r;let B=Y();if(!(B instanceof ln))throw new SyntaxError("Expected identifier for the test");L=new SL(L,$,B)}return L}function se(){let L=R();for(;a(D.Pipe);){++r;let $=Y();if(!($ instanceof ln))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&($=G($)),L=new AL(L,$)}return L}function Y(){let L=t[r++];switch(L.type){case D.NumericLiteral:{let $=L.value;return $.includes(".")?new vL(Number($)):new bL(Number($))}case D.StringLiteral:{let $=L.value;for(;a(D.StringLiteral);)$+=t[r++].value;return new UE($)}case D.Identifier:return new ln(L.value);case D.OpenParen:{let $=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),$}case D.OpenSquareBracket:{let $=[];for(;!a(D.CloseSquareBracket);)$.push(b()),a(D.Comma)&&++r;return++r,new kL($)}case D.OpenCurlyBracket:{let $=new Map;for(;!a(D.CloseCurlyBracket);){let B=b();s(D.Colon,"Expected colon between key and value in object literal");let J=b();$.set(B,J),a(D.Comma)&&++r}return++r,new EL($)}default:throw new SyntaxError(`Unexpected token: ${L.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function GE(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*ae.toUpperCase())}function DL(t){return BL(new Date,t)}function BL(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function UL(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function FL(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(UL(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var jE=class extends Error{},qE=class extends Error{},cr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new de(!!this.value)}toString(){return String(this.value)}},he=class extends cr{type="IntegerValue"},Ze=class extends cr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},te=class extends cr{type="StringValue";builtins=new Map([["upper",new He(()=>new te(this.value.toUpperCase()))],["lower",new He(()=>new te(this.value.toLowerCase()))],["strip",new He(()=>new te(this.value.trim()))],["title",new He(()=>new te($L(this.value)))],["capitalize",new He(()=>new te(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new He(()=>new te(this.value.trimEnd()))],["lstrip",new He(()=>new te(this.value.trimStart()))],["startswith",new He(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.startsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof te))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new He(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.endsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof te))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new de(!0)}return new de(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new He(t=>{let e=t[0]??new Xe;if(!(e instanceof te||e instanceof Xe))throw new Error("sep argument must be a string or null");let r=t[1]??new he(-1);if(!(r instanceof he))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Xe){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ye(s.map(n=>new te(n)))})],["replace",new He(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof te&&r instanceof te))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Xe:s=t[2]:s=new Xe,!(s instanceof he||s instanceof Xe))throw new Error("replace() count argument must be a number or null");return new te(FL(this.value,e.value,r.value,s.value))})]])},de=class extends cr{type="BooleanValue"},GL=/[\x7f-\uffff]/g;function WE(t){return t.replace(GL,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function xs(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let u=JSON.stringify(t.value);return o&&(u=WE(u)),u}case"ArrayValue":case"ObjectValue":{let u=n?" ".repeat(n):"",f=` `+u.repeat(r),m=f+u;if(t.type==="ArrayValue"){let _=t.value.map(w=>xs(w,e,r+1,s));return n?`[${m}${_.join(`${l}${m}`)}${f}]`:`[${_.join(l)}]`}else{let _=Array.from(t.value.entries());i&&(_=_.sort(([x],[v])=>x.localeCompare(v)));let w=_.map(([x,v])=>{let b=JSON.stringify(x);o&&(b=WE(b));let A=`${b}${c}${xs(v,e,r+1,s)}`;return n?`${m}${A}`:A});return n?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var pt=class extends cr{type="ObjectValue";__bool__(){return new de(this.value.size>0)}builtins=new Map([["get",new He(([t,e])=>{if(!(t instanceof te))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Xe})],["items",new He(()=>this.items())],["keys",new He(()=>this.keys())],["values",new He(()=>this.values())],["dictsort",new He(t=>{let e=new Map,r=t.filter(i=>i instanceof _o?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new de(!1);if(!(s instanceof de))throw new Error("case_sensitive must be a boolean");let n=r.at(1)??e.get("by")??new te("key");if(!(n instanceof te))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");let o=r.at(2)??e.get("reverse")??new de(!1);if(!(o instanceof de))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new ye([new te(i),l])).sort((i,l)=>{let c=n.value==="key"?0:1,u=i.value[c],f=l.value[c],m=Lf(u,f,s.value);return o.value?-m:m});return new ye(a)})]]);items(){return new ye(Array.from(this.value.entries()).map(([t,e])=>new ye([new te(t),e])))}keys(){return new ye(Array.from(this.value.keys()).map(t=>new te(t)))}values(){return new ye(Array.from(this.value.values()))}toString(){return xs(this,{},0,!1)}},_o=class extends pt{type="KeywordArgumentsValue"},ye=class extends cr{type="ArrayValue";builtins=new Map([["length",new he(this.value.length)]]);__bool__(){return new de(this.value.length>0)}toString(){return xs(this,{},0,!1)}},VE=class extends ye{type="TupleValue"},He=class extends cr{type="FunctionValue"},Xe=class extends cr{type="NullValue"},Ve=class extends cr{type="UndefinedValue"},ws=class{constructor(t){this.parent=t}variables=new Map([["namespace",new He(t=>{if(t.length===0)return new pt(new Map);if(t.length!==1||!(t[0]instanceof pt))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]);tests=new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof He],["odd",t=>{if(!(t instanceof he))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof he))throw new Error(`cannot even on ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["none",t=>t.type==="NullValue"],["string",t=>t.type==="StringValue"],["number",t=>t instanceof he||t instanceof Ze],["integer",t=>t instanceof he],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t instanceof pt],["sequence",t=>t instanceof ye||t instanceof pt||t instanceof te],["lower",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]]);set(t,e){return this.declareVariable(t,lc(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Ve}catch{return new Ve}}};function jL(t){t.set("false",!1),t.set("true",!0),t.set("none",null),t.set("raise_exception",e=>{throw new Error(e)}),t.set("range",RL),t.set("strftime_now",DL),t.set("True",!0),t.set("False",!1),t.set("None",null)}function HE(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof pt)s=s.value.get(n)??new Ve;else if(s instanceof ye){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&oo instanceof he||o instanceof Ze||o instanceof de,n=o=>o instanceof de?o.value?1:0:o.value;if(s(t)&&s(e)){let o=n(t),a=n(e);return oa?1:0}if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);if(t.type==="StringValue"){let o=t.value,a=e.value;return r||(o=o.toLowerCase(),a=a.toLowerCase()),oa?1:0}else throw new Error(`Cannot compare type: ${t.type}`)}var qL=class{global;constructor(t){this.global=t??new ws}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){let r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}let s=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new de(r.value==s.value);case"!=":return new de(r.value!=s.value)}if(r instanceof Ve||s instanceof Ve){if(s instanceof Ve&&["in","not in"].includes(t.operator.value))return new de(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof Xe||s instanceof Xe)throw new Error("Cannot perform operation on null values");if(t.operator.value==="~")return new te(r.value.toString()+s.value.toString());if((r instanceof he||r instanceof Ze)&&(s instanceof he||s instanceof Ze)){let n=r.value,o=s.value;switch(t.operator.value){case"+":case"-":case"*":{let a=t.operator.value==="+"?n+o:t.operator.value==="-"?n-o:n*o;return r instanceof Ze||s instanceof Ze?new Ze(a):new he(a)}case"/":return new Ze(n/o);case"%":{let a=n%o;return r instanceof Ze||s instanceof Ze?new Ze(a):new he(a)}case"<":return new de(n":return new de(n>o);case">=":return new de(n>=o);case"<=":return new de(n<=o)}}else if(r instanceof ye&&s instanceof ye){if(t.operator.value==="+")return new ye(r.value.concat(s.value))}else if(s instanceof ye){let n=s.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new de(n);case"not in":return new de(!n)}}}if((r instanceof te||s instanceof te)&&t.operator.value==="+")return new te(r.value.toString()+s.value.toString());if(r instanceof te&&s instanceof te)switch(t.operator.value){case"in":return new de(s.value.includes(r.value));case"not in":return new de(!s.value.includes(r.value))}if(r instanceof te&&s instanceof pt)switch(t.operator.value){case"in":return new de(s.value.has(r.value));case"not in":return new de(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(t,e){let r=[],s=new Map;for(let n of t)if(n.type==="SpreadExpression"){let o=n,a=this.evaluate(o.argument,e);if(!(a instanceof ye))throw new Error(`Cannot unpack non-iterable type: ${a.type}`);for(let i of a.value)r.push(i)}else if(n.type==="KeywordArgumentExpression"){let o=n;s.set(o.key.value,this.evaluate(o.value,e))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(n,e))}return[r,s]}applyFilter(t,e,r){if(e.type==="Identifier"){let s=e;if(s.value==="safe")return t;if(s.value==="tojson")return new te(xs(t,{}));if(t instanceof ye)switch(s.value){case"list":return t;case"first":return t.value[0];case"last":return t.value[t.value.length-1];case"length":return new he(t.value.length);case"reverse":return new ye(t.value.slice().reverse());case"sort":return new ye(t.value.slice().sort((n,o)=>Lf(n,o,!1)));case"join":return new te(t.value.map(n=>n.value).join(""));case"string":return new te(xs(t,{},0,!1));case"unique":{let n=new Set,o=[];for(let a of t.value)n.has(a.value)||(n.add(a.value),o.push(a));return new ye(o)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(t instanceof te)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=t.builtins.get(s.value);if(n instanceof He)return n.value([],r);if(n instanceof he)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new te(t.value.trim());case"indent":return new te(t.value.split(` `).map((n,o)=>o===0||n.length===0?n:" "+n).join(` `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new he(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ze(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof he||t instanceof Ze)switch(s.value){case"abs":return t instanceof he?new he(Math.abs(t.value)):new Ze(Math.abs(t.value));case"int":return new he(Math.floor(t.value));case"float":return new Ze(t.value);case"string":return new te(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof pt)switch(s.value){case"items":return new ye(Array.from(t.value.entries()).map(([n,o])=>new ye([new te(n),o])));case"length":return new he(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof He?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof de)switch(s.value){case"bool":return new de(t.value);case"int":return new he(t.value?1:0);case"float":return new Ze(t.value?1:0);case"string":return new te(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new Xe;if(!(a instanceof he||a instanceof Xe))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new de(!1);if(!(i instanceof de))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new de(!1);if(!(l instanceof de))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Xe,u=null;if(c instanceof ye||c instanceof VE){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.value;if(!(f instanceof te)||!(m instanceof te))throw new Error("separators must be a tuple of two strings");u=[f.value,m.value]}else if(!(c instanceof Xe))throw new Error("If set, separators must be a tuple of two strings");return new te(xs(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:u}))}else if(n==="join"){let o;if(t instanceof te)o=Array.from(t.value);else if(t instanceof ye)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new te("");if(!(l instanceof te))throw new Error("separator must be a string");return new te(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new he(0):new Ze(0));if(t instanceof te){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new he(l):new Ze(l)}else{if(t instanceof he||t instanceof Ze)return t;if(t instanceof de)return n==="int"?new he(t.value?1:0):new Ze(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new te(""),l=o[1]??a.get("boolean")??new de(!1);if(!(l instanceof de))throw new Error("`default` filter flag must be a boolean");return t instanceof Ve||l.value&&!t.__bool__().value?i:t}if(t instanceof ye){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new de(!1);if(!(i instanceof de))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new de(!1);if(!(l instanceof de))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Xe;if(!(c instanceof te||c instanceof he||c instanceof Xe))throw new Error("attribute must be a string, integer, or null");let u=f=>{if(c instanceof Xe)return f;let m=c instanceof he?String(c.value):c.value;return HE(f,m)};return new ye(t.value.slice().sort((f,m)=>{let _=u(f),w=u(m),x=Lf(_,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof pt)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let u=t.value.filter(f=>{let m=f.value.get(a.value),_=m?c(m,l):!1;return o?_:!_});return new ye(u)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof te))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof pt))throw new Error("items in map must be an object");let u=HE(c,a.value);return u instanceof Ve?i??new Ve:u});return new ye(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof te){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new he(4);if(!(i instanceof he))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new de(!1),c=o.at(2)??a.get("blank")??new de(!1),u=t.value.split(` `),f=" ".repeat(i.value),m=u.map((_,w)=>!l.value&&w===0||!c.value&&_.length===0?_:f+_);return new te(m.join(` `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof He))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new _o(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof pt){let o=t.builtins.get(n);if(o&&o instanceof He){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new _o(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new de(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new Ve}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new de(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new te(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new _o(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ye||t instanceof te))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof he||s instanceof Ve))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof Ve))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof he||o instanceof Ve))throw new Error("Slice step must be numeric or undefined");return t instanceof ye?new ye(GE(t.value,s.value,n.value,o.value)):new te(GE(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new te(t.property.value);let n;if(r instanceof pt){if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof ye||r instanceof te)if(s instanceof he)n=r.value.at(s.value),r instanceof te&&(n=new te(r.value.at(s.value)));else if(s instanceof te)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof cr?n:new Ve}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ye))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o_.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let _=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(_.value.length!==w.value.length)throw new Error(`Too ${_.value.length>w.value.length?"few":"many"} items to unpack`);m=x=>{for(let v=0;v<_.value.length;++v){if(_.value[v].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_.value[v].type}`);x.setVariable(_.value[v].value,w.value[v])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(u),!this.evaluate(s,u).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let c=0;c0?o[c-1]:new Ve],["nextitem",c{let n=new ws(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a{let c=new ws(l);if(t.callerArgs)for(let u=0;uthis.evaluate(r,e)));case"TupleLiteral":return new VE(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof te))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new pt(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Xe;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function lc(t){switch(typeof t){case"number":return Number.isInteger(t)?new he(t):new Ze(t);case"string":return new te(t);case"boolean":return new de(t);case"undefined":return new Ve;case"object":return t===null?new Xe:Array.isArray(t)?new ye(t.map(lc)):new pt(new Map(Object.entries(t).map(([e,r])=>[e,lc(r)])));case"function":return new He((e,r)=>{let s=t(...e.map(n=>n.value))??null;return lc(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var ot=` `,WL="{%- ",VL=" -%}";function HL(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function XL(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Qt(t.body,0,r).replace(/\n$/,"")}function gt(...t){return WL+t.join(" ")+VL}function Qt(t,e,r){return t.map(s=>KL(s,e,r)).join(ot)}function KL(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Qt(t.body,e,r);case"If":return YL(t,e,r);case"For":return QL(t,e,r);case"Set":return JL(t,e,r);case"Macro":return ZL(t,e,r);case"Break":return s+gt("break");case"Continue":return s+gt("continue");case"CallStatement":return ez(t,e,r);case"FilterStatement":return tz(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function YL(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+gt("if",ke(n[0].test))+ot+Qt(n[0].body,e+1,r);for(let i=1;i0&&(a+=ot+s+gt("else")+ot+Qt(o.alternate,e+1,r)),a+=ot+s+gt("endif"),a}function QL(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+gt("for",ke(t.loopvar),"in",n)+ot+Qt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=ot+s+gt("else")+ot+Qt(t.defaultBlock,e+1,r)),o+=ot+s+gt("endfor"),o}function JL(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+gt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+ot+Qt(t.body,e+1,r)+ot+s+gt("endset")}function ZL(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+gt("macro",`${t.name.value}(${n})`)+ot+Qt(t.body,e+1,r)+ot+s+gt("endmacro")}function ez(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+gt(`call${n}`,o)+ot;return a+=Qt(t.body,e+1,r)+ot,a+=s+gt("endcall"),a}function tz(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+gt("filter",n)+ot;return o+=Qt(t.body,e+1,r)+ot,o+=s+gt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=HL(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var XE=class{parsed;constructor(t){let e=pL(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=NL(e)}render(t){let e=new ws;if(jL(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new qL(e).run(this.parsed).value}format(t){return XL(this.parsed,t?.indent||" ")}};var rz={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"},Lr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=_t.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=_t.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=_t.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",rz[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await _t.promises.readFile(this.filePath)).buffer}async blob(){let e=await _t.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await _t.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var zr=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(ie.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[KE(this._random_fn,r)]}};function KE(t,e){let r=0;for(let n=0;nKE(ys.random,t);var sz=new zr,un=class{constructor(e){this.path=e}async match(e){let r=Ut.join(this.path,e),s=new Lr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Ut.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=sz._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),u=0;await _t.promises.mkdir(Ut.dirname(n),{recursive:!0});let f=_t.createWriteStream(i),m=r.body.getReader();for(;;){let{done:_,value:w}=await m.read();if(_)break;await new Promise((v,b)=>{f.write(w,A=>{if(A){b(A);return}v()})}),u+=w.length;let x=c?u/c*100:0;s?.({progress:x,loaded:u,total:c})}await new Promise((_,w)=>{f.close(x=>x?w(x):_())}),await _t.promises.rename(i,n)}catch(l){try{await _t.promises.unlink(i)}catch{}throw l}}async delete(e){let r=Ut.join(this.path,e);try{return await _t.promises.unlink(r),!0}catch{return!1}}};var QE={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"},cc=100,JE=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function ho(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Nr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function ZE(t){return!(!JE.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function eA(t,e,r){if(!r)return null;let s=QE[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function tA(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:u}=await i.read();if(c)return;let f=a+u.length;if(f>n){n=f;let _=new Uint8Array(n);_.set(o),o=_}o.set(u,a),a=f;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}function zf(t){return Nr(t,["blob:"])}function Nf(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}var sA="SHA-256",nz="experimental_transformers-hash-cache",rA=t=>({algorithm:sA,value:t}),go=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(nz),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let[s]=await navigator.crossOriginStorage.requestFileHandles([rA(r)]),n=await s.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([rA(r)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(sA,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Zt(t=null){let e=null;if(_e.useCustomCache){if(!_e.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!_e.customCache.match||!_e.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=_e.customCache}if(!e&&_e.experimental_useCrossOriginStorage&&go.isAvailable()&&(e=new go),!e&&_e.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(_e.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&_e.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new un(t??_e.cacheDir)}return e}async function nA(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var uc=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var oz=100,Rf=new uc(oz);function pc(t,e){let r=Rf.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Rf.delete(t),Promise.reject(n)));return Rf.put(t,s),s}async function az(t){if(!Nr(t,["http:","https:"]))return null;let e=$f(t);return e.set("Range","bytes=0-0"),_e.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ct(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return pc(s,()=>iz(t,e,r))}async function iz(t,e,r){let s=await Zt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=$r(t,e,r,s),l=await Dr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),u=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:u||void 0,fromCache:!0}}if(_e.allowLocalModels&&!Nr(n,["http:","https:"]))try{let u=await Rr(n);if(typeof u!="string"&&u.status!==404){let f=u.headers.get("content-length"),m=u.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(_e.allowRemoteModels&&!r.local_files_only&&i)try{let c=await az(o);if(c&&c.status>=200&&c.status<300){let u,f=c.headers.get("content-type");if(c.status===206){let m=c.headers.get("content-range");if(m){let _=m.match(/bytes \d+-\d+\/(\d+)/);_&&(u=parseInt(_[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(u===void 0){let m=c.headers.get("content-length");u=m?parseInt(m,10):void 0}return{exists:!0,size:u,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Rr(t){return _e.useFS&&!Nr(t,["http:","https:","blob:"])?new Lr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):_e.fetch(t,{headers:$f(t)})}function $f(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=_e.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Nr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function $r(t,e,r={},s=null){let n=r.revision??"main",o=ho(t,e),a=ZE(t),i=a?ho(_e.localModelPath,o):o,l=ho(_e.remoteHost,_e.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof un?n==="main"?o:ho(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Dr(t,e,r){if(t)return await nA(t,e,r)}async function lz(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>lr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function cz(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:u}=$r(t,e,s,o),f,m=!1,_;_=await Dr(o,i,c);let w=_!==void 0;if(w)f=c;else{if(_e.allowLocalModels)if(Nr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!_e.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{_=await Rr(i),f=i}catch(A){ee.warn(`Unable to load from local path "${i}": "${A}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!_e.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!u)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Rr(l),_.status!==200)return eA(_.status,l,r);f=c}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}lr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let b;if(typeof _!="string")if(!s.progress_callback)b=new Uint8Array(await _.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))b=new Uint8Array(await _.arrayBuffer()),lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:b.length,total:b.length});else{let A,S=_.headers.get("content-length");if(S)A=parseInt(S,10);else try{let M=await Ct(t,e,s);M.size&&(A=M.size)}catch{}b=await tA(_,M=>{lr(s.progress_callback,{status:"progress",name:t,file:e,...M})},A)}x=b}if(m&&f&&typeof _!="string"&&await lz(t,e,o,f,_,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof _!="string"){let b=parseInt(_.headers.get("content-length"),10)||0;lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:b,total:b})}if(lr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof Lr)return _.filePath;let v=await o?.match(f);if(v instanceof Lr)return v.filePath;if(v instanceof Response)return new Uint8Array(await v.arrayBuffer());if(typeof v=="string")return v;throw new Error("Unable to get model file path or buffer.")}var fc=new Map;async function wo(t,e,r=!0,s={},n=!1){if(!_e.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!_e.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}lr(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=fc.get(o);if(!a){let i=await Zt(s?.cache_dir);a=cz(t,e,r,s,n,i).then(l=>(fc.delete(o),l),l=>{throw fc.delete(o),l}),fc.set(o,a)}return await a}async function xo(t,e,r=!0,s={}){let n=await wo(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function st(t,e,r=!0,s={}){let n=await xo(t,e,r,s);return n===null?{}:JSON.parse(n)}function aA(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,u=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=u%e[c]*o[c],u=Math.floor(u/e[c]);a[l]=t[i]}return[a,s]}function Re(t){let e=Pe(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function Bf(t){let e=Pe(t)[0],r=0;for(let o=0;oo-e-s)}function lA(t,e){let r=0;for(let s=0;se+r*r,0))}function yo(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function cA(t){return t>0&&(t&t-1)===0}var dc=class{constructor(e){if(this.size=e|0,this.size<=1||!cA(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l>>1;for(let _=2;_>1;++u){let f=(u+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,_=f*Math.atan2(c,l),w=2*u;o[w]=m*Math.cos(_),o[w+1]=m*Math.sin(_),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new dc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,u=this._a;if(s)for(let f=0;f>1,w=r[_];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function bs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function pA(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function fA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let u=1;u0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var dA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,m=l&1023;if(f===31)c=u|2139095040|m<<13;else if(f===0)if(m===0)c=u;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,c=u|_<<23|m<<13}else c=u|f+112<<23|m<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;opz});var pz={};var Id={};hs(Id,{InferenceSession:()=>_d,TRACE:()=>kc,TRACE_EVENT_BEGIN:()=>jr,TRACE_EVENT_END:()=>qr,TRACE_FUNC_BEGIN:()=>Ms,TRACE_FUNC_END:()=>Ss,Tensor:()=>er,default:()=>Uz,env:()=>Ke,registerBackend:()=>Ts});var dd=Object.defineProperty,fz=Object.getOwnPropertyDescriptor,dz=Object.getOwnPropertyNames,mz=Object.prototype.hasOwnProperty,_z=(t=>typeof _s<"u"?_s:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof _s<"u"?_s:e)[r]}):t)(function(t){if(typeof _s<"u")return _s.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>()=>(t&&(e=t(t=0)),e),So=(t,e)=>{for(var r in e)dd(t,r,{get:e[r],enumerable:!0})},hz=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of dz(e))!mz.call(t,n)&&n!==r&&dd(t,n,{get:()=>e[n],enumerable:!(s=fz(e,n))||s.enumerable});return t},vc=t=>hz(dd({},"__esModule",{value:!0}),t),bo,Br,Ts,mA,FA,GA=be(()=>{"use strict";bo=new Map,Br=[],Ts=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=bo.get(t);if(s===void 0)bo.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Br.indexOf(t);n!==-1&&Br.splice(n,1);for(let o=0;o{let e=bo.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},FA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Br:r,n,o=[],a=new Set;for(let l of s){let c=await mA(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),gz=be(()=>{"use strict";GA()}),jA,wz=be(()=>{"use strict";jA="1.24.0-dev.20251116-b39e144322"}),Ff,ft,qA=be(()=>{"use strict";wz(),Ff="warning",ft={wasm:{},webgl:{},webgpu:{},versions:{common:jA},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Ff=t}},get logLevel(){return Ff}},Object.defineProperty(ft,"logLevel",{enumerable:!0})}),Ke,xz=be(()=>{"use strict";qA(),Ke=ft}),WA,VA,yz=be(()=>{"use strict";WA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;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?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,v=3,b=0,A=f,S=f*2,M=-1;i==="RGBA"?(b=0,A=f,S=f*2,M=f*3):i==="RGB"?(b=0,A=f,S=f*2):i==="RBG"&&(b=0,S=f,A=f*2),s=r.createImageData(n,o);for(let I=0;I{"use strict";md(),_c=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,v=0,b=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(v=0,A=c,b=c*2):l==="BGR"&&(A=0,b=c,v=c*2);for(let M=0;M{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,_c(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(_c(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return _c(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},XA=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Rt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},KA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Rt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},YA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Rt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},QA=(t,e,r)=>new Rt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Es,To,Gf,JA,vz=be(()=>{"use strict";Es=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),To=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Gf=!1,JA=()=>{if(!Gf){Gf=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Es.set("int64",BigInt64Array),To.set(BigInt64Array,"int64")),e&&(Es.set("uint64",BigUint64Array),To.set(BigUint64Array,"uint64")),s?(Es.set("float16",r),To.set(r,"float16")):Es.set("float16",Uint16Array)}}}),ZA,e2,kz=be(()=>{"use strict";md(),ZA=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Rt(t.type,t.data,e);case"cpu-pinned":return new Rt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Rt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Rt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Rt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Rt,md=be(()=>{"use strict";yz(),bz(),vz(),kz(),Rt=class{constructor(t,e,r){JA();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=Es.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=Es.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=To.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=ZA(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return HA(t,e)}static fromTexture(t,e){return XA(t,e)}static fromGpuBuffer(t,e){return KA(t,e)}static fromMLTensor(t,e){return YA(t,e)}static fromPinnedBuffer(t,e,r){return QA(t,e,r)}toDataURL(t){return WA(this,t)}toImageData(t){return VA(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return e2(this,t)}}}),er,t2=be(()=>{"use strict";md(),er=Rt}),kc,jf,Ms,Ss,jr,qr,r2=be(()=>{"use strict";qA(),kc=(t,e)=>{(typeof ft.trace>"u"?!ft.wasm.trace:!ft.trace)||console.timeStamp(`${t}::ORT::${e}`)},jf=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof ft.trace>"u"?!ft.wasm.trace:!ft.trace)||jf("BEGIN",t)},Ss=t=>{(typeof ft.trace>"u"?!ft.wasm.trace:!ft.trace)||jf("END",t)},jr=t=>{(typeof ft.trace>"u"?!ft.wasm.trace:!ft.trace)||console.time(`ORT::${t}`)},qr=t=>{(typeof ft.trace>"u"?!ft.wasm.trace:!ft.trace)||console.timeEnd(`ORT::${t}`)}}),s2,Ez=be(()=>{"use strict";GA(),t2(),r2(),s2=class n2{constructor(e){this.handler=e}async run(e,r,s){Ms(),jr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof er||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,u=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(u.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof er)&&(c=!0,a=!1,n[f]=m)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let u=i[c];u instanceof er?l[c]=u:l[c]=new er(u.type,u.data,u.dims)}return qr("InferenceSession.run"),Ss(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Ms(),jr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,f=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(m=e.byteLength-f,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||f+m>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(u,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await FA(a),c=await i.createInferenceSessionHandler(o,l);return qr("InferenceSession.create"),Ss(),new n2(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}}}),_d,Az=be(()=>{"use strict";Ez(),_d=s2}),Tz=be(()=>{"use strict"}),Mz=be(()=>{"use strict"}),Sz=be(()=>{"use strict"}),Oz=be(()=>{"use strict"}),o2={};So(o2,{InferenceSession:()=>_d,TRACE:()=>kc,TRACE_EVENT_BEGIN:()=>jr,TRACE_EVENT_END:()=>qr,TRACE_FUNC_BEGIN:()=>Ms,TRACE_FUNC_END:()=>Ss,Tensor:()=>er,env:()=>Ke,registerBackend:()=>Ts});var Os=be(()=>{"use strict";gz(),xz(),Az(),t2(),Tz(),Mz(),r2(),Sz(),Oz()}),hd=be(()=>{"use strict"}),a2={};So(a2,{default:()=>i2});var qf,Wf,i2,Iz=be(()=>{"use strict";v2(),Is(),gd(),qf="ort-wasm-proxy-worker",Wf=globalThis.self?.name===qf,Wf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":wd(r.wasm).then(()=>{kd(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;Ed(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Tc(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;Ad(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":Td(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;Md(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},Od([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":Sd(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),i2=Wf?null:t=>new Worker(t??zt,{type:"module",name:qf})}),l2={};So(l2,{default:()=>c2});async function _A(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(p,d)=>{p.startsWith("./")&&(p=p.substring(2)),(e.Uc||(e.Uc=new Map)).set(p,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let o=()=>{let p=d=>(...h)=>{let g=ar;return h=d(...h),ar!=g?new Promise((E,T)=>{of={resolve:E,reject:T}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=p(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(p,d)=>{throw d},c=import.meta.url,u="";if(r||s){try{u=new URL(".",c).href}catch{}s&&(i=p=>{var d=new XMLHttpRequest;return d.open("GET",p,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async p=>{if(O(p))return new Promise((h,g)=>{var E=new XMLHttpRequest;E.open("GET",p,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?h(E.response):g(E.status)},E.onerror=g,E.send(null)});var d=await fetch(p,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,_,w,x,v,b=console.log.bind(console),A=console.error.bind(console),S=b,M=A,I=!1,O=p=>p.startsWith("file://");function k(){Cr.buffer!=F.buffer&&le()}if(n){let p=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let E=[];self.onmessage=T=>E.push(T),v=()=>{postMessage({Oc:"loaded"});for(let T of E)p(T);self.onmessage=p};for(let T of h.de)e[T]&&!e[T].proxy||(e[T]=(...P)=>{postMessage({Oc:"callHandler",ce:T,args:P})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));Cr=h.je,le(),m=h.ke,qe(),ec()}else if(g==="run"){(function(E){var T=(k(),C)[E+52>>>2>>>0];E=(k(),C)[E+56>>>2>>>0],bk(T,T-E),ue(T)})(h.Nc),wf(h.Nc,0,0,1,0,0),lv(),rf(h.Nc),G||(sk(),G=!0);try{DM(h.he,h.Wc)}catch(E){if(E!="unwind")throw E}}else h.target!=="setimmediate"&&(g==="checkMailbox"?G&&Vl():g&&(M(`worker: received unknown command ${g}`),M(h)))}catch(E){throw hk(),E}};var R=p,G=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=p}var F,K,V,Q,U,C,se,Y,L,$,B,J=!1;function le(){var p=Cr.buffer;e.HEAP8=F=new Int8Array(p),V=new Int16Array(p),e.HEAPU8=K=new Uint8Array(p),Q=new Uint16Array(p),e.HEAP32=U=new Int32Array(p),e.HEAPU32=C=new Uint32Array(p),se=new Float32Array(p),Y=new Float64Array(p),L=new BigInt64Array(p),$=new BigUint64Array(p)}function je(){J=!0,n?v():br._b()}function ce(p){throw M(p="Aborted("+p+")"),I=!0,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),x?.(p),p}function At(){return{a:{f:BM,J:UM,k:FM,p:GM,l:jM,ta:qM,b:WM,ca:VM,Ka:mv,q:HM,da:wv,_a:xv,Ga:yv,Ia:bv,$a:vv,Ya:kv,Ra:Ev,Xa:Av,pa:Tv,Ha:Mv,Yb:Sv,Za:Ov,Fa:Iv,eb:XM,Da:YM,Tb:QM,Rb:ZM,Ca:tS,M:rS,I:sS,Sb:nS,ka:pS,Ub:fS,Ua:dS,Wb:_S,La:hS,Pb:gS,la:wS,Ta:rf,bb:xS,U:kS,n:SS,c:ef,sb:OS,w:IS,L:CS,z:PS,j:LS,o:Dv,tb:zS,G:NS,T:RS,h:$S,u:DS,m:BS,i:US,Oa:FS,Pa:GS,Qa:jS,Ma:Gv,Na:jv,Qb:qv,fb:WS,db:XS,Y:KS,rb:YS,ma:QS,cb:VS,gb:JS,ab:ZS,Xb:eO,N:qS,hb:tO,X:rO,Vb:sO,ob:fO,C:dO,sa:mO,ra:_O,qb:hO,W:gO,v:wO,nb:xO,mb:yO,lb:bO,pb:vO,kb:kO,jb:EO,ib:AO,Va:Yv,Wa:Qv,Ja:Zs,ea:Jv,oa:Zv,Sa:ek,na:tk,Db:NI,xa:MI,Eb:zI,ya:TI,F:hI,e:sI,s:tI,x:eI,D:dI,Ib:kI,ba:bI,B:aI,za:EI,$:SI,ha:vI,Fb:PI,Gb:CI,Ba:gI,Aa:yI,Jb:wI,wa:LI,aa:AI,d:rI,A:oI,r:nI,Cb:RI,t:lI,y:mI,H:iI,E:cI,K:_I,S:OI,ja:fI,_:II,Kb:pI,Lb:uI,P:xI,g:MO,a:Cr,Ob:Js,Hb:SO,ia:OO,O:IO,qa:CO,Mb:PO,Q:LO,zb:zO,Ab:NO,ua:RO,fa:$O,R:DO,Ea:BO,va:UO,Z:FO,xb:GO,Zb:jO,V:qO,Bb:WO,ub:VO,vb:XO,wb:KO,ga:YO,yb:QO,Nb:JO}}}async function qe(){function p(g,E){var T=br=g.exports;g={};for(let[P,z]of Object.entries(T))typeof z=="function"?(T=yS(z),g[P]=T):g[P]=z;return br=g,br=(function(){var P=br,z=Z=>Ie=>Z(Ie)>>>0,j=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=z(P.$b),P.Cc=j(P.Cc),P.Ec=z(P.Ec),P.rd=(Z=>(Ie,Ne)=>Z(Ie,Ne)>>>0)(P.rd),P.wd=z(P.wd),P.xd=j(P.xd),P.Bd=z(P.Bd),P})(),av.push(br.id),rk=(g=br).$b,sk=g.ac,e._OrtInit=g.bc,e._OrtGetLastError=g.cc,e._OrtCreateSessionOptions=g.dc,e._OrtAppendExecutionProvider=g.ec,e._OrtAddFreeDimensionOverride=g.fc,e._OrtAddSessionConfigEntry=g.gc,e._OrtReleaseSessionOptions=g.hc,e._OrtCreateSession=g.ic,e._OrtReleaseSession=g.jc,e._OrtGetInputOutputCount=g.kc,e._OrtGetInputOutputMetadata=g.lc,e._OrtFree=g.mc,e._OrtCreateTensor=g.nc,e._OrtGetTensorData=g.oc,e._OrtReleaseTensor=g.pc,e._OrtCreateRunOptions=g.qc,e._OrtAddRunConfigEntry=g.rc,e._OrtReleaseRunOptions=g.sc,e._OrtCreateBinding=g.tc,e._OrtBindInput=g.uc,e._OrtBindOutput=g.vc,e._OrtClearBoundOutputs=g.wc,e._OrtReleaseBinding=g.xc,e._OrtRunWithBinding=g.yc,e._OrtRun=g.zc,e._OrtEndProfiling=g.Ac,ff=e._OrtGetWebGpuDevice=g.Bc,Jl=g.Cc,Xt=e._free=g.Dc,nn=e._malloc=g.Ec,nk=e._wgpuBufferRelease=g.Fc,ok=e._wgpuCreateInstance=g.Gc,ak=g.Hc,ik=g.Ic,lk=g.Jc,ck=g.Kc,uk=g.Lc,pk=g.Pc,fk=g.Zc,dk=g._c,mk=g.$c,df=g.bd,mf=g.cd,_f=g.dd,hf=g.ed,lo=g.fd,gf=g.gd,_k=g.hd,wf=g.kd,hk=g.ld,gk=g.md,wk=g.nd,xf=g.od,xk=g.pd,yk=g.qd,yf=g.rd,xe=g.sd,co=g.td,bk=g.ud,ue=g.vd,Zl=g.wd,pe=g.xd,vk=g.yd,bf=g.zd,kk=g.Ad,Ek=g.Bd,Ak=g.Cd,vf=g.Dd,Tk=g.Ed,Mk=g.Fd,Sk=g.Gd,Ok=g.Hd,Ik=g.Id,Ck=g.Jd,Pk=g.Kd,Lk=g.Ld,zk=g.Md,Nk=g.Nd,Rk=g.Od,$k=g.Pd,Dk=g.Qd,Bk=g.Rd,Uk=g.Td,Fk=g.Ud,Gk=g.Vd,jk=g.Wd,qk=g.Yd,Wk=g.Zd,Vk=g._d,Hk=g.$d,Xk=g.ae,Kk=g.be,Yk=g.pe,Qk=g.qe,Jk=g.re,Zk=g.se,eE=g.te,tE=g.ue,rE=g.ve,sE=g.we,nE=g.xe,oE=g.ye,aE=g.ze,iE=g.Xe,lE=g.Ye,cE=g.Ze,uE=g._e,m=E,br}var d,h=At();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(E,T)=>{g(p(E,T))})}):n?p(new WebAssembly.Instance(m,At()),m):(B??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",u):u+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var E=B;if(!f&&!O(E))try{var T=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(P){M(`wasm streaming compile failed: ${P}`),M("falling back to ArrayBuffer instantiation")}return(async function(P,z){try{var j=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==B&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(j,z)}catch(Z){M(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(E,g)})(h),p(d.instance,d.module))}class lt{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var Tt=p=>{p.terminate(),p.onmessage=()=>{}},Be=[],Se=0,rt=null,nr=p=>{Ir.length==0&&(uv(),cv(Ir[0]));var d=Ir.pop();if(!d)return 6;oo.push(d),fs[p.Nc]=d,d.Nc=p.Nc;var h={Oc:"run",he:p.ge,Wc:p.Wc,Nc:p.Nc};return d.postMessage(h,p.Yc),0},Oe=0,Ue=(p,d,...h)=>{var g,E=16*h.length,T=pe(),P=Zl(E),z=P>>>3;for(g of h)typeof g=="bigint"?((k(),L)[z++>>>0]=1n,(k(),L)[z++>>>0]=g):((k(),L)[z++>>>0]=0n,(k(),Y)[z++>>>0]=g);return p=gk(p,0,E,P,d),ue(T),p};function Js(p){if(n)return Ue(0,1,p);if(_=p,!(0{if(_=p,n)throw no(p),"unwind";Js(p)},Ir=[],oo=[],av=[],fs={},iv=p=>{var d=p.Nc;delete fs[d],Ir.push(p),oo.splice(oo.indexOf(p),1),p.Nc=0,wk(d)};function lv(){av.forEach(p=>p())}var cv=p=>new Promise(d=>{p.onmessage=E=>{var T=E.data;if(E=T.Oc,T.Vc&&T.Vc!=Jl()){var P=fs[T.Vc];P?P.postMessage(T,T.Yc):M(`Internal error! Worker sent a message "${E}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else E==="checkMailbox"?Vl():E==="spawnThread"?nr(T):E==="cleanupThread"?St(()=>{iv(fs[T.ie])}):E==="loaded"?(p.loaded=!0,d(p)):T.target==="setimmediate"?p.postMessage(T):E==="uncaughtException"?p.onerror(T.error):E==="callHandler"?e[T.ce](...T.args):E&&M(`worker sent an unknown command ${E}`)},p.onerror=E=>{throw M(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);p.postMessage({Oc:"load",de:g,je:Cr,ke:m})});function uv(){var p=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ir.push(p)}var Cr,DM=(p,d)=>{Oe=0,p=vf(p,d),0-9007199254740992>p||9007199254740992>>=0);return(k(),F)[d.Qc+12>>>0]==0&&(pv(d,!0),Wl--),fv(d,!1),ql.push(d),Ek(p)}var en=0,UM=()=>{xe(0,0);var p=ql.pop();vk(p.Xc),en=0};function pv(p,d){d=d?1:0,(k(),F)[p.Qc+12>>>0]=d}function fv(p,d){d=d?1:0,(k(),F)[p.Qc+13>>>0]=d}class Yp{constructor(d){this.Xc=d,this.Qc=d-24}}var Qp=p=>{var d=en;if(!d)return co(0),0;var h=new Yp(d);(k(),C)[h.Qc+16>>>2>>>0]=d;var g=(k(),C)[h.Qc+4>>>2>>>0];if(!g)return co(0),d;for(var E of p){if(E===0||E===g)break;if(kk(E,g,h.Qc+16))return co(E),d}return co(g),d};function FM(){return Qp([])}function GM(p){return Qp([p>>>0])}function jM(p,d,h,g){return Qp([p>>>0,d>>>0,h>>>0,g>>>0])}var qM=()=>{var p=ql.pop();p||ce("no exception to throw");var d=p.Xc;throw(k(),F)[p.Qc+13>>>0]==0&&(ql.push(p),fv(p,!0),pv(p,!1),Wl++),bf(d),en=d};function WM(p,d,h){var g=new Yp(p>>>=0);throw d>>>=0,h>>>=0,(k(),C)[g.Qc+16>>>2>>>0]=0,(k(),C)[g.Qc+4>>>2>>>0]=d,(k(),C)[g.Qc+8>>>2>>>0]=h,bf(p),Wl++,en=p}var VM=()=>Wl;function dv(p,d,h,g){return n?Ue(2,1,p,d,h,g):mv(p,d,h,g)}function mv(p,d,h,g){if(p>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return n&&E.length===0?dv(p,d,h,g):(p={ge:h,Nc:p,Wc:g,Yc:E},n?(p.Oc="spawnThread",postMessage(p,E),0):nr(p))}function HM(p){throw en||=p>>>0,en}var _v=globalThis.TextDecoder&&new TextDecoder,hv=(p,d,h,g)=>{if(h=d+h,g)return h;for(;p[d]&&!(d>=h);)++d;return d},gv=(p,d=0,h,g)=>{if(16<(h=hv(p,d>>>=0,h,g))-d&&p.buffer&&_v)return _v.decode(p.buffer instanceof ArrayBuffer?p.subarray(d,h):p.slice(d,h));for(g="";d(E=(240&E)==224?(15&E)<<12|T<<6|P:(7&E)<<18|T<<12|P<<6|63&p[d++])?g+=String.fromCharCode(E):(E-=65536,g+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else g+=String.fromCharCode(E)}return g},tn=(p,d,h)=>(p>>>=0)?gv((k(),K),p,d,h):"";function wv(p,d,h){return n?Ue(3,1,p,d,h):0}function xv(p,d){if(n)return Ue(4,1,p,d)}function yv(p,d){if(n)return Ue(5,1,p,d)}function bv(p,d,h){if(n)return Ue(6,1,p,d,h)}function vv(p,d,h){return n?Ue(7,1,p,d,h):0}function kv(p,d){if(n)return Ue(8,1,p,d)}function Ev(p,d,h){if(n)return Ue(9,1,p,d,h)}function Av(p,d,h,g){if(n)return Ue(10,1,p,d,h,g)}function Tv(p,d,h,g){if(n)return Ue(11,1,p,d,h,g)}function Mv(p,d,h,g){if(n)return Ue(12,1,p,d,h,g)}function Sv(p){if(n)return Ue(13,1,p)}function Ov(p,d){if(n)return Ue(14,1,p,d)}function Iv(p,d,h){if(n)return Ue(15,1,p,d,h)}var XM=()=>ce(""),or=p=>{p>>>=0;for(var d="";;){var h=(k(),K)[p++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},Jp={},Zp={},KM={},rn=class extends Error{constructor(p){super(p),this.name="BindingError"}};function hr(p,d,h={}){return(function(g,E,T={}){var P=E.name;if(!g)throw new rn(`type "${P}" must have a positive integer typeid pointer`);if(Zp.hasOwnProperty(g)){if(T.ee)return;throw new rn(`Cannot register type '${P}' twice`)}Zp[g]=E,delete KM[g],Jp.hasOwnProperty(g)&&(E=Jp[g],delete Jp[g],E.forEach(z=>z()))})(p,d,h)}var Cv=(p,d,h)=>{switch(d){case 1:return h?g=>(k(),F)[g>>>0]:g=>(k(),K)[g>>>0];case 2:return h?g=>(k(),V)[g>>>1>>>0]:g=>(k(),Q)[g>>>1>>>0];case 4:return h?g=>(k(),U)[g>>>2>>>0]:g=>(k(),C)[g>>>2>>>0];case 8:return h?g=>(k(),L)[g>>>3>>>0]:g=>(k(),$)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${p}`)}};function YM(p,d,h,g,E){p>>>=0,h>>>=0,d=or(d>>>0);let T=P=>P;if(g=g===0n){let P=8*h;T=z=>BigInt.asUintN(P,z),E=T(E)}hr(p,{name:d,Mc:T,Sc:(P,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Rc:Cv(d,h,!g),Tc:null})}function QM(p,d,h,g){hr(p>>>=0,{name:d=or(d>>>0),Mc:function(E){return!!E},Sc:function(E,T){return T?h:g},Rc:function(E){return this.Mc((k(),K)[E>>>0])},Tc:null})}var Pv=[],ds=[0,1,,1,null,1,!0,1,!1,1];function ef(p){9<(p>>>=0)&&--ds[p+1]==0&&(ds[p]=void 0,Pv.push(p))}var Bt=p=>{if(!p)throw new rn(`Cannot use deleted val. handle = ${p}`);return ds[p]},Ht=p=>{switch(p){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Pv.pop()||ds.length;return ds[d]=p,ds[d+1]=1,d}};function tf(p){return this.Mc((k(),C)[p>>>2>>>0])}var JM={name:"emscripten::val",Mc:p=>{var d=Bt(p);return ef(p),d},Sc:(p,d)=>Ht(d),Rc:tf,Tc:null};function ZM(p){return hr(p>>>0,JM)}var eS=(p,d)=>{switch(d){case 4:return function(h){return this.Mc((k(),se)[h>>>2>>>0])};case 8:return function(h){return this.Mc((k(),Y)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${p}`)}};function tS(p,d,h){h>>>=0,hr(p>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,E)=>E,Rc:eS(d,h),Tc:null})}function rS(p,d,h,g,E){p>>>=0,h>>>=0,d=or(d>>>0);let T=z=>z;if(g===0){var P=32-8*h;T=z=>z<

>>P,E=T(E)}hr(p,{name:d,Mc:T,Sc:(z,j)=>j,Rc:Cv(d,h,g!==0),Tc:null})}function sS(p,d,h){function g(T){var P=(k(),C)[T>>>2>>>0];return T=(k(),C)[T+4>>>2>>>0],new E((k(),F).buffer,T,P)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];hr(p>>>=0,{name:h=or(h>>>0),Mc:g,Rc:g},{ee:!0})}var gr=(p,d,h)=>{var g=(k(),K);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,T++}}g[d>>>0]=0,p=d-E}else p=0;return p},wr=p=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function nS(p,d){hr(p>>>=0,{name:d=or(d>>>0),Mc(h){var g=(k(),C)[h>>>2>>>0];return g=tn(h+4,g,!0),Xt(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var E=typeof g=="string";if(!(E||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new rn("Cannot pass non-string to std::string");var T=E?wr(g):g.length,P=nn(4+T+1),z=P+4;return(k(),C)[P>>>2>>>0]=T,E?gr(g,z,T+1):(k(),K).set(g,z>>>0),h!==null&&h.push(Xt,P),P},Rc:tf,Tc(h){Xt(h)}})}var Lv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,oS=(p,d,h)=>{if(p>>>=1,16<(d=hv((k(),Q),p,d/2,h))-p&&Lv)return Lv.decode((k(),Q).slice(p,d));for(h="";p>>0];h+=String.fromCharCode(g)}return h},aS=(p,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*p.length?h/2:p.length;for(var E=0;E>>1>>>0]=T,d+=2}return(k(),V)[d>>>1>>>0]=0,d-g},iS=p=>2*p.length,lS=(p,d,h)=>{var g="";p>>>=2;for(var E=0;!(E>=d/4);E++){var T=(k(),C)[p+E>>>0];if(!T&&!h)break;g+=String.fromCodePoint(T)}return g},cS=(p,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var E=0;E>>2>>>0]=T,(d+=4)+4>h)break}return(k(),U)[d>>>2>>>0]=0,d-g},uS=p=>{for(var d=0,h=0;h>>=0,d>>>=0,h=or(h>>>=0),d===2)var g=oS,E=aS,T=iS;else g=lS,E=cS,T=uS;hr(p,{name:h,Mc:P=>{var z=(k(),C)[P>>>2>>>0];return z=g(P+4,z*d,!0),Xt(P),z},Sc:(P,z)=>{if(typeof z!="string")throw new rn(`Cannot pass non-string to C++ string type ${h}`);var j=T(z),Z=nn(4+j+d);return(k(),C)[Z>>>2>>>0]=j/d,E(z,Z+4,j+d),P!==null&&P.push(Xt,Z),Z},Rc:tf,Tc(P){Xt(P)}})}function fS(p,d){hr(p>>>=0,{fe:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function dS(p){wf(p>>>0,!s,1,!r,131072,!1),lv()}var St=p=>{if(!I)try{if(p(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function rf(p){p>>>=0,mS||(Atomics.waitAsync((k(),U),p>>>2,p).value.then(Vl),p+=128,Atomics.store((k(),U),p>>>2,1))}var Vl=()=>St(()=>{var p=Jl();p&&(rf(p),yk())});function _S(p,d){(p>>>=0)==d>>>0?setTimeout(Vl):n?postMessage({Vc:p,Oc:"checkMailbox"}):(p=fs[p])&&p.postMessage({Oc:"checkMailbox"})}var sf=[];function hS(p,d,h,g,E){for(d>>>=0,E>>>=0,sf.length=0,h=E>>>3,g=E+g>>>3;h>>0]?(k(),L)[h++>>>0]:(k(),Y)[h++>>>0],sf.push(T)}return(d?kf[d]:ZO[p])(...sf)}var gS=()=>{Oe=0};function wS(p){p>>>=0,n?postMessage({Oc:"cleanupThread",ie:p}):iv(fs[p])}function xS(p){}var Hl=p=>{try{p()}catch(d){ce(d)}};function yS(p){var d=(...h)=>{Xl.push(p);try{return p(...h)}finally{I||(Xl.pop(),ar&&Pr===1&&Xl.length===0&&(Pr=0,Oe+=1,Hl(lE),typeof Fibers<"u"&&Fibers.De()))}};return Rv.set(p,d),d}var Pr=0,ar=null,zv=0,Xl=[],nf=new Map,Nv=new Map,Rv=new Map,bS=0,of=null,vS=[],$v=p=>(function(d){if(!I){if(Pr===0){var h=!1,g=!1;d((E=0)=>{if(!I&&(zv=E,h=!0,g)){Pr=2,Hl(()=>cE(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),E=!1;try{var T=(function(){var j=(k(),U)[ar+8>>>2>>>0];return j=Nv.get(j),j=Rv.get(j),--Oe,j()})()}catch(j){T=j,E=!0}var P=!1;if(!ar){var z=of;z&&(of=null,(E?z.reject:z.resolve)(T),P=!0)}if(E&&!P)throw T}}),g=!0,h||(Pr=1,ar=(function(){var E=nn(65548),T=E+12;if((k(),C)[E>>>2>>>0]=T,(k(),C)[E+4>>>2>>>0]=T+65536,T=Xl[0],!nf.has(T)){var P=bS++;nf.set(T,P),Nv.set(P,T)}return T=nf.get(T),(k(),U)[E+8>>>2>>>0]=T,E})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Hl(()=>iE(ar)))}else Pr===2?(Pr=0,Hl(uE),Xt(ar),ar=null,vS.forEach(St)):ce(`invalid state: ${Pr}`);return zv}})(d=>{p().then(d)});function kS(p){return p>>>=0,$v(async()=>{var d=await Bt(p);return Ht(d)})}var af=[],ES=p=>{var d=af.length;return af.push(p),d},AS=(p,d)=>{for(var h=Array(p),g=0;g>>2>>>0],P=Zp[T];if(P===void 0)throw p=`parameter ${g}`,T=rk(T),d=or(T),Xt(T),new rn(`${p} has unknown type ${d}`);h[E]=P}return h},TS=(p,d,h)=>{var g=[];return p=p(g,h),g.length&&((k(),C)[d>>>2>>>0]=Ht(g)),p},MS={},Kl=p=>{var d=MS[p];return d===void 0?or(p):d};function SS(p,d,h){var[g,...E]=AS(p,d>>>0);d=g.Sc.bind(g);var T=E.map(j=>j.Rc.bind(j));p--;var P={toValue:Bt};switch(p=T.map((j,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=j,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:P.getStringOrSymbol=Kl,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${p})`,g.fe||(P.toReturnWire=d,P.emval_returnValue=TS,z=`return emval_returnValue(toReturnWire, destructorsRef, ${z})`),z=`return function (handle, methodName, destructorsRef, args) { ${z} }`,h=new Function(Object.keys(P),z)(...Object.values(P)),z=`methodCaller<(${E.map(j=>j.name)}) => ${g.name}>`,ES(Object.defineProperty(h,"name",{value:z}))}function OS(p,d){return d>>>=0,(p=Bt(p>>>0))==Bt(d)}function IS(p){return(p>>>=0)?(p=Kl(p),Ht(globalThis[p])):Ht(globalThis)}function CS(p){return p=Kl(p>>>0),Ht(e[p])}function PS(p,d){return d>>>=0,p=Bt(p>>>0),d=Bt(d),Ht(p[d])}function LS(p){9<(p>>>=0)&&(ds[p+1]+=1)}function Dv(p,d,h,g,E){return af[p>>>0](d>>>0,h>>>0,g>>>0,E>>>0)}function zS(p,d,h,g,E){return Dv(p>>>0,d>>>0,h>>>0,g>>>0,E>>>0)}function NS(){return Ht([])}function RS(p){p=Bt(p>>>0);for(var d=Array(p.length),h=0;h>>0))}function DS(){return Ht({})}function BS(p){for(var d=Bt(p>>>=0);d.length;){var h=d.pop();d.pop()(h)}ef(p)}function US(p,d,h){d>>>=0,h>>>=0,p=Bt(p>>>0),d=Bt(d),h=Bt(h),p[d]=h}function FS(p,d){p=Mt(p),d>>>=0,p=new Date(1e3*p),(k(),U)[d>>>2>>>0]=p.getUTCSeconds(),(k(),U)[d+4>>>2>>>0]=p.getUTCMinutes(),(k(),U)[d+8>>>2>>>0]=p.getUTCHours(),(k(),U)[d+12>>>2>>>0]=p.getUTCDate(),(k(),U)[d+16>>>2>>>0]=p.getUTCMonth(),(k(),U)[d+20>>>2>>>0]=p.getUTCFullYear()-1900,(k(),U)[d+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(k(),U)[d+28>>>2>>>0]=p}var Bv=p=>p%4==0&&(p%100!=0||p%400==0),Uv=[0,31,60,91,121,152,182,213,244,274,305,335],Fv=[0,31,59,90,120,151,181,212,243,273,304,334];function GS(p,d){p=Mt(p),d>>>=0,p=new Date(1e3*p),(k(),U)[d>>>2>>>0]=p.getSeconds(),(k(),U)[d+4>>>2>>>0]=p.getMinutes(),(k(),U)[d+8>>>2>>>0]=p.getHours(),(k(),U)[d+12>>>2>>>0]=p.getDate(),(k(),U)[d+16>>>2>>>0]=p.getMonth(),(k(),U)[d+20>>>2>>>0]=p.getFullYear()-1900,(k(),U)[d+24>>>2>>>0]=p.getDay();var h=(Bv(p.getFullYear())?Uv:Fv)[p.getMonth()]+p.getDate()-1|0;(k(),U)[d+28>>>2>>>0]=h,(k(),U)[d+36>>>2>>>0]=-60*p.getTimezoneOffset(),h=new Date(p.getFullYear(),6,1).getTimezoneOffset();var g=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=0|(h!=g&&p.getTimezoneOffset()==Math.min(g,h)),(k(),U)[d+32>>>2>>>0]=p}function jS(p){p>>>=0;var d=new Date((k(),U)[p+20>>>2>>>0]+1900,(k(),U)[p+16>>>2>>>0],(k(),U)[p+12>>>2>>>0],(k(),U)[p+8>>>2>>>0],(k(),U)[p+4>>>2>>>0],(k(),U)[p>>>2>>>0],0),h=(k(),U)[p+32>>>2>>>0],g=d.getTimezoneOffset(),E=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(T,E);return 0>h?(k(),U)[p+32>>>2>>>0]=+(E!=T&&P==g):0>>2>>>0]=d.getDay(),h=(Bv(d.getFullYear())?Uv:Fv)[d.getMonth()]+d.getDate()-1|0,(k(),U)[p+28>>>2>>>0]=h,(k(),U)[p>>>2>>>0]=d.getSeconds(),(k(),U)[p+4>>>2>>>0]=d.getMinutes(),(k(),U)[p+8>>>2>>>0]=d.getHours(),(k(),U)[p+12>>>2>>>0]=d.getDate(),(k(),U)[p+16>>>2>>>0]=d.getMonth(),(k(),U)[p+20>>>2>>>0]=d.getYear(),p=d.getTime(),BigInt(isNaN(p)?-1:p/1e3)}function Gv(p,d,h,g,E,T,P){return n?Ue(16,1,p,d,h,g,E,T,P):-52}function jv(p,d,h,g,E,T){if(n)return Ue(17,1,p,d,h,g,E,T)}var ao={},qS=()=>performance.timeOrigin+performance.now();function qv(p,d){if(n)return Ue(18,1,p,d);if(ao[p]&&(clearTimeout(ao[p].id),delete ao[p]),!d)return 0;var h=setTimeout(()=>{delete ao[p],St(()=>xk(p,performance.timeOrigin+performance.now()))},d);return ao[p]={id:h,Ce:d},0}function WS(p,d,h,g){p>>>=0,d>>>=0,h>>>=0,g>>>=0;var E=new Date().getFullYear(),T=new Date(E,0,1).getTimezoneOffset();E=new Date(E,6,1).getTimezoneOffset();var P=Math.max(T,E);(k(),C)[p>>>2>>>0]=60*P,(k(),U)[d>>>2>>>0]=+(T!=E),p=(d=z=>{var j=Math.abs(z);return`UTC${0<=z?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`})(T),d=d(E),EDate.now(),HS=1;function XS(p,d,h){if(h>>>=0,!(0<=p&&3>=p))return 28;if(p===0)p=Date.now();else{if(!HS)return 52;p=performance.timeOrigin+performance.now()}return p=Math.round(1e6*p),(k(),L)[h>>>3>>>0]=BigInt(p),0}var lf=[],Wv=(p,d)=>{lf.length=0;for(var h;h=(k(),K)[p++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,lf.push(h==112?(k(),C)[d>>>2>>>0]:h==106?(k(),L)[d>>>3>>>0]:h==105?(k(),U)[d>>>2>>>0]:(k(),Y)[d>>>3>>>0]),d+=g?8:4}return lf};function KS(p,d,h){return p>>>=0,d=Wv(d>>>0,h>>>0),kf[p](...d)}function YS(p,d,h){return p>>>=0,d=Wv(d>>>0,h>>>0),kf[p](...d)}var QS=()=>{};function JS(p,d){return M(tn(p>>>0,d>>>0))}var ZS=()=>{throw Oe+=1,"unwind"};function eO(){return 4294901760}var tO=()=>1,rO=()=>navigator.hardwareConcurrency;function sO(p){p>>>=0;var d=(k(),K).length;if(p<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,p+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(p,g)/65536))-Cr.buffer.byteLength+65535)/65536|0;try{Cr.grow(g),le();var E=1;break e}catch{}E=void 0}if(E)return!0}return!1}var ir=p=>{var d=wr(p)+1,h=Zl(d);return gr(p,h,d),h},cf=(p,d)=>{(k(),C)[p>>>2>>>0]=d;var h=(k(),C)[p>>>2>>>0];(k(),C)[p+4>>>2>>>0]=(d-h)/4294967296},io=p=>(k(),C)[p>>>2>>>0]+4294967296*(k(),U)[p+4>>>2>>>0],mt=[],nO=(p,d)=>{mt[p>>>0]=d},xr=[],Yl=[],sn=(p,d)=>{Yl[p]=new Promise(h=>d.finally(()=>h(p)))},oe=p=>{if(p)return mt[p>>>0]},oO=(p,d)=>{for(p=(k(),C)[p>>>2>>>0];p;p=(k(),C)[p>>>2>>>0])d[(k(),U)[p+4>>>2>>>0]](p)},Ql=(p,d,h)=>{(k(),C)[p>>>2>>>0]=d,(k(),C)[p+4>>>2>>>0]=h},Vv=p=>{var d=(k(),C)[p>>>2>>>0];return p=(k(),C)[p+4>>>2>>>0],tn(d,p)},yr=p=>{var d=(k(),C)[p>>>2>>>0];return p=(k(),C)[p+4>>>2>>>0],d?tn(d,p):p===0?"":void 0},aO=p=>{var d=yr(p+4),h=(h=(k(),C)[p+12>>>2>>>0])?oe(h):"auto";if(p+=16){var g=oe((k(),C)[p+4>>>2>>>0]),E=(k(),C)[p+16>>>2>>>0],T=(k(),C)[p+20>>>2>>>0];if(E){for(var P={},z=0;z>>3>>>0]}E=P}else E=void 0;p={module:g,constants:E,entryPoint:yr(p+8)}}else p=void 0;return{label:d,layout:h,compute:p}},Hv=(p,d)=>{function h(g,E){g=p[g],(k(),C)[d+E>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),cf(d+64,p.maxUniformBufferBindingSize),cf(d+72,p.maxStorageBufferBindingSize),h("maxVertexBuffers",88),cf(d+96,p.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),p.Ae!==void 0&&h("maxImmediateSize",148)},iO=[,"validation","out-of-memory","internal"],lO=[,"compatibility","core"],Xv={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},cO=[,"low-power","high-performance"],uO=[,"occlusion","timestamp"],pO={undefined:1,unknown:1,destroyed:2};function fO(p,d,h,g,E,T){d=Mt(d),h=Mt(h),g>>>=0,E>>>=0,T>>>=0;var P=oe(p>>>0);if(p={},T){var z=(k(),C)[T+12>>>2>>>0];if(z){var j=(k(),C)[T+16>>>2>>>0];p.requiredFeatures=Array.from((k(),C).subarray(j>>>2>>>0,j+4*z>>>2>>>0),ae=>Xv[ae])}var Z=(k(),C)[T+20>>>2>>>0];if(Z){let ae=function(Ot,ut,ms=!1){ut=Z+ut,(ut=(k(),C)[ut>>>2>>>0])==4294967295||ms&&ut==0||(Fe[Ot]=ut)},ct=function(Ot,ut){ut=Z+ut;var ms=(k(),C)[ut>>>2>>>0],$I=(k(),C)[ut+4>>>2>>>0];ms==4294967295&&$I==4294967295||(Fe[Ot]=io(ut))};var Ie=ae,Ne=ct,Fe={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),ct("maxUniformBufferBindingSize",64),ct("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),ct("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),p.requiredLimits=Fe}(z=(k(),C)[T+24>>>2>>>0])&&(z={label:yr(z+4)},p.defaultQueue=z),p.label=yr(T+4)}Oe+=1,sn(d,P.requestDevice(p).then(ae=>{--Oe,St(()=>{mt[E>>>0]=ae.queue,mt[g>>>0]=ae,Oe+=1,sn(h,ae.lost.then(ct=>{St(()=>{ae.onuncapturederror=()=>{};var Ot=pe(),ut=ir(ct.message);mf(h,pO[ct.reason],ut),ue(Ot)}),--Oe})),ae.onuncapturederror=ct=>{var Ot=5;ct.error instanceof GPUValidationError?Ot=2:ct.error instanceof GPUOutOfMemoryError?Ot=3:ct.error instanceof GPUInternalError&&(Ot=4);var ut=pe();ct=ir(ct.error.message),_k(g,Ot,ct),ue(ut)},"adapterInfo"in ae||(ae.adapterInfo=P.info),gf(d,1,g,0)})},ae=>{--Oe,St(()=>{var ct=pe(),Ot=ir(ae.message);gf(d,3,g,Ot),h&&mf(h,4,Ot),ue(ct)})}))}function dO(p){var d=oe(p>>>=0),h=xr[p];if(h){for(var g=0;g>>=0;var g=oe(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=yf(16,E.byteLength);return(k(),K).set(new Uint8Array(E),T>>>0),xr[p].push(()=>Xt(T)),T}function _O(p,d,h){h>>>=0;var g=oe(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=yf(16,E.byteLength);return(k(),K).fill(0,T,E.byteLength),xr[p].push(()=>{new Uint8Array(E).set((k(),K).subarray(T>>>0,T+E.byteLength>>>0)),Xt(T)}),T}function hO(p,d,h,g,E){p>>>=0,d=Mt(d),h=Mt(h),E>>>=0;var T=oe(p);xr[p]=[],E==4294967295&&(E=void 0),Oe+=1,sn(d,T.mapAsync(h,g>>>0,E).then(()=>{--Oe,St(()=>{_f(d,1,0)})},P=>{--Oe,St(()=>{pe();var z=ir(P.message);_f(d,P.name==="AbortError"?4:P.name==="OperationError"?3:0,z),delete xr[p]})}))}function gO(p){var d=oe(p>>>=0),h=xr[p];if(h){for(var g=0;g>>0]}function xO(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=!!(k(),C)[d+32>>>2>>>0];d={label:yr(d+4),usage:(k(),C)[d+16>>>2>>>0],size:io(d+24),mappedAtCreation:g},p=oe(p);try{var E=p.createBuffer(d)}catch{return!1}return mt[h>>>0]=E,g&&(xr[h]=[]),!0}function yO(p,d,h,g){p>>>=0,d=Mt(d),g>>>=0,h=aO(h>>>0),p=oe(p),Oe+=1,sn(d,p.createComputePipelineAsync(h).then(E=>{--Oe,St(()=>{mt[g>>>0]=E,df(d,1,g,0)})},E=>{--Oe,St(()=>{var T=pe(),P=ir(E.message);df(d,E.reason==="validation"?3:E.reason==="internal"?4:0,g,P),ue(T)})}))}function bO(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=(k(),C)[d>>>2>>>0],E=(k(),U)[g+4>>>2>>>0];d={label:yr(d+4),code:""},E===2&&(d.code=Vv(g+8)),p=oe(p).createShaderModule(d),mt[h>>>0]=p}var vO=p=>{(p=oe(p)).onuncapturederror=null,p.destroy()};function kO(p,d){d=Mt(d),p=oe(p>>>0),Oe+=1,sn(d,p.popErrorScope().then(h=>{--Oe,St(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var E=pe(),T=h?ir(h.message):0;hf(d,1,g,T),ue(E)})},h=>{--Oe,St(()=>{var g=pe(),E=ir(h.message);hf(d,1,5,E),ue(g)})}))}function EO(p,d,h,g){if(d=Mt(d),g>>>=0,h>>>=0){var E={featureLevel:lO[(k(),U)[h+4>>>2>>>0]],powerPreference:cO[(k(),U)[h+8>>>2>>>0]],forceFallbackAdapter:!!(k(),C)[h+12>>>2>>>0]};(p=(k(),C)[h>>>2>>>0])!==0&&(k(),E.Fe=!!(k(),C)[p+8>>>2>>>0])}"gpu"in navigator?(Oe+=1,sn(d,navigator.gpu.requestAdapter(E).then(T=>{--Oe,St(()=>{if(T)mt[g>>>0]=T,lo(d,1,g,0);else{var P=pe(),z=ir("WebGPU not available on this browser (requestAdapter returned null)");lo(d,3,g,z),ue(P)}})},T=>{--Oe,St(()=>{var P=pe(),z=ir(T.message);lo(d,4,g,z),ue(P)})}))):(E=pe(),p=ir("WebGPU not available on this browser (navigator.gpu is not available)"),lo(d,3,g,p),ue(E))}function AO(p,d,h){return p>>>=0,d>>>=0,h>>>=0,$v(async()=>{var g=[];if(h){var E=(k(),U)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(z=>setTimeout(z,E,0))}else g.length=d;for(var T=0;T{if(!uf){var p,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(p in pf)pf[p]===void 0?delete d[p]:d[p]=pf[p];var h=[];for(p in d)h.push(`${p}=${d[p]}`);uf=h}return uf};function Yv(p,d){if(n)return Ue(19,1,p,d);p>>>=0,d>>>=0;var h,g=0,E=0;for(h of Kv()){var T=d+g;(k(),C)[p+E>>>2>>>0]=T,g+=gr(h,T,1/0)+1,E+=4}return 0}function Qv(p,d){if(n)return Ue(20,1,p,d);p>>>=0,d>>>=0;var h=Kv();for(var g of((k(),C)[p>>>2>>>0]=h.length,p=0,h))p+=wr(g)+1;return(k(),C)[d>>>2>>>0]=p,0}function Jv(p){return n?Ue(21,1,p):52}function Zv(p,d,h,g){return n?Ue(22,1,p,d,h,g):52}function ek(p,d,h,g){return n?Ue(23,1,p,d,h,g):70}var TO=[null,[],[]];function tk(p,d,h,g){if(n)return Ue(24,1,p,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var E=0,T=0;T>>2>>>0],z=(k(),C)[d+4>>>2>>>0];d+=8;for(var j=0;j>>0],Ne=TO[Z];Ie===0||Ie===10?((Z===1?S:M)(gv(Ne)),Ne.length=0):Ne.push(Ie)}E+=z}return(k(),C)[g>>>2>>>0]=E,0}function MO(p){return p>>>0}function SO(p,d){return Hv(oe(p>>>0).limits,d>>>0),1}function OO(p,d){return oe(p>>>0).features.has(Xv[d])}function IO(p){return BigInt(oe(p>>>0).size)}function CO(p){return BigInt(oe(p>>>0).usage)}function PO(p,d){if(p>>>=0,d>>>=0){var h=yr(d+4);h={label:h,timestampWrites:d=(d=(k(),C)[d+12>>>2>>>0])!==0?{querySet:oe((k(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(k(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(k(),C)[d+12>>>2>>>0]}:void 0}}return d=oe(p),p=uk(0),h=d.beginComputePass(h),mt[p>>>0]=h,p}function LO(p,d,h,g,E,T){h=Mt(h),E=Mt(E),T=Mt(T),oe(p>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),E,T)}function zO(p){var d=oe(p>>>0);return p=lk(0),d=d.finish(),mt[p>>>0]=d,p}function NO(p,d,h,g,E,T){T=Mt(T),oe(p>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(E>>>0),T)}function RO(p,d,h,g){oe(p>>>0).dispatchWorkgroups(d,h,g)}function $O(p,d,h){h=Mt(h),oe(p>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function DO(p){oe(p>>>0).end()}function BO(p,d,h,g,E){g>>>=0,E>>>=0,p=oe(p>>>0),h=oe(h>>>0),g==0?p.setBindGroup(d,h):p.setBindGroup(d,h,(k(),C),E>>>2,g)}function UO(p,d){oe(p>>>0).setPipeline(oe(d>>>0))}function FO(p,d,h){oe(p>>>0).Ee(oe(d>>>0),h)}function GO(p,d){var h=oe(p>>>0);return p=ik(0),d=h.getBindGroupLayout(d),mt[p>>>0]=d,p}function jO(p,d){function h(E){var T=(k(),C)[E+8>>>2>>>0],P=(k(),C)[E+32>>>2>>>0],z=(k(),C)[E+36>>>2>>>0],j=0;return oO(E,{327681:Z=>{j=(k(),C)[Z+8>>>2>>>0]}}),T?((P=io(E+24))==-1&&(P=void 0),T={buffer:oe(T),offset:io(E+16),size:P}):T=oe(P||z||j),{binding:(k(),C)[E+4>>>2>>>0],resource:T}}p>>>=0,d={label:yr(4+(d>>>=0)),layout:oe((k(),C)[d+12>>>2>>>0]),entries:(function(E,T){for(var P=[],z=0;z>>2>>>0],(k(),C)[d+20>>>2>>>0])},p=oe(p);var g=ak(0);return nO(g,p.createBindGroup(d)),g}function qO(p,d){var h;return p>>>=0,(d>>>=0)&&(h={label:yr(d+4)}),d=oe(p),p=ck(0),h=d.createCommandEncoder(h),mt[p>>>0]=h,p}function WO(p,d){p>>>=0,d>>>=0,d={type:uO[(k(),U)[d+12>>>2>>>0]],count:(k(),C)[d+16>>>2>>>0]};var h=oe(p);return p=pk(0),d=h.createQuerySet(d),mt[p>>>0]=d,p}function VO(p,d){p=oe(p>>>0).adapterInfo,d>>>=0,(k(),C)[d+52>>>2>>>0]=p.subgroupMinSize,(k(),C)[d+56>>>2>>>0]=p.subgroupMaxSize;var h=p.vendor+p.architecture+p.device+p.description,g=wr(h)+1,E=nn(g);return E&&gr(h,E,g),h=E,g=wr(p.vendor),Ql(d+4,h,g),h+=g,g=wr(p.architecture),Ql(d+12,h,g),h+=g,g=wr(p.device),Ql(d+20,h,g),Ql(d+28,h+g,wr(p.description)),(k(),U)[d+36>>>2>>>0]=2,p=p.isFallbackAdapter?3:4,(k(),U)[d+40>>>2>>>0]=p,(k(),C)[d+44>>>2>>>0]=0,(k(),C)[d+48>>>2>>>0]=0,1}var HO={"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 XO(p,d){d>>>=0;var h=oe(p>>>0);p=nn(4*h.features.size);var g=0,E=0;for(let T of h.features)0<=(h=HO[T])&&((k(),U)[p+g>>>2>>>0]=h,g+=4,E++);(k(),C)[d+4>>>2>>>0]=p,(k(),C)[d>>>2>>>0]=E}function KO(p,d){return Hv(oe(p>>>0).limits,d>>>0),1}function YO(p,d){oe(p>>>0).pushErrorScope(iO[d])}function QO(p,d,h){d>>>=0,h>>>=0,p=oe(p>>>0),d=Array.from((k(),U).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),p.submit(d)}function JO(p,d,h,g,E){h=Mt(h),g>>>=0,E>>>=0,p=oe(p>>>0),d=oe(d>>>0),g=(k(),K).subarray(g>>>0,g+E>>>0),p.writeBuffer(d,h,g,0,E)}n||(function(){for(var p=e.numThreads-1;p--;)uv();Be.push(async()=>{var d=(async function(){if(!n)return Promise.all(Ir.map(cv))})();Se++,await d,--Se==0&&rt&&(d=rt,rt=null,d())})})(),n||(Cr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>pe(),e.stackRestore=p=>ue(p),e.stackAlloc=p=>Zl(p),e.setValue=function(p,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(k(),F)[p>>>0]=d;break;case"i16":(k(),V)[p>>>1>>>0]=d;break;case"i32":(k(),U)[p>>>2>>>0]=d;break;case"i64":(k(),L)[p>>>3>>>0]=BigInt(d);break;case"float":(k(),se)[p>>>2>>>0]=d;break;case"double":(k(),Y)[p>>>3>>>0]=d;break;case"*":(k(),C)[p>>>2>>>0]=d;break;default:ce(`invalid type for setValue: ${h}`)}},e.getValue=function(p,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(k(),F)[p>>>0];case"i16":return(k(),V)[p>>>1>>>0];case"i32":return(k(),U)[p>>>2>>>0];case"i64":return(k(),L)[p>>>3>>>0];case"float":return(k(),se)[p>>>2>>>0];case"double":return(k(),Y)[p>>>3>>>0];case"*":return(k(),C)[p>>>2>>>0];default:ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=tn,e.stringToUTF8=gr,e.lengthBytesUTF8=wr;var rk,sk,ff,Jl,Xt,nn,nk,ok,ak,ik,lk,ck,uk,pk,fk,dk,mk,df,mf,_f,hf,lo,gf,_k,wf,hk,gk,wk,xf,xk,yk,yf,xe,co,bk,ue,Zl,pe,vk,bf,kk,Ek,Ak,vf,Tk,Mk,Sk,Ok,Ik,Ck,Pk,Lk,zk,Nk,Rk,$k,Dk,Bk,Uk,Fk,Gk,jk,qk,Wk,Vk,Hk,Xk,Kk,Yk,Qk,Jk,Zk,eE,tE,rE,sE,nE,oE,aE,iE,lE,cE,uE,br,ZO=[Js,no,dv,wv,xv,yv,bv,vv,kv,Ev,Av,Tv,Mv,Sv,Ov,Iv,Gv,jv,qv,Yv,Qv,Jv,Zv,ek,tk],kf={937076:(p,d,h,g,E)=>{if(e===void 0||!e.Uc)return 1;if((p=tn(Number(p>>>0))).startsWith("./")&&(p=p.substring(2)),!(p=e.Uc.get(p)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>p.byteLength)return 3;try{let T=p.subarray(d,d+h);switch(E){case 0:(k(),K).set(T,g>>>0);break;case 1:e.ad?e.ad(g,T):e.oe(g,T);break;default:return 4}return 0}catch{return 4}},937900:(p,d,h)=>{e.Sd(p,(k(),K).subarray(d>>>0,d+h>>>0))},937964:()=>e.me(),938006:p=>{e.jd(p)},938043:()=>typeof wasmOffsetConverter<"u"};function eI(p,d,h,g){var E=pe();try{return Lk(p,d,h,g)}catch(T){if(ue(E),T!==T+0)throw T;xe(1,0)}}function tI(p,d,h){var g=pe();try{return Ik(p,d,h)}catch(E){if(ue(g),E!==E+0)throw E;xe(1,0)}}function rI(p){var d=pe();try{Tk(p)}catch(h){if(ue(d),h!==h+0)throw h;xe(1,0)}}function sI(p,d){var h=pe();try{return vf(p,d)}catch(g){if(ue(h),g!==g+0)throw g;xe(1,0)}}function nI(p,d,h){var g=pe();try{Ak(p,d,h)}catch(E){if(ue(g),E!==E+0)throw E;xe(1,0)}}function oI(p,d){var h=pe();try{zk(p,d)}catch(g){if(ue(h),g!==g+0)throw g;xe(1,0)}}function aI(p,d,h,g,E,T,P){var z=pe();try{return Ok(p,d,h,g,E,T,P)}catch(j){if(ue(z),j!==j+0)throw j;xe(1,0)}}function iI(p,d,h,g,E,T){var P=pe();try{Mk(p,d,h,g,E,T)}catch(z){if(ue(P),z!==z+0)throw z;xe(1,0)}}function lI(p,d,h,g){var E=pe();try{Pk(p,d,h,g)}catch(T){if(ue(E),T!==T+0)throw T;xe(1,0)}}function cI(p,d,h,g,E,T,P){var z=pe();try{Rk(p,d,h,g,E,T,P)}catch(j){if(ue(z),j!==j+0)throw j;xe(1,0)}}function uI(p,d,h,g,E,T,P){var z=pe();try{$k(p,d,h,g,E,T,P)}catch(j){if(ue(z),j!==j+0)throw j;xe(1,0)}}function pI(p,d,h,g,E,T,P,z){var j=pe();try{Vk(p,d,h,g,E,T,P,z)}catch(Z){if(ue(j),Z!==Z+0)throw Z;xe(1,0)}}function fI(p,d,h,g,E,T,P,z,j,Z,Ie,Ne){var Fe=pe();try{Dk(p,d,h,g,E,T,P,z,j,Z,Ie,Ne)}catch(ae){if(ue(Fe),ae!==ae+0)throw ae;xe(1,0)}}function dI(p,d,h,g,E){var T=pe();try{return Nk(p,d,h,g,E)}catch(P){if(ue(T),P!==P+0)throw P;xe(1,0)}}function mI(p,d,h,g,E){var T=pe();try{Sk(p,d,h,g,E)}catch(P){if(ue(T),P!==P+0)throw P;xe(1,0)}}function _I(p,d,h,g,E,T,P,z){var j=pe();try{Ck(p,d,h,g,E,T,P,z)}catch(Z){if(ue(j),Z!==Z+0)throw Z;xe(1,0)}}function hI(p){var d=pe();try{return Hk(p)}catch(h){if(ue(d),h!==h+0)throw h;xe(1,0)}}function gI(p,d,h){var g=pe();try{return Xk(p,d,h)}catch(E){if(ue(g),E!==E+0)throw E;xe(1,0)}}function wI(p,d){var h=pe();try{return aE(p,d)}catch(g){if(ue(h),g!==g+0)throw g;return xe(1,0),0n}}function xI(p,d,h,g,E){var T=pe();try{Kk(p,d,h,g,E)}catch(P){if(ue(T),P!==P+0)throw P;xe(1,0)}}function yI(p){var d=pe();try{return Bk(p)}catch(h){if(ue(d),h!==h+0)throw h;return xe(1,0),0n}}function bI(p,d,h,g,E,T){var P=pe();try{return qk(p,d,h,g,E,T)}catch(z){if(ue(P),z!==z+0)throw z;xe(1,0)}}function vI(p,d,h,g,E,T){var P=pe();try{return Yk(p,d,h,g,E,T)}catch(z){if(ue(P),z!==z+0)throw z;xe(1,0)}}function kI(p,d,h,g,E,T){var P=pe();try{return Qk(p,d,h,g,E,T)}catch(z){if(ue(P),z!==z+0)throw z;xe(1,0)}}function EI(p,d,h,g,E,T,P,z){var j=pe();try{return Wk(p,d,h,g,E,T,P,z)}catch(Z){if(ue(j),Z!==Z+0)throw Z;xe(1,0)}}function AI(p,d,h,g,E){var T=pe();try{return Jk(p,d,h,g,E)}catch(P){if(ue(T),P!==P+0)throw P;return xe(1,0),0n}}function TI(p,d,h,g){var E=pe();try{return Zk(p,d,h,g)}catch(T){if(ue(E),T!==T+0)throw T;xe(1,0)}}function MI(p,d,h,g){var E=pe();try{return eE(p,d,h,g)}catch(T){if(ue(E),T!==T+0)throw T;xe(1,0)}}function SI(p,d,h,g,E,T,P,z,j,Z,Ie,Ne){var Fe=pe();try{return tE(p,d,h,g,E,T,P,z,j,Z,Ie,Ne)}catch(ae){if(ue(Fe),ae!==ae+0)throw ae;xe(1,0)}}function OI(p,d,h,g,E,T,P,z,j,Z,Ie){var Ne=pe();try{rE(p,d,h,g,E,T,P,z,j,Z,Ie)}catch(Fe){if(ue(Ne),Fe!==Fe+0)throw Fe;xe(1,0)}}function II(p,d,h,g,E,T,P,z,j,Z,Ie,Ne,Fe,ae,ct,Ot){var ut=pe();try{sE(p,d,h,g,E,T,P,z,j,Z,Ie,Ne,Fe,ae,ct,Ot)}catch(ms){if(ue(ut),ms!==ms+0)throw ms;xe(1,0)}}function CI(p,d,h,g){var E=pe();try{return nE(p,d,h,g)}catch(T){if(ue(E),T!==T+0)throw T;xe(1,0)}}function PI(p,d,h,g,E){var T=pe();try{return oE(p,d,h,g,E)}catch(P){if(ue(T),P!==P+0)throw P;xe(1,0)}}function LI(p,d,h){var g=pe();try{return Fk(p,d,h)}catch(E){if(ue(g),E!==E+0)throw E;return xe(1,0),0n}}function zI(p,d,h){var g=pe();try{return Uk(p,d,h)}catch(E){if(ue(g),E!==E+0)throw E;xe(1,0)}}function NI(p,d,h){var g=pe();try{return Gk(p,d,h)}catch(E){if(ue(g),E!==E+0)throw E;xe(1,0)}}function RI(p,d,h,g){var E=pe();try{jk(p,d,h,g)}catch(T){if(ue(E),T!==T+0)throw T;xe(1,0)}}function ec(){if(0{let d=new WeakMap,h,g,E=1;e.webgpuRegisterDevice=z=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var j=d.get(z);if(!j){let Z=((Ie,Ne=0)=>{var Fe=mk(Ne);return Ne=dk(Ne,Fe),mt[Fe>>>0]=Ie.queue,mt[Ne>>>0]=Ie,Ne})(z,j=ok(0));j=[E++,j,Z],d.set(z,j)}return h=z,g=j[0],j}h=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(g!==void 0){var j=g;if(g=void 0,z){let Z=ff(j);T.set(z,Z),j===0&&p(h??oe(Z))}h=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let P=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,j,Z)=>{if(Z)return z[P]=[Z,NaN],Z;if(Z=z[P])return Z[1]++,Z[0];if((j=T.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return j=((Ie,Ne=0)=>(Ie.mapState==="unmapped"||ce(),Ne=fk(Ne),mt[Ne>>>0]=Ie,Ne))(z,j),z[P]=[j,1],j},e.webgpuUnregisterBuffer=z=>{let j=z[P];if(!j)throw Error("Buffer is not registered");j[1]--,j[1]===0&&(nk(j[0]),delete z[P])},e.webgpuGetBuffer=z=>oe(z),e.webgpuCreateDownloader=(z,j,Z)=>{if((Z=T.get(Z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Ie=oe(Z),Ne=16*Math.ceil(Number(j)/16);return async()=>{let Fe=Ie.createBuffer({size:Ne,usage:9});try{let ae=Ie.createCommandEncoder();return ae.copyBufferToBuffer(z,0,Fe,0,Ne),Ie.queue.submit([ae.finish()]),await Fe.mapAsync(GPUMapMode.READ),Fe.getMappedRange().slice(0,j)}finally{Fe.destroy()}}},e.ad=(z,j)=>{var Z=j.buffer;let Ie=j.byteOffset,Ne=j.byteLength;if(j=16*Math.ceil(Number(Ne)/16),z=oe(z),!h){var Fe=ff(g);h=oe(Fe)}let ae=(Fe=h.createBuffer({mappedAtCreation:!0,size:j,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(Z,Ie,Ne)),Fe.unmap(),(Z=h.createCommandEncoder()).copyBufferToBuffer(Fe,0,z,0,j),h.queue.submit([Z.finish()]),Fe.destroy()}},e.webnnInit=p=>{let d=p[0];[e.me,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.le,e.webnnEnableTraceEvent]=p.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.le,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,E,T)=>d.registerMLTensor(h,g,E,T),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,E,T,P,z)=>d.registerMLConstant(h,g,E,T,P,e.Uc,z),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},J?e:new Promise((p,d)=>{w=p,x=d})}var c2,hA,Cz=be(()=>{"use strict";c2=_A,hA=globalThis.self?.name?.startsWith("em-pthread"),hA&&_A()}),Vf,ld,gA,zt,u2,hc,wA,xA,Hf,yA,Xf,p2,Kf,f2,gd=be(()=>{"use strict";hd(),Vf=typeof location>"u"?void 0:location.origin,ld=import.meta.url>"file:"&&import.meta.url<"file;",gA=()=>{if(ld){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Vf).href}return import.meta.url},zt=gA(),u2=()=>{if(zt&&!zt.startsWith("blob:"))return zt.substring(0,zt.lastIndexOf("/")+1)},hc=(t,e)=>{try{let r=e??zt;return(r?new URL(t,r):new URL(t)).origin===Vf}catch{return!1}},wA=(t,e)=>{let r=e??zt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},xA=(t,e)=>`${e??"./"}${t}`,Hf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},yA=async t=>(await import(t)).default,Xf=(Iz(),vc(a2)).default,p2=async()=>{if(!zt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(hc(zt))return[void 0,Xf()];let t=await Hf(zt);return[t,Xf(t)]},Kf=(Cz(),vc(l2)).default,f2=async(t,e,r,s)=>{let n=Kf&&!(t||e);if(n)if(zt)n=hc(zt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Kf];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??wA(o,e),i=r&&a&&!hc(a,e),l=i?await Hf(a):a??xA(o,e);return[i?l:void 0,await yA(l)]}}}),Yf,gc,vo,Qf,bA,vA,kA,wd,De,Is=be(()=>{"use strict";gd(),gc=!1,vo=!1,Qf=!1,bA=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},vA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},kA=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},wd=async t=>{if(gc)return Promise.resolve();if(vo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Qf)throw new Error("previous call to 'initializeWebAssembly()' failed.");vo=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!kA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vA())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=bA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,u=t.wasmBinary,[f,m]=await f2(i,o,r>1,!!u||!!c),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,v)=>{let b={numThreads:r};if(u)b.wasmBinary=u,b.locateFile=A=>A;else if(c||o)b.locateFile=A=>c??o+A;else if(i&&i.indexOf("blob:")!==0)b.locateFile=A=>new URL(A,i).href;else if(f){let A=u2();A&&(b.locateFile=S=>A+S)}m(b).then(A=>{vo=!1,gc=!0,Yf=A,x(),f&&URL.revokeObjectURL(f)},A=>{vo=!1,Qf=!0,v(A)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(gc&&Yf)return Yf;throw new Error("WebAssembly is not initialized yet.")}}),Nt,Ec,Le,xd=be(()=>{"use strict";Is(),Nt=(t,e)=>{let r=De(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Ec=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")Ec(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Le=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),d2,Pz=be(()=>{"use strict";Is(),xd(),d2=t=>{let e=De(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=Nt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Le("Can't create run options."),t?.extra!==void 0&&Ec(t.extra,"",new WeakSet,(a,i)=>{let l=Nt(a,s),c=Nt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Le(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),EA,AA,TA,wc,Ur,MA,m2,Lz=be(()=>{"use strict";Is(),xd(),EA=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},AA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},TA=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},wc=(t,e,r,s)=>{let n=Nt(e,s),o=Nt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&Le(`Can't set a session config entry: ${e} - ${r}.`)},Ur=(t,e,r,s)=>{let n=Nt(e,s),o=Nt(r,s);t.push([n,o])},MA=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&wc(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let _=n;if(_.device)if(typeof GPUDevice<"u"&&_.device instanceof GPUDevice)f=_.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&Ur(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&Ur(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];Ur(a,"forceCpuNodeNames",x.join(` `),r)}_.validationMode&&Ur(a,"validationMode",_.validationMode,r)}let m=De().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;Ur(a,"deviceId",_.toString(),r),Ur(a,"webgpuInstance",w.toString(),r),Ur(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Nt(o,r),l=a.length,c=0,u=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),u=De()._malloc(l*De().PTR_SIZE),r.push(u);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};TA(n);try{let o=EA(n.graphOptimizationLevel??"all"),a=AA(n.executionMode??"sequential"),i=typeof n.logId=="string"?Nt(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 u=typeof n.optimizedModelFilePath=="string"?Nt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,u),r===0&&Le("Can't create session options."),n.executionProviders&&await MA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);wc(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,m]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let _=Nt(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&Le(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&Ec(n.extra,"",new WeakSet,(f,m)=>{wc(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Le("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),As,bc,fn,Mo,Ac,yd,bd,cd,dn=be(()=>{"use strict";As=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},bc=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},fn=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},Mo=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Ac=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},yd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",bd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",cd=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),vd,_2=be(()=>{"use strict";hd(),vd=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),h2,zz=be(()=>{"use strict";dn(),h2=(t,e)=>new(Mo(e))(t)}),SA,OA,IA,CA,g2,PA,bt,w2=be(()=>{"use strict";dn(),SA=["V","I","W","E","F"],OA=(t,e)=>{console.log(`[${SA[t]},${new Date().toISOString()}]${e}`)},g2=(t,e)=>{IA=t,CA=e},PA=(t,e)=>{let r=Ac(t),s=Ac(IA);r>=s&&OA(r,typeof e=="function"?e():e)},bt=(...t)=>{CA&&PA(...t)}}),Jf,ud,Zf,LA,ed,zA,td,rd,sd,NA,x2,Nz=be(()=>{"use strict";dn(),w2(),Jf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ud=(t,e)=>{if(e==="int32")return t;let r=Jf.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(Mo(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},Zf=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},LA=1,ed=()=>LA++,zA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),td=(t,e)=>{let r=Jf.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},rd=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return td(this.dataType,this.tensorShape)}destroy(){bt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=Zf(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},sd=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=zA.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);bt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==td(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=ud(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else bt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?Zf(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},NA=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=ed();return this.tensorTrackersById.set(t,new sd(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){bt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){bt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=ed(),a=new rd({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new sd(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,u]of this.freeTensors.entries())if(u.canReuseTensor(i,e,r)){bt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}bt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new rd({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},x2=(...t)=>new NA(...t)}),y2={};So(y2,{WebNNBackend:()=>b2});var ko,RA,b2,Rz=be(()=>{"use strict";dn(),Is(),zz(),Nz(),w2(),ko=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),RA=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},b2=class{constructor(t){this.tensorManager=x2(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,g2(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){bt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){bt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)bt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>RA(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){bt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=ko.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){bt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=ko.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");bt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return h2(r,e)}}registerMLTensor(t,e,r,s){let n=ko.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return bt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,u;switch(n.dataType){case"float32":u=new Float32Array(c);break;case"float16":u=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":u=new Int32Array(c);break;case"uint32":u=new Uint32Array(c);break;case"int64":if(a){let f=ud(new Uint8Array(c),"int64");u=new Int32Array(f.buffer),n.dataType="int32"}else u=new BigInt64Array(c);break;case"uint64":u=new BigUint64Array(c);break;case"int8":u=new Int8Array(c);break;case"int4":case"uint4":case"uint8":u=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return bt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,u)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=ko.get(As(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),$A,kd,Ed,Fr,DA,nd,Tc,Ad,Td,od,Md,Sd,Od,v2=be(()=>{"use strict";Os(),Pz(),Lz(),dn(),Is(),xd(),_2(),$A=(t,e)=>{De()._OrtInit(t,e)!==0&&Le("Can't initialize onnxruntime.")},kd=async t=>{$A(t.wasm.numThreads,Ac(t.logLevel))},Ed=async(t,e)=>{De().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&De().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(Rz(),vc(y2)).WebNNBackend(t);De().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Fr=new Map,DA=t=>{let e=De(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Le("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},nd=(t,e)=>{let r=De(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Le("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],u=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Ad=async(t,e)=>{let r,s,n=De();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=Tc(t);let o=0,a=0,i=0,l=[],c=[],u=[];try{if([a,l]=await m2(e),e?.externalData&&n.mountExternalData){let M=[];for(let I of e.externalData){let O=typeof I=="string"?I:I.path;M.push(vd(typeof I=="string"?I:I.data).then(k=>{n.mountExternalData(O,k)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let I=M,O=I?.context,k=I?.gpuDevice,R=I?.deviceType,G=I?.powerPreference;O?n.currentContext=O:k?n.currentContext=await n.webnnCreateMLContext(k):n.currentContext=await n.webnnCreateMLContext({deviceType:R,powerPreference:G})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Le("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=DA(o),_=!!e?.enableGraphCapture,w=[],x=[],v=[],b=[],A=[];for(let M=0;MM==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Le("Can't create IO binding."),S={handle:i,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>cd(M))}),Fr.set(o,[o,c,u,S,_,!1]),[o,w,x,v,b]}catch(f){throw c.forEach(m=>n._OrtFree(m)),u.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Le("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Le("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Le("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},Td=t=>{let e=De(),r=Fr.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Le("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Le("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Le("Can't release session."),Fr.delete(t)},od=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],u=t[1],f=t[3],m=f,_,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let b=t[2].gpuBuffer;w=fn(As(c),u);{let A=i.webgpuRegisterBuffer;if(!A)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=A(b,s)}}else if(f==="ml-tensor"){let b=t[2].mlTensor;w=fn(As(c),u);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=A(s,b,As(c),u)}else{let b=t[2];if(Array.isArray(b)){w=l*b.length,_=i._malloc(w),r.push(_);for(let A=0;Ai.setValue(v+S*l,A,l===4?"i32":"i64"));let b=i._OrtCreateTensor(As(c),_,w,v,u.length,cd(m));b===0&&Le(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(b)}finally{i.stackRestore(x)}},Md=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=Fr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],u=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,v=s.length,b=0,A=[],S=[],M=[],I=[],O=[],k=a.stackSave(),R=a.stackAlloc(x*i),G=a.stackAlloc(x*i),F=a.stackAlloc(v*i),K=a.stackAlloc(v*i);try{[b,A]=d2(o),jr("wasm prepareInputOutputTensor");for(let C=0;CBe*Se,1);B=bc(je);let Tt=m?.outputPreferredLocations[s[C]];if(B==="string"){if(Tt==="gpu-buffer"||Tt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Be=[];for(let Se=0;Se0){let Be=a.webgpuGetBuffer;if(!Be)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Se=Be(J),rt=fn(je,lt);if(rt===void 0||!yd(B))throw new Error(`Unsupported data type: ${B}`);$=!0;{a.webgpuRegisterBuffer(Se,t,J);let nr=a.webgpuCreateDownloader(Se,rt,t);Q.push([B,qe,{gpuBuffer:Se,download:async()=>{let Oe=await nr();return new(Mo(B))(Oe)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&Le("Can't release tensor.")}},"gpu-buffer"])}}else if(Tt==="ml-tensor"&<>0){let Be=a.webnnEnsureTensor,Se=a.webnnIsGraphInputOutputTypeSupported;if(!Be||!Se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(fn(je,lt)===void 0||!bd(B))throw new Error(`Unsupported data type: ${B}`);if(!Se(t,B,!1))throw new Error(`preferredLocation "ml-tensor" for ${B} output is not supported by current WebNN Context.`);let rt=await Be(t,J,je,qe,!1);$=!0,Q.push([B,qe,{mlTensor:rt,download:a.webnnCreateMLTensorDownloader(J,B),dispose:()=>{a.webnnReleaseTensorId(J),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(Tt==="ml-tensor-cpu-output"&<>0){let Be=a.webnnCreateMLTensorDownloader(J,B)(),Se=Q.length;$=!0,U.push((async()=>{let rt=[Se,await Be];return a.webnnReleaseTensorId(J),a._OrtReleaseTensor(se),rt})()),Q.push([B,qe,[],"cpu"])}else{let Be=Mo(B),Se=new Be(lt);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(J,J+Se.byteLength)),Q.push([B,qe,Se,"cpu"])}}finally{a.stackRestore(Y),B==="string"&&J&&a._free(J),$||a._OrtReleaseTensor(se)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Le("Can't clear bound outputs."),Fr.set(t,[c,u,f,m,_,!1]));for(let[C,se]of await Promise.all(U))Q[C][2]=se;return qr("wasm ProcessOutputTensor"),Q}finally{a.webnnOnRunEnd?.(c),a.stackRestore(k),r.forEach(V=>{V&&V[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(V[2].gpuBuffer)}),n.forEach(V=>{V&&V[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(V[2].gpuBuffer)}),S.forEach(V=>a._OrtReleaseTensor(V)),M.forEach(V=>a._OrtReleaseTensor(V)),I.forEach(V=>a._free(V)),b!==0&&a._OrtReleaseRunOptions(b),A.forEach(V=>a._free(V))}},Sd=t=>{let e=De(),r=Fr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Le("Can't get an profile file name."),e._OrtFree(n)},Od=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Gr,jt,pn,Eo,Ao,xc,ad,yc,vs,ks,BA,k2,E2,A2,T2,M2,S2,O2,I2=be(()=>{"use strict";Os(),v2(),Is(),gd(),Gr=()=>!!Ke.wasm.proxy&&typeof document<"u",pn=!1,Eo=!1,Ao=!1,yc=new Map,vs=(t,e)=>{let r=yc.get(t);r?r.push(e):yc.set(t,[e])},ks=()=>{if(pn||!Eo||Ao||!jt)throw new Error("worker not ready")},BA=t=>{switch(t.data.type){case"init-wasm":pn=!1,t.data.err?(Ao=!0,ad[1](t.data.err)):(Eo=!0,ad[0]()),xc&&(URL.revokeObjectURL(xc),xc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=yc.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},k2=async()=>{if(!Eo){if(pn)throw new Error("multiple calls to 'initWasm()' detected.");if(Ao)throw new Error("previous call to 'initWasm()' failed.");if(pn=!0,Gr())return new Promise((t,e)=>{jt?.terminate(),p2().then(([r,s])=>{try{jt=s,jt.onerror=o=>e(o),jt.onmessage=BA,ad=[t,e];let n={type:"init-wasm",in:Ke};!n.in.wasm.wasmPaths&&(r||ld)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),jt.postMessage(n),xc=r}catch(n){e(n)}},e)});try{await wd(Ke.wasm),await kd(Ke),Eo=!0}catch(t){throw Ao=!0,t}finally{pn=!1}}},E2=async t=>{if(Gr())return ks(),new Promise((e,r)=>{vs("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ke}};jt.postMessage(s)});await Ed(Ke,t)},A2=async t=>Gr()?(ks(),new Promise((e,r)=>{vs("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};jt.postMessage(s,[t.buffer])})):Tc(t),T2=async(t,e)=>{if(Gr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ks(),new Promise((r,s)=>{vs("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),jt.postMessage(n,o)})}else return Ad(t,e)},M2=async t=>{if(Gr())return ks(),new Promise((e,r)=>{vs("release",[e,r]);let s={type:"release",in:t};jt.postMessage(s)});Td(t)},S2=async(t,e,r,s,n,o)=>{if(Gr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return ks(),new Promise((a,i)=>{vs("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};jt.postMessage(c,Od(l))})}else return Md(t,e,r,s,n,o)},O2=async t=>{if(Gr())return ks(),new Promise((e,r)=>{vs("end-profiling",[e,r]);let s={type:"end-profiling",in:t};jt.postMessage(s)});Sd(t)}}),id,UA,C2,$z=be(()=>{"use strict";Os(),I2(),dn(),hd(),_2(),id=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},UA=t=>{switch(t[3]){case"cpu":return new er(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!yd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return er.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!bd(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return er.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},C2=class{async fetchModelAndCopyToWasmMemory(t){return A2(await vd(t))}async loadModel(t,e){Ms();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await T2(r,e),Ss()}async dispose(){return M2(this.sessionId)}async run(t,e,r){Ms();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],_=f[1],w=this.inputNames.indexOf(m);if(w===-1)throw new Error(`invalid input '${m}'`);s.push(_),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],_=f[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(_),a.push(w)});let i=s.map((f,m)=>id(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?id(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await S2(this.sessionId,n,i,a,l,r),u={};for(let f=0;ffd,initializeFlags:()=>pd,wasmBackend:()=>L2});var pd,fd,L2,Dz=be(()=>{"use strict";Os(),I2(),$z(),pd=()=>{(typeof Ke.wasm.initTimeout!="number"||Ke.wasm.initTimeout<0)&&(Ke.wasm.initTimeout=0);let t=Ke.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Ke.wasm.simd=!1),typeof Ke.wasm.proxy!="boolean"&&(Ke.wasm.proxy=!1),typeof Ke.wasm.trace!="boolean"&&(Ke.wasm.trace=!1),typeof Ke.wasm.numThreads!="number"||!Number.isInteger(Ke.wasm.numThreads)||Ke.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ke.wasm.numThreads=1;else{let e=typeof navigator>"u"?_z("node:os").cpus().length:navigator.hardwareConcurrency;Ke.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},fd=class{async init(t){pd(),await k2(),await E2(t)}async createInferenceSessionHandler(t,e){let r=new C2;return await r.loadModel(t,e),r}},L2=new fd});Os();Os();Os();var Bz="1.25.0-dev",Uz=o2;{let t=(Dz(),vc(P2)).wasmBackend;Ts("webgpu",t,5),Ts("webnn",t,5),Ts("cpu",t,10),Ts("wasm",t,10)}Object.defineProperty(Ke.versions,"web",{value:Bz,enumerable:!0});async function z2(t){let e=t.split("/").pop(),r;try{if(r=await Zt(),r){let n=await r.match(t);if(n)return n}}catch(n){ee.warn(`Failed to load ${e} from cache:`,n)}let s=await _e.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){ee.warn(`Failed to cache ${e}:`,n)}return s}async function N2(t){let e=await z2(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return ee.warn("Failed to read WASM binary:",r),null}}async function R2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await z2(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ee.warn("Failed to read WASM factory:",r),null}}var $2="1.24.3";var D2="warning",Cd={wasm:{},webgl:{},webgpu:{},versions:{common:$2},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);D2=t}},get logLevel(){return D2}};Object.defineProperty(Cd,"logLevel",{enumerable:!0});var B2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;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?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,v=3,b=0,A=f,S=f*2,M=-1;i==="RGBA"?(b=0,A=f,S=f*2,M=f*3):i==="RGB"?(b=0,A=f,S=f*2):i==="RBG"&&(b=0,S=f,A=f*2),s=r.createImageData(n,o);for(let I=0;I{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,v=0,b=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(v=0,A=c,b=c*2):l==="BGR"&&(A=0,b=c,v=c*2);for(let I=0;I{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,Pd(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(Pd(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Pd(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},G2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new wt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},j2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new wt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},q2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new wt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},W2=(t,e,r)=>new wt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Cs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Oo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),V2=!1,H2=()=>{if(!V2){V2=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Cs.set("int64",BigInt64Array),Oo.set(BigInt64Array,"int64")),e&&(Cs.set("uint64",BigUint64Array),Oo.set(BigUint64Array,"uint64")),s?(Cs.set("float16",r),Oo.set(r,"float16")):Cs.set("float16",Uint16Array)}};var X2=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new wt(t.type,t.data,e);case"cpu-pinned":return new wt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new wt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new wt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new wt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var wt=class{constructor(e,r,s){H2();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Cs.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(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=e.gpuBuffer,this.downloader=e.download,this.disposer=e.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=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof e=="string")if(n=e,l=s,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=Cs.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="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(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let c=Oo.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}let a=X2(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="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=n,this.dims=o,this.size=a}static async fromImage(e,r){return F2(e,r)}static fromTexture(e,r){return G2(e,r)}static fromGpuBuffer(e,r){return j2(e,r)}static fromMLTensor(e,r){return q2(e,r)}static fromPinnedBuffer(e,r,s){return W2(e,r,s)}toDataURL(e){return B2(this,e)}toImageData(e){return U2(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 r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return K2(this,e)}};var Mc=wt;var Fz=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 Z2(t){return t<=It.DEBUG?0:t<=It.INFO?2:t<=It.WARNING||t<=It.ERROR?3:4}var Gz={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},qt=[],Ld,_n,Y2=Symbol.for("onnxruntime");if(Y2 in globalThis)_n=globalThis[Y2];else if(ie.IS_NODE_ENV){switch(_n=Uf,process.platform){case"win32":qt.push("dml");break;case"linux":process.arch==="x64"&&qt.push("cuda");break;case"darwin":qt.push("coreml");break}qt.push("webgpu"),qt.push("cpu"),Ld=["cpu"]}else _n=Id,ie.IS_WEBNN_AVAILABLE&&qt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&qt.push("webgpu"),qt.push("wasm"),Ld=["wasm"];var jz=_n.InferenceSession;function eT(t=null){if(!t)return Ld;switch(t){case"auto":return qt;case"gpu":return qt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(qt.includes(t))return[Fz[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${qt.join(", ")}.`)}var Q2=Promise.resolve(),mn=null;async function qz(){if(mn)return mn;if(!(_e.useWasmCache&&typeof at?.wasm?.wasmPaths=="object"&&at?.wasm?.wasmPaths?.wasm&&at?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return mn=Promise.resolve(),mn}return mn=(async()=>{let e=at.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!zf(e.wasm)?(async()=>{try{let s=await N2(Nf(e.wasm));s&&(at.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!zf(e.mjs)?(async()=>{try{let s=await R2(Nf(e.mjs));s&&(at.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(at.wasm.wasmPaths.mjs=e.mjs)})(),mn}async function Sc(t,e,r){await qz();let s=Z2(_e.logLevel??It.WARNING),n=()=>jz.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?Q2=Q2.then(n):n());return o.config=r,o}var J2=Promise.resolve();async function Oc(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?J2=J2.then(r):r()}function Ic(t){return t instanceof _n.Tensor}var at=_n?.env;function Io(){return at?.wasm?.proxy}if(at){let t=function(e){let r=Z2(e);at.logLevel=Gz[r]};if(at.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&at.versions?.web&&!at.wasm.wasmPaths){let e=`/assets/${at.versions.web}/dist/`;at.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}at.wasm.proxy=!1}at.webgpu&&(at.webgpu.powerPreference="high-performance"),t(_e.logLevel??It.WARNING),_e.backends.onnx={...at,setLogLevel:t}}var Wr=async(t,e,r)=>{let s=await Sc(new Uint8Array(t),e);return(async n=>{let o=Io(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Oc(s,a);return Array.isArray(r)?r.map(l=>new N(i[l])):new N(i[r])})},pr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Wr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Wr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Wr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Wr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Wr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Wr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Wr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Wr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var tT=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"}),zd=ie.IS_NODE_ENV?"cpu":"wasm";function Cc(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${zd}).`),zd):zd}var nT=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),xt=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),rT=xt.fp32,sT=Object.freeze({[tT.wasm]:xt.q8}),Vr=Object.freeze({[xt.fp32]:"",[xt.fp16]:"_fp16",[xt.int8]:"_int8",[xt.uint8]:"_uint8",[xt.q8]:"_quantized",[xt.q4]:"_q4",[xt.q4f16]:"_q4f16",[xt.bnb4]:"_bnb4"});function Pc(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===xt.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==xt.auto&&xt.hasOwnProperty(l))return l}i=sT[r]??rT}else o&&xt.hasOwnProperty(o)?i=o:i=sT[r]??rT;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var kr=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var N=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return Ic(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new Mc(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;s_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[u])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([u,f])=>f-u),o=n.reduce((u,f)=>u*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let u=1;u=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[u]=a[f]}return new t(this.type,i,r)}permute(...e){return Vz(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,m)=>f+m,i=0n):(a=(f,m)=>f+m**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,u]=Co(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*u,u*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Nd(this.dims)}squeeze(e=null){return new t(this.type,this.data,oT(this.dims,e))}squeeze_(e=null){return this.dims=oT(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,aT(this.dims,e))}unsqueeze_(e){return this.dims=aT(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Pe(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Co((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=yo(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Pe(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthu===1)){if(e.length===this.dims.length)return this.clone();let u=e.length-this.dims.length,f=Array(u).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((u,f)=>u*e[f]),o=n.reduce((u,f)=>u*f,1),a=this.data,i=new a.constructor(o),l=Nd(s),c=Nd(n);for(let u=0;uBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,dA(this.data),this.dims);return new t(e,kr[e].from(this.data,r),this.dims)}};function Wz(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew N("int64",t,[t.length]);async function zc(t,e,r,s,n){return await(await pr.slice)({x:t,s:Lc(e),e:Lc(r),a:Lc(s),t:Lc(n??new Array(s.length).fill(1))})}function lT(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let u=0;ur!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function aT(t,e){return e=fr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function fr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ve(t,e=0){e=fr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--m){let x=c[m],v=_%x;m===e&&(v+=a),f+=v*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[u]}a+=c[e]}}return new N(o,n,r)}function yt(t,e=0){return ve(t.map(r=>r.unsqueeze(e)),e)}function Co(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=fr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=m%w;u+=x*_,_*=i[f]}m=Math.floor(m/w)}l[u]=t(l[u],o[c],c,u)}return s||i.splice(r,1),[e.type,l,i]}function $d(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((b,A)=>b+A,0)/n.length,w=Math.sqrt(n.reduce((b,A)=>b+(A-_)**2,0)/(n.length-r)),x=new N(t.type,[_],[]);return[new N(t.type,[w],[]),x]}e=fr(e,o.length);let a=Nc(t,e,s),i=a.data,[l,c,u]=Co((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;mc+u,0);return new N(t.type,[l/n.length],[])}e=fr(e,s.length);let[o,a,i]=Co((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function Dd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new N(r,new s(n).fill(e),t)}function Ye(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return Dd(t,e,r,s)}function Po(t,e){return Ye(t.dims,e)}function et(t){return Dd(t,1n,"int64",BigInt64Array)}function Rc(t){return et(t.dims)}function Bd(t){return Dd(t,0n,"int64",BigInt64Array)}function Ud(t){return Bd(t.dims)}function RD(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>ys.random()),t)}function cT(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>ys.gauss()),t)}function uT(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),u=i%8;a[c]|=l<<7-u,r&&u===0&&(a[c]-=128)}return new N(s,a,[t.dims[0],t.dims[1]/8])}async function hn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ct(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Fd(t,e){let r=await hn(t);return await Promise.all(r.map(s=>st(t,s,!0,e)))}function Gd(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var Hz=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Xz(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?ht(t[n],i):ht(i,t[n])}}function Kz(t,e){for(let r of Object.keys(t))t[r].length=e}function Ps(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function Yz(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var W=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new RE(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ps(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ps(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ps(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ps(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ps(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ps(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=Yz(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Fd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,{text_pair:r=null,add_special_tokens:s=!0,padding:n=!1,truncation:o=null,max_length:a=null,return_tensor:i=!0,return_token_type_ids:l=null}={}){let c=Array.isArray(e),u;if(c){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");u=e.map((m,_)=>this._encode_plus(m,{text_pair:r[_],add_special_tokens:s,return_token_type_ids:l}))}else u=e.map(m=>this._encode_plus(m,{add_special_tokens:s,return_token_type_ids:l}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:l})]}if(a===null?a=this.model_max_length:o===null&&(n===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),a=this.model_max_length):n===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),n===!0&&(a=Math.min(Pe(u.map(m=>m.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),n||o)for(let m=0;ma?o&&Kz(u[m],a):n&&Xz(u[m],a,_=>_==="input_ids"?this.pad_token_id:0,this.padding_side));let f={};if(i){if(!(n&&o)&&u.some(_=>{for(let w of Object.keys(_))if(_[w].length!==u[0][w]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[u.length,u[0].input_ids.length];for(let _ of Object.keys(u[0]))f[_]=new N("int64",BigInt64Array.from(u.flatMap(w=>w[_]).map(BigInt)),m)}else{for(let m of Object.keys(u[0]))f[m]=u.map(_=>_[m]);if(!c)for(let m of Object.keys(f))f[m]=f[m][0]}return f}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof N&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof N&&(e=Gd(e)),!Array.isArray(e)||e.length===0||!wE(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,{tools:r=null,documents:s=null,chat_template:n=null,add_generation_prompt:o=!1,tokenize:a=!0,padding:i=!1,truncation:l=!1,max_length:c=null,return_tensor:u=!0,return_dict:f=!0,tokenizer_kwargs:m={},..._}={}){if(n=this.get_chat_template({chat_template:n,tools:r}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let w=this._compiled_template_cache.get(n);w===void 0&&(w=new XE(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let b of Hz){let A=Ps(this.config,b);A&&(x[b]=A)}let v=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,..._});if(a){let b=this._call(v,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:u,...m});return f?b:b.input_ids}return v}};function gn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var zm={};hs(zm,{AlbertTokenizer:()=>jd,AutoTokenizer:()=>ne,BartTokenizer:()=>qd,BertTokenizer:()=>Wd,BlenderbotSmallTokenizer:()=>Vd,BlenderbotTokenizer:()=>Hd,BloomTokenizer:()=>Xd,CLIPTokenizer:()=>Yd,CamembertTokenizer:()=>Kd,CodeGenTokenizer:()=>Jd,CodeLlamaTokenizer:()=>Qd,CohereAsrTokenizer:()=>em,CohereTokenizer:()=>Zd,ConvBertTokenizer:()=>tm,DebertaTokenizer:()=>sm,DebertaV2Tokenizer:()=>rm,DistilBertTokenizer:()=>nm,ElectraTokenizer:()=>om,EsmTokenizer:()=>am,FalconTokenizer:()=>im,GPT2Tokenizer:()=>um,GPTNeoXTokenizer:()=>cm,GemmaTokenizer:()=>lm,HerbertTokenizer:()=>pm,LlamaTokenizer:()=>fm,M2M100Tokenizer:()=>dm,MBart50Tokenizer:()=>_m,MBartTokenizer:()=>Lo,MPNetTokenizer:()=>wm,MarianTokenizer:()=>mm,MgpstrTokenizer:()=>hm,MobileBertTokenizer:()=>gm,NllbTokenizer:()=>xm,NougatTokenizer:()=>ym,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>bm,RoFormerTokenizer:()=>km,RobertaTokenizer:()=>vm,SiglipTokenizer:()=>Em,SpeechT5Tokenizer:()=>Am,SqueezeBertTokenizer:()=>Tm,T5Tokenizer:()=>Mm,TokenizersBackend:()=>W,VitsTokenizer:()=>Om,Wav2Vec2CTCTokenizer:()=>Im,WhisperTokenizer:()=>Cm,XLMRobertaTokenizer:()=>Pm,XLMTokenizer:()=>Lm});var jd=class extends W{return_token_type_ids=!0};var qd=class extends W{};var Wd=class extends W{return_token_type_ids=!0};var Vd=class extends W{};var Hd=class extends W{};var Xd=class extends W{};var Kd=class extends W{};var Yd=class extends W{};var Qd=class extends W{};var Jd=class extends W{};var Zd=class extends W{};var em=class extends W{};var tm=class extends W{return_token_type_ids=!0};var rm=class extends W{return_token_type_ids=!0};var sm=class extends W{return_token_type_ids=!0};var nm=class extends W{};var om=class extends W{return_token_type_ids=!0};var am=class extends W{};var im=class extends W{};var lm=class extends W{};var cm=class extends W{};var um=class extends W{};var pm=class extends W{return_token_type_ids=!0};var fm=class extends W{padding_side="left"};var dm=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var mm=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),ee.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||ee.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),ht([n],super._encode_text(o))}}};var Lo=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var _m=class extends Lo{};var hm=class extends W{};var gm=class extends W{return_token_type_ids=!0};var wm=class extends W{};var xm=class extends W{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var ym=class extends W{};var bm=class extends W{};var vm=class extends W{};var km=class extends W{return_token_type_ids=!0};var Em=class extends W{};var Am=class extends W{};var Tm=class extends W{return_token_type_ids=!0};var Mm=class extends W{};var Sm=class extends Ft{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function fT(t){t=t.toLowerCase();let e=Qz.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),zo.has(t))e=t;else{let n=t.length===2?zo.keys():zo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var Jz="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",dT=new RegExp(`^[${Jz}]+$`,"gu"),Zz=.1,Cm=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],u=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],v=[],b=!1,A=null,S=new Set(this.all_special_ids);for(let O of e){let k=O.tokens,R=i?O.token_timestamps:null,G=null,F=m;if("stride"in O){let[Q,U,C]=O.stride;if(f-=U,A=Q-C,U&&(F=U/n+m),C)for(let se=k.length-1;se>=0;--se){let Y=Number(k[se]);if(Y>=m){if(G!==null&&(Y-m)*n=m&&U<=w){let C=(U-m)*n+f,se=bs(C,2);if(G!==null&&U>=G)b=!0;else if(b||x.length>0&&U0&&u.timestamp[1]!==null))for(let B of u.words)B.timestamp[1]>u.timestamp[1]&&u.timestamp[1]>=B.timestamp[0]&&(B.timestamp[1]=u.timestamp[1]);c.push(u),x=[],K=[],v=[],V=[],u=l()}}else if(K.push(U),i){let C=bs(R[Q]+f,2),se;if(Q+10?(x.push(K),i&&v.push(V)):x.every(Q=>Q.length===0)&&(u=l(),x=[],K=[],v=[],V=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[O,k]=this.findLongestCommonSequence(x,v),R=this.decode(O);u.text=R,i&&(u.words=this.collateWordTimestamps(O,k,a)),c.push(u)}let M=Object.create(null),I=c.map(O=>O.text).join("");if(r||s){for(let O=0;O0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cU===F[C]&&l[I+C][0]-Zz<=r[c][R+C][0]).length:K=k.filter((U,C)=>U===F[C]).length;let V=M/1e4,Q=K/M+V;K>1&&Q>f&&(f=Q,m=[I,O,R,G])}let[w,x,v,b]=m,A=Math.floor((x+w)/2),S=Math.floor((b+v)/2);if(a&&f===0&&n>0){let M=l[n-1][0],I=r[c].findIndex(O=>O[0]>=M);S=I===-1?u.length:I}o.push(...s.slice(0,A)),s=u.slice(S),n=s.length,a&&(i.push(...l.slice(0,A)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let u=0;u=this._tokenizer.token_to_id("<|endoftext|>"),_=c.startsWith(" "),w=c.trim(),x=dT.test(w);if(m||_||x||o.length===0)o.push(c),a.push(u),i.push(f);else{let v=o.length-1;o[v]+=c,a[v].push(...u),i[v].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,u=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[u]=a[c]+a[u],i[u]=ht(i[c],i[u]),l[u]=ht(l[c],l[u]),a[c]="",i[c]=[],l[c]=[]):u=c,--c;for(c=0,u=1;uf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var Pm=class extends W{};var Lm=class extends W{return_token_type_ids=!0;constructor(e,r){super(e,r),ee.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var ne=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Fd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",u=zm[c];return u||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=W),new u(i,l)}};var Hr="https://github.com/huggingface/transformers.js/issues/new/choose";var No="preprocessor_config.json",Er=No,$c="processor_config.json",Dc="chat_template.jinja";var re=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?st(e,$c,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?xo(e,Dc,!0,r):null]);return new this(s,n,o)}};var uu={};hs(uu,{ChatterboxProcessor:()=>Ym,CohereAsrProcessor:()=>Qm,Florence2Processor:()=>j_,Gemma3Processor:()=>q_,Gemma3nProcessor:()=>W_,Gemma4Processor:()=>V_,Glm46VProcessor:()=>H_,GraniteSpeechProcessor:()=>X_,GroundingDinoProcessor:()=>K_,Idefics3Processor:()=>au,JinaCLIPProcessor:()=>Q_,Lfm2VlProcessor:()=>J_,LlavaProcessor:()=>Z_,MgpstrProcessor:()=>eh,MoonshineProcessor:()=>th,OwlViTProcessor:()=>rh,PaliGemmaProcessor:()=>sh,Phi3VProcessor:()=>nh,PixtralProcessor:()=>oh,Processor:()=>re,PyAnnoteProcessor:()=>ah,Qwen2VLProcessor:()=>zs,Qwen2_5_VLProcessor:()=>Ho,Qwen3VLProcessor:()=>ih,Sam2Processor:()=>iu,Sam2VideoProcessor:()=>lh,SamProcessor:()=>Xo,SmolVLMProcessor:()=>au,SpeechT5Processor:()=>ch,UltravoxProcessor:()=>uh,VLChatProcessor:()=>Y_,VoxtralProcessor:()=>ph,VoxtralRealtimeProcessor:()=>dh,Wav2Vec2Processor:()=>mh,Wav2Vec2ProcessorWithLM:()=>_h,WhisperProcessor:()=>hh});var Ee=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await st(e,No,!0,r);return new this(s)}};function Ae(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var jo={};hs(jo,{ASTFeatureExtractor:()=>$m,ChatterboxFeatureExtractor:()=>Dm,ClapFeatureExtractor:()=>Bm,CohereAsrFeatureExtractor:()=>Um,DacFeatureExtractor:()=>Bo,EncodecFeatureExtractor:()=>$o,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Uo,Gemma4AudioFeatureExtractor:()=>Fo,GraniteSpeechFeatureExtractor:()=>Fm,MoonshineFeatureExtractor:()=>Gm,ParakeetFeatureExtractor:()=>Do,PyAnnoteFeatureExtractor:()=>Go,SeamlessM4TFeatureExtractor:()=>jm,SnacFeatureExtractor:()=>qm,SpeechT5FeatureExtractor:()=>Wm,VoxtralRealtimeFeatureExtractor:()=>Xm,Wav2Vec2FeatureExtractor:()=>Vm,WeSpeakerFeatureExtractor:()=>Hm,WhisperFeatureExtractor:()=>Km});var eN=()=>{};var mT={fromWeb:eN};var tN=()=>{};var _T=tN;async function Bc(t,e){if(ie.IS_BROWSER_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(ie.IS_FS_AVAILABLE){let r=e.stream(),s=mT.fromWeb(r),n=_t.createWriteStream(t);await _T(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function Rm(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Rr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&ee.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function Nm(t,e="htk"){let r=sN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var nN={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function oN(t,e="htk"){let r=nN[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function aN(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function it(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=Nm(r,a),c=Nm(s,a),u=gT(l,c,e+2),f=oN(u,a),m;if(i){let w=n/((t-1)*2);m=Nm(Float64Array.from({length:t},(x,v)=>v*w),a),f=u}else m=gT(0,Math.floor(n/2),t);let _=aN(m,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(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(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let J=Math.floor(r/2);switch(i){case"reflect":{t=iN(t,J,J);break}case"constant":{let le=new t.constructor(t.length+2*J);le.set(t,J),t=le;break}case"semicausal":{let le=new t.constructor(t.length+J);le.set(t,J),t=le;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let F=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&FF?I&&(Q=M):Q=V=M);let U=new mc(n),C=new Float64Array(n),se=new Float64Array(U.outputBufferSize),Y=new Float32Array(K*Q);for(let J=0;J=1;--ce)C[ce]-=c*C[ce-1];C[0]*=1-c}for(let ce=0;ceMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function uN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return Uc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),Uc(n,8,"WAVE"),Uc(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),Uc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function Uc(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),uN(e,this.sampling_rate)}async save(e){return Bc(e,this.toBlob())}};var $m=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=it(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=dt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return nt(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Ae(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(ys.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await nt(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Ae(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=u){l.push(e.slice(c,u));break}let f=Math.max(c,c+a-i),m=Math.min(c+a,u),_;m<=f?_=c+a:_=this._find_split_point_energy(e,f,m,n),_=Math.max(c+1,Math.min(_,u)),l.push(e.slice(c,_)),c=_}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let u=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Ye([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Fo=class extends Uo{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return nt(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Ae(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,u=Math.floor(l/2),f=l+1,m=new Uint8Array(s+u+(r.pad_to_multiple_of??128));m.fill(1,u,u+s);let _=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:u*s,confidence:f/(u-c)})))}return n}};var jm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=it(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=dt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),nt(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Ae(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,v=a.data;for(let b=0;b0){let A=new Float32Array(x*(w+b));A.set(v),A.fill(this.config.padding_value,v.length);let S=w+b;a=new N(a.type,A,[S,x]),o&&(i=new N("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,u=this.config.stride;if(l%u!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${u}).`);let m=a.view(1,Math.floor(l/u),c*u),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let v=i.data;for(let b=1,A=0;bo+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Ae(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new N("float32",r,s),attention_mask:new N("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Hm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=it(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=dt(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),nt(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){Ae(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&ee.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var Ge=class{static async from_pretrained(e,r={}){let s=await st(e,No,!0,r),n=s.feature_extractor_type,o=jo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Hr}.`);return new o(s)}};var Ym=class extends re{static tokenizer_class=ne;static feature_extractor_class=Ge;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var fN=new Set(["ja","zh"]),Qm=class extends re{static tokenizer_class=ne;static feature_extractor_class=Ge;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=fN.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var Fc={};var Ls,yT,Xr;if(ie.IS_WEB_ENV)Ls=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Xr=self.createImageBitmap,yT=self.ImageData;else if(Fc)Xr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Je(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var dN={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},mN=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Je=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Rr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await Xr(e),s=Ls(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=Fc(await e.arrayBuffer());return await Xr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:u=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,u,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Xr(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new N("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Ls(e.width,e.height),s=new yT(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=mN.get(r)??"image/png",n=await this.toBlob(s);return Bc(e,n)}else if(ie.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(ie.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return Fc(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},_N=Je.read.bind(Je);function bT(t,e,r=0,s=null){let n=t/e,o=pA(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),oe&&b.push(S)}else{let S=Pe(v.data)[1];if(S===l-1||(A=Re(v.data),A[S]I*f[(O+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(A[S])}}c.push(m)}return c}function Gc(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[b]&&(f[b]=v[b],m[b]=x)}let _=new Array(i.dims[0]);for(let x=0;xx!==void 0);n.push({segmentation:u,labels:w})}return n}function hN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(m),a.push(u))}return[n,o,a]}function gN(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let u=0;u=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function wN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new N("int32",new Int32Array(i*l),[i,l]),u=[];if(a!==null)for(let x=0;xm[A]&&(f[A]=x,m[A]=b[A])}let _=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=yo(s.data)[0],a=Pe(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,u=0,f=0,m=s.data;for(let _=0;_this.preprocess(o)));return{pixel_values:yt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await st(e,Er,!0,r);return new this(s)}};var kn={};hs(kn,{BeitFeatureExtractor:()=>Zm,BitImageProcessor:()=>e_,CHMv2ImageProcessor:()=>r_,CLIPFeatureExtractor:()=>s_,CLIPImageProcessor:()=>Wc,ChineseCLIPFeatureExtractor:()=>t_,ConvNextFeatureExtractor:()=>n_,ConvNextImageProcessor:()=>Vc,DINOv3ViTImageProcessor:()=>i_,DPTFeatureExtractor:()=>c_,DPTImageProcessor:()=>Kc,DeiTFeatureExtractor:()=>o_,DeiTImageProcessor:()=>Hc,DetrFeatureExtractor:()=>a_,DetrImageProcessor:()=>Xc,DonutFeatureExtractor:()=>l_,DonutImageProcessor:()=>xn,EfficientNetImageProcessor:()=>u_,GLPNFeatureExtractor:()=>d_,Gemma3ImageProcessor:()=>p_,Gemma4ImageProcessor:()=>qo,Glm46VImageProcessor:()=>f_,GroundingDinoImageProcessor:()=>m_,Idefics3ImageProcessor:()=>Yc,ImageFeatureExtractor:()=>X,ImageProcessor:()=>X,JinaCLIPImageProcessor:()=>h_,Lfm2VlImageProcessor:()=>g_,LlavaOnevisionImageProcessor:()=>w_,Mask2FormerImageProcessor:()=>y_,MaskFormerFeatureExtractor:()=>x_,MaskFormerImageProcessor:()=>yn,MobileNetV1FeatureExtractor:()=>b_,MobileNetV1ImageProcessor:()=>Qc,MobileNetV2FeatureExtractor:()=>v_,MobileNetV2ImageProcessor:()=>Jc,MobileNetV3FeatureExtractor:()=>k_,MobileNetV3ImageProcessor:()=>Zc,MobileNetV4FeatureExtractor:()=>E_,MobileNetV4ImageProcessor:()=>eu,MobileViTFeatureExtractor:()=>A_,MobileViTImageProcessor:()=>tu,NougatImageProcessor:()=>T_,OwlViTFeatureExtractor:()=>M_,OwlViTImageProcessor:()=>bn,Owlv2ImageProcessor:()=>S_,Phi3VImageProcessor:()=>C_,PixtralImageProcessor:()=>P_,PvtImageProcessor:()=>L_,Qwen2VLImageProcessor:()=>Wo,RTDetrImageProcessor:()=>z_,Sam2ImageProcessor:()=>Vo,Sam3ImageProcessor:()=>Vo,SamImageProcessor:()=>Vo,SapiensFeatureExtractor:()=>N_,SapiensImageProcessor:()=>ru,SegformerFeatureExtractor:()=>R_,SegformerImageProcessor:()=>su,SiglipImageProcessor:()=>$_,SmolVLMImageProcessor:()=>Yc,Swin2SRImageProcessor:()=>D_,VLMImageProcessor:()=>__,ViTFeatureExtractor:()=>B_,ViTImageProcessor:()=>nu,VitMatteImageProcessor:()=>U_,VitPoseImageProcessor:()=>F_,YolosFeatureExtractor:()=>G_,YolosImageProcessor:()=>ou});var Zm=class extends X{};var e_=class extends X{};var t_=class extends X{};var r_=class extends X{};var Wc=class extends X{},s_=class extends Wc{};var Vc=class extends X{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},n_=class extends Vc{};var Hc=class extends X{},o_=class extends Hc{};var Xc=class extends X{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ye(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Kr(...e)}post_process_panoptic_segmentation(...e){return jc(...e)}post_process_instance_segmentation(...e){return qc(...e)}},a_=class extends Xc{};var i_=class extends X{};var xn=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let u=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:u,...n})}},l_=class extends xn{};var Kc=class extends X{},c_=class extends Kc{};var u_=class extends X{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var p_=class extends X{};function xN(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let u=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,u)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,u)),[l,c]}function yN(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,u=n*n*s,f=new Float32Array(o*u),m=0;for(let x=0;xa),0));let u=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/c),_=Math.floor(a.dims[3]/c),w=a.view(u,i,f,Math.floor(m/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(u*m*_,f*i*c*c),x=new N("int64",[u,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var f_=class extends Wo{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return wn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var d_=class extends X{};var m_=class extends X{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=et([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Yc=class extends X{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let b of n){let A=await Promise.all(b.map(I=>this.preprocess(I)));l.push(...A.map(I=>I.original_size)),c.push(...A.map(I=>I.reshaped_input_size)),A.forEach(I=>I.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let I=new Array(A.length),O=new Array(A.length);M=await Promise.all(A.map(async(k,R)=>{let G=this.get_resize_for_vision_encoder(k.pixel_values,S),F=await vt(k.pixel_values,{size:[G.height,G.width]}),{frames:K,num_splits_h:V,num_splits_w:Q}=await this.split_image(F,this.max_image_size);return I[R]=V,O[R]=Q,ve(K,0)})),a.push(I),i.push(O)}else{let I=[S,S];M=await Promise.all(A.map(O=>vt(O.pixel_values,{size:I}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(ve(M,0))}let u=o.length,[f,m,_,w]=o[0].dims,x,v;if(u===1)x=o[0].unsqueeze_(0),v=Ye([u,f,_,w],!0);else{let b=Math.max(...o.map(M=>M.dims.at(0)));v=Ye([u,b,_,w],!0);let A=v.data,S=b*_*w;for(let M=0;Ms||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let u=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var h_=class extends X{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function kT(t,e){return Math.round(t/e)*e}function bN(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function vN(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function kN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,u=new Float32Array(r*a*i*l),f=n*o;for(let m=0;mthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=vN(this.min_tiles,this.max_tiles),[n,o]=bN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let m=await Promise.all(f.map(_=>this.preprocess(_,{do_pad:!1})));for(let{pixel_values:_}of m){let[,w,x]=_.dims,v=_.unsqueeze_(0),b=this.encoder_patch_size*this.downsample_factor,A=b**2,[S,M]=wn(Math.max(b,w),Math.max(b,x),b,this.min_image_tokens*A,this.max_image_tokens*A).map(F=>Math.max(b,F)),I,O=1,k=1,R=this._is_image_too_large(w,x),G=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(R&&G){let{grid_width:F,grid_height:K,target_width:V,target_height:Q}=this._get_grid_layout(w,x);O=K,k=F;let U=await vt(v,{size:[Q,V]});I=[];for(let C=0;C(u-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||I_(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(m=>this.preprocess(m))),o=n.map(m=>m.original_size),a=n.map(m=>m.reshaped_input_size),i=[];for(let{pixel_values:m}of n){m.unsqueeze_(0);let[_,w]=m.dims.slice(-2),x=await vt(m,{size:[$t,$t],mode:"bicubic"});if(r>0){let v=[],b=I_(r),A=vn(w/b),S=vn(_/b);for(let I=0;Im.map(_=>$t*O_(_/$t))),u=new N("int64",c.flat(),[s,2]),f=c.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:f}}};var P_=class extends X{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");let f=c*u,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var L_=class extends X{};var z_=class extends X{post_process_object_detection(...e){return Kr(...e)}};var Vo=class extends X{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Of(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);m=new N("bool",w,m.dims)}i.push(m)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var ru=class extends X{post_process_semantic_segmentation(...e){return Gc(...e)}},N_=class extends ru{};var su=class extends X{post_process_semantic_segmentation(...e){return Gc(...e)}},R_=class extends su{};var $_=class extends X{};var D_=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var nu=class extends X{},B_=class extends nu{};var U_=class extends X{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:yt(s.map((a,i)=>ve([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var F_=class extends X{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let u=0;u/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[u,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),c.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var q_=class extends re{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` ${n}${i}${a} `}async _call(e,r=null,s={}){typeof e=="string"&&(e=[e]);let n;return r&&(n=await this.image_processor(r,s),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,s),...n}}};var W_=class extends re{static image_processor_class=Te;static feature_extractor_class=Ge;static tokenizer_class=ne;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:c,image_token:u,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=` ${o}${m}${i} `,this.image_token_id=l,this.boi_token=c,this.image_token=u;let _=u.repeat(this.image_seq_length);this.full_image_sequence=` ${c}${_}${f} `}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;s&&(o=await this.feature_extractor(s,n),e=e.map(l=>l.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return r&&(a=await this.image_processor(r,n),e=e.map(l=>l.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...o}}};var V_=class extends re{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:n,boa_token:o,eoa_token:a,image_token:i,boi_token:l,eoi_token:c}=this.tokenizer.config;this.audio_token=n,this.boa_token=o,this.eoa_token=a,this.image_token=i,this.boi_token=l,this.eoi_token=c}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([st(e,$c,!0,r),ne.from_pretrained(e,r),xo(e,Dc,!1,r)]),a={tokenizer:n};return s.image_processor&&(a.image_processor=new qo(s.image_processor)),s.feature_extractor&&(a.feature_extractor=new Fo(s.feature_extractor)),new this(s,a,o)}_compute_audio_num_tokens(e,r){let s=Math.round(r*20/1e3),n=Math.round(r*10/1e3),o=Math.floor(s/2),a=Math.floor((e+o-s-1)/n)+1;if(a<=0)return 0;for(let i=0;i<2;++i)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;if(r){o=await this.image_processor(r,n);let i=o.num_soft_tokens_per_image,l=0;e=e.map(c=>c.replaceAll(this.image_token,()=>` ${this.boi_token}${this.image_token.repeat(i[l++])}${this.eoi_token} `))}let a;if(s){let i=Array.isArray(s)?s:[s];a=await this.feature_extractor(i[0],n);let l=this.feature_extractor.config.sampling_rate??16e3,c=0;e=e.map(u=>u.replaceAll(this.audio_token,()=>` ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[c++].length,l))}${this.eoa_token} `))}return{...this.tokenizer(e,n),...o,...a}}};var zs=class extends re{static image_processor_class=Te;static tokenizer_class=ne;static image_token="<|image_pad|>";async _call(e,r=null,...s){Array.isArray(e)||(e=[e]);let n,o;if(r&&(n=await this.image_processor(r),o=n.image_grid_thw),o){let i=this.image_processor.config.merge_size**2,l=0,c=this.constructor.image_token,u=o.tolist();e=e.map(f=>{for(;f.includes(c);){let m=Number(u[l++].reduce((_,w)=>_*w,1n));f=f.replace(c,"<|placeholder|>".repeat(Math.floor(m/i)))}return f.replaceAll("<|placeholder|>",c)})}return{...this.tokenizer(e),...n}}};var H_=class extends zs{static image_token="<|image|>"};var X_=class extends re{static tokenizer_class=ne;static feature_extractor_class=Ge;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:r}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:n}=this.feature_extractor.config,o=Math.floor(s/n),a=Math.floor(e/r)+1,i=Math.floor(a/2);return Math.ceil(i/s)*o}async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let{input_features:a}=await this.feature_extractor(r);n.input_features=a;let i=this._get_num_audio_features(r.length),l=new Uint8Array(i).fill(1);n.input_features_mask=new N("bool",l,[1,i]);let c=this.config.audio_token??"<|audio|>";if(!e.includes(c))throw new Error(`The input text does not contain the audio token ${c}.`);e=e.replaceAll(c,c.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};function TN(t,e){let s=t.dims.at(-1)-1,n=t.tolist();n.fill(!1,0,1),n.fill(!1,s);let o=e.tolist();return n.map((a,i)=>a?i:null).filter(a=>a!==null).map(a=>o[a])}var K_=class extends re{static tokenizer_class=ne;static image_processor_class=Te;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=a.dims.at(1),u=a.sigmoid(),f=u.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>Jm(x))),_=[];for(let w=0;wM.map((I,O)=>I*x[(O+1)%2])));let v=f[w],b=[],A=[],S=[];for(let M=0;M`+n.repeat(t);a+=` `}return a+=` ${s}${o}`+n.repeat(t)+`${s}`,a}function SN(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function ON(t,e,r,s,n,o){return t===0&&e===0?SN(r,s,n,o):MN(r,t,e,s,n,o)}var au=class extends re{static image_processor_class=Te;static tokenizer_class=ne;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(e,r=null,s={}){s.return_row_col_info??=!0;let n;r&&(n=await this.image_processor(r,s)),Array.isArray(e)||(e=[e]);let o=n.rows??[new Array(e.length).fill(0)],a=n.cols??[new Array(e.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let f=0;fON(A,w[S],i,this.fake_image_token,this.image_token,this.global_img_token)),v=m.split(this.image_token);if(v.length===0)throw new Error("The image token should be present in the text.");let b=v[0];for(let A=0;Av.images).flatMap(v=>v.images).map(v=>Je.read(v)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=v=>n.encode(v,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[c,u,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),m=a(i[0]),_=new Array(m.length).fill(!1);for(let v=1;v0){let v=await this.image_processor(r);return v.pixel_values.unsqueeze_(0),{...x,...v}}return x}};var Q_=class extends re{static tokenizer_class=ne;static image_processor_class=Te;async _call(e=null,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},o=r?await this.image_processor(r,s):{};return{...n,...o}}};var J_=class extends re{static tokenizer_class=ne;static image_processor_class=Te;async _call(e,r=null,s={}){let{image_rows:n,image_cols:o,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(r){let l=this.config.image_token??"",{tile_size:c=512,downsample_factor:u=2,encoder_patch_size:f=16,use_thumbnail:m=!0}=this.image_processor.config,_=S=>Math.ceil(Math.floor(S/f)/u),w=_(c)**2,x=this.config.image_start_token??"<|image_start|>",v=this.config.image_end_token??"<|image_end|>",b=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(r)||(r=[r]);let A=0;r=r.map(S=>{let M=S.split(l);return M[0]+M.slice(1).map(I=>{let O=A++,[k,R]=a[O],G=n[O],F=o[O],K=_(k)*_(R),V=x;if(G>1||F>1){let Q=l.repeat(w);for(let U=0;U`+Q;m&&(V+=b+l.repeat(K))}else V+=l.repeat(K);return V+v+I}).join("")})}return{...i,...r?this.tokenizer(r,s):{}}}};var Z_=class extends re{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:c,num_additional_image_tokens:u}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+u;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let m=0;m0?x.reduce((b,A)=>b*A,1):0;c.push(w),l.push(v)}return[o(c),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,c]=this._decode_helper(s,"wp"),u=[],f=[];for(let m=0;mc.includes(En))?a=r.map(c=>{let u=c.replaceAll(En,En.repeat(o)),f=u.lastIndexOf(En),m=f===-1?0:f+En.length;return u.slice(0,m)+n+u.slice(m)+` `}):(ee.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(c=>IN(c,n,o,En,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var AT="<|image|>",CN=/<\|image_\d+\|>/g,nh=class extends re{static image_processor_class=Te;static tokenizer_class=ne;async _call(e,r=null,{padding:s=!0,truncation:n=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(r){i=await this.image_processor(r,{num_crops:o});let{num_img_tokens:l}=i,c=e.map((f,m)=>f.split(CN).join(AT.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let u=this.tokenizer._tokenizer.token_to_id(AT);a.input_ids.map_(f=>f==u?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var oh=class extends re{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:c,image_end_token:u,patch_size:f,spatial_merge_size:m}=this.config,_=f*m,w=Math.floor(a/_),x=Math.floor(i/_);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let v=0;vzN(w,l)),u=c.map(w=>w.length),f=c.flat(),m=(await Promise.all(f.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=m.length>1?ve(m,0):m[0];let _=a[0];for(let w=0;w0){if(c>cc)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${cc}).`);let u=wh(a,c);for(let f of u){let m=`${s.subfolder??""}/${f}`;l.push(new Promise(async(_,w)=>{let x=await wo(t,m,!0,s,i);_(x instanceof Uint8Array?{path:f,data:x}:f)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async u=>{if(typeof u.data=="string"){let f=await wo(t,u.data,!0,s);return{...u,data:f}}return u}));return Promise.all(l)}async function BN(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=Cc(r.device??o.device,e,{warn:M=>ee.info(M)}),i=eT(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=Pc(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:M=>ee.info(M)});if(Vr.hasOwnProperty(c)){if(a==="webgpu"&&!ie.IS_NODE_ENV&&c===xt.fp16&&!await nT())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(xt).join(", ")}`);let u=o.kv_cache_dtype,f=u?typeof u=="string"?u:u[c]??"float32":void 0;if(f&&!["float32","float16"].includes(f))throw new Error(`Invalid kv_cache_dtype: ${f}. Should be one of: float32, float16`);let m=Vr[c],_={...r.session_options};_.executionProviders??=i;let w=o.free_dimension_overrides;w?_.freeDimensionOverrides??=w:a.startsWith("webnn")&&!_.freeDimensionOverrides&&ee.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${a}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let x=MT(t,e,r,m),v=r.use_external_data_format??o.use_external_data_format,b=await ST(t,e,m,r,v,_);if(b.length>0&&(!ie.IS_NODE_ENV||b.some(M=>typeof M!="string"))&&(_.externalData=b),s&&a==="webgpu"&&u!==!1){let M=Ns(r.config,{prefix:"present",session_name:n});if(Object.keys(M).length>0&&!Io()){let I={};for(let O in M)I[O]="gpu-buffer";_.preferredOutputLocation=I}}return{buffer_or_path:await x,session_options:_,session_config:{dtype:c,kv_cache_dtype:f,device:a}}}async function OT(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let o=s?.[n]??!1,{buffer_or_path:a,session_options:i,session_config:l}=await BN(t,e[n],r,o,n),c=await Sc(a,i,l);return[n,c]})))}function IT(t){for(let e in t)Ic(t[e])?t[e]=new N(t[e]):typeof t[e]=="object"&&IT(t[e]);return t}async function fe(t,e){let r=UN(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return ie.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await Oc(t,s);return IT(n)}catch(s){let n=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i={type:a.type,dims:a.dims,location:a.location};return i.location!=="gpu-buffer"&&(i.data=a.data),[o,i]}));throw ee.error(`An error occurred during model execution: "${s}".`),ee.error("Inputs given to model:",n),s}}function UN(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof N)){s.push(a);continue}r[a]=Io()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(e).length,o=t.inputNames.length;if(n>o){let a=Object.keys(e).filter(i=>!t.inputNames.includes(i));ee.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var $e=class{};var q=class extends $e{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},ge=class extends $e{constructor({logits:e}){super(),this.logits=e}},we=class extends $e{constructor({logits:e}){super(),this.logits=e}},Me=class extends $e{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},kt=class extends $e{constructor({logits:e}){super(),this.logits=e}};var fu=class extends $e{constructor({alphas:e}){super(),this.alphas=e}};var Dt=class extends We{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Ko=class extends We{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Rs=class extends We{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,r){let s=r;for(let n of this.processors)s=n(e,s);return s}[Symbol.iterator](){return this.processors.values()}},du=class extends Dt{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s=1&&o[o.length-1]>=this.timestamp_begin,i=o.length<2||o[o.length-2]>=this.timestamp_begin;if(a&&(i?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&this.max_initial_timestamp_index!==null){let f=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(f+1).fill(-1/0)}let l=Bf(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),u=Pe(l.subarray(0,this.timestamp_begin))[0];c>u&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},gu=class extends Dt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);let s=e.length,n=r.slice([0,s],null),o=r.slice([s,r.dims[0]],null);for(let a=0;a1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=s}},PT=class extends Ko{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,s),this.filter_value=r}};var Sn=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,Qe(e,Object.getOwnPropertyNames(this)))}};var Yr=class extends We{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},On=class t extends We{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof Yr&&(e=[e]),this.criteria.push(...e)}_call(e,r){let s=new Array(e.length).fill(!1);for(let n of this.criteria){let o=n(e,r);for(let a=0;ar.length>=this.max_length)}},Au=class extends Yr{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(s=>{let n=s.at(-1);return this.eos_token_id.some(o=>n==o)})}},LT=class extends Yr{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var $s=class extends We{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,r){let s=e.dims.at(-1),n=e.data;if(r===-1)n=n.slice(-s);else{let o=r*s;n=n.slice(o,o+s)}return n}randomSelect(e){return YE(e)}static getSampler(e){if(e.do_sample)return new yh(e);if(e.num_beams>1)return new bh(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 xh(e)}},xh=class extends $s{async sample(e){let r=Pe(e.data)[1];return[[BigInt(r),0]]}},yh=class extends $s{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await tr(e,r),o=Re(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},bh=class extends $s{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await tr(e,r),o=Re(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var vh=class{constructor(e){if(e)for(let r in e){if(r in this)throw new TypeError(`Key "${r}" conflicts with an existing property on DynamicCache`);let s=e[r];if(!(s instanceof N))throw new TypeError(`Expected a Tensor for key "${r}", got ${typeof s}`);this[r]=s}}get_seq_length(){let e=this;for(let r in e)if(r.startsWith("past_key_values."))return e[r].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}async dispose(){let e=[];for(let r of Object.values(this))r.location==="gpu-buffer"&&e.push(r.dispose());await Promise.all(e)}},Yo=vh;var H={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},dr={[H.DecoderOnly]:{sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[H.DecoderOnlyWithoutHead]:{sessions:(t,e)=>({model:e.model_file_name??"model"})},[H.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[H.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[H.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[H.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),t.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[H.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[H.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},optional_configs:{generation_config:"generation_config.json"}},[H.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[H.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[H.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[H.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[H.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[H.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[H.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(t,e)=>({model:e.model_file_name??"model"})}};function kh(t){return dr[t]?.text_only_sessions??null}function Qo(t,e,r={}){let s=dr[t]??dr.default;return{sessions:s.sessions(e,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function In(t,{warn:e=!0}={}){let r=t.architectures||[];for(let s of r){let n=rr.get(s);if(n!==void 0)return n}if(t.model_type){let s=rr.get(t.model_type);if(s!==void 0)return s;for(let n of Object.values(Ds))if(n.has(t.model_type)){let o=rr.get(n.get(t.model_type));if(o!==void 0)return o}}if(e){let s=r.length>0?r.join(", "):"(none)";ee.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Hr}`)}return H.EncoderOnly}function Jo(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return Wt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=JSON.stringify([t,r,s,n]);return pc(o,()=>Wt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n}))}async function Cn(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await Jo(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,u=r??a.dtype,f=In(e),m=(x,v=null)=>{v=v??x;let b=Cc(c,x),A=Pc(u,x,b),S=Vr[A]??"",M=`${v}${S}.onnx`,I=l?`${l}/${M}`:M;o.push(I);let O=gh(i,M,x);for(let k of wh(M,O)){let R=l?`${l}/${k}`:k;o.push(R)}},{sessions:_,optional_configs:w}=Qo(f,e,{model_file_name:n});for(let[x,v]of Object.entries(_))m(x,v);if(w)for(let x of Object.values(w))o.push(x);return o}var Ds=null;function RT(t){Ds=t}function Eh(t){if(t instanceof N)return t;if(t.length===0)throw Error("items must be non-empty");if(Array.isArray(t[0])){if(t.some(e=>e.length!==t[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new N("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new N("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function Ah(t){return new N("bool",[t],[1])}var zT={[H.DecoderOnly]:{can_generate:!0,forward:Pt,prepare_inputs:Pn},[H.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Pt,prepare_inputs:Pn},[H.Seq2Seq]:{can_generate:!0,forward:Tu,prepare_inputs:Zo},[H.Vision2Seq]:{can_generate:!0,forward:Tu,prepare_inputs:Zo},[H.Musicgen]:{can_generate:!0,forward:Tu},[H.EncoderDecoder]:{can_generate:!1,forward:Tu},[H.ImageTextToText]:{can_generate:!0,forward:jN,prepare_inputs:Mu},[H.AudioTextToText]:{can_generate:!0,forward:GN,prepare_inputs:Mu},[H.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Mu},[H.Phi3V]:{can_generate:!0,prepare_inputs:Mu},[H.MultiModality]:{can_generate:!0},[H.AutoEncoder]:{can_generate:!1,forward:FN},[H.Chatterbox]:{can_generate:!0,forward:Vt},[H.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Pn},default:{can_generate:!1,forward:Vt}};function NT(t,e){let r=rr.get(t),s=!1,n=e?.architectures?.[0];if(n&&n!==t&&t?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let i=rr.get(n);i!==void 0&&(r=i,s=!0)}let o=zT[r]??zT.default,a=dr[r]??dr.default;return{typeConfig:{...o,...a},textOnly:s,modelType:r}}var rr=new Map,Su=new Map,Bs=new Map,y=class extends We{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,r,s){super(),this.config=e,this.sessions=r,this.configs=s;let n=Bs.get(this.constructor),{typeConfig:o}=NT(n,e);this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:f,session_options:m},w=Bs.get(this);s=_.config=await Wt.from_pretrained(e,_);let{typeConfig:x,textOnly:v,modelType:b}=NT(w,s);if(b===void 0){let I=w??s?.model_type;I!=="custom"&&ee.warn(`Model type for '${I}' not found, assuming encoder-only architecture. Please report this at ${Hr}.`)}if(r&&!(r instanceof gs)){let I={};try{let O=await Cn(e,{config:s,dtype:u,device:c,model_file_name:i});(await Promise.all(O.map(R=>Ct(e,R,_)))).forEach((R,G)=>{if(R.exists){let F=O[G]==="config.json";I[O[G]]={loaded:F?R.size??0:0,total:R.size??0}}})}catch(O){ee.warn(`Unable to fetch model file metadata for total progress tracking: ${O}`)}Object.keys(I).length>0&&(_.progress_callback=new gs(r,I))}let A=x.sessions(s,_,v),S=[OT(e,A,_,x.cache_sessions)];x.optional_configs&&S.push(WN(e,x.optional_configs,_));let M=await Promise.all(S);return new this(s,...M)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new Rs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new wu(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new gu(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new bu(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new xu(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&n.push(new yu(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new du(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new mu(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&n.push(new _u(e.suppress_tokens)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new Mn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new vu(e.guidance_scale)),e.temperature===0&&e.do_sample&&(ee.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&n.push(new ku(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=Sn){let n={...this.config};for(let a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);let o=new s(n);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),r&&Object.assign(o,Qe(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new On;return e.max_length!==null&&s.push(new Eu(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new Au(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[Ds.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Ds.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Ds.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Ds.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 a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new N("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=ve([s.decoder_attention_mask,et([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=ve([s.attention_mask,et([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:r,model_kwargs:s}){let n=Qe(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...c}=r,u=await this._prepare_inputs_embeds(r);r={...c,...Qe(u,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Vt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=ve([o,Po(o,0)],0),"attention_mask"in r&&(r.attention_mask=ve([r.attention_mask,Ud(r.attention_mask)],0));else if(r.decoder_input_ids){let a=Eh(r.decoder_input_ids).dims[0];if(a!==o.dims[0]){if(o.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${o.dims[0]}) than the decoder inputs (${a}).`);o=ve(Array.from({length:a},()=>o),0)}}return r.encoder_outputs=o,r}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:o,generation_config:a}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof N)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=o,this.config.model_type==="musicgen")i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${n.length}`);i=n}else i=Array.from({length:e},()=>[n]);i=Eh(i)}return l.decoder_attention_mask=Rc(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),u=this.config.is_encoder_decoder;u&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let f;u?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];let m=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=m+r.max_new_tokens);let _=this._get_logits_processor(r,m,s),w=this._get_stopping_criteria(r,n),x=l[c].dims.at(0),v=$s.getSampler(r),b=new Array(x).fill(0),A=f.tolist();o&&o.put(A);let S,M={},I={};for(;;){if(l=this.prepare_inputs_for_generation(A,l,r),S=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let V=this.getAttentions(S);for(let Q in V)Q in M||(M[Q]=[]),M[Q].push(V[Q])}else this._return_dict_in_generate_keys&&Object.assign(I,Qe(S,this._return_dict_in_generate_keys));let R=S.logits.slice(null,-1,null).to("float32"),G=_(A,R),F=[];for(let V=0;VV))break;l=this._update_model_kwargs_for_generation({generated_input_ids:F,outputs:S,model_inputs:l,is_encoder_decoder:u})}o&&o.end();let O=this.getPastKeyValues(S,l.past_key_values,!0),k=new N("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:k,past_key_values:O,...M,...I};for(let R of Object.values(S))R.location==="gpu-buffer"&&R.dispose();return k}getPastKeyValues(e,r,s=!1){let n=Object.create(null);for(let o in e)if(o.startsWith("present")){let a=o.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values"),i=o.includes("encoder");if(i&&r?n[a]=r[a]:n[a]=e[o],r&&(!i||s)){let l=r[a];l.location==="gpu-buffer"&&l.dispose()}}return new Yo(n)}getAttentions(e){let r={};for(let s of["cross_attentions","encoder_attentions","decoder_attentions"])for(let n in e)n.startsWith(s)&&(s in r||(r[s]=[]),r[s].push(e[n]));return r}addPastKeyValues(e,r){if(r)Object.assign(e,r);else{let s=this.sessions.decoder_model_merged??this.sessions.model,n=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=s?.config?.kv_cache_dtype??"float32",a=o==="float16"?kr.float16:kr.float32,i=Ns(this.config,{batch_size:n});for(let l in i){let c=i[l].reduce((u,f)=>u*f,1);e[l]=new N(o,new a(c),i[l])}}}async _encode_input(e,r,s){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);let n=this.sessions[e];return(await fe(n,Qe(r,n.inputNames)))[s]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function Tu(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:o,...a}=e;if(!r){let i=Qe(e,t.sessions.model.inputNames);r=(await Vt(t,i)).last_hidden_state}return a.input_ids=n,a.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=e.attention_mask),o&&!a.attention_mask&&(a.attention_mask=o),await Pt(t,a,!0)}async function Vt(t,e){let r=t.sessions.model,s=Qe(e,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Ud(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=et([n[0],n[2],n[3]])}return await fe(r,s)}async function FN(t,e){let r=await t.encode(e);return await t.decode(r)}async function Pt(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=Ah(!!n)),s.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(t.config.model_type)?1:0;o.position_ids=qN(o,n,i)}s.inputNames.includes("num_logits_to_keep")&&!o.num_logits_to_keep&&(o.num_logits_to_keep=new N("int64",[0n],[])),t.addPastKeyValues(o,n);let a=Qe(o,s.inputNames);return await fe(s,a)}async function $T(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:f=null,...m}){if(!l){l=await t.encode_text({input_ids:o,...m});let w=Qe(m,s);if(Object.keys(w).length>0){if(o.dims[1]!==1){let x=await e({...w,...m});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&o.dims[1]===1){let x=o.dims[1],v=c.get_seq_length();a=ve([et([o.dims[0],v]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(t.config.model_type)){let{image_grid_thw:w,video_grid_thw:x}=m;[i]=t.get_rope_index(o,w,x,a)}return await Pt(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:u,logits_processor:f},!0)}async function GN(t,e){return await $T(t,{...e,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:t.encode_audio.bind(t),merge_function:t._merge_input_ids_with_audio_features.bind(t)})}async function jN(t,e){return await $T(t,{...e,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:t.encode_image.bind(t),merge_function:t._merge_input_ids_with_image_features.bind(t)})}function Th(t,e=0){let[r,s]=t.dims,n=t.data,o=new BigInt64Array(n.length);for(let a=0;aa.dims[1]||n[n.at(-1)])),{...r,decoder_input_ids:Eh(e)}}function Mu(t,...e){return t.config.is_encoder_decoder?Zo(t,...e):Pn(t,...e)}function DT({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((u,f,m)=>(f==t&&u.push(m),u),[])),a=o.reduce((c,u)=>c+u.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let c=0;c{let n=await st(t,e[s],!1,r);return[s,n]})))}var ml={};hs(ml,{ASTForAudioClassification:()=>Dh,ASTModel:()=>$h,ASTPreTrainedModel:()=>sa,AfmoeForCausalLM:()=>zh,AfmoeModel:()=>Lh,AfmoePreTrainedModel:()=>ta,AlbertForMaskedLM:()=>Ih,AlbertForQuestionAnswering:()=>Oh,AlbertForSequenceClassification:()=>Sh,AlbertModel:()=>Mh,AlbertPreTrainedModel:()=>Us,ApertusForCausalLM:()=>Ph,ApertusModel:()=>Ch,ApertusPreTrainedModel:()=>ea,ArceeForCausalLM:()=>Rh,ArceeModel:()=>Nh,ArceePreTrainedModel:()=>ra,BartForConditionalGeneration:()=>Uh,BartForSequenceClassification:()=>Fh,BartModel:()=>Bh,BartPretrainedModel:()=>zn,BeitForImageClassification:()=>jh,BeitModel:()=>Gh,BeitPreTrainedModel:()=>na,BertForMaskedLM:()=>Wh,BertForQuestionAnswering:()=>Xh,BertForSequenceClassification:()=>Vh,BertForTokenClassification:()=>Hh,BertModel:()=>qh,BertPreTrainedModel:()=>Qr,BlenderbotForConditionalGeneration:()=>Yh,BlenderbotModel:()=>Kh,BlenderbotPreTrainedModel:()=>oa,BlenderbotSmallForConditionalGeneration:()=>Jh,BlenderbotSmallModel:()=>Qh,BlenderbotSmallPreTrainedModel:()=>aa,BloomForCausalLM:()=>eg,BloomModel:()=>Zh,BloomPreTrainedModel:()=>ia,CHMv2ForDepthEstimation:()=>ig,CHMv2PreTrainedModel:()=>Pu,CLIPModel:()=>cg,CLIPPreTrainedModel:()=>mr,CLIPSegForImageSegmentation:()=>mg,CLIPSegModel:()=>dg,CLIPSegPreTrainedModel:()=>fa,CLIPTextModel:()=>ug,CLIPTextModelWithProjection:()=>pa,CLIPVisionModel:()=>pg,CLIPVisionModelWithProjection:()=>fg,CamembertForMaskedLM:()=>rg,CamembertForQuestionAnswering:()=>og,CamembertForSequenceClassification:()=>sg,CamembertForTokenClassification:()=>ng,CamembertModel:()=>tg,CamembertPreTrainedModel:()=>Jr,ChatterboxModel:()=>la,ChatterboxPreTrainedModel:()=>Iu,ChineseCLIPModel:()=>ag,ChineseCLIPPreTrainedModel:()=>Cu,ClapAudioModelWithProjection:()=>ua,ClapModel:()=>lg,ClapPreTrainedModel:()=>Nn,ClapTextModelWithProjection:()=>ca,CodeGenForCausalLM:()=>hg,CodeGenModel:()=>_g,CodeGenPreTrainedModel:()=>da,Cohere2ForCausalLM:()=>yg,Cohere2Model:()=>xg,Cohere2PreTrainedModel:()=>_a,CohereAsrForConditionalGeneration:()=>vg,CohereAsrModel:()=>bg,CohereAsrPreTrainedModel:()=>ha,CohereForCausalLM:()=>wg,CohereModel:()=>gg,CoherePreTrainedModel:()=>ma,ConvBertForMaskedLM:()=>Eg,ConvBertForQuestionAnswering:()=>Mg,ConvBertForSequenceClassification:()=>Ag,ConvBertForTokenClassification:()=>Tg,ConvBertModel:()=>kg,ConvBertPreTrainedModel:()=>Zr,ConvNextForImageClassification:()=>Og,ConvNextModel:()=>Sg,ConvNextPreTrainedModel:()=>ga,ConvNextV2ForImageClassification:()=>Cg,ConvNextV2Model:()=>Ig,ConvNextV2PreTrainedModel:()=>wa,DFineForObjectDetection:()=>Ng,DFineModel:()=>zg,DFinePreTrainedModel:()=>ya,DINOv3ConvNextModel:()=>iw,DINOv3ConvNextPreTrainedModel:()=>Bu,DINOv3ViTModel:()=>lw,DINOv3ViTPreTrainedModel:()=>Uu,DPTForDepthEstimation:()=>hw,DPTModel:()=>_w,DPTPreTrainedModel:()=>Ma,DacDecoderModel:()=>va,DacDecoderOutput:()=>zu,DacEncoderModel:()=>ba,DacEncoderOutput:()=>Lu,DacModel:()=>Rg,DacPreTrainedModel:()=>Rn,DebertaForMaskedLM:()=>Dg,DebertaForQuestionAnswering:()=>Fg,DebertaForSequenceClassification:()=>Bg,DebertaForTokenClassification:()=>Ug,DebertaModel:()=>$g,DebertaPreTrainedModel:()=>es,DebertaV2ForMaskedLM:()=>Wg,DebertaV2ForQuestionAnswering:()=>Xg,DebertaV2ForSequenceClassification:()=>Vg,DebertaV2ForTokenClassification:()=>Hg,DebertaV2Model:()=>qg,DebertaV2PreTrainedModel:()=>ts,DecisionTransformerModel:()=>Kg,DecisionTransformerPreTrainedModel:()=>Nu,DeepseekV3ForCausalLM:()=>jg,DeepseekV3Model:()=>Gg,DeepseekV3PreTrainedModel:()=>ka,DeiTForImageClassification:()=>Qg,DeiTModel:()=>Yg,DeiTPreTrainedModel:()=>Ea,DepthAnythingForDepthEstimation:()=>Jg,DepthAnythingPreTrainedModel:()=>Ru,DepthProForDepthEstimation:()=>Zg,DepthProPreTrainedModel:()=>$u,DetrForObjectDetection:()=>tw,DetrForSegmentation:()=>rw,DetrModel:()=>ew,DetrObjectDetectionOutput:()=>Dn,DetrPreTrainedModel:()=>$n,DetrSegmentationOutput:()=>Du,Dinov2ForImageClassification:()=>nw,Dinov2Model:()=>sw,Dinov2PreTrainedModel:()=>Aa,Dinov2WithRegistersForImageClassification:()=>aw,Dinov2WithRegistersModel:()=>ow,Dinov2WithRegistersPreTrainedModel:()=>Ta,DistilBertForMaskedLM:()=>dw,DistilBertForQuestionAnswering:()=>fw,DistilBertForSequenceClassification:()=>uw,DistilBertForTokenClassification:()=>pw,DistilBertModel:()=>cw,DistilBertPreTrainedModel:()=>rs,DonutSwinModel:()=>mw,DonutSwinPreTrainedModel:()=>Fu,EdgeTamModel:()=>Tb,EfficientNetForImageClassification:()=>ww,EfficientNetModel:()=>gw,EfficientNetPreTrainedModel:()=>Sa,ElectraForMaskedLM:()=>yw,ElectraForQuestionAnswering:()=>kw,ElectraForSequenceClassification:()=>bw,ElectraForTokenClassification:()=>vw,ElectraModel:()=>xw,ElectraPreTrainedModel:()=>ss,Ernie4_5ForCausalLM:()=>Aw,Ernie4_5Model:()=>Ew,Ernie4_5PretrainedModel:()=>Oa,EsmForMaskedLM:()=>Mw,EsmForSequenceClassification:()=>Sw,EsmForTokenClassification:()=>Ow,EsmModel:()=>Tw,EsmPreTrainedModel:()=>Fs,EuroBertForMaskedLM:()=>Cw,EuroBertForSequenceClassification:()=>Pw,EuroBertForTokenClassification:()=>Lw,EuroBertModel:()=>Iw,EuroBertPreTrainedModel:()=>Gs,ExaoneForCausalLM:()=>Nw,ExaoneModel:()=>zw,ExaonePreTrainedModel:()=>Ia,FalconForCausalLM:()=>$w,FalconH1ForCausalLM:()=>Bw,FalconH1Model:()=>Dw,FalconH1PreTrainedModel:()=>Pa,FalconModel:()=>Rw,FalconPreTrainedModel:()=>Ca,FastViTForImageClassification:()=>Fw,FastViTModel:()=>Uw,FastViTPreTrainedModel:()=>La,Florence2ForConditionalGeneration:()=>Gw,Florence2PreTrainedModel:()=>Gu,GLPNForDepthEstimation:()=>ox,GLPNModel:()=>nx,GLPNPreTrainedModel:()=>Ua,GPT2LMHeadModel:()=>_x,GPT2Model:()=>mx,GPT2PreTrainedModel:()=>Wa,GPTBigCodeForCausalLM:()=>ix,GPTBigCodeModel:()=>ax,GPTBigCodePreTrainedModel:()=>Fa,GPTJForCausalLM:()=>gx,GPTJModel:()=>hx,GPTJPreTrainedModel:()=>Va,GPTNeoForCausalLM:()=>cx,GPTNeoModel:()=>lx,GPTNeoPreTrainedModel:()=>Ga,GPTNeoXForCausalLM:()=>px,GPTNeoXModel:()=>ux,GPTNeoXPreTrainedModel:()=>ja,Gemma2ForCausalLM:()=>Vw,Gemma2Model:()=>Ww,Gemma2PreTrainedModel:()=>Na,Gemma3ForCausalLM:()=>Yw,Gemma3ForConditionalGeneration:()=>Wu,Gemma3Model:()=>Kw,Gemma3PreTrainedModel:()=>qu,Gemma3nForCausalLM:()=>Qw,Gemma3nForConditionalGeneration:()=>ns,Gemma3nPreTrainedModel:()=>Vu,Gemma4ForCausalLM:()=>Jw,Gemma4ForConditionalGeneration:()=>Bn,GemmaForCausalLM:()=>qw,GemmaModel:()=>jw,GemmaPreTrainedModel:()=>za,GlmForCausalLM:()=>ex,GlmModel:()=>Zw,GlmMoeDsaForCausalLM:()=>rx,GlmMoeDsaModel:()=>tx,GlmMoeDsaPreTrainedModel:()=>$a,GlmOcrForConditionalGeneration:()=>sx,GlmPreTrainedModel:()=>Ra,GptOssForCausalLM:()=>dx,GptOssModel:()=>fx,GptOssPreTrainedModel:()=>qa,GraniteForCausalLM:()=>xx,GraniteModel:()=>wx,GraniteMoeHybridForCausalLM:()=>bx,GraniteMoeHybridModel:()=>yx,GraniteMoeHybridPreTrainedModel:()=>Xa,GranitePreTrainedModel:()=>Ha,GraniteSpeechForConditionalGeneration:()=>vx,GroundingDinoForObjectDetection:()=>kx,GroundingDinoPreTrainedModel:()=>Ku,GroupViTModel:()=>Ex,GroupViTPreTrainedModel:()=>Yu,HeliumForCausalLM:()=>Tx,HeliumModel:()=>Ax,HeliumPreTrainedModel:()=>Ka,HieraForImageClassification:()=>Sx,HieraModel:()=>Mx,HieraPreTrainedModel:()=>Ya,HubertForCTC:()=>Nx,HubertForSequenceClassification:()=>Rx,HubertModel:()=>zx,HubertPreTrainedModel:()=>Lx,HunYuanDenseV1ForCausalLM:()=>Dx,HunYuanDenseV1Model:()=>$x,HunYuanDenseV1PreTrainedModel:()=>Qa,IJepaForImageClassification:()=>Fx,IJepaModel:()=>Ux,IJepaPreTrainedModel:()=>Ja,Idefics3ForConditionalGeneration:()=>Bx,JAISLMHeadModel:()=>jx,JAISModel:()=>Gx,JAISPreTrainedModel:()=>Za,JinaCLIPModel:()=>qx,JinaCLIPPreTrainedModel:()=>Fn,JinaCLIPTextModel:()=>ei,JinaCLIPVisionModel:()=>Wx,Lfm2ForCausalLM:()=>Hx,Lfm2Model:()=>Vx,Lfm2MoeForCausalLM:()=>Yx,Lfm2MoeModel:()=>Kx,Lfm2MoePreTrainedModel:()=>ri,Lfm2PreTrainedModel:()=>ti,Lfm2VlForConditionalGeneration:()=>Qx,LightOnOcrForConditionalGeneration:()=>Xx,LiteWhisperForConditionalGeneration:()=>F1,Llama4ForCausalLM:()=>ey,Llama4PreTrainedModel:()=>Qu,LlamaForCausalLM:()=>Zx,LlamaModel:()=>Jx,LlamaPreTrainedModel:()=>si,LlavaForConditionalGeneration:()=>Et,LlavaOnevisionForConditionalGeneration:()=>Et,LlavaPreTrainedModel:()=>ju,LlavaQwen2ForCausalLM:()=>Xw,LongT5ForConditionalGeneration:()=>ry,LongT5Model:()=>ty,LongT5PreTrainedModel:()=>ni,M2M100ForConditionalGeneration:()=>ny,M2M100Model:()=>sy,M2M100PreTrainedModel:()=>oi,MBartForCausalLM:()=>fy,MBartForConditionalGeneration:()=>uy,MBartForSequenceClassification:()=>py,MBartModel:()=>cy,MBartPreTrainedModel:()=>Ws,MPNetForMaskedLM:()=>Jy,MPNetForQuestionAnswering:()=>t0,MPNetForSequenceClassification:()=>Zy,MPNetForTokenClassification:()=>e0,MPNetModel:()=>Qy,MPNetPreTrainedModel:()=>os,MT5ForConditionalGeneration:()=>o0,MT5Model:()=>n0,MT5PreTrainedModel:()=>wi,MarianMTModel:()=>ay,MarianModel:()=>oy,MarianPreTrainedModel:()=>ai,MaskFormerForInstanceSegmentation:()=>ly,MaskFormerModel:()=>iy,MaskFormerPreTrainedModel:()=>ii,Metric3DForDepthEstimation:()=>dy,Metric3DPreTrainedModel:()=>Ju,Metric3Dv2ForDepthEstimation:()=>my,Metric3Dv2PreTrainedModel:()=>Zu,MgpstrForSceneTextRecognition:()=>_y,MgpstrModelOutput:()=>ep,MgpstrPreTrainedModel:()=>tp,MimiDecoderModel:()=>ci,MimiDecoderOutput:()=>sp,MimiEncoderModel:()=>li,MimiEncoderOutput:()=>rp,MimiModel:()=>hy,MimiPreTrainedModel:()=>Gn,Mistral4ForCausalLM:()=>yy,Mistral4Model:()=>xy,Mistral4PreTrainedModel:()=>pi,MistralForCausalLM:()=>wy,MistralModel:()=>gy,MistralPreTrainedModel:()=>ui,MobileBertForMaskedLM:()=>vy,MobileBertForQuestionAnswering:()=>Ey,MobileBertForSequenceClassification:()=>ky,MobileBertModel:()=>by,MobileBertPreTrainedModel:()=>Vs,MobileLLMForCausalLM:()=>Ty,MobileLLMModel:()=>Ay,MobileLLMPreTrainedModel:()=>fi,MobileNetV1ForImageClassification:()=>Sy,MobileNetV1ForSemanticSegmentation:()=>Oy,MobileNetV1Model:()=>My,MobileNetV1PreTrainedModel:()=>jn,MobileNetV2ForImageClassification:()=>Cy,MobileNetV2ForSemanticSegmentation:()=>Py,MobileNetV2Model:()=>Iy,MobileNetV2PreTrainedModel:()=>qn,MobileNetV3ForImageClassification:()=>zy,MobileNetV3ForSemanticSegmentation:()=>Ny,MobileNetV3Model:()=>Ly,MobileNetV3PreTrainedModel:()=>Wn,MobileNetV4ForImageClassification:()=>$y,MobileNetV4ForSemanticSegmentation:()=>Dy,MobileNetV4Model:()=>Ry,MobileNetV4PreTrainedModel:()=>Vn,MobileViTForImageClassification:()=>Uy,MobileViTModel:()=>By,MobileViTPreTrainedModel:()=>di,MobileViTV2ForImageClassification:()=>Gy,MobileViTV2Model:()=>Fy,MobileViTV2PreTrainedModel:()=>mi,ModernBertDecoderForCausalLM:()=>Xy,ModernBertDecoderModel:()=>Hy,ModernBertDecoderPreTrainedModel:()=>_i,ModernBertForMaskedLM:()=>qy,ModernBertForSequenceClassification:()=>Wy,ModernBertForTokenClassification:()=>Vy,ModernBertModel:()=>jy,ModernBertPreTrainedModel:()=>Hs,Moondream1ForConditionalGeneration:()=>Hw,MoonshineForConditionalGeneration:()=>Yy,MoonshineModel:()=>Ky,MoonshinePreTrainedModel:()=>hi,MptForCausalLM:()=>s0,MptModel:()=>r0,MptPreTrainedModel:()=>gi,MultiModalityCausalLM:()=>a0,MultiModalityPreTrainedModel:()=>np,MusicgenForCausalLM:()=>l0,MusicgenForConditionalGeneration:()=>yi,MusicgenModel:()=>i0,MusicgenPreTrainedModel:()=>xi,NanoChatForCausalLM:()=>u0,NanoChatModel:()=>c0,NanoChatPreTrainedModel:()=>bi,NemotronHForCausalLM:()=>f0,NemotronHModel:()=>p0,NemotronHPreTrainedModel:()=>vi,NeoBertForMaskedLM:()=>m0,NeoBertForQuestionAnswering:()=>g0,NeoBertForSequenceClassification:()=>_0,NeoBertForTokenClassification:()=>h0,NeoBertModel:()=>d0,NeoBertPreTrainedModel:()=>as,NomicBertModel:()=>w0,NomicBertPreTrainedModel:()=>op,OPTForCausalLM:()=>I0,OPTModel:()=>O0,OPTPreTrainedModel:()=>Si,Olmo2ForCausalLM:()=>v0,Olmo2Model:()=>b0,Olmo2PreTrainedModel:()=>Ei,Olmo3ForCausalLM:()=>E0,Olmo3Model:()=>k0,Olmo3PreTrainedModel:()=>Ai,OlmoForCausalLM:()=>y0,OlmoHybridForCausalLM:()=>T0,OlmoHybridModel:()=>A0,OlmoHybridPreTrainedModel:()=>Ti,OlmoModel:()=>x0,OlmoPreTrainedModel:()=>ki,OpenELMForCausalLM:()=>S0,OpenELMModel:()=>M0,OpenELMPreTrainedModel:()=>Mi,OwlViTForObjectDetection:()=>z0,OwlViTModel:()=>L0,OwlViTPreTrainedModel:()=>Ii,Owlv2ForObjectDetection:()=>P0,Owlv2Model:()=>C0,Owlv2PreTrainedModel:()=>Oi,PaliGemmaForConditionalGeneration:()=>N0,ParakeetForCTC:()=>R0,ParakeetPreTrainedModel:()=>ap,PatchTSMixerForPrediction:()=>D0,PatchTSMixerModel:()=>$0,PatchTSMixerPreTrainedModel:()=>Ci,PatchTSTForPrediction:()=>U0,PatchTSTModel:()=>B0,PatchTSTPreTrainedModel:()=>Pi,Phi3ForCausalLM:()=>q0,Phi3Model:()=>j0,Phi3PreTrainedModel:()=>zi,Phi3VForCausalLM:()=>Ni,Phi3VPreTrainedModel:()=>ip,PhiForCausalLM:()=>G0,PhiModel:()=>F0,PhiPreTrainedModel:()=>Li,PreTrainedModel:()=>y,PvtForImageClassification:()=>V0,PvtModel:()=>W0,PvtPreTrainedModel:()=>Ri,PyAnnoteForAudioFrameClassification:()=>X0,PyAnnoteModel:()=>H0,PyAnnotePreTrainedModel:()=>$i,Qwen2ForCausalLM:()=>Y0,Qwen2Model:()=>K0,Qwen2MoeForCausalLM:()=>J0,Qwen2MoeModel:()=>Q0,Qwen2MoePreTrainedModel:()=>Bi,Qwen2PreTrainedModel:()=>Di,Qwen2VLForCausalLM:()=>Da,Qwen2VLForConditionalGeneration:()=>Un,Qwen2VLPreTrainedModel:()=>Hu,Qwen2_5_VLForCausalLM:()=>Ba,Qwen2_5_VLForConditionalGeneration:()=>js,Qwen3ForCausalLM:()=>eb,Qwen3Model:()=>Z0,Qwen3MoeForCausalLM:()=>rb,Qwen3MoeModel:()=>tb,Qwen3MoePreTrainedModel:()=>Fi,Qwen3NextForCausalLM:()=>nb,Qwen3NextModel:()=>sb,Qwen3NextPreTrainedModel:()=>Gi,Qwen3PreTrainedModel:()=>Ui,Qwen3VLForCausalLM:()=>ji,Qwen3VLForConditionalGeneration:()=>Xs,Qwen3VLMoeForCausalLM:()=>ab,Qwen3VLMoeForConditionalGeneration:()=>ob,Qwen3_5ForCausalLM:()=>qi,Qwen3_5ForConditionalGeneration:()=>Hn,Qwen3_5MoeForCausalLM:()=>lb,Qwen3_5MoeForConditionalGeneration:()=>ib,RFDetrForObjectDetection:()=>fb,RFDetrModel:()=>pb,RFDetrObjectDetectionOutput:()=>lp,RFDetrPreTrainedModel:()=>Vi,RTDetrForObjectDetection:()=>Lg,RTDetrModel:()=>Pg,RTDetrObjectDetectionOutput:()=>_r,RTDetrPreTrainedModel:()=>xa,RTDetrV2ForObjectDetection:()=>Eb,RTDetrV2Model:()=>kb,RTDetrV2ObjectDetectionOutput:()=>cp,RTDetrV2PreTrainedModel:()=>Hi,ResNetForImageClassification:()=>ub,ResNetModel:()=>cb,ResNetPreTrainedModel:()=>Wi,RoFormerForMaskedLM:()=>xb,RoFormerForQuestionAnswering:()=>vb,RoFormerForSequenceClassification:()=>yb,RoFormerForTokenClassification:()=>bb,RoFormerModel:()=>wb,RoFormerPreTrainedModel:()=>ls,RobertaForMaskedLM:()=>mb,RobertaForQuestionAnswering:()=>gb,RobertaForSequenceClassification:()=>_b,RobertaForTokenClassification:()=>hb,RobertaModel:()=>db,RobertaPreTrainedModel:()=>is,Sam2ImageSegmentationOutput:()=>fp,Sam2Model:()=>Xi,Sam2PreTrainedModel:()=>dp,Sam3TrackerModel:()=>Mb,SamImageSegmentationOutput:()=>up,SamModel:()=>Ab,SamPreTrainedModel:()=>pp,SapiensForDepthEstimation:()=>Ob,SapiensForNormalEstimation:()=>Ib,SapiensForSemanticSegmentation:()=>Sb,SapiensPreTrainedModel:()=>Xn,SegformerForImageClassification:()=>Pb,SegformerForSemanticSegmentation:()=>Lb,SegformerModel:()=>Cb,SegformerPreTrainedModel:()=>Kn,SiglipModel:()=>zb,SiglipPreTrainedModel:()=>Ki,SiglipTextModel:()=>Yi,SiglipVisionModel:()=>Nb,SmolLM3ForCausalLM:()=>$b,SmolLM3Model:()=>Rb,SmolLM3PreTrainedModel:()=>Qi,SnacDecoderModel:()=>Zi,SnacEncoderModel:()=>Ji,SnacModel:()=>Db,SnacPreTrainedModel:()=>Yn,SolarOpenForCausalLM:()=>Ub,SolarOpenModel:()=>Bb,SolarOpenPreTrainedModel:()=>el,SpeechT5ForSpeechToText:()=>Gb,SpeechT5ForTextToSpeech:()=>jb,SpeechT5HifiGan:()=>qb,SpeechT5Model:()=>Fb,SpeechT5PreTrainedModel:()=>Qn,SqueezeBertForMaskedLM:()=>Vb,SqueezeBertForQuestionAnswering:()=>Xb,SqueezeBertForSequenceClassification:()=>Hb,SqueezeBertModel:()=>Wb,SqueezeBertPreTrainedModel:()=>Ks,StableLmForCausalLM:()=>Yb,StableLmModel:()=>Kb,StableLmPreTrainedModel:()=>tl,Starcoder2ForCausalLM:()=>Jb,Starcoder2Model:()=>Qb,Starcoder2PreTrainedModel:()=>rl,StyleTextToSpeech2Model:()=>Zb,StyleTextToSpeech2PreTrainedModel:()=>mp,SupertonicForConditionalGeneration:()=>sl,SupertonicPreTrainedModel:()=>_p,Swin2SRForImageSuperResolution:()=>n1,Swin2SRModel:()=>s1,Swin2SRPreTrainedModel:()=>nl,SwinForImageClassification:()=>t1,SwinForSemanticSegmentation:()=>r1,SwinModel:()=>e1,SwinPreTrainedModel:()=>Jn,T5ForConditionalGeneration:()=>a1,T5Model:()=>o1,T5PreTrainedModel:()=>ol,TableTransformerForObjectDetection:()=>l1,TableTransformerModel:()=>i1,TableTransformerObjectDetectionOutput:()=>hp,TableTransformerPreTrainedModel:()=>al,TrOCRForCausalLM:()=>c1,TrOCRPreTrainedModel:()=>gp,UltravoxModel:()=>qs,UltravoxPreTrainedModel:()=>Xu,UniSpeechForCTC:()=>p1,UniSpeechForSequenceClassification:()=>f1,UniSpeechModel:()=>u1,UniSpeechPreTrainedModel:()=>Zn,UniSpeechSatForAudioFrameClassification:()=>h1,UniSpeechSatForCTC:()=>m1,UniSpeechSatForSequenceClassification:()=>_1,UniSpeechSatModel:()=>d1,UniSpeechSatPreTrainedModel:()=>Ys,VaultGemmaForCausalLM:()=>w1,VaultGemmaModel:()=>g1,VaultGemmaPreTrainedModel:()=>il,ViTForImageClassification:()=>b1,ViTMAEModel:()=>v1,ViTMAEPreTrainedModel:()=>wp,ViTMSNForImageClassification:()=>E1,ViTMSNModel:()=>k1,ViTMSNPreTrainedModel:()=>cl,ViTModel:()=>y1,ViTPreTrainedModel:()=>ll,VisionEncoderDecoderModel:()=>x1,VitMatteForImageMatting:()=>A1,VitMattePreTrainedModel:()=>xp,VitPoseForPoseEstimation:()=>T1,VitPosePreTrainedModel:()=>yp,VitsModel:()=>M1,VitsModelOutput:()=>bp,VitsPreTrainedModel:()=>vp,VoxtralForConditionalGeneration:()=>S1,VoxtralRealtimeForConditionalGeneration:()=>ul,VoxtralRealtimePreTrainedModel:()=>kp,Wav2Vec2BertForCTC:()=>P1,Wav2Vec2BertForSequenceClassification:()=>L1,Wav2Vec2BertModel:()=>C1,Wav2Vec2BertPreTrainedModel:()=>eo,Wav2Vec2ForAudioFrameClassification:()=>Px,Wav2Vec2ForCTC:()=>Ix,Wav2Vec2ForSequenceClassification:()=>Cx,Wav2Vec2Model:()=>Ox,Wav2Vec2PreTrainedModel:()=>sr,WavLMForAudioFrameClassification:()=>D1,WavLMForCTC:()=>N1,WavLMForSequenceClassification:()=>R1,WavLMForXVector:()=>$1,WavLMModel:()=>z1,WavLMPreTrainedModel:()=>cs,WeSpeakerResNetModel:()=>B1,WeSpeakerResNetPreTrainedModel:()=>Ap,WhisperForConditionalGeneration:()=>Mp,WhisperModel:()=>U1,WhisperPreTrainedModel:()=>pl,XLMForQuestionAnswering:()=>V1,XLMForSequenceClassification:()=>q1,XLMForTokenClassification:()=>W1,XLMModel:()=>G1,XLMPreTrainedModel:()=>us,XLMRobertaForMaskedLM:()=>X1,XLMRobertaForQuestionAnswering:()=>Q1,XLMRobertaForSequenceClassification:()=>K1,XLMRobertaForTokenClassification:()=>Y1,XLMRobertaModel:()=>H1,XLMRobertaPreTrainedModel:()=>ps,XLMWithLMHeadModel:()=>j1,XVectorOutput:()=>Ep,YolosForObjectDetection:()=>Z1,YolosModel:()=>J1,YolosObjectDetectionOutput:()=>Sp,YolosPreTrainedModel:()=>fl,YoutuForCausalLM:()=>tv,YoutuModel:()=>ev,YoutuPreTrainedModel:()=>dl});var Us=class extends y{},Mh=class extends Us{},Sh=class extends Us{async _call(e){return new q(await super._call(e))}},Oh=class extends Us{async _call(e){return new Me(await super._call(e))}},Ih=class extends Us{async _call(e){return new we(await super._call(e))}};var ea=class extends y{},Ch=class extends ea{},Ph=class extends ea{};var ta=class extends y{},Lh=class extends ta{},zh=class extends ta{};var ra=class extends y{},Nh=class extends ra{},Rh=class extends ra{};var sa=class extends y{},$h=class extends sa{},Dh=class extends sa{};var zn=class extends y{},Bh=class extends zn{},Uh=class extends zn{},Fh=class extends zn{async _call(e){return new q(await super._call(e))}};var na=class extends y{},Gh=class extends na{},jh=class extends na{async _call(e){return new q(await super._call(e))}};var Qr=class extends y{},qh=class extends Qr{},Wh=class extends Qr{async _call(e){return new we(await super._call(e))}},Vh=class extends Qr{async _call(e){return new q(await super._call(e))}},Hh=class extends Qr{async _call(e){return new ge(await super._call(e))}},Xh=class extends Qr{async _call(e){return new Me(await super._call(e))}};var oa=class extends y{},Kh=class extends oa{},Yh=class extends oa{};var aa=class extends y{},Qh=class extends aa{},Jh=class extends aa{};var ia=class extends y{},Zh=class extends ia{},eg=class extends ia{};var Jr=class extends y{},tg=class extends Jr{},rg=class extends Jr{async _call(e){return new we(await super._call(e))}},sg=class extends Jr{async _call(e){return new q(await super._call(e))}},ng=class extends Jr{async _call(e){return new ge(await super._call(e))}},og=class extends Jr{async _call(e){return new Me(await super._call(e))}};var VN=4299n,BT=6561n,Iu=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},la=class extends Iu{async encode_speech(e){return fe(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,audio_features:u=null,audio_tokens:f=null,speaker_embeddings:m=null,speaker_features:_=null,...w}){let x;if(!a){let b=this.sessions.embed_tokens.inputNames,A={input_ids:e};if(b.includes("exaggeration")){if(!(n instanceof N)){let S=e.dims[0];if(n==null)n=Ye([S],.5);else if(typeof n=="number")n=Ye([S],n);else if(Array.isArray(n))n=new N("float32",n,[S]);else throw new Error("Unsupported type for `exaggeration` input")}A.exaggeration=n}if(b.includes("position_ids")&&(A.position_ids=o),{inputs_embeds:a}=await fe(this.sessions.embed_tokens,A),u&&f&&m&&_&&(x={audio_features:u,audio_tokens:f,speaker_embeddings:m,speaker_features:_}),x||s)x??=await this.encode_speech(s),a=ve([x.audio_features,a],1),r=et([a.dims[0],a.dims[1]]);else{let S=a.dims[1];if(!i||S!==1)throw new Error("Incorrect state encountered during generation.");let M=i.get_seq_length();r=et([a.dims[0],M+S])}}return{...await Pt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c},!1),...x}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==BT)-1);r.position_ids=new N("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=BT?0:i++)});r.position_ids=new N("int64",o.flat(),r.input_ids.dims)}return r.input_ids.dims[1]===1&&(delete r.audio_values,delete r.audio_features,delete r.audio_tokens,delete r.speaker_embeddings,delete r.speaker_features),Pn(this,e,r,s)}async generate(e){let{sequences:r,audio_tokens:s,speaker_embeddings:n,speaker_features:o}=await super.generate({...e,return_dict_in_generate:!0}),a=r.slice(null,[e.input_ids.dims[1],-1]),i=Ye([a.dims[0],3],VN),l=ve([s,a,i],1),{waveform:c}=await fe(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var Cu=class extends y{},ag=class extends Cu{};var Pu=class extends y{},ig=class extends Pu{};var Nn=class extends y{},lg=class extends Nn{},ca=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},ua=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var mr=class extends y{},cg=class extends mr{},ug=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},pa=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},pg=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},fg=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var fa=class extends y{},dg=class extends fa{},mg=class extends fa{};var da=class extends y{},_g=class extends da{},hg=class extends da{};var ma=class extends y{},gg=class extends ma{},wg=class extends ma{};var _a=class extends y{},xg=class extends _a{},yg=class extends _a{};var ha=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},bg=class extends ha{},vg=class extends ha{};var Zr=class extends y{},kg=class extends Zr{},Eg=class extends Zr{async _call(e){return new we(await super._call(e))}},Ag=class extends Zr{async _call(e){return new q(await super._call(e))}},Tg=class extends Zr{async _call(e){return new ge(await super._call(e))}},Mg=class extends Zr{async _call(e){return new Me(await super._call(e))}};var ga=class extends y{},Sg=class extends ga{},Og=class extends ga{async _call(e){return new q(await super._call(e))}};var wa=class extends y{},Ig=class extends wa{},Cg=class extends wa{async _call(e){return new q(await super._call(e))}};var xa=class extends y{},Pg=class extends xa{},Lg=class extends xa{async _call(e){return new _r(await super._call(e))}},_r=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var ya=class extends y{},zg=class extends ya{},Ng=class extends ya{async _call(e){return new _r(await super._call(e))}};var Lu=class extends $e{constructor({audio_codes:e}){super(),this.audio_codes=e}},zu=class extends $e{constructor({audio_values:e}){super(),this.audio_values=e}},Rn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Rg=class extends Rn{async encode(e){return new Lu(await fe(this.sessions.encoder_model,e))}async decode(e){return new zu(await fe(this.sessions.decoder_model,e))}},ba=class extends Rn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},va=class extends Rn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var es=class extends y{},$g=class extends es{},Dg=class extends es{async _call(e){return new we(await super._call(e))}},Bg=class extends es{async _call(e){return new q(await super._call(e))}},Ug=class extends es{async _call(e){return new ge(await super._call(e))}},Fg=class extends es{async _call(e){return new Me(await super._call(e))}};var ka=class extends y{},Gg=class extends ka{},jg=class extends ka{};var ts=class extends y{},qg=class extends ts{},Wg=class extends ts{async _call(e){return new we(await super._call(e))}},Vg=class extends ts{async _call(e){return new q(await super._call(e))}},Hg=class extends ts{async _call(e){return new ge(await super._call(e))}},Xg=class extends ts{async _call(e){return new Me(await super._call(e))}};var Nu=class extends y{},Kg=class extends Nu{};var Ea=class extends y{},Yg=class extends Ea{},Qg=class extends Ea{async _call(e){return new q(await super._call(e))}};var Ru=class extends y{},Jg=class extends Ru{};var $u=class extends y{},Zg=class extends $u{};var $n=class extends y{},ew=class extends $n{},tw=class extends $n{async _call(e){return new Dn(await super._call(e))}},rw=class extends $n{async _call(e){return new Du(await super._call(e))}},Dn=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},Du=class extends $e{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var Aa=class extends y{},sw=class extends Aa{},nw=class extends Aa{async _call(e){return new q(await super._call(e))}};var Ta=class extends y{},ow=class extends Ta{},aw=class extends Ta{async _call(e){return new q(await super._call(e))}};var Bu=class extends y{},iw=class extends Bu{};var Uu=class extends y{},lw=class extends Uu{};var rs=class extends y{},cw=class extends rs{},uw=class extends rs{async _call(e){return new q(await super._call(e))}},pw=class extends rs{async _call(e){return new ge(await super._call(e))}},fw=class extends rs{async _call(e){return new Me(await super._call(e))}},dw=class extends rs{async _call(e){return new we(await super._call(e))}};var Fu=class extends y{},mw=class extends Fu{};var Ma=class extends y{},_w=class extends Ma{},hw=class extends Ma{};var Sa=class extends y{},gw=class extends Sa{},ww=class extends Sa{async _call(e){return new q(await super._call(e))}};var ss=class extends y{},xw=class extends ss{},yw=class extends ss{async _call(e){return new we(await super._call(e))}},bw=class extends ss{async _call(e){return new q(await super._call(e))}},vw=class extends ss{async _call(e){return new ge(await super._call(e))}},kw=class extends ss{async _call(e){return new Me(await super._call(e))}};var Oa=class extends y{},Ew=class extends Oa{},Aw=class extends Oa{};var Fs=class extends y{},Tw=class extends Fs{},Mw=class extends Fs{async _call(e){return new we(await super._call(e))}},Sw=class extends Fs{async _call(e){return new q(await super._call(e))}},Ow=class extends Fs{async _call(e){return new ge(await super._call(e))}};var Gs=class extends y{},Iw=class extends Gs{},Cw=class extends Gs{async _call(e){return new we(await super._call(e))}},Pw=class extends Gs{async _call(e){return new q(await super._call(e))}},Lw=class extends Gs{async _call(e){return new ge(await super._call(e))}};var Ia=class extends y{},zw=class extends Ia{},Nw=class extends Ia{};var Ca=class extends y{},Rw=class extends Ca{},$w=class extends Ca{};var Pa=class extends y{},Dw=class extends Pa{},Bw=class extends Pa{};var La=class extends y{},Uw=class extends La{},Fw=class extends La{async _call(e){return new q(await super._call(e))}};var Gu=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},Gw=class extends Gu{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:ve([r,e],1),attention_mask:ve([et(r.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:s,attention_mask:n}){if(!e&&!r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,a;return e&&(o=await this.encode_text({input_ids:e})),r&&(a=await this.encode_image({pixel_values:r})),o&&a?{inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:a,input_ids:e,attention_mask:n}):s=o||a,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:r,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:o,encoder_outputs:a,past_key_values:i,inputs_embeds:l,decoder_inputs_embeds:c}){if(l||({inputs_embeds:l,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:l,attention_mask:s})),!a){let{last_hidden_state:f}=await Vt(this,{inputs_embeds:l,attention_mask:s});a=f}if(!c){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:n})}return await Pt(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var za=class extends y{},jw=class extends za{},qw=class extends za{};var Na=class extends y{},Ww=class extends Na{},Vw=class extends Na{};var ju=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Et=class extends ju{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Ln({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},Hw=class extends Et{},Xw=class extends Et{};var qu=class extends y{},Kw=class extends qu{},Wu=class extends Et{},Yw=class extends Wu{};var Vu=class extends y{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},ns=class extends Vu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:f=null,...m}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await fe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:w}=await this._encode_vision({pixel_values:s,...m});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:w}=await fe(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Pt(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,attention_mask:r,position_ids:a,generation_config:u,logits_processor:f},!0)}_encode_vision(e){return fe(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Ln({image_token_id:this.config.image_token_id,...e,image_features:s})}_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return Ou({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},Qw=class extends ns{};var Bn=class extends ns{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(e){return fe(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},Jw=class extends Bn{};var Ra=class extends y{},Zw=class extends Ra{},ex=class extends Ra{};var $a=class extends y{},tx=class extends $a{},rx=class extends $a{};var Hu=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Un=class extends Hu{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,r){if(r){let{data:s,dims:n}=Th(r),o=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),a=Array.from({length:n[0]},(i,l)=>Pe(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return[new N("int64",o,[3,...n]),new N("int64",a,[a.length,1])]}else{let[s,n]=e.dims,o=BigInt64Array.from({length:3*s*n},(a,i)=>BigInt(Math.floor(i%n/s)));return[new N("int64",o,[3,...e.dims]),Bd([s,1])]}}_reorder_and_write_positions(e,r,s,n){let o=e.reduce((c,u)=>c+u.length,0),a=new Array(o),i=0;for(let c=0;c<3;++c)for(let u of e){let f=u.length/3;for(let m=c*f;m<(c+1)*f;++m)a[i++]=u[m]}let l=0;for(let c=0;c(S==l&&A.push(M),A),[]).map(A=>c[A+1]),m=f.filter(A=>A==a).length,_=f.filter(A=>A==i).length,w=[],x=0,v=m,b=_;for(let A=0;Ale>x&&J==a),M=c.findIndex((J,le)=>le>x&&J==i),I=v>0&&S!==-1?S:c.length+1,O=b>0&&M!==-1?M:c.length+1,k,R,G,F;I0?Pe(w.at(-1))[0]+1:0;w.push(Array.from({length:3*U},(J,le)=>C+le%U));let se=U+C,Y=K*V*Q,L=Array.from({length:Y},(J,le)=>se+Math.floor(le/(V*Q))),$=Array.from({length:Y},(J,le)=>se+Math.floor(le/Q)%V),B=Array.from({length:Y},(J,le)=>se+le%Q);w.push([L,$,B].flat()),x=k+Y}if(x0?Pe(w.at(-1))[0]+1:0,S=c.length-x;w.push(Array.from({length:3*S},(M,I)=>A+I%S))}return w}get_rope_index(e,r,s,n){let{vision_config:o}=this.config,a=o.spatial_merge_size??2;if(r||s){let i=e.tolist();n||(n=Rc(e));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),u=r?r.tolist():[],f=s?s.tolist():[],m={image_index:0,video_index:0},_=[];for(let w=0;wl[w][S]==1),v=this._get_multimodal_rope_positions({filtered_ids:x,image_grid_thw_list:u,video_grid_thw_list:f,spatial_merge_size:a,state:m}),b=this._reorder_and_write_positions(v,l[w],c,w);_.push(Pe(b)[0]+1-i[w].length)}return[new N("int64",c.flat(1/0),[3,e.dims[0],e.dims[1]]),new N("int64",_,[_.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:r}){return(await fe(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(e){return Ln({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,r,s){if(!r.attention_mask||r.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return r;if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;let o=r.past_key_values.get_seq_length();if(oa+l);r.position_ids=yt([i,i,i],0)}}return r}},Da=class extends Un{};var js=class extends Un{image_grid_thw_name="image_grid_thw"},Ba=class extends Da{image_grid_thw_name="image_grid_thw"};var sx=class extends js{get_vision_position_ids(e,r,s,n){let o=Math.floor(r[0]/s),a=Math.floor(r[1]/n),i=Math.floor(r[2]/n),l=a*i*o,c=Array.from({length:l},()=>e),u=Array.from({length:l},(m,_)=>e+Math.floor(_/(i*o))),f=Array.from({length:l},(m,_)=>e+_%i);return[...c,...u,...f]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:o}){let{image_token_id:a}=this.config,i=[],l=0,c=e[0]==a?1:0;for(let m=1;m<=e.length;++m){let _=mu+b%x)),u+=x}else{let x=r[o.image_index++].map(Number),v=x[0];f.push(this.get_vision_position_ids(u,x,v,n)),u+=Math.max(x[1],x[2])/n}return f}};var Ua=class extends y{},nx=class extends Ua{},ox=class extends Ua{};var Fa=class extends y{},ax=class extends Fa{},ix=class extends Fa{};var Ga=class extends y{},lx=class extends Ga{},cx=class extends Ga{};var ja=class extends y{},ux=class extends ja{},px=class extends ja{};var qa=class extends y{},fx=class extends qa{},dx=class extends qa{};var Wa=class extends y{},mx=class extends Wa{},_x=class extends Wa{};var Va=class extends y{},hx=class extends Va{},gx=class extends Va{};var Ha=class extends y{},wx=class extends Ha{},xx=class extends Ha{};var Xa=class extends y{},yx=class extends Xa{},bx=class extends Xa{};var Xu=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},qs=class extends Xu{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return Ou({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}};var vx=class extends qs{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var Ku=class extends y{},kx=class extends Ku{};var Yu=class extends y{},Ex=class extends Yu{};var Ka=class extends y{},Ax=class extends Ka{},Tx=class extends Ka{};var Ya=class extends y{},Mx=class extends Ya{},Sx=class extends Ya{async _call(e){return new q(await super._call(e))}};var sr=class extends y{},Ox=class extends sr{},Ix=class extends sr{async _call(e){return new kt(await super._call(e))}},Cx=class extends sr{async _call(e){return new q(await super._call(e))}},Px=class extends sr{async _call(e){return new ge(await super._call(e))}};var Lx=class extends y{},zx=class extends sr{},Nx=class extends sr{async _call(e){return new kt(await super._call(e))}},Rx=class extends sr{async _call(e){return new q(await super._call(e))}};var Qa=class extends y{},$x=class extends Qa{},Dx=class extends Qa{};var Bx=class extends Et{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var Ja=class extends y{},Ux=class extends Ja{},Fx=class extends Ja{async _call(e){return new q(await super._call(e))}};var Za=class extends y{},Gx=class extends Za{},jx=class extends Za{};var Fn=class extends y{},qx=class extends Fn{async forward(e){let r=!e.input_ids,s=!e.pixel_values;if(r&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(r&&(e.input_ids=et([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=Ye([0,3,c,c],0)}let{text_embeddings:n,image_embeddings:o,l2norm_text_embeddings:a,l2norm_image_embeddings:i}=await super.forward(e),l={};return r||(l.text_embeddings=n,l.l2norm_text_embeddings=a),s||(l.image_embeddings=o,l.l2norm_image_embeddings=i),l}},ei=class extends Fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Wx=class extends Fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var ti=class extends y{},Vx=class extends ti{},Hx=class extends ti{};var Xx=class extends Et{};var ri=class extends y{},Kx=class extends ri{},Yx=class extends ri{};var Qx=class extends Et{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var si=class extends y{},Jx=class extends si{},Zx=class extends si{};var Qu=class extends y{},ey=class extends Qu{};var ni=class extends y{},ty=class extends ni{},ry=class extends ni{};var oi=class extends y{},sy=class extends oi{},ny=class extends oi{};var ai=class extends y{},oy=class extends ai{},ay=class extends ai{};var ii=class extends y{},iy=class extends ii{},ly=class extends ii{};var Ws=class extends y{},cy=class extends Ws{},uy=class extends Ws{},py=class extends Ws{async _call(e){return new q(await super._call(e))}},fy=class extends Ws{};var Ju=class extends y{},dy=class extends Ju{};var Zu=class extends y{},my=class extends Zu{};var ep=class extends $e{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},tp=class extends y{},_y=class extends tp{async _call(e){return new ep(await super._call(e))}};var rp=class extends $e{constructor({audio_codes:e}){super(),this.audio_codes=e}},sp=class extends $e{constructor({audio_values:e}){super(),this.audio_values=e}},Gn=class extends y{main_input_name="input_values";forward_params=["input_values"]},hy=class extends Gn{async encode(e){return new rp(await fe(this.sessions.encoder_model,e))}async decode(e){return new sp(await fe(this.sessions.decoder_model,e))}},li=class extends Gn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ci=class extends Gn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var ui=class extends y{},gy=class extends ui{},wy=class extends ui{};var pi=class extends y{},xy=class extends pi{},yy=class extends pi{};var Vs=class extends y{},by=class extends Vs{},vy=class extends Vs{async _call(e){return new we(await super._call(e))}},ky=class extends Vs{async _call(e){return new q(await super._call(e))}},Ey=class extends Vs{async _call(e){return new Me(await super._call(e))}};var fi=class extends y{},Ay=class extends fi{},Ty=class extends fi{};var jn=class extends y{},My=class extends jn{},Sy=class extends jn{async _call(e){return new q(await super._call(e))}},Oy=class extends jn{};var qn=class extends y{},Iy=class extends qn{},Cy=class extends qn{async _call(e){return new q(await super._call(e))}},Py=class extends qn{};var Wn=class extends y{},Ly=class extends Wn{},zy=class extends Wn{async _call(e){return new q(await super._call(e))}},Ny=class extends Wn{};var Vn=class extends y{},Ry=class extends Vn{},$y=class extends Vn{async _call(e){return new q(await super._call(e))}},Dy=class extends Vn{};var di=class extends y{},By=class extends di{},Uy=class extends di{async _call(e){return new q(await super._call(e))}};var mi=class extends y{},Fy=class extends mi{},Gy=class extends mi{async _call(e){return new q(await super._call(e))}};var Hs=class extends y{},jy=class extends Hs{},qy=class extends Hs{async _call(e){return new we(await super._call(e))}},Wy=class extends Hs{async _call(e){return new q(await super._call(e))}},Vy=class extends Hs{async _call(e){return new ge(await super._call(e))}};var _i=class extends y{},Hy=class extends _i{},Xy=class extends _i{};var hi=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Ky=class extends hi{},Yy=class extends hi{};var os=class extends y{},Qy=class extends os{},Jy=class extends os{async _call(e){return new we(await super._call(e))}},Zy=class extends os{async _call(e){return new q(await super._call(e))}},e0=class extends os{async _call(e){return new ge(await super._call(e))}},t0=class extends os{async _call(e){return new Me(await super._call(e))}};var gi=class extends y{},r0=class extends gi{},s0=class extends gi{};var wi=class extends y{},n0=class extends wi{},o0=class extends wi{};var np=class extends y{},a0=class extends np{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){let r=this._generation_mode??"text",s;if(r==="text"||!e.past_key_values){let l=this.sessions.prepare_inputs_embeds,c=Qe(e,l.inputNames);s=await fe(l,c)}else{let l=this.sessions.gen_img_embeds,c=Qe({image_ids:e.input_ids},l.inputNames);s=await fe(l,c)}let n={...e,...s},o=await Pt(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await fe(a,Qe(o,a.inputNames));return{...s,...o,...i}}prepare_inputs_for_generation(e,r,s){let n=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=ve([r.input_ids,r.input_ids],0):(r.input_ids=ve([r.input_ids,Po(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=ve([r.attention_mask,Po(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Ye([0,0,3,384,384],1)),n&&(r.images_seq_mask=new N("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new N("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let r=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[r,null]),o=this.sessions.image_decode,{decoded_image:a}=await fe(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let u=Je.fromTensor(c);l.push(u)}return l}};var xi=class extends y{},i0=class extends xi{},l0=class extends xi{},yi=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[r,s]=e.dims,n=this.config.decoder.num_codebooks,o=s-n,a=0;for(let c=0;c0&&m<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new N(e.type,e.data.slice(0,a),[i,n,l])}prepare_inputs_for_generation(e,r,s){let n=BigInt(this.config.decoder.pad_token_id),o=structuredClone(e);for(let a=0;a=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),Zo(this,o,r,s)}async generate(e){let r=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await fe(this.sessions.encodec_decode,{audio_codes:s});return n}};var bi=class extends y{},c0=class extends bi{},u0=class extends bi{};var vi=class extends y{},p0=class extends vi{},f0=class extends vi{};var as=class extends y{},d0=class extends as{},m0=class extends as{async _call(e){return new we(await super._call(e))}},_0=class extends as{async _call(e){return new q(await super._call(e))}},h0=class extends as{async _call(e){return new ge(await super._call(e))}},g0=class extends as{async _call(e){return new Me(await super._call(e))}};var op=class extends y{},w0=class extends op{};var ki=class extends y{},x0=class extends ki{},y0=class extends ki{};var Ei=class extends y{},b0=class extends Ei{},v0=class extends Ei{};var Ai=class extends y{},k0=class extends Ai{},E0=class extends Ai{};var Ti=class extends y{},A0=class extends Ti{},T0=class extends Ti{};var Mi=class extends y{},M0=class extends Mi{},S0=class extends Mi{};var Si=class extends y{},O0=class extends Si{},I0=class extends Si{};var Oi=class extends y{},C0=class extends Oi{},P0=class extends Oi{};var Ii=class extends y{},L0=class extends Ii{},z0=class extends Ii{};var N0=class extends Et{};var ap=class extends y{},R0=class extends ap{async _call(e){return new kt(await super._call(e))}};var Ci=class extends y{},$0=class extends Ci{},D0=class extends Ci{};var Pi=class extends y{},B0=class extends Pi{},U0=class extends Pi{};var Li=class extends y{},F0=class extends Li{},G0=class extends Li{};var zi=class extends y{},j0=class extends zi{},q0=class extends zi{};var ip=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Ni=class extends ip{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,...u}){if(!a){let m;if(s&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:m}=await fe(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let _=this.config.normalized_config.hidden_size;m=new N("float32",[],[0,_])}({inputs_embeds:a}=await fe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await Pt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var Ri=class extends y{},W0=class extends Ri{},V0=class extends Ri{async _call(e){return new q(await super._call(e))}};var $i=class extends y{},H0=class extends $i{},X0=class extends $i{async _call(e){return new ge(await super._call(e))}};var Di=class extends y{},K0=class extends Di{},Y0=class extends Di{};var Bi=class extends y{},Q0=class extends Bi{},J0=class extends Bi{};var Ui=class extends y{},Z0=class extends Ui{},eb=class extends Ui{};var Fi=class extends y{},tb=class extends Fi{},rb=class extends Fi{};var Gi=class extends y{},sb=class extends Gi{},nb=class extends Gi{};var Xs=class extends js{},ji=class extends Ba{};var ob=class extends Xs{},ab=class extends ji{};var Hn=class extends Xs{},qi=class extends Hn{};var ib=class extends Hn{},lb=class extends qi{};var Wi=class extends y{},cb=class extends Wi{},ub=class extends Wi{async _call(e){return new q(await super._call(e))}};var Vi=class extends y{},pb=class extends Vi{},fb=class extends Vi{async _call(e){return new lp(await super._call(e))}},lp=class extends _r{};var is=class extends y{},db=class extends is{},mb=class extends is{async _call(e){return new we(await super._call(e))}},_b=class extends is{async _call(e){return new q(await super._call(e))}},hb=class extends is{async _call(e){return new ge(await super._call(e))}},gb=class extends is{async _call(e){return new Me(await super._call(e))}};var ls=class extends y{},wb=class extends ls{},xb=class extends ls{async _call(e){return new we(await super._call(e))}},yb=class extends ls{async _call(e){return new q(await super._call(e))}},bb=class extends ls{async _call(e){return new ge(await super._call(e))}},vb=class extends ls{async _call(e){return new Me(await super._call(e))}};var Hi=class extends y{},kb=class extends Hi{},Eb=class extends Hi{async _call(e){return new cp(await super._call(e))}},cp=class extends _r{};var up=class extends $e{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},pp=class extends y{},Ab=class extends pp{async get_image_embeddings({pixel_values:e}){return await Vt(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??=et(e.input_points.dims.slice(0,-1));let r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await fe(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new up(await super._call(e))}};var fp=class extends $e{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},dp=class extends y{},Xi=class extends dp{async get_image_embeddings({pixel_values:e}){return await Vt(this,{pixel_values:e})}async forward(e){let{num_feature_levels:r}=this.config.vision_config;if(Array.from({length:r},(a,i)=>`image_embeddings.${i}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??=et(a.slice(0,-1)),e.input_boxes??=Ye([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Ye([a[0],a[1],0],-1n),e.input_points=Ye([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,o=Qe(e,n.inputNames);return await fe(n,o)}async _call(e){return new fp(await super._call(e))}},Tb=class extends Xi{},Mb=class extends Xi{};var Xn=class extends y{},Sb=class extends Xn{},Ob=class extends Xn{},Ib=class extends Xn{};var Kn=class extends y{},Cb=class extends Kn{},Pb=class extends Kn{},Lb=class extends Kn{};var Ki=class extends y{},zb=class extends Ki{},Yi=class extends Ki{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Nb=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Qi=class extends y{},Rb=class extends Qi{},$b=class extends Qi{};var Yn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Db=class extends Yn{async encode(e){return await fe(this.sessions.encoder_model,e)}async decode(e){return await fe(this.sessions.decoder_model,e)}},Ji=class extends Yn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Zi=class extends Yn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var el=class extends y{},Bb=class extends el{},Ub=class extends el{};var Qn=class extends y{},Fb=class extends Qn{},Gb=class extends Qn{},jb=class extends Qn{async generate_speech(e,r,{threshold:s=.5,minlenratio:n=0,maxlenratio:o=20,vocoder:a=null}={}){let i={input_ids:e},{encoder_outputs:l,encoder_attention_mask:c}=await Vt(this,i),u=l.dims[1]/this.config.reduction_factor,f=Math.floor(u*o),m=Math.floor(u*n),_=this.config.num_mel_bins,w=[],x=null,v=null,b=0;for(;;){++b;let M=Ah(!!v),I;v?I=v.output_sequence_out:I=new N("float32",new Float32Array(_),[1,1,_]);let O={use_cache_branch:M,output_sequence:I,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(O,x),v=await fe(this.sessions.decoder_model_merged,O),x=this.getPastKeyValues(v,x);let{prob:k,spectrum:R}=v;if(w.push(R),b>=m&&(Array.from(k.data).filter(G=>G>=s).length>0||b>=f))break}let A=ve(w),{waveform:S}=await fe(a.sessions.model,{spectrogram:A});return{spectrogram:A,waveform:S}}},qb=class extends y{main_input_name="spectrogram"};var Ks=class extends y{},Wb=class extends Ks{},Vb=class extends Ks{async _call(e){return new we(await super._call(e))}},Hb=class extends Ks{async _call(e){return new q(await super._call(e))}},Xb=class extends Ks{async _call(e){return new Me(await super._call(e))}};var tl=class extends y{},Kb=class extends tl{},Yb=class extends tl{};var rl=class extends y{},Qb=class extends rl{},Jb=class extends rl{};var mp=class extends y{},Zb=class extends mp{};var _p=class extends y{},sl=class extends _p{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:c}=this.config,{last_hidden_state:u,durations:f}=await fe(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=f.div(o).mul_(a),_=l*i,w=m.data,x=Int32Array.from(w,F=>Math.ceil(F/_)),v=Math.max(...x),b=e.dims[0],A=new BigInt64Array(b*v);for(let F=0;Fv*b,1);l[w]=new N(c,new u(x),f[w])}let m=new N(c,new u(i*UT),[1,i,UT]),_=e[Symbol.asyncIterator]?.()??e[Symbol.iterator]?.();if(!_)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:m,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:_,text_hidden_size:r.hidden_size}}async function KN(t,e){let r=e.dims[2],s=Math.floor((HN+r-3)/2)+1,n=new N("int64",BigInt64Array.from({length:s},(u,f)=>BigInt(t.enc_past_seq_len+f)),[1,s]),o=t.enc_past_seq_len+s,a=et([1,o]),{audio_embeds:i,present_padding_cache:l,...c}=await fe(t.encoder_session,{input_features:e,attention_mask:a,position_ids:n,past_padding_cache:t.enc_padding_cache,...t.enc_kv_cache});t.enc_padding_cache.location==="gpu-buffer"&&t.enc_padding_cache.dispose(),t.enc_padding_cache=l;for(let u in c)if(u.startsWith("present.")){let f=u.replace("present","past_key_values"),m=t.enc_kv_cache[f];m?.location==="gpu-buffer"&&m.dispose(),t.enc_kv_cache[f]=c[u]}return t.enc_past_seq_len=o,i}async function YN(t,e){for(;t.audio_embed_total_tokens0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let u=0;u=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var I1=class extends Yr{constructor(e){super(),this._s=e}_call(e){let r=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>r)}},kp=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},ul=class extends kp{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=O1.get(this);o&&await YN(o,o.audio_consumed+n);let{inputs_embeds:a}=await fe(this.sessions.embed_tokens,{input_ids:e});o&&QN(o,a,n);let i={inputs_embeds:a,...s};this.addPastKeyValues(i,r);let l=this.sessions.decoder_model_merged,c=Qe(i,l.inputNames);return await fe(l,c)}async generate({input_features:e,stopping_criteria:r,...s}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let n=XN(this,e);O1.set(this,n);let o=new On;o.push(new I1(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),O1.delete(this)}}};var eo=class extends y{},C1=class extends eo{},P1=class extends eo{async _call(e){return new kt(await super._call(e))}},L1=class extends eo{async _call(e){return new q(await super._call(e))}};var Ep=class extends $e{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},cs=class extends y{},z1=class extends cs{},N1=class extends cs{async _call(e){return new kt(await super._call(e))}},R1=class extends cs{async _call(e){return new q(await super._call(e))}},$1=class extends cs{async _call(e){return new Ep(await super._call(e))}},D1=class extends cs{async _call(e){return new ge(await super._call(e))}};var Ap=class extends y{},B1=class extends Ap{};var Tp=class extends Sn{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1};var pl=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},U1=class extends pl{},Mp=class extends pl{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,Tp)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(ee.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${fT(s)}|>`;r.push(e.lang_to_id[a]),r.push(e.task_to_id[n??"transcribe"])}else if(s||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(ee.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,...o}){r=this._prepare_generation_config(r,o);let a=o.decoder_input_ids??this._retrieve_init_tokens(r);if(r.return_timestamps&&(s??=new Rs,s.push(new hu(r,a))),r.begin_suppress_tokens&&(s??=new Rs,s.push(new Mn(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");r.task==="translate"&&ee.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}if(r.return_timestamps&&!o.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:a,kwargs:o});let i=await super.generate({inputs:e,generation_config:r,logits_processor:s,decoder_input_ids:a,...o});return r.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,r.alignment_heads,r.num_frames,.02,a.length)),i}async _generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:n,kwargs:o}){let a=r.no_timestamps_token_id+1,i=Array.isArray(r.eos_token_id)?r.eos_token_id[0]:r.eos_token_id,l=r.return_token_timestamps,c=e,u=c.dims[2],f=2,m=this.config.max_source_positions,_=f*m,w=0,x=[],v=[];for(;wL+Y)}if(R.length>0&&R.at(-1)===i&&R.pop(),R.length===0)break;let F=R.map(Y=>Y>=a),K=R.length>=2&&F[R.length-1]&&!F[R.length-2],V=[];for(let Y=0;Y0)if(K)Q=A-w;else{let Y=V.at(-1);Q=(R[Y-1]-a)*f,U=Y}else Q=A-w;let C=Math.floor(w/f),se=a+1500;for(let Y=0;Y=a&&(R[Y]=Math.min(R[Y]+C,se));x.push(...R.slice(0,U)),G&&v.push(...G.slice(0,U)),w+=Q}x.push(i);let b=[...n,...x];if(l){let A=new N("int64",b.map(BigInt),[1,b.length]),S=[...new Array(n.length).fill(0),...v,0],M=new N("float32",new Float32Array(S),[1,S.length]);return{sequences:A,token_timestamps:M}}return new N("int64",b.map(BigInt),[1,b.length])}_extract_token_timestamps(e,r,s=null,n=.02,o=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");s==null&&ee.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(ee.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let i=e.cross_attentions,l=Array.from({length:this.config.decoder_layers},(b,A)=>ve(i.map(S=>S[A]),2)),c=yt(r.map(([b,A])=>{if(b>=l.length)throw new Error(`Layer index ${b} is out of bounds for cross attentions (length ${l.length}).`);return s?l[b].slice(null,A,null,[0,s]):l[b].slice(null,A)})).transpose(1,0,2,3),[u,f]=$d(c,-2,0,!0),m=c.clone();for(let b=0;b0?m.slice(null,null,[o,m.dims[2]],null):m,w=[Nc(_,1)],x=e.sequences.dims,v=new N("float32",new Float32Array(x[0]*x[1]),x);for(let b=0;bS[F+1]-S[F]),O=ht([1],I).map(G=>!!G),k=[];for(let G=0;G0&&R.push(k.at(-1)),v[b].data.set(R)}return v}},F1=class extends Mp{};var us=class extends y{},G1=class extends us{},j1=class extends us{async _call(e){return new we(await super._call(e))}},q1=class extends us{async _call(e){return new q(await super._call(e))}},W1=class extends us{async _call(e){return new ge(await super._call(e))}},V1=class extends us{async _call(e){return new Me(await super._call(e))}};var ps=class extends y{},H1=class extends ps{},X1=class extends ps{async _call(e){return new we(await super._call(e))}},K1=class extends ps{async _call(e){return new q(await super._call(e))}},Y1=class extends ps{async _call(e){return new ge(await super._call(e))}},Q1=class extends ps{async _call(e){return new Me(await super._call(e))}};var fl=class extends y{},J1=class extends fl{},Z1=class extends fl{async _call(e){return new Sp(await super._call(e))}},Sp=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var dl=class extends y{},ev=class extends dl{},tv=class extends dl{};var JN=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"]]),ZN=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"]]),e3=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),t3=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"]]),FT=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),GT=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),jT=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),qT=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"]]),WT=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"]]),VT=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),HT=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"]]),r3=new Map([["multi_modality","MultiModalityCausalLM"]]),XT=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"]]),KT=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"]]),YT=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),QT=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"]]),JT=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),s3=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),ZT=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"]]),eM=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),tM=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),to=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),rM=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),sM=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),nM=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),oM=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),aM=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),iM=new Map([["wavlm","WavLMForXVector"]]),lM=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),cM=new Map([["vitmatte","VitMatteForImageMatting"]]),n3=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),uM=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),pM=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),fM=new Map([["sapiens","SapiensForNormalEstimation"]]),dM=new Map([["vitpose","VitPoseForPoseEstimation"]]),mM=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),rv=[[JN,H.EncoderOnly],[ZN,H.EncoderDecoder],[t3,H.DecoderOnlyWithoutHead],[e3,H.AutoEncoder],[qT,H.EncoderOnly],[WT,H.EncoderOnly],[VT,H.Seq2Seq],[FT,H.Seq2Seq],[HT,H.DecoderOnly],[r3,H.MultiModality],[XT,H.EncoderOnly],[KT,H.EncoderOnly],[YT,H.Vision2Seq],[QT,H.ImageTextToText],[JT,H.AudioTextToText],[ZT,H.EncoderOnly],[to,H.EncoderOnly],[sM,H.EncoderOnly],[rM,H.EncoderOnly],[cM,H.EncoderOnly],[n3,H.EncoderOnly],[uM,H.EncoderOnly],[pM,H.EncoderOnly],[fM,H.EncoderOnly],[dM,H.EncoderOnly],[eM,H.EncoderOnly],[tM,H.EncoderOnly],[nM,H.MaskGeneration],[oM,H.EncoderOnly],[aM,H.EncoderOnly],[GT,H.Seq2Seq],[jT,H.EncoderOnly],[iM,H.EncoderOnly],[lM,H.EncoderOnly],[mM,H.EncoderOnly]];for(let[t,e]of rv)for(let r of t.values()){rr.set(r,e);let s=ml[r];Bs.set(s,r),Su.set(r,s)}var o3=[["MusicgenForConditionalGeneration",yi,H.Musicgen],["Phi3VForCausalLM",Ni,H.Phi3V],["CLIPTextModelWithProjection",pa,H.EncoderOnly],["SiglipTextModel",Yi,H.EncoderOnly],["JinaCLIPTextModel",ei,H.EncoderOnly],["ClapTextModelWithProjection",ca,H.EncoderOnly],["ClapAudioModelWithProjection",ua,H.EncoderOnly],["DacEncoderModel",ba,H.EncoderOnly],["DacDecoderModel",va,H.EncoderOnly],["MimiEncoderModel",li,H.EncoderOnly],["MimiDecoderModel",ci,H.EncoderOnly],["SnacEncoderModel",Ji,H.EncoderOnly],["SnacDecoderModel",Zi,H.EncoderOnly],["Gemma3nForConditionalGeneration",ns,H.ImageAudioTextToText],["Gemma4ForConditionalGeneration",Bn,H.ImageAudioTextToText],["SupertonicForConditionalGeneration",sl,H.Supertonic],["ChatterboxModel",la,H.Chatterbox],["VoxtralRealtimeForConditionalGeneration",ul,H.VoxtralRealtime]];for(let[t,e,r]of o3)rr.set(t,r),Bs.set(e,t),Su.set(t,e);var _M=new Map([["modnet",to],["birefnet",to],["isnet",to],["ben",to]]);for(let[t,e]of _M.entries())e.set(t,"PreTrainedModel"),rr.set(t,H.EncoderOnly),Su.set(t,y);var hM=new Set(_M.keys());rr.set("PreTrainedModel",H.EncoderOnly);Bs.set(y,"PreTrainedModel");var ze={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:qT,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:WT,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:GT,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:jT,MODEL_FOR_MASKED_LM_MAPPING_NAMES:XT,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:KT,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:ZT,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:to,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:rM,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:sM,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:eM,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:tM,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:nM,MODEL_FOR_CTC_MAPPING_NAMES:oM,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:aM,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:iM,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:lM,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:s3,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:cM,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:uM,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:pM,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:fM,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:dM,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:mM,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:QT,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:JT,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:VT,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:FT,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:HT,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:YT};RT(ze);var Ce=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let r of this.MODEL_CLASS_MAPPINGS)if(r.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:f,session_options:m};if(_.config=await Wt.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:w}=_.config;for(let x of this.MODEL_CLASS_MAPPINGS){let v=x.get(w);if(!v){for(let b of x.values())if(b[0]===w){v=b;break}if(!v)continue}return await ml[v].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return hM.has(w)||ee.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,_);throw Error(`Unsupported model type: ${w}`)}},Ar=class extends Ce{static MODEL_CLASS_MAPPINGS=rv.map(e=>e[0]);static BASE_IF_FAIL=!0},_l=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},Op=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},ro=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},Ip=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},Cp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},Pp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},Lp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},zp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},Np=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},Rp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},$p=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},hl=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},gl=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},wl=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},Dp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Bp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},gM=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},Up=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_CTC_MAPPING_NAMES]},Fp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},wM=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},xM=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},Gp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},yM=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},jp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},qp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},bM=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},vM=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},Wp=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},kM=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},EM=class extends Ce{static MODEL_CLASS_MAPPINGS=[ze.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function tt(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Je.read(e)))}async function Tr(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?Rm(r,e):r instanceof Float64Array?new Float32Array(r):r))}function xl(t,e){e&&(t=t.map(a=>a|0));let[r,s,n,o]=t;return{xmin:r,ymin:s,xmax:n,ymax:o}}var me=class extends We{constructor({task:e,model:r,tokenizer:s=null,processor:n=null}){super(),this.task=e,this.model=r,this.tokenizer=s,this.processor=n}async dispose(){await this.model.dispose()}};var yl=class extends me{async _call(e,{top_k:r=1}={}){let s=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(s),{problem_type:o,id2label:a}=this.model.config,i=o==="multi_label_classification"?c=>c.sigmoid():c=>new N("float32",Re(c.data),c.dims),l=[];for(let c of n.logits){let u=i(c),f=await tr(u,r),m=f[0].tolist(),w=f[1].tolist().map((x,v)=>({label:a?a[x]:`LABEL_${x}`,score:m[v]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var bl=class extends me{async _call(e,{ignore_labels:r=["O"]}={}){let s=Array.isArray(e),n=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),a=(await this.model(n)).logits,i=this.model.config.id2label,l=[];for(let c=0;cO==f),v=a[_].tolist(),b=i[_].tolist();for(let O=1;Ok==w[O])!==-1)&&(v[O]=-1/0,b[O]=-1/0);let A=Re(v).map((O,k)=>[O,k]),S=Re(b).map((O,k)=>[O,k]);A[0][0]=0,S[0][0]=0;let M=xE(A,S).filter(O=>O[0][1]<=O[1][1]).map(O=>[O[0][1],O[1][1],O[0][0]*O[1][0]]).sort((O,k)=>k[2]-O[2]),I=[];for(let O=0;Ov==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][f],_=await tr(new N("float32",Re(m.data),m.dims),r),w=_[0].tolist(),x=_[1].tolist();i.push(x.map((v,b)=>{let A=u.slice();return A[f]=v,{score:w[b],token:Number(v),token_str:this.tokenizer.decode([v]),sequence:this.tokenizer.decode(A,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Mr=class extends me{_key="generated_text";async _call(e,r={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(l=>s[this.task].prefix+l));let n=this.tokenizer,o={padding:!0,truncation:!0},a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,o,r):a=n(e,o);let i=await this.model.generate({...a,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}};var El=class extends Mr{_key="summary_text"};var Al=class extends Mr{_key="translation_text"};function AM(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Tl=class extends me{async _call(e,r={}){let s=!1,n=!1,o=r.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=r.tokenizer_encode_kwargs,i;if(typeof e=="string")i=e=[e];else if(Array.isArray(e)&&e.every(w=>typeof w=="string"))s=!0,i=e;else{if(AM(e))e=[e];else if(Array.isArray(e)&&e.every(AM))s=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=!0,i=e.map(w=>this.tokenizer.apply_chat_template(w,{tokenize:!1,add_generation_prompt:!0,...a})),o=!1,a=void 0}let l=n?!1:r.return_full_text??!0;this.tokenizer.padding_side="left";let c=this.tokenizer(i,{add_special_tokens:o,padding:!0,truncation:!0,...a}),u=await this.model.generate({...c,...r}),f=this.tokenizer.batch_decode(u,{skip_special_tokens:!0}),m;!l&&c.input_ids.dims.at(-1)>0&&(m=this.tokenizer.batch_decode(c.input_ids,{skip_special_tokens:!0}).map(w=>w.length));let _=Array.from({length:e.length},w=>[]);for(let w=0;w[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(ee.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(ee.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let u=[];for(let _ of a){let w=this.tokenizer(c,{text_pair:_,padding:!0,truncation:!0}),x=await this.model(w);i?u.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):u.push(x.logits.data[this.entailment_id])}let m=(i?u.map(_=>Re(_)[1]):Re(u)).map((_,w)=>[_,w]).sort((_,w)=>w[0]-_[0]);l.push({sequence:c,labels:m.map(_=>r[_[1]]),scores:m.map(_=>_[0])})}return o?l:l[0]}};var Sl=class extends me{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await Tr(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),u=(await this.model(l)).logits[0],f=await tr(new N("float32",Re(u.data),u.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,v)=>({label:o?o[x]:`LABEL_${x}`,score:m[v]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var Ol=class extends me{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(u=>s.replace("{}",u)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await Tr(e,i),c=[];for(let u of l){let f=await this.processor(u),m=await this.model({...a,...f}),_=Re(m.logits_per_audio.data);c.push([..._].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var Il=class extends me{async _call(e,r={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,r);case"moonshine":return this._call_moonshine(e,r);case"cohere_asr":return this._call_cohere_asr(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&ee.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&ee.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Tr(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).logits[0],m=[];for(let w of f)m.push(Pe(w.data)[1]);let _=this.tokenizer.decode(m,{skip_special_tokens:!0}).trim();i.push({text:_})}return s?i[0]:i}async _call_whisper(e,r){let s=r.return_timestamps??!1,n=r.chunk_length_s??0,o=r.force_full_sequences??!1,a=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);let l=!Array.isArray(e),c=l?[e]:e,u=this.processor.feature_extractor.config,f=u.chunk_length/this.model.config.max_source_positions,m=u.hop_length,_=u.sampling_rate,w=await Tr(c,_),x=[];for(let v of w){let b=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let M=_*n,I=_*a,O=M-2*I,k=0;for(;;){let R=k+M,G=v.subarray(k,R),F=await this.processor(G),K=k===0,V=R>=v.length;if(b.push({stride:[G.length,K?0:I,V?0:I],input_features:F.input_features,is_last:V}),V)break;k+=O}}else b=[{stride:[v.length,0,0],input_features:(await this.processor(v)).input_features,is_last:!0}];for(let M of b){i.num_frames=Math.floor(M.stride[0]/m);let I=await this.model.generate({inputs:M.input_features,...i});if(s==="word"){let O=I.sequences.tolist()[0],k=I.token_timestamps.tolist()[0],R=this.tokenizer.timestamp_begin,G=Math.max(O.findIndex(F=>Number(F)>=R),0);M.tokens=O.slice(G),M.token_timestamps=k.slice(G).map(F=>bs(F,2))}else M.tokens=I[0].tolist();M.stride=M.stride.map(O=>O/_)}let[A,S]=this.tokenizer._decode_asr(b,{time_precision:f,return_timestamps:s,force_full_sequences:o});x.push({text:A,...S})}return l?x[0]:x}async _call_moonshine(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Tr(n,o),i=[];for(let l of a){let c=await this.processor(l),u=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:u,...r,...c}),m=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}async _call_cohere_asr(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor,a=o.config.sampling_rate,i=await Tr(n,a),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),u=[];for(let f of i){let m=o.split_audio(f),_=[];for(let x of m){let v=await this.processor(x),b=await this.model.generate({...v,decoder_input_ids:c,...r}),A=this.tokenizer.decode(b[0].tolist(),{skip_special_tokens:!0}).trim();_.push(A)}let w=this.processor.constructor.join_chunks(_,l);u.push({text:w})}return s?u[0]:u}};var Cl=class extends me{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,r){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await _e.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new N("float32",e,[e.length]);else if(!(e instanceof N))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,c=[];for(let u=0;u({generated_text:u.trim()}));a.push(c)}return s?a:a[0]}};var Ll=class extends me{async _call(e,{top_k:r=5}={}){let s=await tt(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),{id2label:a}=this.model.config,i=[];for(let l of o.logits){let c=await tr(new N("float32",Re(l.data),l.dims),r),u=c[0].tolist(),m=c[1].tolist().map((_,w)=>({label:a?a[_]:`LABEL_${_}`,score:u[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var TM={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Qs=class extends me{async _call(e,{threshold:r=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:o=null,target_sizes:a=null,subtask:i=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let c=await tt(e),u=c.map(A=>[A.height,A.width]),f=await this.processor(c),{inputNames:m,outputNames:_}=this.model.sessions.model;if(!m.includes("pixel_values")){if(m.length!==1)throw Error(`Expected a single input name, but got ${m.length} inputs: ${m}.`);let A=m[0];if(A in f)throw Error(`Input name ${A} already exists in the inputs.`);f[A]=f.pixel_values}let w=await this.model(f),x=null;if(i!==null)x=TM[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(TM))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=A;break}}let v=this.model.config.id2label,b=[];if(i)if(i==="panoptic"||i==="instance"){let A=x(w,r,s,n,o,a??u)[0],S=A.segmentation;for(let M of A.segments_info){let I=new Uint8ClampedArray(S.data.length);for(let k=0;kR<-1e-5||R>1+1e-5)&&O.sigmoid_();let k=await Je.fromTensor(O.mul_(255).to("uint8")).resize(I[1],I[0]);b.push({label:null,score:null,mask:k})}}return b}};var zl=class extends Qs{async _call(e,r={}){let s=await tt(e),n=await super._call(e,r),o=s.map((a,i)=>{let l=a.clone();return l.putAlpha(n[i].mask),l});return Array.isArray(e)?o:o[0]}};var Nl=class extends me{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await tt(e),a=r.map(m=>s.replace("{}",m)),i=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(o),c=await this.model({...i,pixel_values:l}),u=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Re(m.data),f=[];for(let m of c.logits_per_image){let w=[...u(m)].map((x,v)=>({score:x,label:r[v]}));w.sort((x,v)=>v.score-x.score),f.push(w)}return n?f:f[0]}};var Rl=class extends me{async _call(e,{threshold:r=.9,percentage:s=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let o=await tt(e),a=s?null:o.map(_=>[_.height,_.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),c=await this.model({pixel_values:i,pixel_mask:l}),u=this.processor.image_processor.post_process_object_detection(c,r,a),{id2label:f}=this.model.config,m=u.map(_=>_.boxes.map((w,x)=>({score:_.scores[x],label:f[_.classes[x]],box:xl(w,!s)})));return n?m:m[0]}};var $l=class extends me{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await tt(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=await this.processor(i),u=[];for(let f=0;f({score:b.scores[S],label:b.labels[S],box:xl(A,!o)}))}else{let b=this.processor.image_processor.post_process_object_detection(x,s,_,!0)[0];v=b.boxes.map((A,S)=>({score:b.scores[S],label:r[b.classes[S]],box:xl(A,!o)}))}v.sort((b,A)=>A.score-b.score),n!==null&&(v=v.slice(0,n)),u.push(v)}return a?u:u[0]}};var Dl=class extends me{async _call(e,r,s={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await tt(e))[0],{pixel_values:o}=await this.processor(n),a=`${r}`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...s}),u=this.tokenizer.batch_decode(l)[0].match(/(.*?)<\/s_answer>/),f=null;return u&&u.length>=2&&(f=u[1].trim()),[{answer:f}]}};var Bl=class extends me{async _call(e){let r=await tt(e),s=await this.processor(r),n=await this.model(s),o=[];for(let a of n.reconstruction){let i=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(Je.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var Ul=class extends me{async _call(e){let r=await tt(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a`onnx/${m}`);return i.filter(m=>!m.startsWith("onnx/")||f.some(_=>m.startsWith(_)))}}return i}async function Lce(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:u=null,model_file_name:f=null,session_options:m={}}={}){t=Vp[t]??t;let _=so[t.split("_",1)[0]];if(!_)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(so)}]`);e||(e=_.default.model,ee.info(`No model specified. Using default model: "${e}".`),!l&&_.default.dtype&&(l=_.default.dtype));let w=await Or(t,e,{device:i,dtype:l}),x={};r&&(await Promise.all(w.map(async K=>Ct(e,K)))).forEach((K,V)=>{K.exists&&(x[w[V]]={loaded:0,total:K.size??0})});let v={progress_callback:r?new gs(r,x):void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:u,model_file_name:f,session_options:m},b=w.includes("tokenizer.json"),A=w.includes("preprocessor_config.json"),S=_.model,M;if(Array.isArray(S)){let F=s??await Wt.from_pretrained(e,v),{model_type:K}=F,V=S.find(Q=>Q.supports(K));if(!V)throw Error(`Unsupported model type "${K}" for task "${t}". None of the candidate model classes support this type.`);M=V.from_pretrained(e,{...v,config:F})}else M=S.from_pretrained(e,v);let[I,O,k]=await Promise.all([b?ne.from_pretrained(e,v):null,A?pu.from_pretrained(e,v):null,M]),R={task:t,model:k};I&&(R.tokenizer=I),O&&(R.processor=O),lr(r,{status:"ready",task:t,model:e});let G=_.pipeline;return new G(R)}var a3=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,sv=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},MM=ie.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),nv=class extends sv{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,skip_special_tokens:o=!0,decode_kwargs:a={},...i}={}){super(),this.tokenizer=e,this.skip_prompt=r,this.callback_function=s??MM,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:o,...a,...i},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let r=this.next_tokens_are_prompt;if(r&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let s=e[0];if(this.token_callback_function?.(s),s.length===1&&this.special_ids.has(s[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let l=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(l,!1),this.token_cache=[],this.print_len=0}let a=this.tokenizer.decode(s,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=ht(this.token_cache,s);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),o;r||n.endsWith(` `)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&a3(n.charCodeAt(n.length-1))?(o=n.slice(this.print_len),this.print_len+=o.length):(o=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=o.length),this.on_finalized_text(o,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,r){e.length>0&&this.callback_function?.(e),r&&this.callback_function===MM&&ie.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}},SM=class extends nv{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:c=!0,decode_kwargs:u={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,callback_function:s,token_callback_function:n,decode_kwargs:u}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var jl=class{constructor(e,r){this.image=e,this.timestamp=r}},Xp=class{constructor(e,r){e.length>0&&e[0]instanceof Je&&(e=e.map((s,n)=>new jl(s,(n+1)/(e.length+1)*r))),this.frames=e,this.duration=r}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};async function i3(t,{num_frames:e=null,fps:r=null}={}){if(!ie.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(e==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let s=[],n=document.createElement("video");if(n.crossOrigin="anonymous",n.muted=!0,typeof t=="string")n.src=t;else if(t instanceof Blob)n.src=URL.createObjectURL(t);else if(t instanceof HTMLVideoElement)n.src=t.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(f=>n.onloadedmetadata=f),n.seekable.start(0)===n.seekable.end(0)){let m=await(await _e.fetch(n.src)).blob();n.src=URL.createObjectURL(m),await new Promise(_=>n.onloadedmetadata=_)}let o=n.duration,a,i;e!=null?(a=e,i=e===1?0:o/(e-1)):(i=1/r,a=Math.floor(o/i));let l=[];for(let f=0;f{n.onseeked=x}),u.drawImage(n,0,0,c.width,c.height);let m=u.getImageData(0,0,c.width,c.height),_=new Je(m.data,c.width,c.height,4),w=new jl(_,f);s.push(w)}return n.remove(),new Xp(s,o)}async function Kp(t,e,r={}){let s=await Zt(r?.cache_dir);if(!s)return{allCached:!1,files:e.map(a=>({file:a,cached:!1}))};let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=$r(t,o,r,s),l=await Dr(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function OM(t,e,r={}){let s=await Zt(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=$r(t,e,r,s);return!!await Dr(s,n,o)}async function IM(t,e={}){if(!t)throw new Error("modelId is required");if(!await OM(t,"config.json",e))return!1;let r=await Sr(t,e);return(await Kp(t,r,e)).allCached}async function CM(t,e={}){if(!t)throw new Error("modelId is required");let r=await Sr(t,e);return await Kp(t,r,e)}async function PM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await OM(e,"config.json",r))return!1;let s=await Or(t,e,r);return(await Kp(e,s,r)).allCached}async function LM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Or(t,e,r);return await Kp(e,s,r)}async function zM(t,e,r={}){let s=await Zt(r?.cache_dir);if(!s)return{filesDeleted:0,filesCached:0,files:e.map(o=>({file:o,deleted:!1,wasCached:!1}))};if(!s.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=$r(t,o,r,s),c=!!await Dr(s,a,i),u=!1;if(c){let f=await s.delete(i),m=!f&&i!==a?await s.delete(a):!1;u=f||m}return{file:o,deleted:u,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function NM(t,e={}){if(!t)throw new Error("modelId is required");let r=await Sr(t,e);return await zM(t,r,e)}async function RM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Or(t,e,r);return await zM(e,s,r)}var l3=Object.keys(Vr);async function $M(t,{config:e=null,model_file_name:r=null,revision:s="main",cache_dir:n=null,local_files_only:o=!1}={}){e=await Jo(t,{config:e,cache_dir:n,local_files_only:o,revision:s});let a="onnx",i=In(e),{sessions:l}=Qo(i,e,{model_file_name:r}),c=Object.values(l),u={revision:s,cache_dir:n,local_files_only:o};return(await Promise.all(l3.map(async m=>{let _=Vr[m]??"",w=await Promise.all(c.map(async x=>{let v=`${a}/${x}${_}.onnx`;return(await Ct(t,v,u)).exists}));return{dtype:m,available:w.every(Boolean)}}))).filter(m=>m.available).map(m=>m.dtype)}var ov=class{static async get_files(e,r={}){return Sr(e,r)}static async get_pipeline_files(e,r,s={}){return Or(e,r,s)}static async get_model_files(e,r={}){return Cn(e,r)}static async get_tokenizer_files(e){return hn(e)}static async get_processor_files(e){return Hp(e)}static async get_available_dtypes(e,r={}){return $M(e,r)}static async is_cached(e,r={}){return IM(e,r)}static async is_cached_files(e,r={}){return CM(e,r)}static async is_pipeline_cached(e,r,s={}){return PM(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return LM(e,r,s)}static async get_file_metadata(e,r,s={}){return Ct(e,r,s)}static async clear_cache(e,r={}){return NM(e,r)}static async clear_pipeline_cache(e,r,s={}){return RM(e,r,s)}};export{$m as ASTFeatureExtractor,Dh as ASTForAudioClassification,$h as ASTModel,sa as ASTPreTrainedModel,zh as AfmoeForCausalLM,Lh as AfmoeModel,ta as AfmoePreTrainedModel,Ih as AlbertForMaskedLM,Oh as AlbertForQuestionAnswering,Sh as AlbertForSequenceClassification,Mh as AlbertModel,Us as AlbertPreTrainedModel,jd as AlbertTokenizer,Ph as ApertusForCausalLM,Ch as ApertusModel,ea as ApertusPreTrainedModel,Rh as ArceeForCausalLM,Nh as ArceeModel,ra as ArceePreTrainedModel,Sl as AudioClassificationPipeline,Wt as AutoConfig,Ge as AutoFeatureExtractor,Te as AutoImageProcessor,Ar as AutoModel,Fp as AutoModelForAudioClassification,xM as AutoModelForAudioFrameClassification,EM as AutoModelForAudioTextToText,Up as AutoModelForCTC,Lp as AutoModelForCausalLM,qp as AutoModelForDepthEstimation,Gp as AutoModelForDocumentQuestionAnswering,$p as AutoModelForImageClassification,Wp as AutoModelForImageFeatureExtraction,yM as AutoModelForImageMatting,hl as AutoModelForImageSegmentation,kM as AutoModelForImageTextToText,jp as AutoModelForImageToImage,gM as AutoModelForMaskGeneration,zp as AutoModelForMaskedLM,bM as AutoModelForNormalEstimation,Dp as AutoModelForObjectDetection,vM as AutoModelForPoseEstimation,Np as AutoModelForQuestionAnswering,gl as AutoModelForSemanticSegmentation,ro as AutoModelForSeq2SeqLM,_l as AutoModelForSequenceClassification,Ip as AutoModelForSpeechSeq2Seq,Cp as AutoModelForTextToSpectrogram,Pp as AutoModelForTextToWaveform,Op as AutoModelForTokenClassification,wl as AutoModelForUniversalSegmentation,Rp as AutoModelForVision2Seq,wM as AutoModelForXVector,Bp as AutoModelForZeroShotObjectDetection,pu as AutoProcessor,ne as AutoTokenizer,Il as AutomaticSpeechRecognitionPipeline,zl as BackgroundRemovalPipeline,Uh as BartForConditionalGeneration,Fh as BartForSequenceClassification,Bh as BartModel,zn as BartPretrainedModel,qd as BartTokenizer,sv as BaseStreamer,Zm as BeitFeatureExtractor,jh as BeitForImageClassification,Gh as BeitModel,na as BeitPreTrainedModel,Wh as BertForMaskedLM,Xh as BertForQuestionAnswering,Vh as BertForSequenceClassification,Hh as BertForTokenClassification,qh as BertModel,Qr as BertPreTrainedModel,Wd as BertTokenizer,e_ as BitImageProcessor,Yh as BlenderbotForConditionalGeneration,Kh as BlenderbotModel,oa as BlenderbotPreTrainedModel,Jh as BlenderbotSmallForConditionalGeneration,Qh as BlenderbotSmallModel,aa as BlenderbotSmallPreTrainedModel,Vd as BlenderbotSmallTokenizer,Hd as BlenderbotTokenizer,eg as BloomForCausalLM,Zh as BloomModel,ia as BloomPreTrainedModel,Xd as BloomTokenizer,ig as CHMv2ForDepthEstimation,r_ as CHMv2ImageProcessor,Pu as CHMv2PreTrainedModel,s_ as CLIPFeatureExtractor,Wc as CLIPImageProcessor,cg as CLIPModel,mr as CLIPPreTrainedModel,mg as CLIPSegForImageSegmentation,dg as CLIPSegModel,fa as CLIPSegPreTrainedModel,ug as CLIPTextModel,pa as CLIPTextModelWithProjection,Yd as CLIPTokenizer,pg as CLIPVisionModel,fg as CLIPVisionModelWithProjection,rg as CamembertForMaskedLM,og as CamembertForQuestionAnswering,sg as CamembertForSequenceClassification,ng as CamembertForTokenClassification,tg as CamembertModel,Jr as CamembertPreTrainedModel,Kd as CamembertTokenizer,Dm as ChatterboxFeatureExtractor,la as ChatterboxModel,Iu as ChatterboxPreTrainedModel,Ym as ChatterboxProcessor,t_ as ChineseCLIPFeatureExtractor,ag as ChineseCLIPModel,Cu as ChineseCLIPPreTrainedModel,ua as ClapAudioModelWithProjection,Bm as ClapFeatureExtractor,lg as ClapModel,Nn as ClapPreTrainedModel,ca as ClapTextModelWithProjection,vu as ClassifierFreeGuidanceLogitsProcessor,hg as CodeGenForCausalLM,_g as CodeGenModel,da as CodeGenPreTrainedModel,Jd as CodeGenTokenizer,Qd as CodeLlamaTokenizer,yg as Cohere2ForCausalLM,xg as Cohere2Model,_a as Cohere2PreTrainedModel,Um as CohereAsrFeatureExtractor,vg as CohereAsrForConditionalGeneration,bg as CohereAsrModel,ha as CohereAsrPreTrainedModel,Qm as CohereAsrProcessor,em as CohereAsrTokenizer,wg as CohereForCausalLM,gg as CohereModel,ma as CoherePreTrainedModel,Zd as CohereTokenizer,Eg as ConvBertForMaskedLM,Mg as ConvBertForQuestionAnswering,Ag as ConvBertForSequenceClassification,Tg as ConvBertForTokenClassification,kg as ConvBertModel,Zr as ConvBertPreTrainedModel,tm as ConvBertTokenizer,n_ as ConvNextFeatureExtractor,Og as ConvNextForImageClassification,Vc as ConvNextImageProcessor,Sg as ConvNextModel,ga as ConvNextPreTrainedModel,Cg as ConvNextV2ForImageClassification,Ig as ConvNextV2Model,wa as ConvNextV2PreTrainedModel,Ng as DFineForObjectDetection,zg as DFineModel,ya as DFinePreTrainedModel,iw as DINOv3ConvNextModel,Bu as DINOv3ConvNextPreTrainedModel,i_ as DINOv3ViTImageProcessor,lw as DINOv3ViTModel,Uu as DINOv3ViTPreTrainedModel,c_ as DPTFeatureExtractor,hw as DPTForDepthEstimation,Kc as DPTImageProcessor,_w as DPTModel,Ma as DPTPreTrainedModel,va as DacDecoderModel,zu as DacDecoderOutput,ba as DacEncoderModel,Lu as DacEncoderOutput,Bo as DacFeatureExtractor,Rg as DacModel,Rn as DacPreTrainedModel,Dg as DebertaForMaskedLM,Fg as DebertaForQuestionAnswering,Bg as DebertaForSequenceClassification,Ug as DebertaForTokenClassification,$g as DebertaModel,es as DebertaPreTrainedModel,sm as DebertaTokenizer,Wg as DebertaV2ForMaskedLM,Xg as DebertaV2ForQuestionAnswering,Vg as DebertaV2ForSequenceClassification,Hg as DebertaV2ForTokenClassification,qg as DebertaV2Model,ts as DebertaV2PreTrainedModel,rm as DebertaV2Tokenizer,Kg as DecisionTransformerModel,Nu as DecisionTransformerPreTrainedModel,jg as DeepseekV3ForCausalLM,Gg as DeepseekV3Model,ka as DeepseekV3PreTrainedModel,o_ as DeiTFeatureExtractor,Qg as DeiTForImageClassification,Hc as DeiTImageProcessor,Yg as DeiTModel,Ea as DeiTPreTrainedModel,Jg as DepthAnythingForDepthEstimation,Ru as DepthAnythingPreTrainedModel,Ul as DepthEstimationPipeline,Zg as DepthProForDepthEstimation,$u as DepthProPreTrainedModel,a_ as DetrFeatureExtractor,tw as DetrForObjectDetection,rw as DetrForSegmentation,Xc as DetrImageProcessor,ew as DetrModel,Dn as DetrObjectDetectionOutput,$n as DetrPreTrainedModel,Du as DetrSegmentationOutput,nw as Dinov2ForImageClassification,sw as Dinov2Model,Aa as Dinov2PreTrainedModel,aw as Dinov2WithRegistersForImageClassification,ow as Dinov2WithRegistersModel,Ta as Dinov2WithRegistersPreTrainedModel,dw as DistilBertForMaskedLM,fw as DistilBertForQuestionAnswering,uw as DistilBertForSequenceClassification,pw as DistilBertForTokenClassification,cw as DistilBertModel,rs as DistilBertPreTrainedModel,nm as DistilBertTokenizer,Dl as DocumentQuestionAnsweringPipeline,l_ as DonutFeatureExtractor,xn as DonutImageProcessor,mw as DonutSwinModel,Fu as DonutSwinPreTrainedModel,Yo as DynamicCache,Tb as EdgeTamModel,ww as EfficientNetForImageClassification,u_ as EfficientNetImageProcessor,gw as EfficientNetModel,Sa as EfficientNetPreTrainedModel,yw as ElectraForMaskedLM,kw as ElectraForQuestionAnswering,bw as ElectraForSequenceClassification,vw as ElectraForTokenClassification,xw as ElectraModel,ss as ElectraPreTrainedModel,om as ElectraTokenizer,$o as EncodecFeatureExtractor,Au as EosTokenCriteria,Aw as Ernie4_5ForCausalLM,Ew as Ernie4_5Model,Oa as Ernie4_5PretrainedModel,Mw as EsmForMaskedLM,Sw as EsmForSequenceClassification,Ow as EsmForTokenClassification,Tw as EsmModel,Fs as EsmPreTrainedModel,am as EsmTokenizer,Cw as EuroBertForMaskedLM,Pw as EuroBertForSequenceClassification,Lw as EuroBertForTokenClassification,Iw as EuroBertModel,Gs as EuroBertPreTrainedModel,Nw as ExaoneForCausalLM,zw as ExaoneModel,Ia as ExaonePreTrainedModel,$w as FalconForCausalLM,Bw as FalconH1ForCausalLM,Dw as FalconH1Model,Pa as FalconH1PreTrainedModel,Rw as FalconModel,Ca as FalconPreTrainedModel,im as FalconTokenizer,Fw as FastViTForImageClassification,Uw as FastViTModel,La as FastViTPreTrainedModel,Fl as FeatureExtractionPipeline,Ee as FeatureExtractor,kl as FillMaskPipeline,Gw as Florence2ForConditionalGeneration,Gu as Florence2PreTrainedModel,j_ as Florence2Processor,du as ForcedBOSTokenLogitsProcessor,mu as ForcedEOSTokenLogitsProcessor,d_ as GLPNFeatureExtractor,ox as GLPNForDepthEstimation,nx as GLPNModel,Ua as GLPNPreTrainedModel,_x as GPT2LMHeadModel,mx as GPT2Model,Wa as GPT2PreTrainedModel,um as GPT2Tokenizer,ix as GPTBigCodeForCausalLM,ax as GPTBigCodeModel,Fa as GPTBigCodePreTrainedModel,gx as GPTJForCausalLM,hx as GPTJModel,Va as GPTJPreTrainedModel,cx as GPTNeoForCausalLM,lx as GPTNeoModel,Ga as GPTNeoPreTrainedModel,px as GPTNeoXForCausalLM,ux as GPTNeoXModel,ja as GPTNeoXPreTrainedModel,cm as GPTNeoXTokenizer,Vw as Gemma2ForCausalLM,Ww as Gemma2Model,Na as Gemma2PreTrainedModel,Yw as Gemma3ForCausalLM,Wu as Gemma3ForConditionalGeneration,p_ as Gemma3ImageProcessor,Kw as Gemma3Model,qu as Gemma3PreTrainedModel,q_ as Gemma3Processor,Uo as Gemma3nAudioFeatureExtractor,Qw as Gemma3nForCausalLM,ns as Gemma3nForConditionalGeneration,Vu as Gemma3nPreTrainedModel,W_ as Gemma3nProcessor,Fo as Gemma4AudioFeatureExtractor,Jw as Gemma4ForCausalLM,Bn as Gemma4ForConditionalGeneration,qo as Gemma4ImageProcessor,V_ as Gemma4Processor,qw as GemmaForCausalLM,jw as GemmaModel,za as GemmaPreTrainedModel,lm as GemmaTokenizer,f_ as Glm46VImageProcessor,H_ as Glm46VProcessor,ex as GlmForCausalLM,Zw as GlmModel,rx as GlmMoeDsaForCausalLM,tx as GlmMoeDsaModel,$a as GlmMoeDsaPreTrainedModel,sx as GlmOcrForConditionalGeneration,Ra as GlmPreTrainedModel,dx as GptOssForCausalLM,fx as GptOssModel,qa as GptOssPreTrainedModel,xx as GraniteForCausalLM,wx as GraniteModel,bx as GraniteMoeHybridForCausalLM,yx as GraniteMoeHybridModel,Xa as GraniteMoeHybridPreTrainedModel,Ha as GranitePreTrainedModel,Fm as GraniteSpeechFeatureExtractor,vx as GraniteSpeechForConditionalGeneration,X_ as GraniteSpeechProcessor,kx as GroundingDinoForObjectDetection,m_ as GroundingDinoImageProcessor,Ku as GroundingDinoPreTrainedModel,K_ as GroundingDinoProcessor,Ex as GroupViTModel,Yu as GroupViTPreTrainedModel,Tx as HeliumForCausalLM,Ax as HeliumModel,Ka as HeliumPreTrainedModel,pm as HerbertTokenizer,Sx as HieraForImageClassification,Mx as HieraModel,Ya as HieraPreTrainedModel,Nx as HubertForCTC,Rx as HubertForSequenceClassification,zx as HubertModel,Lx as HubertPreTrainedModel,Dx as HunYuanDenseV1ForCausalLM,$x as HunYuanDenseV1Model,Qa as HunYuanDenseV1PreTrainedModel,Fx as IJepaForImageClassification,Ux as IJepaModel,Ja as IJepaPreTrainedModel,Bx as Idefics3ForConditionalGeneration,Yc as Idefics3ImageProcessor,au as Idefics3Processor,Ll as ImageClassificationPipeline,Gl as ImageFeatureExtractionPipeline,X as ImageFeatureExtractor,X as ImageProcessor,Qs as ImageSegmentationPipeline,Bl as ImageToImagePipeline,Pl as ImageToTextPipeline,LT as InterruptableStoppingCriteria,jx as JAISLMHeadModel,Gx as JAISModel,Za as JAISPreTrainedModel,h_ as JinaCLIPImageProcessor,qx as JinaCLIPModel,Fn as JinaCLIPPreTrainedModel,Q_ as JinaCLIPProcessor,ei as JinaCLIPTextModel,Wx as JinaCLIPVisionModel,Hx as Lfm2ForCausalLM,Vx as Lfm2Model,Yx as Lfm2MoeForCausalLM,Kx as Lfm2MoeModel,ri as Lfm2MoePreTrainedModel,ti as Lfm2PreTrainedModel,Qx as Lfm2VlForConditionalGeneration,g_ as Lfm2VlImageProcessor,J_ as Lfm2VlProcessor,Xx as LightOnOcrForConditionalGeneration,F1 as LiteWhisperForConditionalGeneration,ey as Llama4ForCausalLM,Qu as Llama4PreTrainedModel,Zx as LlamaForCausalLM,Jx as LlamaModel,si as LlamaPreTrainedModel,fm as LlamaTokenizer,Et as LlavaForConditionalGeneration,Et as LlavaOnevisionForConditionalGeneration,w_ as LlavaOnevisionImageProcessor,ju as LlavaPreTrainedModel,Z_ as LlavaProcessor,Xw as LlavaQwen2ForCausalLM,It as LogLevel,Dt as LogitsProcessor,Rs as LogitsProcessorList,Ko as LogitsWarper,ry as LongT5ForConditionalGeneration,ty as LongT5Model,ni as LongT5PreTrainedModel,ny as M2M100ForConditionalGeneration,sy as M2M100Model,oi as M2M100PreTrainedModel,dm as M2M100Tokenizer,_m as MBart50Tokenizer,fy as MBartForCausalLM,uy as MBartForConditionalGeneration,py as MBartForSequenceClassification,cy as MBartModel,Ws as MBartPreTrainedModel,Lo as MBartTokenizer,Jy as MPNetForMaskedLM,t0 as MPNetForQuestionAnswering,Zy as MPNetForSequenceClassification,e0 as MPNetForTokenClassification,Qy as MPNetModel,os as MPNetPreTrainedModel,wm as MPNetTokenizer,o0 as MT5ForConditionalGeneration,n0 as MT5Model,wi as MT5PreTrainedModel,ay as MarianMTModel,oy as MarianModel,ai as MarianPreTrainedModel,mm as MarianTokenizer,y_ as Mask2FormerImageProcessor,x_ as MaskFormerFeatureExtractor,ly as MaskFormerForInstanceSegmentation,yn as MaskFormerImageProcessor,iy as MaskFormerModel,ii as MaskFormerPreTrainedModel,Eu as MaxLengthCriteria,dy as Metric3DForDepthEstimation,Ju as Metric3DPreTrainedModel,my as Metric3Dv2ForDepthEstimation,Zu as Metric3Dv2PreTrainedModel,_y as MgpstrForSceneTextRecognition,ep as MgpstrModelOutput,tp as MgpstrPreTrainedModel,eh as MgpstrProcessor,hm as MgpstrTokenizer,ci as MimiDecoderModel,sp as MimiDecoderOutput,li as MimiEncoderModel,rp as MimiEncoderOutput,hy as MimiModel,Gn as MimiPreTrainedModel,xu as MinLengthLogitsProcessor,yu as MinNewTokensLengthLogitsProcessor,yy as Mistral4ForCausalLM,xy as Mistral4Model,pi as Mistral4PreTrainedModel,wy as MistralForCausalLM,gy as MistralModel,ui as MistralPreTrainedModel,vy as MobileBertForMaskedLM,Ey as MobileBertForQuestionAnswering,ky as MobileBertForSequenceClassification,by as MobileBertModel,Vs as MobileBertPreTrainedModel,gm as MobileBertTokenizer,Ty as MobileLLMForCausalLM,Ay as MobileLLMModel,fi as MobileLLMPreTrainedModel,b_ as MobileNetV1FeatureExtractor,Sy as MobileNetV1ForImageClassification,Oy as MobileNetV1ForSemanticSegmentation,Qc as MobileNetV1ImageProcessor,My as MobileNetV1Model,jn as MobileNetV1PreTrainedModel,v_ as MobileNetV2FeatureExtractor,Cy as MobileNetV2ForImageClassification,Py as MobileNetV2ForSemanticSegmentation,Jc as MobileNetV2ImageProcessor,Iy as MobileNetV2Model,qn as MobileNetV2PreTrainedModel,k_ as MobileNetV3FeatureExtractor,zy as MobileNetV3ForImageClassification,Ny as MobileNetV3ForSemanticSegmentation,Zc as MobileNetV3ImageProcessor,Ly as MobileNetV3Model,Wn as MobileNetV3PreTrainedModel,E_ as MobileNetV4FeatureExtractor,$y as MobileNetV4ForImageClassification,Dy as MobileNetV4ForSemanticSegmentation,eu as MobileNetV4ImageProcessor,Ry as MobileNetV4Model,Vn as MobileNetV4PreTrainedModel,A_ as MobileViTFeatureExtractor,Uy as MobileViTForImageClassification,tu as MobileViTImageProcessor,By as MobileViTModel,di as MobileViTPreTrainedModel,Gy as MobileViTV2ForImageClassification,Fy as MobileViTV2Model,mi as MobileViTV2PreTrainedModel,ov as ModelRegistry,Xy as ModernBertDecoderForCausalLM,Hy as ModernBertDecoderModel,_i as ModernBertDecoderPreTrainedModel,qy as ModernBertForMaskedLM,Wy as ModernBertForSequenceClassification,Vy as ModernBertForTokenClassification,jy as ModernBertModel,Hs as ModernBertPreTrainedModel,Hw as Moondream1ForConditionalGeneration,Gm as MoonshineFeatureExtractor,Yy as MoonshineForConditionalGeneration,Ky as MoonshineModel,hi as MoonshinePreTrainedModel,th as MoonshineProcessor,s0 as MptForCausalLM,r0 as MptModel,gi as MptPreTrainedModel,a0 as MultiModalityCausalLM,np as MultiModalityPreTrainedModel,l0 as MusicgenForCausalLM,yi as MusicgenForConditionalGeneration,i0 as MusicgenModel,xi as MusicgenPreTrainedModel,u0 as NanoChatForCausalLM,c0 as NanoChatModel,bi as NanoChatPreTrainedModel,f0 as NemotronHForCausalLM,p0 as NemotronHModel,vi as NemotronHPreTrainedModel,m0 as NeoBertForMaskedLM,g0 as NeoBertForQuestionAnswering,_0 as NeoBertForSequenceClassification,h0 as NeoBertForTokenClassification,d0 as NeoBertModel,as as NeoBertPreTrainedModel,xm as NllbTokenizer,bu as NoBadWordsLogitsProcessor,gu as NoRepeatNGramLogitsProcessor,w0 as NomicBertModel,op as NomicBertPreTrainedModel,T_ as NougatImageProcessor,ym as NougatTokenizer,I0 as OPTForCausalLM,O0 as OPTModel,Si as OPTPreTrainedModel,Rl as ObjectDetectionPipeline,v0 as Olmo2ForCausalLM,b0 as Olmo2Model,Ei as Olmo2PreTrainedModel,E0 as Olmo3ForCausalLM,k0 as Olmo3Model,Ai as Olmo3PreTrainedModel,y0 as OlmoForCausalLM,T0 as OlmoHybridForCausalLM,A0 as OlmoHybridModel,Ti as OlmoHybridPreTrainedModel,x0 as OlmoModel,ki as OlmoPreTrainedModel,S0 as OpenELMForCausalLM,M0 as OpenELMModel,Mi as OpenELMPreTrainedModel,M_ as OwlViTFeatureExtractor,z0 as OwlViTForObjectDetection,bn as OwlViTImageProcessor,L0 as OwlViTModel,Ii as OwlViTPreTrainedModel,rh as OwlViTProcessor,P0 as Owlv2ForObjectDetection,S_ as Owlv2ImageProcessor,C0 as Owlv2Model,Oi as Owlv2PreTrainedModel,N0 as PaliGemmaForConditionalGeneration,sh as PaliGemmaProcessor,Do as ParakeetFeatureExtractor,R0 as ParakeetForCTC,ap as ParakeetPreTrainedModel,D0 as PatchTSMixerForPrediction,$0 as PatchTSMixerModel,Ci as PatchTSMixerPreTrainedModel,U0 as PatchTSTForPrediction,B0 as PatchTSTModel,Pi as PatchTSTPreTrainedModel,q0 as Phi3ForCausalLM,j0 as Phi3Model,zi as Phi3PreTrainedModel,Ni as Phi3VForCausalLM,C_ as Phi3VImageProcessor,ip as Phi3VPreTrainedModel,nh as Phi3VProcessor,G0 as PhiForCausalLM,F0 as PhiModel,Li as PhiPreTrainedModel,P_ as PixtralImageProcessor,oh as PixtralProcessor,y as PreTrainedModel,W as PreTrainedTokenizer,Tn as PretrainedConfig,re as Processor,V0 as PvtForImageClassification,L_ as PvtImageProcessor,W0 as PvtModel,Ri as PvtPreTrainedModel,Go as PyAnnoteFeatureExtractor,X0 as PyAnnoteForAudioFrameClassification,H0 as PyAnnoteModel,$i as PyAnnotePreTrainedModel,ah as PyAnnoteProcessor,vl as QuestionAnsweringPipeline,Y0 as Qwen2ForCausalLM,K0 as Qwen2Model,J0 as Qwen2MoeForCausalLM,Q0 as Qwen2MoeModel,Bi as Qwen2MoePreTrainedModel,Di as Qwen2PreTrainedModel,bm as Qwen2Tokenizer,Da as Qwen2VLForCausalLM,Un as Qwen2VLForConditionalGeneration,Wo as Qwen2VLImageProcessor,Hu as Qwen2VLPreTrainedModel,zs as Qwen2VLProcessor,Ba as Qwen2_5_VLForCausalLM,js as Qwen2_5_VLForConditionalGeneration,Ho as Qwen2_5_VLProcessor,eb as Qwen3ForCausalLM,Z0 as Qwen3Model,rb as Qwen3MoeForCausalLM,tb as Qwen3MoeModel,Fi as Qwen3MoePreTrainedModel,nb as Qwen3NextForCausalLM,sb as Qwen3NextModel,Gi as Qwen3NextPreTrainedModel,Ui as Qwen3PreTrainedModel,ji as Qwen3VLForCausalLM,Xs as Qwen3VLForConditionalGeneration,ab as Qwen3VLMoeForCausalLM,ob as Qwen3VLMoeForConditionalGeneration,ih as Qwen3VLProcessor,qi as Qwen3_5ForCausalLM,Hn as Qwen3_5ForConditionalGeneration,lb as Qwen3_5MoeForCausalLM,ib as Qwen3_5MoeForConditionalGeneration,fb as RFDetrForObjectDetection,pb as RFDetrModel,lp as RFDetrObjectDetectionOutput,Vi as RFDetrPreTrainedModel,Lg as RTDetrForObjectDetection,z_ as RTDetrImageProcessor,Pg as RTDetrModel,_r as RTDetrObjectDetectionOutput,xa as RTDetrPreTrainedModel,Eb as RTDetrV2ForObjectDetection,kb as RTDetrV2Model,cp as RTDetrV2ObjectDetectionOutput,Hi as RTDetrV2PreTrainedModel,Ro as RawAudio,Je as RawImage,Xp as RawVideo,jl as RawVideoFrame,wu as RepetitionPenaltyLogitsProcessor,ub as ResNetForImageClassification,cb as ResNetModel,Wi as ResNetPreTrainedModel,xb as RoFormerForMaskedLM,vb as RoFormerForQuestionAnswering,yb as RoFormerForSequenceClassification,bb as RoFormerForTokenClassification,wb as RoFormerModel,ls as RoFormerPreTrainedModel,km as RoFormerTokenizer,mb as RobertaForMaskedLM,gb as RobertaForQuestionAnswering,_b as RobertaForSequenceClassification,hb as RobertaForTokenClassification,db as RobertaModel,is as RobertaPreTrainedModel,vm as RobertaTokenizer,Vo as Sam2ImageProcessor,fp as Sam2ImageSegmentationOutput,Xi as Sam2Model,dp as Sam2PreTrainedModel,iu as Sam2Processor,lh as Sam2VideoProcessor,Vo as Sam3ImageProcessor,Mb as Sam3TrackerModel,Vo as SamImageProcessor,up as SamImageSegmentationOutput,Ab as SamModel,pp as SamPreTrainedModel,Xo as SamProcessor,N_ as SapiensFeatureExtractor,Ob as SapiensForDepthEstimation,Ib as SapiensForNormalEstimation,Sb as SapiensForSemanticSegmentation,ru as SapiensImageProcessor,Xn as SapiensPreTrainedModel,jm as SeamlessM4TFeatureExtractor,R_ as SegformerFeatureExtractor,Pb as SegformerForImageClassification,Lb as SegformerForSemanticSegmentation,su as SegformerImageProcessor,Cb as SegformerModel,Kn as SegformerPreTrainedModel,$_ as SiglipImageProcessor,zb as SiglipModel,Ki as SiglipPreTrainedModel,Yi as SiglipTextModel,Em as SiglipTokenizer,Nb as SiglipVisionModel,$b as SmolLM3ForCausalLM,Rb as SmolLM3Model,Qi as SmolLM3PreTrainedModel,Yc as SmolVLMImageProcessor,au as SmolVLMProcessor,Zi as SnacDecoderModel,Ji as SnacEncoderModel,qm as SnacFeatureExtractor,Db as SnacModel,Yn as SnacPreTrainedModel,Ub as SolarOpenForCausalLM,Bb as SolarOpenModel,el as SolarOpenPreTrainedModel,Wm as SpeechT5FeatureExtractor,Gb as SpeechT5ForSpeechToText,jb as SpeechT5ForTextToSpeech,qb as SpeechT5HifiGan,Fb as SpeechT5Model,Qn as SpeechT5PreTrainedModel,ch as SpeechT5Processor,Am as SpeechT5Tokenizer,Vb as SqueezeBertForMaskedLM,Xb as SqueezeBertForQuestionAnswering,Hb as SqueezeBertForSequenceClassification,Wb as SqueezeBertModel,Ks as SqueezeBertPreTrainedModel,Tm as SqueezeBertTokenizer,Yb as StableLmForCausalLM,Kb as StableLmModel,tl as StableLmPreTrainedModel,Jb as Starcoder2ForCausalLM,Qb as Starcoder2Model,rl as Starcoder2PreTrainedModel,Yr as StoppingCriteria,On as StoppingCriteriaList,Zb as StyleTextToSpeech2Model,mp as StyleTextToSpeech2PreTrainedModel,El as SummarizationPipeline,sl as SupertonicForConditionalGeneration,_p as SupertonicPreTrainedModel,Mn as SuppressTokensAtBeginLogitsProcessor,_u as SuppressTokensLogitsProcessor,n1 as Swin2SRForImageSuperResolution,D_ as Swin2SRImageProcessor,s1 as Swin2SRModel,nl as Swin2SRPreTrainedModel,t1 as SwinForImageClassification,r1 as SwinForSemanticSegmentation,e1 as SwinModel,Jn as SwinPreTrainedModel,a1 as T5ForConditionalGeneration,o1 as T5Model,ol as T5PreTrainedModel,Mm as T5Tokenizer,l1 as TableTransformerForObjectDetection,i1 as TableTransformerModel,hp as TableTransformerObjectDetectionOutput,al as TableTransformerPreTrainedModel,ku as TemperatureLogitsWarper,N as Tensor,Mr as Text2TextGenerationPipeline,yl as TextClassificationPipeline,Tl as TextGenerationPipeline,nv as TextStreamer,Cl as TextToAudioPipeline,bl as TokenClassificationPipeline,W as TokenizersBackend,PT as TopKLogitsWarper,CT as TopPLogitsWarper,c1 as TrOCRForCausalLM,gp as TrOCRPreTrainedModel,Al as TranslationPipeline,qs as UltravoxModel,Xu as UltravoxPreTrainedModel,uh as UltravoxProcessor,p1 as UniSpeechForCTC,f1 as UniSpeechForSequenceClassification,u1 as UniSpeechModel,Zn as UniSpeechPreTrainedModel,h1 as UniSpeechSatForAudioFrameClassification,m1 as UniSpeechSatForCTC,_1 as UniSpeechSatForSequenceClassification,d1 as UniSpeechSatModel,Ys as UniSpeechSatPreTrainedModel,Y_ as VLChatProcessor,__ as VLMImageProcessor,w1 as VaultGemmaForCausalLM,g1 as VaultGemmaModel,il as VaultGemmaPreTrainedModel,B_ as ViTFeatureExtractor,b1 as ViTForImageClassification,nu as ViTImageProcessor,v1 as ViTMAEModel,wp as ViTMAEPreTrainedModel,E1 as ViTMSNForImageClassification,k1 as ViTMSNModel,cl as ViTMSNPreTrainedModel,y1 as ViTModel,ll as ViTPreTrainedModel,x1 as VisionEncoderDecoderModel,A1 as VitMatteForImageMatting,U_ as VitMatteImageProcessor,xp as VitMattePreTrainedModel,T1 as VitPoseForPoseEstimation,F_ as VitPoseImageProcessor,yp as VitPosePreTrainedModel,M1 as VitsModel,bp as VitsModelOutput,vp as VitsPreTrainedModel,Om as VitsTokenizer,S1 as VoxtralForConditionalGeneration,ph as VoxtralProcessor,Xm as VoxtralRealtimeFeatureExtractor,ul as VoxtralRealtimeForConditionalGeneration,kp as VoxtralRealtimePreTrainedModel,dh as VoxtralRealtimeProcessor,P1 as Wav2Vec2BertForCTC,L1 as Wav2Vec2BertForSequenceClassification,C1 as Wav2Vec2BertModel,eo as Wav2Vec2BertPreTrainedModel,Im as Wav2Vec2CTCTokenizer,Vm as Wav2Vec2FeatureExtractor,Px as Wav2Vec2ForAudioFrameClassification,Ix as Wav2Vec2ForCTC,Cx as Wav2Vec2ForSequenceClassification,Ox as Wav2Vec2Model,sr as Wav2Vec2PreTrainedModel,mh as Wav2Vec2Processor,_h as Wav2Vec2ProcessorWithLM,D1 as WavLMForAudioFrameClassification,N1 as WavLMForCTC,R1 as WavLMForSequenceClassification,$1 as WavLMForXVector,z1 as WavLMModel,cs as WavLMPreTrainedModel,Hm as WeSpeakerFeatureExtractor,B1 as WeSpeakerResNetModel,Ap as WeSpeakerResNetPreTrainedModel,Km as WhisperFeatureExtractor,Mp as WhisperForConditionalGeneration,U1 as WhisperModel,pl as WhisperPreTrainedModel,hh as WhisperProcessor,SM as WhisperTextStreamer,hu as WhisperTimeStampLogitsProcessor,Cm as WhisperTokenizer,V1 as XLMForQuestionAnswering,q1 as XLMForSequenceClassification,W1 as XLMForTokenClassification,G1 as XLMModel,us as XLMPreTrainedModel,X1 as XLMRobertaForMaskedLM,Q1 as XLMRobertaForQuestionAnswering,K1 as XLMRobertaForSequenceClassification,Y1 as XLMRobertaForTokenClassification,H1 as XLMRobertaModel,ps as XLMRobertaPreTrainedModel,Pm as XLMRobertaTokenizer,Lm as XLMTokenizer,j1 as XLMWithLMHeadModel,Ep as XVectorOutput,G_ as YolosFeatureExtractor,Z1 as YolosForObjectDetection,ou as YolosImageProcessor,J1 as YolosModel,Sp as YolosObjectDetectionOutput,fl as YolosPreTrainedModel,tv as YoutuForCausalLM,ev as YoutuModel,dl as YoutuPreTrainedModel,Ol as ZeroShotAudioClassificationPipeline,Ml as ZeroShotClassificationPipeline,Nl as ZeroShotImageClassificationPipeline,$l as ZeroShotObjectDetectionPipeline,ve as cat,uz as cos_sim,lA as dot,_e as env,Ye as full,Po as full_like,Rd as interpolate,vt as interpolate_4d,ND as layer_norm,_N as load_image,i3 as load_video,Bf as log_softmax,iT as matmul,Nc as mean,lT as mean_pooling,et as ones,Rc as ones_like,Vz as permute,Lce as pipeline,uT as quantize_embeddings,RD as rand,cT as randn,ys as random,Rm as read_audio,zD as rfft,zc as slice,Re as softmax,yt as stack,$d as std_mean,tr as topk,Bd as zeros,Ud as zeros_like};