var AI=Object.defineProperty;var fs=(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 en=(t,e)=>{for(var r in e)AI(t,r,{get:e[r],enumerable:!0})};import MI from"fs";import tn from"path";import TI from"url";var SI="4.2.0",Mf=typeof self<"u",rn=!gE(MI),_E=!gE(tn),sc=Mf&&"caches"in self,OI=typeof globalThis.Deno<"u",a3=typeof globalThis.Bun<"u",oc=OI&&sc&&!rn,mE=typeof process<"u",hE=mE&&process?.release?.name==="node"&&!oc,Tf=typeof window<"u"&&typeof window.document<"u",Sf=Mf&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),II=Tf||Sf||oc,CI=hE||typeof navigator<"u"&&"gpu"in navigator,PI=typeof navigator<"u"&&"ml"in navigator,zI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",LI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",NI=typeof ServiceWorkerGlobalScope<"u"&&Mf&&self instanceof ServiceWorkerGlobalScope,$I=()=>{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},RI=$I(),ie=Object.freeze({IS_BROWSER_ENV:Tf,IS_WEBWORKER_ENV:Sf,IS_WEB_ENV:II,IS_SERVICE_WORKER_ENV:NI,IS_DENO_WEB_RUNTIME:oc,IS_WEB_CACHE_AVAILABLE:sc,IS_WEBGPU_AVAILABLE:CI,IS_WEBNN_AVAILABLE:PI,IS_SAFARI:RI,IS_PROCESS_AVAILABLE:mE,IS_NODE_ENV:hE,IS_FS_AVAILABLE:rn,IS_PATH_AVAILABLE:_E,IS_CRYPTO_AVAILABLE:zI,IS_CHROME_AVAILABLE:LI}),Of=rn&&_E,nc="./";if(Of){let t=Object(import.meta).url;t?nc=tn.dirname(tn.dirname(TI.fileURLToPath(t))):typeof __dirname<"u"&&(nc=tn.dirname(__dirname))}var DI=Of?tn.join(nc,"/.cache/"):null,fE="/models/",FI=Of?tn.join(nc,fE):fE,BI=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,St=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),dE=St.WARNING,me={version:SI,backends:{onnx:{}},get logLevel(){return dE},set logLevel(t){dE=t,me.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(Tf||Sf||oc),localModelPath:FI,useFS:rn,useBrowserCache:sc,useFSCache:rn,cacheDir:DI,useCustomCache:!1,customCache:null,useWasmCache:sc||rn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:BI};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 or(t,e){t&&t(e)}var ds=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 If(t){return t==null||t===-1}function Cf(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function gt(...t){return Array.prototype.concat.apply([],t)}function xE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function sn(t,e){return Math.abs((t+e)%(2*e)-e)}function Ve(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function yE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){me.logLevel<=St.ERROR&&console.error(...t)},warn(...t){me.logLevel<=St.WARNING&&console.warn(...t)},info(...t){me.logLevel<=St.INFO&&console.log(...t)},debug(...t){me.logLevel<=St.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var UI=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]]))})(),qI=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),WI=qI(SE),vE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",VI=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}]+`]]),ac="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",zf=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"),ic=(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 VI)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=HI(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},HI=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),XI=(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,YI=t=>Number.isInteger(t)||typeof t=="bigint",QI=t=>{let e=0;for(let r of t)++e;return e},JI=t=>OE(t.toLowerCase()),Vt=(...t)=>Array.prototype.concat.apply([],t),Lf=t=>new Map(Object.entries(t)),ZI=(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},eC=t=>t.match(/\S+/g)||[],tC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},co=tC,rC=class extends co{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},xr=rC,sC=class extends xr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},aC=oC,iC=class extends xr{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)}},lC=iC,cC=class extends xr{normalize(t){let e=ic(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},uC=cC,pC=class extends xr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},lc=pC,fC=class extends lc{constructor(){super(...arguments),this.form="NFC"}},dC=fC,_C=class extends lc{constructor(){super(...arguments),this.form="NFD"}},mC=_C,hC=class extends lc{constructor(){super(...arguments),this.form="NFKC"}},gC=hC,wC=class extends lc{constructor(){super(...arguments),this.form="NFKD"}},xC=wC,yC=class extends xr{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}},bC=yC,vC=class extends xr{normalize(t){return OE(t)}},kC=vC,EC=class extends xr{normalize(t){return t.toLowerCase()}},AC=EC,MC=class extends xr{normalize(t){return t=this.config.prepend+t,t}},TC=MC;function SC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new nC(t);case"Precompiled":return new aC(t);case"Sequence":return new lC(t);case"Replace":return new uC(t);case"NFC":return new dC(t);case"NFD":return new mC(t);case"NFKC":return new gC(t);case"NFKD":return new xC(t);case"Strip":return new bC(t);case"StripAccents":return new kC(t);case"Lowercase":return new AC(t);case"Prepend":return new TC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var IE=SC,OC=class extends co{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)}},Ht=OC,IC=class extends Ht{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(""))}},CC=IC,PC=class extends Ht{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},zC=PC,LC=class extends Ht{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]}},NC=LC,$C=class extends Ht{constructor(t){super(),this.config=t,this.pattern=ic(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):ZI(t,this.pattern)}},RC=$C,DC=class extends Ht{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${ac}]+|[${ac}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},FC=DC,BC=class extends Ht{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)||[]}},UC=BC,jC=class extends Ht{constructor(){super(),this.pattern=new RegExp(`[^\\s${ac}]+|[${ac}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},GC=jC,qC=class extends Ht{constructor(t){super(),this.config=t,this.pattern=ic(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},WC=qC,VC=class extends Ht{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])}},HC=VC,XC=class extends Ht{pre_tokenize_text(t){return eC(t)}},KC=XC,YC=class extends Ht{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=eP,AE=class PE{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new PE(!1,new Map)}},tP=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)}}},rP=tP,Pf=class zE{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 zE(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},sP=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 Pf(this.bos_token_id??0,0,0,0,0),n=new Pf(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 Pf(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+a.score;(l===null||p>i)&&(l=c.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},nP=sP;function oP(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=oP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new rP,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()}},uP=cP,pP=class extends cc{constructor(t){super(t),this.tokens_to_ids=Lf(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 uP(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 lP((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}},TE=pP,fP=class extends cc{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Lf(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}},dP=fP;function _P(t,e){switch(t.type){case"WordPiece":return new EE(t);case"Unigram":return new ME(t,e.eos_token);case"BPE":return new TE(t);default:if(t.vocab)return Array.isArray(t.vocab)?new ME(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new TE(t):new EE(t):new dP(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 mP=_P,hP=class extends co{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},uo=hP,gP=class extends uo{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=Vt(n,t),o=Vt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Vt(n,e),o=Vt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},wP=gP,xP=class extends uo{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},yP=xP,bP=class extends uo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Vt([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=Vt(t,n,e,o),s=Vt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},vP=bP,kP=class extends uo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Vt([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=Vt(t,n,e,o),s=Vt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},EP=kP,AP=class extends uo{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>LE(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}},MP=AP;function TP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new wP(t);case"ByteLevel":return new yP(t);case"BertProcessing":return new vP(t);case"RobertaProcessing":return new EP(t);case"Sequence":return new MP(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var LE=TP,SP=class extends co{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("")}},Dt=SP,OP=class extends Dt{constructor(t){super(t),this.byte_decoder=WI,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}},IP=OP,CP=class extends Dt{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=zf(e)),e})}},PP=CP,zP=class extends Dt{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?"":" "))}},$P=NP,RP=class extends Dt{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=zf(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},DP=RP,FP=class extends Dt{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)}},BP=FP,UP=class extends Dt{decode_chain(t){let e=ic(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},jP=UP,GP=class extends Dt{decode_chain(t){return[t.join("")]}},qP=GP,WP=class extends Dt{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}},XP=HP;function KP(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new IP(t);case"WordPiece":return new PP(t);case"Metaspace":return new LP(t);case"BPEDecoder":return new $P(t);case"CTC":return new DP(t);case"Sequence":return new BP(t);case"Replace":return new jP(t);case"Fuse":return new qP(t);case"Strip":return new VP(t);case"ByteFallback":return new XP(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var NE=KP,YP=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=mP(this.tokenizer.model,this.config),this.post_processor=LE(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 GI(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||!YI(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=zf(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=JI(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:Vt(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]],JP=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function ZP(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 ez(t,e={}){let r=[],s=ZP(t,e),n=0,o=0,a=c=>{let p="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],_=JP.get(f);if(_===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);p+=_;continue}if(p+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return p},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new Ft(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let _="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");_+=s[n++]}let m=_.endsWith("-");m&&(_=_.slice(0,-1)),f&&i(),r.push(new Ft(_,D.Comment)),n+=2,m&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Ft("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Ft("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(DE),s.slice(n,n+3)==="-%}"){r.push(new Ft("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Ft("}}",D.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let _=a(po);r.push(new Ft(`${p}${_}`,_.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,_]of QP){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Ft(f,_)),_===D.OpenExpression?o=0:_===D.OpenCurlyBracket?++o:_===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(_=>_!==p);r.push(new Ft(f,D.StringLiteral)),++n;continue}if(po(p)){let f=a(po);if(s[n]==="."&&po(s[n+1])){++n;let _=a(po);f=`${f}.${_}`}r.push(new Ft(f,D.NumericLiteral));continue}if(RE(p)){let f=a(RE);r.push(new Ft(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Kt=class{type="Statement"},tz=class extends Kt{constructor(t){super(),this.body=t}type="Program"},rz=class extends Kt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},sz=class extends Kt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},nz=class extends Kt{type="Break"},oz=class extends Kt{type="Continue"},az=class extends Kt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},iz=class extends Kt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},lz=class extends Kt{constructor(t){super(),this.value=t}type="Comment"},Ct=class extends Kt{type="Expression"},cz=class extends Ct{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},FE=class extends Ct{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},nn=class extends Ct{constructor(t){super(),this.value=t}type="Identifier"},on=class extends Ct{constructor(t){super(),this.value=t}type="Literal"},uz=class extends on{type="IntegerLiteral"},pz=class extends on{type="FloatLiteral"},BE=class extends on{type="StringLiteral"},fz=class extends on{type="ArrayLiteral"},UE=class extends on{type="TupleLiteral"},dz=class extends on{type="ObjectLiteral"},fo=class extends Ct{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},_z=class extends Ct{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},mz=class extends Kt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},hz=class extends Ct{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},gz=class extends Ct{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},wz=class extends Ct{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},xz=class extends Ct{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},yz=class extends Ct{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},bz=class extends Ct{constructor(t){super(),this.argument=t}type="SpreadExpression"},vz=class extends Kt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},kz=class extends Ct{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function Ez(t){let e=new tz([]),r=0;function s(z,$){let B=t[r++];if(!B||B.type!==z)throw new Error(`Parser Error: ${$}. ${B.type} !== ${z}.`);return B}function n(z){if(!l(z))throw new SyntaxError(`Expected ${z}`);++r}function o(){switch(t[r].type){case D.Comment:return new lz(t[r++].value);case D.Text:return c();case D.OpenStatement:return p();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...z){return r+z.length<=t.length&&z.every(($,B)=>$===t[r+B].type)}function i(...z){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&z.includes(t[r+1]?.value)}function l(...z){return r+z.length<=t.length&&z.every(($,B)=>t[r+B].type==="Identifier"&&$===t[r+B].value)}function c(){return new BE(s(D.Text,"Expected text token").value)}function p(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let z=t[r].value,$;switch(z){case"set":++r,$=_();break;case"if":++r,$=m(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,$=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,$=k(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let B=null;a(D.OpenParen)&&(B=U());let Q=Y();if(Q.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let le=U();s(D.CloseStatement,"Expected closing statement token");let Ge=[];for(;!i("endcall");)Ge.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let ce=new FE(Q,le);$=new vz(ce,B,Ge);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),$=new nz;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),$=new oz;break;case"filter":{++r;let B=Y();B instanceof nn&&a(D.OpenParen)&&(B=j(B)),s(D.CloseStatement,"Expected closing statement token");let Q=[];for(;!i("endfilter");)Q.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),$=new mz(B,Q);break}default:throw new SyntaxError(`Unknown statement type: ${z}`)}return $}function f(){s(D.OpenExpression,"Expected opening expression token");let z=A();return s(D.CloseExpression,"Expected closing expression token"),z}function _(){let z=x(),$=null,B=[];if(a(D.Equals))++r,$=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)B.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new az(z,$,B)}function m(){let z=A();s(D.CloseStatement,"Expected closing statement token");let $=[],B=[];for(;!i("elif","else","endif");)$.push(o());if(i("elif")){++r,++r;let Q=m();B.push(Q)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)B.push(o());return new rz(z,$,B)}function w(){let z=Y();if(z.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let $=U();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endmacro");)B.push(o());return new iz(z,$,B)}function x(z=!1){let $=z?Y:A,B=[$()],Q=a(D.Comma);for(;Q&&(++r,B.push($()),!!a(D.Comma)););return Q?new UE(B):B[0]}function k(){let z=x(!0);if(!(z instanceof nn||z instanceof UE))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${z.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let $=A();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endfor","else");)B.push(o());let Q=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)Q.push(o());return new sz(z,$,B,Q)}function A(){return E()}function E(){let z=S();if(l("if")){++r;let $=S();if(l("else")){++r;let B=E();return new kz($,z,B)}else return new hz(z,$)}return z}function S(){let z=T();for(;l("or");){let $=t[r];++r;let B=T();z=new fo($,z,B)}return z}function T(){let z=I();for(;l("and");){let $=t[r];++r;let B=I();z=new fo($,z,B)}return z}function I(){let z;for(;l("not");){let $=t[r];++r;let B=I();z=new wz($,B)}return z??O()}function O(){let z=b();for(;;){let $;if(l("not","in"))$=new Ft("not in",D.Identifier),r+=2;else if(l("in"))$=t[r++];else if(a(D.ComparisonBinaryOperator))$=t[r++];else break;let B=b();z=new fo($,z,B)}return z}function b(){let z=R();for(;a(D.AdditiveBinaryOperator);){let $=t[r];++r;let B=R();z=new fo($,z,B)}return z}function F(){let z=J(Y());return a(D.OpenParen)?j(z):z}function j(z){let $=new FE(z,U());return $=J($),a(D.OpenParen)&&($=j($)),$}function U(){s(D.OpenParen,"Expected opening parenthesis for arguments list");let z=X();return s(D.CloseParen,"Expected closing parenthesis for arguments list"),z}function X(){let z=[];for(;!a(D.CloseParen);){let $;if(t[r].type===D.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let B=A();$=new bz(B)}else if($=A(),a(D.Equals)){if(++r,!($ instanceof nn))throw new SyntaxError("Expected identifier for keyword argument");let B=A();$=new yz($,B)}z.push($),a(D.Comma)&&++r}return z}function K(){let z=[],$=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(z.push(void 0),++r,$=!0):(z.push(A()),a(D.Colon)&&(++r,$=!0));if(z.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($){if(z.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new xz(...z)}return z[0]}function J(z){for(;a(D.Dot)||a(D.OpenSquareBracket);){let $=t[r];++r;let B,Q=$.type===D.OpenSquareBracket;if(Q)B=K(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(B=Y(),B.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");z=new cz(z,B,Q)}return z}function R(){let z=C();for(;a(D.MultiplicativeBinaryOperator);){let $=t[r++],B=C();z=new fo($,z,B)}return z}function C(){let z=se();for(;l("is");){++r;let $=l("not");$&&++r;let B=Y();if(!(B instanceof nn))throw new SyntaxError("Expected identifier for the test");z=new gz(z,$,B)}return z}function se(){let z=F();for(;a(D.Pipe);){++r;let $=Y();if(!($ instanceof nn))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&($=j($)),z=new _z(z,$)}return z}function Y(){let z=t[r++];switch(z.type){case D.NumericLiteral:{let $=z.value;return $.includes(".")?new pz(Number($)):new uz(Number($))}case D.StringLiteral:{let $=z.value;for(;a(D.StringLiteral);)$+=t[r++].value;return new BE($)}case D.Identifier:return new nn(z.value);case D.OpenParen:{let $=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),$}case D.OpenSquareBracket:{let $=[];for(;!a(D.CloseSquareBracket);)$.push(A()),a(D.Comma)&&++r;return++r,new fz($)}case D.OpenCurlyBracket:{let $=new Map;for(;!a(D.CloseCurlyBracket);){let B=A();s(D.Colon,"Expected colon between key and value in object literal");let Q=A();$.set(B,Q),a(D.Comma)&&++r}return++r,new dz($)}default:throw new SyntaxError(`Unexpected token: ${z.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function jE(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 Tz(t){return Sz(new Date,t)}function Sz(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 Oz(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Iz(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(Oz(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var GE=class extends Error{},qE=class extends Error{},ar=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 ar{type="IntegerValue"},Ze=class extends ar{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},te=class extends ar{type="StringValue";builtins=new Map([["upper",new Xe(()=>new te(this.value.toUpperCase()))],["lower",new Xe(()=>new te(this.value.toLowerCase()))],["strip",new Xe(()=>new te(this.value.trim()))],["title",new Xe(()=>new te(Mz(this.value)))],["capitalize",new Xe(()=>new te(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new he(this.value.length)],["rstrip",new Xe(()=>new te(this.value.trimEnd()))],["lstrip",new Xe(()=>new te(this.value.trimStart()))],["startswith",new Xe(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.startsWith(e.value));if(e instanceof 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 Xe(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof te)return new de(this.value.endsWith(e.value));if(e instanceof 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 Xe(t=>{let e=t[0]??new Ke;if(!(e instanceof te||e instanceof Ke))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 Ke){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 Xe(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof te&&r instanceof te))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Ke:s=t[2]:s=new Ke,!(s instanceof he||s instanceof Ke))throw new Error("replace() count argument must be a number or null");return new te(Iz(this.value,e.value,r.value,s.value))})]])},de=class extends ar{type="BooleanValue"},Cz=/[\x7f-\uffff]/g;function WE(t){return t.replace(Cz,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function ms(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=WE(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",f=` `+p.repeat(r),_=f+p;if(t.type==="ArrayValue"){let m=t.value.map(w=>ms(w,e,r+1,s));return n?`[${_}${m.join(`${l}${_}`)}${f}]`:`[${m.join(l)}]`}else{let m=Array.from(t.value.entries());i&&(m=m.sort(([x],[k])=>x.localeCompare(k)));let w=m.map(([x,k])=>{let A=JSON.stringify(x);o&&(A=WE(A));let E=`${A}${c}${ms(k,e,r+1,s)}`;return n?`${_}${E}`:E});return n?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var ft=class extends ar{type="ObjectValue";__bool__(){return new de(this.value.size>0)}builtins=new Map([["get",new Xe(([t,e])=>{if(!(t instanceof te))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Ke})],["items",new Xe(()=>this.items())],["keys",new Xe(()=>this.keys())],["values",new Xe(()=>this.values())],["dictsort",new Xe(t=>{let e=new Map,r=t.filter(i=>i instanceof _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,p=i.value[c],f=l.value[c],_=Nf(p,f,s.value);return o.value?-_:_});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 ms(this,{},0,!1)}},_o=class extends ft{type="KeywordArgumentsValue"},ye=class extends ar{type="ArrayValue";builtins=new Map([["length",new he(this.value.length)]]);__bool__(){return new de(this.value.length>0)}toString(){return ms(this,{},0,!1)}},VE=class extends ye{type="TupleValue"},Xe=class extends ar{type="FunctionValue"},Ke=class extends ar{type="NullValue"},He=class extends ar{type="UndefinedValue"},_s=class{constructor(t){this.parent=t}variables=new Map([["namespace",new Xe(t=>{if(t.length===0)return new ft(new Map);if(t.length!==1||!(t[0]instanceof ft))throw new Error("`namespace` expects either zero arguments or a single object argument");return t[0]})]]);tests=new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof Xe],["odd",t=>{if(!(t instanceof he))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof he))throw new Error(`cannot even on ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["none",t=>t.type==="NullValue"],["string",t=>t.type==="StringValue"],["number",t=>t instanceof he||t instanceof Ze],["integer",t=>t instanceof he],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t instanceof ft],["sequence",t=>t instanceof ye||t instanceof ft||t instanceof te],["lower",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]]);set(t,e){return this.declareVariable(t,uc(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new He}catch{return new He}}};function Pz(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",Az),t.set("strftime_now",Tz),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 ft)s=s.value.get(n)??new He;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 zz=class{global;constructor(t){this.global=t??new _s}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){let r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}let s=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new de(r.value==s.value);case"!=":return new de(r.value!=s.value)}if(r instanceof He||s instanceof He){if(s instanceof He&&["in","not in"].includes(t.operator.value))return new de(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof Ke||s instanceof Ke)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 ft)switch(t.operator.value){case"in":return new de(s.value.has(r.value));case"not in":return new de(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(t,e){let r=[],s=new Map;for(let n of t)if(n.type==="SpreadExpression"){let o=n,a=this.evaluate(o.argument,e);if(!(a instanceof 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(ms(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)=>Nf(n,o,!1)));case"join":return new te(t.value.map(n=>n.value).join(""));case"string":return new te(ms(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 Xe)return n.value([],r);if(n instanceof he)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new te(t.value.trim());case"indent":return new te(t.value.split(` `).map((n,o)=>o===0||n.length===0?n:" "+n).join(` `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new he(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new 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 ft)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 Xe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof de)switch(s.value){case"bool":return new de(t.value);case"int":return new he(t.value?1:0);case"float":return new 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 Ke;if(!(a instanceof he||a instanceof Ke))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 Ke,p=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,_]=c.value;if(!(f instanceof te)||!(_ instanceof te))throw new Error("separators must be a tuple of two strings");p=[f.value,_.value]}else if(!(c instanceof Ke))throw new Error("If set, separators must be a tuple of two strings");return new te(ms(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:p}))}else if(n==="join"){let o;if(t instanceof te)o=Array.from(t.value);else if(t instanceof 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 He||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 Ke;if(!(c instanceof te||c instanceof he||c instanceof Ke))throw new Error("attribute must be a string, integer, or null");let p=f=>{if(c instanceof Ke)return f;let _=c instanceof he?String(c.value):c.value;return HE(f,_)};return new ye(t.value.slice().sort((f,_)=>{let m=p(f),w=p(_),x=Nf(m,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ft)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let p=t.value.filter(f=>{let _=f.value.get(a.value),m=_?c(_,l):!1;return o?m:!m});return new ye(p)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof te))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof ft))throw new Error("items in map must be an object");let p=HE(c,a.value);return p instanceof He?i??new He:p});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),p=t.value.split(` `),f=" ".repeat(i.value),_=p.map((m,w)=>!l.value&&w===0||!c.value&&m.length===0?m:f+m);return new te(_.join(` `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof Xe))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new _o(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ft){let o=t.builtins.get(n);if(o&&o instanceof Xe){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new _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 He}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new de(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new te(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new _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 He))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof he||n instanceof He))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof he||o instanceof He))throw new Error("Slice step must be numeric or undefined");return t instanceof ye?new ye(jE(t.value,s.value,n.value,o.value)):new te(jE(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new te(t.property.value);let n;if(r instanceof ft){if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof 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 ar?n:new He}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof 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;om.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let m=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(m.value.length!==w.value.length)throw new Error(`Too ${m.value.length>w.value.length?"few":"many"} items to unpack`);_=x=>{for(let k=0;k0?o[c-1]:new He],["nextitem",c{let n=new _s(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a{let c=new _s(l);if(t.callerArgs)for(let p=0;pthis.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 ft(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Ke;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function uc(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 He;case"object":return t===null?new Ke:Array.isArray(t)?new ye(t.map(uc)):new ft(new Map(Object.entries(t).map(([e,r])=>[e,uc(r)])));case"function":return new Xe((e,r)=>{let s=t(...e.map(n=>n.value))??null;return uc(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var at=` `,Lz="{%- ",Nz=" -%}";function $z(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 Rz(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Xt(t.body,0,r).replace(/\n$/,"")}function wt(...t){return Lz+t.join(" ")+Nz}function Xt(t,e,r){return t.map(s=>Dz(s,e,r)).join(at)}function Dz(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Xt(t.body,e,r);case"If":return Fz(t,e,r);case"For":return Bz(t,e,r);case"Set":return Uz(t,e,r);case"Macro":return jz(t,e,r);case"Break":return s+wt("break");case"Continue":return s+wt("continue");case"CallStatement":return Gz(t,e,r);case"FilterStatement":return qz(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function Fz(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+wt("if",ke(n[0].test))+at+Xt(n[0].body,e+1,r);for(let i=1;i0&&(a+=at+s+wt("else")+at+Xt(o.alternate,e+1,r)),a+=at+s+wt("endif"),a}function Bz(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+wt("for",ke(t.loopvar),"in",n)+at+Xt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=at+s+wt("else")+at+Xt(t.defaultBlock,e+1,r)),o+=at+s+wt("endfor"),o}function Uz(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+wt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+at+Xt(t.body,e+1,r)+at+s+wt("endset")}function jz(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+wt("macro",`${t.name.value}(${n})`)+at+Xt(t.body,e+1,r)+at+s+wt("endmacro")}function Gz(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+wt(`call${n}`,o)+at;return a+=Xt(t.body,e+1,r)+at,a+=s+wt("endcall"),a}function qz(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+wt("filter",n)+at;return o+=Xt(t.body,e+1,r)+at,o+=s+wt("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=$z(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=ez(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ez(e)}render(t){let e=new _s;if(Pz(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new zz(e).run(this.parsed).value}format(t){return Rz(this.parsed,t?.indent||" ")}};import an from"fs";var Wz={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"},Or=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=an.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=an.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=an.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",Wz[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 an.promises.readFile(this.filePath)).buffer}async blob(){let e=await an.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await an.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};import mo from"fs";import pc from"path";var Ir=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(hs.random,t);var Vz=new Ir,ln=class{constructor(e){this.path=e}async match(e){let r=pc.join(this.path,e),s=new Or(r);if(s.exists)return s}async put(e,r,s=void 0){let n=pc.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=Vz._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await mo.promises.mkdir(pc.dirname(n),{recursive:!0});let f=mo.createWriteStream(i),_=r.body.getReader();for(;;){let{done:m,value:w}=await _.read();if(m)break;await new Promise((k,A)=>{f.write(w,E=>{if(E){A(E);return}k()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,total:c})}await new Promise((m,w)=>{f.close(x=>x?w(x):m())}),await mo.promises.rename(i,n)}catch(l){try{await mo.promises.unlink(i)}catch{}throw l}}async delete(e){let r=pc.join(this.path,e);try{return await mo.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"},fc=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 Cr(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:p}=await i.read();if(c)return;let f=a+p.length;if(f>n){n=f;let m=new Uint8Array(n);m.set(o),o=m}o.set(p,a),a=f;let _=a/n*100;return e({progress:_,loaded:a,total:n}),l()}return await l(),o}function $f(t){return Cr(t,["blob:"])}function Rf(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",Hz="experimental_transformers-hash-cache",rA=t=>({algorithm:sA,value:t}),go=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(Hz),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 Yt(t=null){let e=null;if(me.useCustomCache){if(!me.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!me.customCache.match||!me.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=me.customCache}if(!e&&me.experimental_useCrossOriginStorage&&go.isAvailable()&&(e=new go),!e&&me.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(me.cacheKey)}catch(r){ee.warn("An error occurred while opening the browser cache:",r)}}if(!e&&me.useFSCache){if(!ie.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new ln(t??me.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 dc=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 Xz=100,Df=new dc(Xz);function _c(t,e){let r=Df.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Df.delete(t),Promise.reject(n)));return Df.put(t,s),s}async function Kz(t){if(!Cr(t,["http:","https:"]))return null;let e=Ff(t);return e.set("Range","bytes=0-0"),me.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ot(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return _c(s,()=>Yz(t,e,r))}async function Yz(t,e,r){let s=await Yt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=zr(t,e,r,s),l=await Lr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(me.allowLocalModels&&!Cr(n,["http:","https:"]))try{let p=await Pr(n);if(typeof p!="string"&&p.status!==404){let f=p.headers.get("content-length"),_=p.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:_||void 0,fromCache:!1}}}catch{}if(me.allowRemoteModels&&!r.local_files_only&&i)try{let c=await Kz(o);if(c&&c.status>=200&&c.status<300){let p,f=c.headers.get("content-type");if(c.status===206){let _=c.headers.get("content-range");if(_){let m=_.match(/bytes \d+-\d+\/(\d+)/);m&&(p=parseInt(m[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let _=c.headers.get("content-length");p=_?parseInt(_,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Pr(t){return me.useFS&&!Cr(t,["http:","https:","blob:"])?new Or(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):me.fetch(t,{headers:Ff(t)})}function Ff(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=me.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Cr(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 zr(t,e,r={},s=null){let n=r.revision??"main",o=ho(t,e),a=ZE(t),i=a?ho(me.localModelPath,o):o,l=ho(me.remoteHost,me.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof ln?n==="main"?o:ho(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Lr(t,e,r){if(t)return await nA(t,e,r)}async function Qz(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=>or(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function Jz(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=zr(t,e,s,o),f,_=!1,m;m=await Lr(o,i,c);let w=m!==void 0;if(w)f=c;else{if(me.allowLocalModels)if(Cr(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(!me.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{m=await Pr(i),f=i}catch(E){ee.warn(`Unable to load from local path "${i}": "${E}"`)}if(m===void 0||typeof m!="string"&&m.status===404){if(s.local_files_only||!me.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(m=await Pr(l),m.status!==200)return eA(m.status,l,r);f=c}_=o&&typeof Response<"u"&&m instanceof Response&&m.status===200}or(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let A;if(typeof m!="string")if(!s.progress_callback)A=new Uint8Array(await m.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))A=new Uint8Array(await m.arrayBuffer()),or(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let E,S=m.headers.get("content-length");if(S)E=parseInt(S,10);else try{let T=await Ot(t,e,s);T.size&&(E=T.size)}catch{}A=await tA(m,T=>{or(s.progress_callback,{status:"progress",name:t,file:e,...T})},E)}x=A}if(_&&f&&typeof m!="string"&&await Qz(t,e,o,f,m,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof m!="string"){let A=parseInt(m.headers.get("content-length"),10)||0;or(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(or(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(m instanceof Or)return m.filePath;let k=await o?.match(f);if(k instanceof Or)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}var mc=new Map;async function wo(t,e,r=!0,s={},n=!1){if(!me.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!me.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}or(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=mc.get(o);if(!a){let i=await Yt(s?.cache_dir);a=Jz(t,e,r,s,n,i).then(l=>(mc.delete(o),l),l=>{throw mc.delete(o),l}),mc.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 nt(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,p=new t.constructor(n*o*e),f=r*s,_=n*o;for(let m=0;m=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function $e(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 Uf(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 hc=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 _=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>1,w=m>>>1,x=w>>>1;for(l=0;l>>1;for(let m=2;m<_;m+=2)e[n-m]=e[m],e[n-m+1]=-e[m+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+o],f=e[n+i],_=e[n+l],m=c+f,w=c-f,x=p+_,k=a*(p-_);r[s]=m+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=m-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},Bf=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p>1;++p){let f=(p+1-e)**2/2,_=Math.sqrt(l**2+c**2)**f,m=f*Math.atan2(c,l),w=2*p;o[w]=_*Math.cos(m),o[w+1]=_*Math.sin(m),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new hc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f>1,w=r[m];n[f]=w*c[f],n[_]=w*c[_]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function gs(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 p=1;p0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var dA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,_=l&1023;if(f===31)c=p|2139095040|_<<13;else if(f===0)if(_===0)c=p;else{let m=113;for(;(_&1024)===0;)_<<=1,--m;_&=-1025,c=p|m<<23|_<<13}else c=p|f+112<<23|_<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;ohd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Fr,TRACE_EVENT_END:()=>Br,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>Qt,default:()=>SL,env:()=>Ye,registerBackend:()=>vs});var _d=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,tL=Object.getOwnPropertyNames,rL=Object.prototype.hasOwnProperty,sL=(t=>typeof fs<"u"?fs:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof fs<"u"?fs:e)[r]}):t)(function(t){if(typeof fs<"u")return fs.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)_d(t,r,{get:e[r],enumerable:!0})},nL=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of tL(e))!rL.call(t,n)&&n!==r&&_d(t,n,{get:()=>e[n],enumerable:!(s=eL(e,n))||s.enumerable});return t},Ac=t=>nL(_d({},"__esModule",{value:!0}),t),bo,Nr,vs,_A,UA,jA=be(()=>{"use strict";bo=new Map,Nr=[],vs=(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=Nr.indexOf(t);n!==-1&&Nr.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}}},UA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Nr:r,n,o=[],a=new Set;for(let l of s){let c=await _A(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)})]}}),oL=be(()=>{"use strict";jA()}),GA,aL=be(()=>{"use strict";GA="1.24.0-dev.20251116-b39e144322"}),jf,dt,qA=be(()=>{"use strict";aL(),jf="warning",dt={wasm:{},webgl:{},webgpu:{},versions:{common:GA},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}`);jf=t}},get logLevel(){return jf}},Object.defineProperty(dt,"logLevel",{enumerable:!0})}),Ye,iL=be(()=>{"use strict";qA(),Ye=dt}),WA,VA,lL=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 p=o*n,f=0,_=p,m=p*2,w=-1;a==="RGBA"?(f=0,_=p,m=p*2,w=p*3):a==="RGB"?(f=0,_=p,m=p*2):a==="RBG"&&(f=0,m=p,_=p*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,m=0,w=1,x=2,k=3,A=0,E=f,S=f*2,T=-1;i==="RGBA"?(A=0,E=f,S=f*2,T=f*3):i==="RGB"?(A=0,E=f,S=f*2):i==="RBG"&&(A=0,S=f,E=f*2),s=r.createImageData(n,o);for(let I=0;I{"use strict";md(),wc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,_=0,m=1,w=2,x=3,k=0,A=c,E=c*2,S=-1;i==="RGB"&&(f=3,_=0,m=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,E=c,A=c*2):l==="BGR"&&(E=0,A=c,k=c*2);for(let T=0;T{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(_=e.resizedHeight,m=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=_,i.width=m}else i.tensorFormat="RGBA",i.height=_,i.width=m;f.drawImage(t,0,0),a=f.getImageData(0,0,m,_).data}else throw new Error("Can not access image data")}else if(s){let p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let _=l();_.width=f,_.height=p;let m=c(_);if(m!=null)m.putImageData(t,0,0),a=m.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let _=t.height,m=t.width;return f.drawImage(t,0,0,m,_),a=f.getImageData(0,0,m,_).data,i.height=_,i.width=m,wc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let _=l(),m=c(_);if(!t||!m)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{_.width=w.width,_.height=w.height,m.drawImage(w,0,0,_.width,_.height);let x=m.getImageData(0,0,_.width,_.height);i.height=_.height,i.width=_.width,p(wc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return wc(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 Lt({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 Lt({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 Lt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},QA=(t,e,r)=>new Lt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ys,Mo,Gf,JA,uL=be(()=>{"use strict";ys=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Mo=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&&(ys.set("int64",BigInt64Array),Mo.set(BigInt64Array,"int64")),e&&(ys.set("uint64",BigUint64Array),Mo.set(BigUint64Array,"uint64")),s?(ys.set("float16",r),Mo.set(r,"float16")):ys.set("float16",Uint16Array)}}}),ZA,e2,pL=be(()=>{"use strict";md(),ZA=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Lt(t.type,t.data,e);case"cpu-pinned":return new Lt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Lt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Lt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Lt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Lt,md=be(()=>{"use strict";lL(),cL(),uL(),pL(),Lt=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=ys.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=ys.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=Mo.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)}}}),Qt,t2=be(()=>{"use strict";md(),Qt=Lt}),Mc,qf,ks,Es,Fr,Br,r2=be(()=>{"use strict";qA(),Mc=(t,e)=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeStamp(`${t}::ORT::${e}`)},qf=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||qf("BEGIN",t)},Es=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||qf("END",t)},Fr=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.time(`ORT::${t}`)},Br=t=>{(typeof dt.trace>"u"?!dt.wasm.trace:!dt.trace)||console.timeEnd(`ORT::${t}`)}}),s2,fL=be(()=>{"use strict";jA(),t2(),r2(),s2=class n2{constructor(e){this.handler=e}async run(e,r,s){ks(),Fr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Qt||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 Qt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let _=r[f];(_===null||_ instanceof Qt)&&(c=!0,a=!1,n[f]=_)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof Qt?l[c]=p:l[c]=new Qt(p.type,p.data,p.dims)}return Br("InferenceSession.run"),Es(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ks(),Fr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,f=0,_=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(_=e.byteLength-f,typeof s=="number"){if(_=s,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||f+_>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,f,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await UA(a),c=await i.createInferenceSessionHandler(o,l);return Br("InferenceSession.create"),Es(),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}}}),hd,dL=be(()=>{"use strict";fL(),hd=s2}),_L=be(()=>{"use strict"}),mL=be(()=>{"use strict"}),hL=be(()=>{"use strict"}),gL=be(()=>{"use strict"}),o2={};So(o2,{InferenceSession:()=>hd,TRACE:()=>Mc,TRACE_EVENT_BEGIN:()=>Fr,TRACE_EVENT_END:()=>Br,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>Qt,env:()=>Ye,registerBackend:()=>vs});var As=be(()=>{"use strict";oL(),iL(),dL(),t2(),_L(),mL(),r2(),hL(),gL()}),gd=be(()=>{"use strict"}),a2={};So(a2,{default:()=>i2});var Wf,Vf,i2,wL=be(()=>{"use strict";v2(),Ms(),wd(),Wf="ort-wasm-proxy-worker",Vf=globalThis.self?.name===Wf,Vf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":xd(r.wasm).then(()=>{Ed(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;Ad(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=Oc(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;Md(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;Sd(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},Id([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":Od(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),i2=Vf?null:t=>new Worker(t??Pt,{type:"module",name:Wf})}),l2={};So(l2,{default:()=>c2});async function mA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let u=d=>(...h)=>{let g=sr;return h=d(...h),sr!=g?new Promise((v,M)=>{lf={resolve:v,reject:M}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=import.meta.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(O(u))return new Promise((h,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):g(v.status)},v.onerror=g,v.send(null)});var d=await fetch(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,_,m,w,x,k,A=console.log.bind(console),E=console.error.bind(console),S=A,T=E,I=!1,O=u=>u.startsWith("file://");function b(){Tr.buffer!=U.buffer&&le()}if(n){let u=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let v=[];self.onmessage=M=>v.push(M),k=()=>{postMessage({Oc:"loaded"});for(let M of v)u(M);self.onmessage=u};for(let M of h.ce)e[M]&&!e[M].proxy||(e[M]=(...P)=>{postMessage({Oc:"callHandler",be:M,args:P})},M=="print"&&(S=e[M]),M=="printErr"&&(T=e[M]));Tr=h.ie,le(),_=h.je,qe(),rc()}else if(g==="run"){(function(v){var M=(b(),C)[v+52>>>2>>>0];v=(b(),C)[v+56>>>2>>>0],kk(M,M-v),pe(M)})(h.Nc),yf(h.Nc,0,0,1,0,0),uv(),nf(h.Nc),j||(ok(),j=!0);try{AT(h.ge,h.Wc)}catch(v){if(v!="unwind")throw v}}else h.target!=="setimmediate"&&(g==="checkMailbox"?j&&Xl():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(v){throw wk(),v}};var F=u,j=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var U,X,K,J,R,C,se,Y,z,$,B,Q=!1;function le(){var u=Tr.buffer;e.HEAP8=U=new Int8Array(u),K=new Int16Array(u),e.HEAPU8=X=new Uint8Array(u),J=new Uint16Array(u),e.HEAP32=R=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),se=new Float32Array(u),Y=new Float64Array(u),z=new BigInt64Array(u),$=new BigUint64Array(u)}function Ge(){Q=!0,n?k():wr._b()}function ce(u){throw T(u="Aborted("+u+")"),I=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function Et(){return{a:{f:MT,J:TT,k:ST,p:OT,l:IT,sa:CT,b:PT,ca:zT,Ja:hv,q:LT,da:yv,Za:bv,Fa:vv,Ha:kv,_a:Ev,Xa:Av,Qa:Mv,Wa:Tv,oa:Sv,Ga:Ov,Xb:Iv,Ya:Cv,Yb:Pv,db:NT,Da:RT,Sb:DT,Qb:BT,Ca:jT,M:GT,I:qT,Rb:WT,ja:JT,Tb:ZT,Ta:eS,Vb:rS,Ka:sS,Ob:nS,ka:oS,Sa:nf,ab:aS,U:uS,n:mS,c:rf,rb:hS,w:gS,L:wS,z:xS,j:yS,o:Bv,sb:bS,G:vS,T:kS,h:ES,u:AS,m:MS,i:TS,Na:SS,Oa:OS,Pa:IS,La:qv,Ma:Wv,Pb:Vv,eb:PS,cb:NS,Y:$S,qb:RS,la:DS,bb:zS,fb:FS,$a:BS,Wb:US,N:CS,gb:jS,X:GS,Ub:qS,nb:ZS,C:eO,ra:tO,qa:rO,pb:sO,W:nO,v:oO,mb:aO,lb:iO,kb:lO,ob:cO,jb:uO,ib:pO,hb:fO,Ua:Jv,Va:Zv,Ia:Xs,V:ek,na:tk,Ra:rk,ma:sk,Cb:vI,xa:hI,Db:bI,ya:mI,F:nI,e:WO,s:GO,x:jO,B:tI,Fb:fI,ba:pI,D:XO,za:dI,$:gI,ga:uI,Gb:cI,Hb:lI,Ba:oI,Aa:iI,Ib:aI,wa:yI,aa:_I,d:qO,A:HO,r:VO,Bb:kI,t:YO,y:rI,H:KO,E:QO,K:sI,R:wI,ia:eI,_:xI,Jb:ZO,Kb:JO,g:_O,a:Tr,Nb:Hs,Eb:mO,ha:hO,O:gO,pa:wO,Lb:xO,ta:yO,Q:bO,yb:vO,zb:kO,ua:EO,ea:AO,P:MO,Ea:TO,va:SO,Z:OO,wb:IO,Zb:CO,S:PO,Ab:zO,tb:LO,ub:$O,vb:RO,fa:DO,xb:FO,Mb:BO}}}async function qe(){function u(g,v){var M=wr=g.exports;g={};for(let[P,L]of Object.entries(M))typeof L=="function"?(M=iS(L),g[P]=M):g[P]=L;return wr=g,wr=(function(){var P=wr,L=Z=>Ie=>Z(Ie)>>>0,G=Z=>()=>Z()>>>0;return(P=Object.assign({},P)).$b=L(P.$b),P.Cc=G(P.Cc),P.Ec=L(P.Ec),P.rd=(Z=>(Ie,Ne)=>Z(Ie,Ne)>>>0)(P.rd),P.wd=L(P.wd),P.xd=G(P.xd),P.Bd=L(P.Bd),P})(),lv.push(wr.id),nk=(g=wr).$b,ok=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,_f=e._OrtGetWebGpuDevice=g.Bc,ec=g.Cc,Wt=e._free=g.Dc,Zs=e._malloc=g.Ec,ak=e._wgpuBufferRelease=g.Fc,ik=e._wgpuCreateInstance=g.Gc,lk=g.Hc,ck=g.Ic,uk=g.Jc,pk=g.Kc,fk=g.Lc,dk=g.Pc,_k=g.Zc,mk=g._c,hk=g.$c,mf=g.bd,hf=g.cd,gf=g.dd,wf=g.ed,io=g.fd,xf=g.gd,gk=g.hd,yf=g.kd,wk=g.ld,xk=g.md,yk=g.nd,bf=g.od,bk=g.pd,vk=g.qd,vf=g.rd,xe=g.sd,lo=g.td,kk=g.ud,pe=g.vd,tc=g.wd,fe=g.xd,Ek=g.yd,kf=g.zd,Ak=g.Ad,Mk=g.Bd,Tk=g.Cd,Ef=g.Dd,Sk=g.Ed,Ok=g.Fd,Ik=g.Gd,Ck=g.Hd,Pk=g.Id,zk=g.Jd,Lk=g.Kd,Nk=g.Ld,$k=g.Md,Rk=g.Nd,Dk=g.Od,Fk=g.Pd,Bk=g.Qd,Uk=g.Rd,jk=g.Td,Gk=g.Ud,qk=g.Vd,Wk=g.Wd,Vk=g.Yd,Hk=g.Zd,Xk=g._d,Kk=g.$d,Yk=g.ae,Qk=g.oe,Jk=g.pe,Zk=g.qe,eE=g.re,tE=g.se,rE=g.te,sE=g.ue,nE=g.ve,oE=g.we,aE=g.xe,iE=g.ye,lE=g.Ye,cE=g.Ze,uE=g._e,pE=g.$e,_=v,wr}var d,h=Et();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(v,M)=>{g(u(v,M))})}):n?u(new WebAssembly.Instance(_,Et()),_):(B??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var v=B;if(!f&&!O(v))try{var M=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(M,g)}catch(P){T(`wasm streaming compile failed: ${P}`),T("falling back to ArrayBuffer instantiation")}return(async function(P,L){try{var G=await(async function(Z){if(!f)try{var Ie=await a(Z);return new Uint8Array(Ie)}catch{}if(Z==B&&f)Z=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Z=i(Z)}return Z})(P);return await WebAssembly.instantiate(G,L)}catch(Z){T(`failed to asynchronously prepare wasm: ${Z}`),ce(Z)}})(v,g)})(h),u(d.instance,d.module))}class ct{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var At=u=>{u.terminate(),u.onmessage=()=>{}},Fe=[],Se=0,rt=null,tr=u=>{Mr.length==0&&(fv(),pv(Mr[0]));var d=Mr.pop();if(!d)return 6;no.push(d),cs[u.Nc]=d,d.Nc=u.Nc;var h={Oc:"run",ge:u.fe,Wc:u.Wc,Nc:u.Nc};return d.postMessage(h,u.Yc),0},Oe=0,Be=(u,d,...h)=>{var g,v=16*h.length,M=fe(),P=tc(v),L=P>>>3;for(g of h)typeof g=="bigint"?((b(),z)[L++>>>0]=1n,(b(),z)[L++>>>0]=g):((b(),z)[L++>>>0]=0n,(b(),Y)[L++>>>0]=g);return u=xk(u,0,v,P,d),pe(M),u};function Hs(u){if(n)return Be(0,1,u);if(m=u,!(0{if(m=u,n)throw so(u),"unwind";Hs(u)},Mr=[],no=[],lv=[],cs={},cv=u=>{var d=u.Nc;delete cs[d],Mr.push(u),no.splice(no.indexOf(u),1),u.Nc=0,yk(d)};function uv(){lv.forEach(u=>u())}var pv=u=>new Promise(d=>{u.onmessage=v=>{var M=v.data;if(v=M.Oc,M.Vc&&M.Vc!=ec()){var P=cs[M.Vc];P?P.postMessage(M,M.Yc):T(`Internal error! Worker sent a message "${v}" to target pthread ${M.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?Xl():v==="spawnThread"?tr(M):v==="cleanupThread"?Mt(()=>{cv(cs[M.he])}):v==="loaded"?(u.loaded=!0,d(u)):M.target==="setimmediate"?u.postMessage(M):v==="uncaughtException"?u.onerror(M.error):v==="callHandler"?e[M.be](...M.args):v&&T(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw T(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);u.postMessage({Oc:"load",ce:g,ie:Tr,je:_})});function fv(){var u=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"});Mr.push(u)}var Tr,AT=(u,d)=>{Oe=0,u=Ef(u,d),0-9007199254740992>u||9007199254740992>>=0);return(b(),U)[d.Qc+12>>>0]==0&&(dv(d,!0),Hl--),_v(d,!1),Vl.push(d),Mk(u)}var Ks=0,TT=()=>{xe(0,0);var u=Vl.pop();Ek(u.Xc),Ks=0};function dv(u,d){d=d?1:0,(b(),U)[u.Qc+12>>>0]=d}function _v(u,d){d=d?1:0,(b(),U)[u.Qc+13>>>0]=d}class Jp{constructor(d){this.Xc=d,this.Qc=d-24}}var Zp=u=>{var d=Ks;if(!d)return lo(0),0;var h=new Jp(d);(b(),C)[h.Qc+16>>>2>>>0]=d;var g=(b(),C)[h.Qc+4>>>2>>>0];if(!g)return lo(0),d;for(var v of u){if(v===0||v===g)break;if(Ak(v,g,h.Qc+16))return lo(v),d}return lo(g),d};function ST(){return Zp([])}function OT(u){return Zp([u>>>0])}function IT(u,d,h,g){return Zp([u>>>0,d>>>0,h>>>0,g>>>0])}var CT=()=>{var u=Vl.pop();u||ce("no exception to throw");var d=u.Xc;throw(b(),U)[u.Qc+13>>>0]==0&&(Vl.push(u),_v(u,!0),dv(u,!1),Hl++),kf(d),Ks=d};function PT(u,d,h){var g=new Jp(u>>>=0);throw d>>>=0,h>>>=0,(b(),C)[g.Qc+16>>>2>>>0]=0,(b(),C)[g.Qc+4>>>2>>>0]=d,(b(),C)[g.Qc+8>>>2>>>0]=h,kf(u),Hl++,Ks=u}var zT=()=>Hl;function mv(u,d,h,g){return n?Be(2,1,u,d,h,g):hv(u,d,h,g)}function hv(u,d,h,g){if(u>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?mv(u,d,h,g):(u={fe:h,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):tr(u))}function LT(u){throw Ks||=u>>>0,Ks}var gv=globalThis.TextDecoder&&new TextDecoder,wv=(u,d,h,g)=>{if(h=d+h,g)return h;for(;u[d]&&!(d>=h);)++d;return d},xv=(u,d=0,h,g)=>{if(16<(h=wv(u,d>>>=0,h,g))-d&&u.buffer&&gv)return gv.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,h):u.slice(d,h));for(g="";d(v=(240&v)==224?(15&v)<<12|M<<6|P:(7&v)<<18|M<<12|P<<6|63&u[d++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},Ys=(u,d,h)=>(u>>>=0)?xv((b(),X),u,d,h):"";function yv(u,d,h){return n?Be(3,1,u,d,h):0}function bv(u,d){if(n)return Be(4,1,u,d)}function vv(u,d){if(n)return Be(5,1,u,d)}function kv(u,d,h){if(n)return Be(6,1,u,d,h)}function Ev(u,d,h){return n?Be(7,1,u,d,h):0}function Av(u,d){if(n)return Be(8,1,u,d)}function Mv(u,d,h){if(n)return Be(9,1,u,d,h)}function Tv(u,d,h,g){if(n)return Be(10,1,u,d,h,g)}function Sv(u,d,h,g){if(n)return Be(11,1,u,d,h,g)}function Ov(u,d,h,g){if(n)return Be(12,1,u,d,h,g)}function Iv(u){if(n)return Be(13,1,u)}function Cv(u,d){if(n)return Be(14,1,u,d)}function Pv(u,d,h){if(n)return Be(15,1,u,d,h)}var NT=()=>ce(""),rr=u=>{u>>>=0;for(var d="";;){var h=(b(),X)[u++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},ef={},tf={},$T={},Qs=class extends Error{constructor(u){super(u),this.name="BindingError"}};function dr(u,d,h={}){return(function(g,v,M={}){var P=v.name;if(!g)throw new Qs(`type "${P}" must have a positive integer typeid pointer`);if(tf.hasOwnProperty(g)){if(M.de)return;throw new Qs(`Cannot register type '${P}' twice`)}tf[g]=v,delete $T[g],ef.hasOwnProperty(g)&&(v=ef[g],delete ef[g],v.forEach(L=>L()))})(u,d,h)}var zv=(u,d,h)=>{switch(d){case 1:return h?g=>(b(),U)[g>>>0]:g=>(b(),X)[g>>>0];case 2:return h?g=>(b(),K)[g>>>1>>>0]:g=>(b(),J)[g>>>1>>>0];case 4:return h?g=>(b(),R)[g>>>2>>>0]:g=>(b(),C)[g>>>2>>>0];case 8:return h?g=>(b(),z)[g>>>3>>>0]:g=>(b(),$)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function RT(u,d,h,g,v){u>>>=0,h>>>=0,d=rr(d>>>0);let M=P=>P;if(g=g===0n){let P=8*h;M=L=>BigInt.asUintN(P,L),v=M(v)}dr(u,{name:d,Mc:M,Sc:(P,L)=>(typeof L=="number"&&(L=BigInt(L)),L),Rc:zv(d,h,!g),Tc:null})}function DT(u,d,h,g){dr(u>>>=0,{name:d=rr(d>>>0),Mc:function(v){return!!v},Sc:function(v,M){return M?h:g},Rc:function(v){return this.Mc((b(),X)[v>>>0])},Tc:null})}var Lv=[],us=[0,1,,1,null,1,!0,1,!1,1];function rf(u){9<(u>>>=0)&&--us[u+1]==0&&(us[u]=void 0,Lv.push(u))}var Rt=u=>{if(!u)throw new Qs(`Cannot use deleted val. handle = ${u}`);return us[u]},qt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Lv.pop()||us.length;return us[d]=u,us[d+1]=1,d}};function sf(u){return this.Mc((b(),C)[u>>>2>>>0])}var FT={name:"emscripten::val",Mc:u=>{var d=Rt(u);return rf(u),d},Sc:(u,d)=>qt(d),Rc:sf,Tc:null};function BT(u){return dr(u>>>0,FT)}var UT=(u,d)=>{switch(d){case 4:return function(h){return this.Mc((b(),se)[h>>>2>>>0])};case 8:return function(h){return this.Mc((b(),Y)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function jT(u,d,h){h>>>=0,dr(u>>>=0,{name:d=rr(d>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:UT(d,h),Tc:null})}function GT(u,d,h,g,v){u>>>=0,h>>>=0,d=rr(d>>>0);let M=L=>L;if(g===0){var P=32-8*h;M=L=>L<

>>P,v=M(v)}dr(u,{name:d,Mc:M,Sc:(L,G)=>G,Rc:zv(d,h,g!==0),Tc:null})}function qT(u,d,h){function g(M){var P=(b(),C)[M>>>2>>>0];return M=(b(),C)[M+4>>>2>>>0],new v((b(),U).buffer,M,P)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];dr(u>>>=0,{name:h=rr(h>>>0),Mc:g,Rc:g},{de:!0})}var _r=(u,d,h)=>{var g=(b(),X);if(d>>>=0,0=P){if(d>=h)break;g[d++>>>0]=P}else if(2047>=P){if(d+1>=h)break;g[d++>>>0]=192|P>>6,g[d++>>>0]=128|63&P}else if(65535>=P){if(d+2>=h)break;g[d++>>>0]=224|P>>12,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P}else{if(d+3>=h)break;g[d++>>>0]=240|P>>18,g[d++>>>0]=128|P>>12&63,g[d++>>>0]=128|P>>6&63,g[d++>>>0]=128|63&P,M++}}g[d>>>0]=0,u=d-v}else u=0;return u},mr=u=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function WT(u,d){dr(u>>>=0,{name:d=rr(d>>>0),Mc(h){var g=(b(),C)[h>>>2>>>0];return g=Ys(h+4,g,!0),Wt(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Qs("Cannot pass non-string to std::string");var M=v?mr(g):g.length,P=Zs(4+M+1),L=P+4;return(b(),C)[P>>>2>>>0]=M,v?_r(g,L,M+1):(b(),X).set(g,L>>>0),h!==null&&h.push(Wt,P),P},Rc:sf,Tc(h){Wt(h)}})}var Nv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,VT=(u,d,h)=>{if(u>>>=1,16<(d=wv((b(),J),u,d/2,h))-u&&Nv)return Nv.decode((b(),J).slice(u,d));for(h="";u>>0];h+=String.fromCharCode(g)}return h},HT=(u,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*u.length?h/2:u.length;for(var v=0;v>>1>>>0]=M,d+=2}return(b(),K)[d>>>1>>>0]=0,d-g},XT=u=>2*u.length,KT=(u,d,h)=>{var g="";u>>>=2;for(var v=0;!(v>=d/4);v++){var M=(b(),C)[u+v>>>0];if(!M&&!h)break;g+=String.fromCodePoint(M)}return g},YT=(u,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var v=0;v>>2>>>0]=M,(d+=4)+4>h)break}return(b(),R)[d>>>2>>>0]=0,d-g},QT=u=>{for(var d=0,h=0;h>>=0,d>>>=0,h=rr(h>>>=0),d===2)var g=VT,v=HT,M=XT;else g=KT,v=YT,M=QT;dr(u,{name:h,Mc:P=>{var L=(b(),C)[P>>>2>>>0];return L=g(P+4,L*d,!0),Wt(P),L},Sc:(P,L)=>{if(typeof L!="string")throw new Qs(`Cannot pass non-string to C++ string type ${h}`);var G=M(L),Z=Zs(4+G+d);return(b(),C)[Z>>>2>>>0]=G/d,v(L,Z+4,G+d),P!==null&&P.push(Wt,Z),Z},Rc:sf,Tc(P){Wt(P)}})}function ZT(u,d){dr(u>>>=0,{ee:!0,name:d=rr(d>>>0),Mc:()=>{},Sc:()=>{}})}function eS(u){yf(u>>>0,!s,1,!r,131072,!1),uv()}var Mt=u=>{if(!I)try{if(u(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function nf(u){u>>>=0,tS||(Atomics.waitAsync((b(),R),u>>>2,u).value.then(Xl),u+=128,Atomics.store((b(),R),u>>>2,1))}var Xl=()=>Mt(()=>{var u=ec();u&&(nf(u),vk())});function rS(u,d){(u>>>=0)==d>>>0?setTimeout(Xl):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=cs[u])&&u.postMessage({Oc:"checkMailbox"})}var of=[];function sS(u,d,h,g,v){for(d>>>=0,v>>>=0,of.length=0,h=v>>>3,g=v+g>>>3;h>>0]?(b(),z)[h++>>>0]:(b(),Y)[h++>>>0],of.push(M)}return(d?Af[d]:UO[u])(...of)}var nS=()=>{Oe=0};function oS(u){u>>>=0,n?postMessage({Oc:"cleanupThread",he:u}):cv(cs[u])}function aS(u){}var Kl=u=>{try{u()}catch(d){ce(d)}};function iS(u){var d=(...h)=>{Yl.push(u);try{return u(...h)}finally{I||(Yl.pop(),sr&&Sr===1&&Yl.length===0&&(Sr=0,Oe+=1,Kl(cE),typeof Fibers<"u"&&Fibers.Be()))}};return Dv.set(u,d),d}var Sr=0,sr=null,$v=0,Yl=[],af=new Map,Rv=new Map,Dv=new Map,lS=0,lf=null,cS=[],Fv=u=>(function(d){if(!I){if(Sr===0){var h=!1,g=!1;d((v=0)=>{if(!I&&($v=v,h=!0,g)){Sr=2,Kl(()=>uE(sr)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var M=(function(){var G=(b(),R)[sr+8>>>2>>>0];return G=Rv.get(G),G=Dv.get(G),--Oe,G()})()}catch(G){M=G,v=!0}var P=!1;if(!sr){var L=lf;L&&(lf=null,(v?L.reject:L.resolve)(M),P=!0)}if(v&&!P)throw M}}),g=!0,h||(Sr=1,sr=(function(){var v=Zs(65548),M=v+12;if((b(),C)[v>>>2>>>0]=M,(b(),C)[v+4>>>2>>>0]=M+65536,M=Yl[0],!af.has(M)){var P=lS++;af.set(M,P),Rv.set(P,M)}return M=af.get(M),(b(),R)[v+8>>>2>>>0]=M,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Kl(()=>lE(sr)))}else Sr===2?(Sr=0,Kl(pE),Wt(sr),sr=null,cS.forEach(Mt)):ce(`invalid state: ${Sr}`);return $v}})(d=>{u().then(d)});function uS(u){return u>>>=0,Fv(async()=>{var d=await Rt(u);return qt(d)})}var cf=[],pS=u=>{var d=cf.length;return cf.push(u),d},fS=(u,d)=>{for(var h=Array(u),g=0;g>>2>>>0],P=tf[M];if(P===void 0)throw u=`parameter ${g}`,M=nk(M),d=rr(M),Wt(M),new Qs(`${u} has unknown type ${d}`);h[v]=P}return h},dS=(u,d,h)=>{var g=[];return u=u(g,h),g.length&&((b(),C)[d>>>2>>>0]=qt(g)),u},_S={},Ql=u=>{var d=_S[u];return d===void 0?rr(u):d};function mS(u,d,h){var[g,...v]=fS(u,d>>>0);d=g.Sc.bind(g);var M=v.map(G=>G.Rc.bind(G));u--;var P={toValue:Rt};switch(u=M.map((G,Z)=>{var Ie=`argFromPtr${Z}`;return P[Ie]=G,`${Ie}(args${Z?"+"+8*Z:""})`}),h){case 0:var L="toValue(handle)";break;case 2:L="new (toValue(handle))";break;case 3:L="";break;case 1:P.getStringOrSymbol=Ql,L="toValue(handle)[getStringOrSymbol(methodName)]"}return L+=`(${u})`,g.ee||(P.toReturnWire=d,P.emval_returnValue=dS,L=`return emval_returnValue(toReturnWire, destructorsRef, ${L})`),L=`return function (handle, methodName, destructorsRef, args) { ${L} }`,h=new Function(Object.keys(P),L)(...Object.values(P)),L=`methodCaller<(${v.map(G=>G.name)}) => ${g.name}>`,pS(Object.defineProperty(h,"name",{value:L}))}function hS(u,d){return d>>>=0,(u=Rt(u>>>0))==Rt(d)}function gS(u){return(u>>>=0)?(u=Ql(u),qt(globalThis[u])):qt(globalThis)}function wS(u){return u=Ql(u>>>0),qt(e[u])}function xS(u,d){return d>>>=0,u=Rt(u>>>0),d=Rt(d),qt(u[d])}function yS(u){9<(u>>>=0)&&(us[u+1]+=1)}function Bv(u,d,h,g,v){return cf[u>>>0](d>>>0,h>>>0,g>>>0,v>>>0)}function bS(u,d,h,g,v){return Bv(u>>>0,d>>>0,h>>>0,g>>>0,v>>>0)}function vS(){return qt([])}function kS(u){u=Rt(u>>>0);for(var d=Array(u.length),h=0;h>>0))}function AS(){return qt({})}function MS(u){for(var d=Rt(u>>>=0);d.length;){var h=d.pop();d.pop()(h)}rf(u)}function TS(u,d,h){d>>>=0,h>>>=0,u=Rt(u>>>0),d=Rt(d),h=Rt(h),u[d]=h}function SS(u,d){u=mt(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getUTCSeconds(),(b(),R)[d+4>>>2>>>0]=u.getUTCMinutes(),(b(),R)[d+8>>>2>>>0]=u.getUTCHours(),(b(),R)[d+12>>>2>>>0]=u.getUTCDate(),(b(),R)[d+16>>>2>>>0]=u.getUTCMonth(),(b(),R)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(b(),R)[d+28>>>2>>>0]=u}var Uv=u=>u%4==0&&(u%100!=0||u%400==0),jv=[0,31,60,91,121,152,182,213,244,274,305,335],Gv=[0,31,59,90,120,151,181,212,243,273,304,334];function OS(u,d){u=mt(u),d>>>=0,u=new Date(1e3*u),(b(),R)[d>>>2>>>0]=u.getSeconds(),(b(),R)[d+4>>>2>>>0]=u.getMinutes(),(b(),R)[d+8>>>2>>>0]=u.getHours(),(b(),R)[d+12>>>2>>>0]=u.getDate(),(b(),R)[d+16>>>2>>>0]=u.getMonth(),(b(),R)[d+20>>>2>>>0]=u.getFullYear()-1900,(b(),R)[d+24>>>2>>>0]=u.getDay();var h=(Uv(u.getFullYear())?jv:Gv)[u.getMonth()]+u.getDate()-1|0;(b(),R)[d+28>>>2>>>0]=h,(b(),R)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),h=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(h!=g&&u.getTimezoneOffset()==Math.min(g,h)),(b(),R)[d+32>>>2>>>0]=u}function IS(u){u>>>=0;var d=new Date((b(),R)[u+20>>>2>>>0]+1900,(b(),R)[u+16>>>2>>>0],(b(),R)[u+12>>>2>>>0],(b(),R)[u+8>>>2>>>0],(b(),R)[u+4>>>2>>>0],(b(),R)[u>>>2>>>0],0),h=(b(),R)[u+32>>>2>>>0],g=d.getTimezoneOffset(),v=new Date(d.getFullYear(),6,1).getTimezoneOffset(),M=new Date(d.getFullYear(),0,1).getTimezoneOffset(),P=Math.min(M,v);return 0>h?(b(),R)[u+32>>>2>>>0]=+(v!=M&&P==g):0>>2>>>0]=d.getDay(),h=(Uv(d.getFullYear())?jv:Gv)[d.getMonth()]+d.getDate()-1|0,(b(),R)[u+28>>>2>>>0]=h,(b(),R)[u>>>2>>>0]=d.getSeconds(),(b(),R)[u+4>>>2>>>0]=d.getMinutes(),(b(),R)[u+8>>>2>>>0]=d.getHours(),(b(),R)[u+12>>>2>>>0]=d.getDate(),(b(),R)[u+16>>>2>>>0]=d.getMonth(),(b(),R)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function qv(u,d,h,g,v,M,P){return n?Be(16,1,u,d,h,g,v,M,P):-52}function Wv(u,d,h,g,v,M){if(n)return Be(17,1,u,d,h,g,v,M)}var oo={},CS=()=>performance.timeOrigin+performance.now();function Vv(u,d){if(n)return Be(18,1,u,d);if(oo[u]&&(clearTimeout(oo[u].id),delete oo[u]),!d)return 0;var h=setTimeout(()=>{delete oo[u],Mt(()=>bk(u,performance.timeOrigin+performance.now()))},d);return oo[u]={id:h,Ae:d},0}function PS(u,d,h,g){u>>>=0,d>>>=0,h>>>=0,g>>>=0;var v=new Date().getFullYear(),M=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var P=Math.max(M,v);(b(),C)[u>>>2>>>0]=60*P,(b(),R)[d>>>2>>>0]=+(M!=v),u=(d=L=>{var G=Math.abs(L);return`UTC${0<=L?"-":"+"}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`})(M),d=d(v),vDate.now(),LS=1;function NS(u,d,h){if(h>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!LS)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(b(),z)[h>>>3>>>0]=BigInt(u),0}var uf=[],Hv=(u,d)=>{uf.length=0;for(var h;h=(b(),X)[u++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,uf.push(h==112?(b(),C)[d>>>2>>>0]:h==106?(b(),z)[d>>>3>>>0]:h==105?(b(),R)[d>>>2>>>0]:(b(),Y)[d>>>3>>>0]),d+=g?8:4}return uf};function $S(u,d,h){return u>>>=0,d=Hv(d>>>0,h>>>0),Af[u](...d)}function RS(u,d,h){return u>>>=0,d=Hv(d>>>0,h>>>0),Af[u](...d)}var DS=()=>{};function FS(u,d){return T(Ys(u>>>0,d>>>0))}var BS=()=>{throw Oe+=1,"unwind"};function US(){return 4294901760}var jS=()=>1,GS=()=>navigator.hardwareConcurrency;function qS(u){u>>>=0;var d=(b(),X).length;if(u<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Tr.buffer.byteLength+65535)/65536|0;try{Tr.grow(g),le();var v=1;break e}catch{}v=void 0}if(v)return!0}return!1}var nr=u=>{var d=mr(u)+1,h=tc(d);return _r(u,h,d),h},pf=(u,d)=>{(b(),C)[u>>>2>>>0]=d;var h=(b(),C)[u>>>2>>>0];(b(),C)[u+4>>>2>>>0]=(d-h)/4294967296},ao=u=>(b(),C)[u>>>2>>>0]+4294967296*(b(),R)[u+4>>>2>>>0],ht=[],WS=(u,d)=>{ht[u>>>0]=d},hr=[],Jl=[],Js=(u,d)=>{Jl[u]=new Promise(h=>d.finally(()=>h(u)))},oe=u=>{if(u)return ht[u>>>0]},VS=(u,d)=>{for(u=(b(),C)[u>>>2>>>0];u;u=(b(),C)[u>>>2>>>0])d[(b(),R)[u+4>>>2>>>0]](u)},Zl=(u,d,h)=>{(b(),C)[u>>>2>>>0]=d,(b(),C)[u+4>>>2>>>0]=h},Xv=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],Ys(d,u)},gr=u=>{var d=(b(),C)[u>>>2>>>0];return u=(b(),C)[u+4>>>2>>>0],d?Ys(d,u):u===0?"":void 0},HS=u=>{var d=gr(u+4),h=(h=(b(),C)[u+12>>>2>>>0])?oe(h):"auto";if(u+=16){var g=oe((b(),C)[u+4>>>2>>>0]),v=(b(),C)[u+16>>>2>>>0],M=(b(),C)[u+20>>>2>>>0];if(v){for(var P={},L=0;L>>3>>>0]}v=P}else v=void 0;u={module:g,constants:v,entryPoint:gr(u+8)}}else u=void 0;return{label:d,layout:h,compute:u}},Kv=(u,d)=>{function h(g,v){g=u[g],(b(),C)[d+v>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),pf(d+64,u.maxUniformBufferBindingSize),pf(d+72,u.maxStorageBufferBindingSize),h("maxVertexBuffers",88),pf(d+96,u.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),u.ze!==void 0&&h("maxImmediateSize",148)},XS=[,"validation","out-of-memory","internal"],KS=[,"compatibility","core"],Yv={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"},YS=[,"low-power","high-performance"],QS=[,"occlusion","timestamp"],JS={undefined:1,unknown:1,destroyed:2};function ZS(u,d,h,g,v,M){d=mt(d),h=mt(h),g>>>=0,v>>>=0,M>>>=0;var P=oe(u>>>0);if(u={},M){var L=(b(),C)[M+12>>>2>>>0];if(L){var G=(b(),C)[M+16>>>2>>>0];u.requiredFeatures=Array.from((b(),C).subarray(G>>>2>>>0,G+4*L>>>2>>>0),ae=>Yv[ae])}var Z=(b(),C)[M+20>>>2>>>0];if(Z){let ae=function(Tt,pt,ps=!1){pt=Z+pt,(pt=(b(),C)[pt>>>2>>>0])==4294967295||ps&&pt==0||(Ue[Tt]=pt)},ut=function(Tt,pt){pt=Z+pt;var ps=(b(),C)[pt>>>2>>>0],EI=(b(),C)[pt+4>>>2>>>0];ps==4294967295&&EI==4294967295||(Ue[Tt]=ao(pt))};var Ie=ae,Ne=ut,Ue={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),ut("maxUniformBufferBindingSize",64),ut("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),ut("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),u.requiredLimits=Ue}(L=(b(),C)[M+24>>>2>>>0])&&(L={label:gr(L+4)},u.defaultQueue=L),u.label=gr(M+4)}Oe+=1,Js(d,P.requestDevice(u).then(ae=>{--Oe,Mt(()=>{ht[v>>>0]=ae.queue,ht[g>>>0]=ae,Oe+=1,Js(h,ae.lost.then(ut=>{Mt(()=>{ae.onuncapturederror=()=>{};var Tt=fe(),pt=nr(ut.message);hf(h,JS[ut.reason],pt),pe(Tt)}),--Oe})),ae.onuncapturederror=ut=>{var Tt=5;ut.error instanceof GPUValidationError?Tt=2:ut.error instanceof GPUOutOfMemoryError?Tt=3:ut.error instanceof GPUInternalError&&(Tt=4);var pt=fe();ut=nr(ut.error.message),gk(g,Tt,ut),pe(pt)},"adapterInfo"in ae||(ae.adapterInfo=P.info),xf(d,1,g,0)})},ae=>{--Oe,Mt(()=>{var ut=fe(),Tt=nr(ae.message);xf(d,3,g,Tt),h&&hf(h,4,Tt),pe(ut)})}))}function eO(u){var d=oe(u>>>=0),h=hr[u];if(h){for(var g=0;g>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=vf(16,v.byteLength);return(b(),X).set(new Uint8Array(v),M>>>0),hr[u].push(()=>Wt(M)),M}function rO(u,d,h){h>>>=0;var g=oe(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var M=vf(16,v.byteLength);return(b(),X).fill(0,M,v.byteLength),hr[u].push(()=>{new Uint8Array(v).set((b(),X).subarray(M>>>0,M+v.byteLength>>>0)),Wt(M)}),M}function sO(u,d,h,g,v){u>>>=0,d=mt(d),h=mt(h),v>>>=0;var M=oe(u);hr[u]=[],v==4294967295&&(v=void 0),Oe+=1,Js(d,M.mapAsync(h,g>>>0,v).then(()=>{--Oe,Mt(()=>{gf(d,1,0)})},P=>{--Oe,Mt(()=>{fe();var L=nr(P.message);gf(d,P.name==="AbortError"?4:P.name==="OperationError"?3:0,L),delete hr[u]})}))}function nO(u){var d=oe(u>>>=0),h=hr[u];if(h){for(var g=0;g>>0]}function aO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=!!(b(),C)[d+32>>>2>>>0];d={label:gr(d+4),usage:(b(),C)[d+16>>>2>>>0],size:ao(d+24),mappedAtCreation:g},u=oe(u);try{var v=u.createBuffer(d)}catch{return!1}return ht[h>>>0]=v,g&&(hr[h]=[]),!0}function iO(u,d,h,g){u>>>=0,d=mt(d),g>>>=0,h=HS(h>>>0),u=oe(u),Oe+=1,Js(d,u.createComputePipelineAsync(h).then(v=>{--Oe,Mt(()=>{ht[g>>>0]=v,mf(d,1,g,0)})},v=>{--Oe,Mt(()=>{var M=fe(),P=nr(v.message);mf(d,v.reason==="validation"?3:v.reason==="internal"?4:0,g,P),pe(M)})}))}function lO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=(b(),C)[d>>>2>>>0],v=(b(),R)[g+4>>>2>>>0];d={label:gr(d+4),code:""},v===2&&(d.code=Xv(g+8)),u=oe(u).createShaderModule(d),ht[h>>>0]=u}var cO=u=>{(u=oe(u)).onuncapturederror=null,u.destroy()};function uO(u,d){d=mt(d),u=oe(u>>>0),Oe+=1,Js(d,u.popErrorScope().then(h=>{--Oe,Mt(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var v=fe(),M=h?nr(h.message):0;wf(d,1,g,M),pe(v)})},h=>{--Oe,Mt(()=>{var g=fe(),v=nr(h.message);wf(d,1,5,v),pe(g)})}))}function pO(u,d,h,g){if(d=mt(d),g>>>=0,h>>>=0){var v={featureLevel:KS[(b(),R)[h+4>>>2>>>0]],powerPreference:YS[(b(),R)[h+8>>>2>>>0]],forceFallbackAdapter:!!(b(),C)[h+12>>>2>>>0]};(u=(b(),C)[h>>>2>>>0])!==0&&(b(),v.De=!!(b(),C)[u+8>>>2>>>0])}"gpu"in navigator?(Oe+=1,Js(d,navigator.gpu.requestAdapter(v).then(M=>{--Oe,Mt(()=>{if(M)ht[g>>>0]=M,io(d,1,g,0);else{var P=fe(),L=nr("WebGPU not available on this browser (requestAdapter returned null)");io(d,3,g,L),pe(P)}})},M=>{--Oe,Mt(()=>{var P=fe(),L=nr(M.message);io(d,4,g,L),pe(P)})}))):(v=fe(),u=nr("WebGPU not available on this browser (navigator.gpu is not available)"),io(d,3,g,u),pe(v))}function fO(u,d,h){return u>>>=0,d>>>=0,h>>>=0,Fv(async()=>{var g=[];if(h){var v=(b(),R)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(L=>setTimeout(L,v,0))}else g.length=d;for(var M=0;M{if(!ff){var u,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in df)df[u]===void 0?delete d[u]:d[u]=df[u];var h=[];for(u in d)h.push(`${u}=${d[u]}`);ff=h}return ff};function Jv(u,d){if(n)return Be(19,1,u,d);u>>>=0,d>>>=0;var h,g=0,v=0;for(h of Qv()){var M=d+g;(b(),C)[u+v>>>2>>>0]=M,g+=_r(h,M,1/0)+1,v+=4}return 0}function Zv(u,d){if(n)return Be(20,1,u,d);u>>>=0,d>>>=0;var h=Qv();for(var g of((b(),C)[u>>>2>>>0]=h.length,u=0,h))u+=mr(g)+1;return(b(),C)[d>>>2>>>0]=u,0}function ek(u){return n?Be(21,1,u):52}function tk(u,d,h,g){return n?Be(22,1,u,d,h,g):52}function rk(u,d,h,g){return n?Be(23,1,u,d,h,g):70}var dO=[null,[],[]];function sk(u,d,h,g){if(n)return Be(24,1,u,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var v=0,M=0;M>>2>>>0],L=(b(),C)[d+4>>>2>>>0];d+=8;for(var G=0;G>>0],Ne=dO[Z];Ie===0||Ie===10?((Z===1?S:T)(xv(Ne)),Ne.length=0):Ne.push(Ie)}v+=L}return(b(),C)[g>>>2>>>0]=v,0}function _O(u){return u>>>0}function mO(u,d){return Kv(oe(u>>>0).limits,d>>>0),1}function hO(u,d){return oe(u>>>0).features.has(Yv[d])}function gO(u){return BigInt(oe(u>>>0).size)}function wO(u){return BigInt(oe(u>>>0).usage)}function xO(u,d){if(u>>>=0,d>>>=0){var h=gr(d+4);h={label:h,timestampWrites:d=(d=(b(),C)[d+12>>>2>>>0])!==0?{querySet:oe((b(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(b(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(b(),C)[d+12>>>2>>>0]}:void 0}}return d=oe(u),u=fk(0),h=d.beginComputePass(h),ht[u>>>0]=h,u}function yO(u,d,h,g){h=mt(h),(g=mt(g))==-1&&(g=void 0),(u=oe(u>>>0)).clearBuffer(oe(d>>>0),h,g)}function bO(u,d,h,g,v,M){h=mt(h),v=mt(v),M=mt(M),oe(u>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),v,M)}function vO(u){var d=oe(u>>>0);return u=uk(0),d=d.finish(),ht[u>>>0]=d,u}function kO(u,d,h,g,v,M){M=mt(M),oe(u>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(v>>>0),M)}function EO(u,d,h,g){oe(u>>>0).dispatchWorkgroups(d,h,g)}function AO(u,d,h){h=mt(h),oe(u>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function MO(u){oe(u>>>0).end()}function TO(u,d,h,g,v){g>>>=0,v>>>=0,u=oe(u>>>0),h=oe(h>>>0),g==0?u.setBindGroup(d,h):u.setBindGroup(d,h,(b(),C),v>>>2,g)}function SO(u,d){oe(u>>>0).setPipeline(oe(d>>>0))}function OO(u,d,h){oe(u>>>0).Ce(oe(d>>>0),h)}function IO(u,d){var h=oe(u>>>0);return u=ck(0),d=h.getBindGroupLayout(d),ht[u>>>0]=d,u}function CO(u,d){function h(v){var M=(b(),C)[v+8>>>2>>>0],P=(b(),C)[v+32>>>2>>>0],L=(b(),C)[v+36>>>2>>>0],G=0;return VS(v,{327681:Z=>{G=(b(),C)[Z+8>>>2>>>0]}}),M?((P=ao(v+24))==-1&&(P=void 0),M={buffer:oe(M),offset:ao(v+16),size:P}):M=oe(P||L||G),{binding:(b(),C)[v+4>>>2>>>0],resource:M}}u>>>=0,d={label:gr(4+(d>>>=0)),layout:oe((b(),C)[d+12>>>2>>>0]),entries:(function(v,M){for(var P=[],L=0;L>>2>>>0],(b(),C)[d+20>>>2>>>0])},u=oe(u);var g=lk(0);return WS(g,u.createBindGroup(d)),g}function PO(u,d){var h;return u>>>=0,(d>>>=0)&&(h={label:gr(d+4)}),d=oe(u),u=pk(0),h=d.createCommandEncoder(h),ht[u>>>0]=h,u}function zO(u,d){u>>>=0,d>>>=0,d={type:QS[(b(),R)[d+12>>>2>>>0]],count:(b(),C)[d+16>>>2>>>0]};var h=oe(u);return u=dk(0),d=h.createQuerySet(d),ht[u>>>0]=d,u}function LO(u,d){u=oe(u>>>0).adapterInfo,d>>>=0,(b(),C)[d+52>>>2>>>0]=u.subgroupMinSize,(b(),C)[d+56>>>2>>>0]=u.subgroupMaxSize;var h=u.vendor+u.architecture+u.device+u.description,g=mr(h)+1,v=Zs(g);return v&&_r(h,v,g),h=v,g=mr(u.vendor),Zl(d+4,h,g),h+=g,g=mr(u.architecture),Zl(d+12,h,g),h+=g,g=mr(u.device),Zl(d+20,h,g),Zl(d+28,h+g,mr(u.description)),(b(),R)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(b(),R)[d+40>>>2>>>0]=u,(b(),C)[d+44>>>2>>>0]=0,(b(),C)[d+48>>>2>>>0]=0,1}var NO={"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 $O(u,d){d>>>=0;var h=oe(u>>>0);u=Zs(4*h.features.size);var g=0,v=0;for(let M of h.features)0<=(h=NO[M])&&((b(),R)[u+g>>>2>>>0]=h,g+=4,v++);(b(),C)[d+4>>>2>>>0]=u,(b(),C)[d>>>2>>>0]=v}function RO(u,d){return Kv(oe(u>>>0).limits,d>>>0),1}function DO(u,d){oe(u>>>0).pushErrorScope(XS[d])}function FO(u,d,h){d>>>=0,h>>>=0,u=oe(u>>>0),d=Array.from((b(),R).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),u.submit(d)}function BO(u,d,h,g,v){h=mt(h),g>>>=0,v>>>=0,u=oe(u>>>0),d=oe(d>>>0),g=(b(),X).subarray(g>>>0,g+v>>>0),u.writeBuffer(d,h,g,0,v)}n||(function(){for(var u=e.numThreads-1;u--;)fv();Fe.push(async()=>{var d=(async function(){if(!n)return Promise.all(Mr.map(pv))})();Se++,await d,--Se==0&&rt&&(d=rt,rt=null,d())})})(),n||(Tr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),le()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>fe(),e.stackRestore=u=>pe(u),e.stackAlloc=u=>tc(u),e.setValue=function(u,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(b(),U)[u>>>0]=d;break;case"i16":(b(),K)[u>>>1>>>0]=d;break;case"i32":(b(),R)[u>>>2>>>0]=d;break;case"i64":(b(),z)[u>>>3>>>0]=BigInt(d);break;case"float":(b(),se)[u>>>2>>>0]=d;break;case"double":(b(),Y)[u>>>3>>>0]=d;break;case"*":(b(),C)[u>>>2>>>0]=d;break;default:ce(`invalid type for setValue: ${h}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(b(),U)[u>>>0];case"i16":return(b(),K)[u>>>1>>>0];case"i32":return(b(),R)[u>>>2>>>0];case"i64":return(b(),z)[u>>>3>>>0];case"float":return(b(),se)[u>>>2>>>0];case"double":return(b(),Y)[u>>>3>>>0];case"*":return(b(),C)[u>>>2>>>0];default:ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=Ys,e.stringToUTF8=_r,e.lengthBytesUTF8=mr;var nk,ok,_f,ec,Wt,Zs,ak,ik,lk,ck,uk,pk,fk,dk,_k,mk,hk,mf,hf,gf,wf,io,xf,gk,yf,wk,xk,yk,bf,bk,vk,vf,xe,lo,kk,pe,tc,fe,Ek,kf,Ak,Mk,Tk,Ef,Sk,Ok,Ik,Ck,Pk,zk,Lk,Nk,$k,Rk,Dk,Fk,Bk,Uk,jk,Gk,qk,Wk,Vk,Hk,Xk,Kk,Yk,Qk,Jk,Zk,eE,tE,rE,sE,nE,oE,aE,iE,lE,cE,uE,pE,wr,UO=[Hs,so,mv,yv,bv,vv,kv,Ev,Av,Mv,Tv,Sv,Ov,Iv,Cv,Pv,qv,Wv,Vv,Jv,Zv,ek,tk,rk,sk],Af={970348:(u,d,h,g,v)=>{if(e===void 0||!e.Uc)return 1;if((u=Ys(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>u.byteLength)return 3;try{let M=u.subarray(d,d+h);switch(v){case 0:(b(),X).set(M,g>>>0);break;case 1:e.ad?e.ad(g,M):e.ne(g,M);break;default:return 4}return 0}catch{return 4}},971172:(u,d,h)=>{e.Sd(u,(b(),X).subarray(d>>>0,d+h>>>0))},971236:()=>e.le(),971278:u=>{e.jd(u)},971315:()=>typeof wasmOffsetConverter<"u"};function jO(u,d,h,g){var v=fe();try{return Nk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function GO(u,d,h){var g=fe();try{return Pk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function qO(u){var d=fe();try{Sk(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function WO(u,d){var h=fe();try{return Ef(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function VO(u,d,h){var g=fe();try{Tk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function HO(u,d){var h=fe();try{$k(u,d)}catch(g){if(pe(h),g!==g+0)throw g;xe(1,0)}}function XO(u,d,h,g,v,M,P){var L=fe();try{return Ck(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function KO(u,d,h,g,v,M){var P=fe();try{Ok(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function YO(u,d,h,g){var v=fe();try{Lk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function QO(u,d,h,g,v,M,P){var L=fe();try{Dk(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function JO(u,d,h,g,v,M,P){var L=fe();try{Fk(u,d,h,g,v,M,P)}catch(G){if(pe(L),G!==G+0)throw G;xe(1,0)}}function ZO(u,d,h,g,v,M,P,L){var G=fe();try{Xk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function eI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne){var Ue=fe();try{Bk(u,d,h,g,v,M,P,L,G,Z,Ie,Ne)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function tI(u,d,h,g,v){var M=fe();try{return Rk(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function rI(u,d,h,g,v){var M=fe();try{Ik(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function sI(u,d,h,g,v,M,P,L){var G=fe();try{zk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function nI(u){var d=fe();try{return Kk(u)}catch(h){if(pe(d),h!==h+0)throw h;xe(1,0)}}function oI(u,d,h){var g=fe();try{return Yk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function aI(u,d){var h=fe();try{return iE(u,d)}catch(g){if(pe(h),g!==g+0)throw g;return xe(1,0),0n}}function iI(u){var d=fe();try{return Uk(u)}catch(h){if(pe(d),h!==h+0)throw h;return xe(1,0),0n}}function lI(u,d,h,g){var v=fe();try{return Qk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function cI(u,d,h,g,v){var M=fe();try{return Jk(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;xe(1,0)}}function uI(u,d,h,g,v,M){var P=fe();try{return Zk(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function pI(u,d,h,g,v,M){var P=fe();try{return Vk(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function fI(u,d,h,g,v,M){var P=fe();try{return eE(u,d,h,g,v,M)}catch(L){if(pe(P),L!==L+0)throw L;xe(1,0)}}function dI(u,d,h,g,v,M,P,L){var G=fe();try{return Hk(u,d,h,g,v,M,P,L)}catch(Z){if(pe(G),Z!==Z+0)throw Z;xe(1,0)}}function _I(u,d,h,g,v){var M=fe();try{return tE(u,d,h,g,v)}catch(P){if(pe(M),P!==P+0)throw P;return xe(1,0),0n}}function mI(u,d,h,g){var v=fe();try{return rE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function hI(u,d,h,g){var v=fe();try{return sE(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function gI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne){var Ue=fe();try{return nE(u,d,h,g,v,M,P,L,G,Z,Ie,Ne)}catch(ae){if(pe(Ue),ae!==ae+0)throw ae;xe(1,0)}}function wI(u,d,h,g,v,M,P,L,G,Z,Ie){var Ne=fe();try{oE(u,d,h,g,v,M,P,L,G,Z,Ie)}catch(Ue){if(pe(Ne),Ue!==Ue+0)throw Ue;xe(1,0)}}function xI(u,d,h,g,v,M,P,L,G,Z,Ie,Ne,Ue,ae,ut,Tt){var pt=fe();try{aE(u,d,h,g,v,M,P,L,G,Z,Ie,Ne,Ue,ae,ut,Tt)}catch(ps){if(pe(pt),ps!==ps+0)throw ps;xe(1,0)}}function yI(u,d,h){var g=fe();try{return Gk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;return xe(1,0),0n}}function bI(u,d,h){var g=fe();try{return jk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function vI(u,d,h){var g=fe();try{return qk(u,d,h)}catch(v){if(pe(g),v!==v+0)throw v;xe(1,0)}}function kI(u,d,h,g){var v=fe();try{Wk(u,d,h,g)}catch(M){if(pe(v),M!==M+0)throw M;xe(1,0)}}function rc(){if(0{let d=new WeakMap,h,g,v=1;e.webgpuRegisterDevice=L=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(L){var G=d.get(L);if(!G){let Z=((Ie,Ne=0)=>{var Ue=hk(Ne);return Ne=mk(Ne,Ue),ht[Ue>>>0]=Ie.queue,ht[Ne>>>0]=Ie,Ne})(L,G=ik(0));G=[v++,G,Z],d.set(L,G)}return h=L,g=G[0],G}h=void 0,g=0};let M=new Map;e.webgpuOnCreateSession=L=>{if(g!==void 0){var G=g;if(g=void 0,L){let Z=_f(G);M.set(L,Z),G===0&&u(h??oe(Z))}h=void 0}},e.webgpuOnReleaseSession=L=>{M.delete(L)};let P=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(L,G,Z)=>{if(Z)return L[P]=[Z,NaN],Z;if(Z=L[P])return Z[1]++,Z[0];if((G=M.get(G))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return G=((Ie,Ne=0)=>(Ie.mapState==="unmapped"||ce(),Ne=_k(Ne),ht[Ne>>>0]=Ie,Ne))(L,G),L[P]=[G,1],G},e.webgpuUnregisterBuffer=L=>{let G=L[P];if(!G)throw Error("Buffer is not registered");G[1]--,G[1]===0&&(ak(G[0]),delete L[P])},e.webgpuGetBuffer=L=>oe(L),e.webgpuCreateDownloader=(L,G,Z)=>{if((Z=M.get(Z))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Ie=oe(Z),Ne=16*Math.ceil(Number(G)/16);return async()=>{let Ue=Ie.createBuffer({size:Ne,usage:9});try{let ae=Ie.createCommandEncoder();return ae.copyBufferToBuffer(L,0,Ue,0,Ne),Ie.queue.submit([ae.finish()]),await Ue.mapAsync(GPUMapMode.READ),Ue.getMappedRange().slice(0,G)}finally{Ue.destroy()}}},e.ad=(L,G)=>{var Z=G.buffer;let Ie=G.byteOffset,Ne=G.byteLength;if(G=16*Math.ceil(Number(Ne)/16),L=oe(L),!h){var Ue=_f(g);h=oe(Ue)}let ae=(Ue=h.createBuffer({mappedAtCreation:!0,size:G,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(Z,Ie,Ne)),Ue.unmap(),(Z=h.createCommandEncoder()).copyBufferToBuffer(Ue,0,L,0,G),h.queue.submit([Z.finish()]),Ue.destroy()}},e.webnnInit=u=>{let d=u[0];[e.le,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.ke,e.webnnEnableTraceEvent]=u.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.ke,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,v,M)=>d.registerMLTensor(h,g,v,M),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,v,M,P,L)=>d.registerMLConstant(h,g,v,M,P,e.Uc,L),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},Q?e:new Promise((u,d)=>{w=u,x=d})}var c2,hA,xL=be(()=>{"use strict";c2=mA,hA=globalThis.self?.name?.startsWith("em-pthread"),hA&&mA()}),Hf,cd,gA,Pt,u2,xc,wA,xA,Xf,yA,Kf,p2,Yf,f2,wd=be(()=>{"use strict";gd(),Hf=typeof location>"u"?void 0:location.origin,cd=import.meta.url>"file:"&&import.meta.url<"file;",gA=()=>{if(cd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Hf).href}return import.meta.url},Pt=gA(),u2=()=>{if(Pt&&!Pt.startsWith("blob:"))return Pt.substring(0,Pt.lastIndexOf("/")+1)},xc=(t,e)=>{try{let r=e??Pt;return(r?new URL(t,r):new URL(t)).origin===Hf}catch{return!1}},wA=(t,e)=>{let r=e??Pt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},xA=(t,e)=>`${e??"./"}${t}`,Xf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},yA=async t=>(await import(t)).default,Kf=(wL(),Ac(a2)).default,p2=async()=>{if(!Pt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(xc(Pt))return[void 0,Kf()];let t=await Xf(Pt);return[t,Kf(t)]},Yf=(xL(),Ac(l2)).default,f2=async(t,e,r,s)=>{let n=Yf&&!(t||e);if(n)if(Pt)n=xc(Pt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Yf];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??wA(o,e),i=r&&a&&!xc(a,e),l=i?await Xf(a):a??xA(o,e);return[i?l:void 0,await yA(l)]}}}),Qf,yc,vo,Jf,bA,vA,kA,xd,De,Ms=be(()=>{"use strict";wd(),yc=!1,vo=!1,Jf=!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}},xd=async t=>{if(yc)return Promise.resolve();if(vo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Jf)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,p=t.wasmBinary,[f,_]=await f2(i,o,r>1,!!p||!!c),m=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{m=!0,x()},e)})),w.push(new Promise((x,k)=>{let A={numThreads:r};if(p)A.wasmBinary=p,A.locateFile=E=>E;else if(c||o)A.locateFile=E=>c??o+E;else if(i&&i.indexOf("blob:")!==0)A.locateFile=E=>new URL(E,i).href;else if(f){let E=u2();E&&(A.locateFile=S=>E+S)}_(A).then(E=>{vo=!1,yc=!0,Qf=E,x(),f&&URL.revokeObjectURL(f)},E=>{vo=!1,Jf=!0,k(E)})})),await Promise.race(w),m)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(yc&&Qf)return Qf;throw new Error("WebAssembly is not initialized yet.")}}),zt,Tc,ze,yd=be(()=>{"use strict";Ms(),zt=(t,e)=>{let r=De(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Tc=(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")Tc(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}`)})},ze=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,yL=be(()=>{"use strict";Ms(),yd(),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=zt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&ze("Can't create run options."),t?.extra!==void 0&&Tc(t.extra,"",new WeakSet,(a,i)=>{let l=zt(a,s),c=zt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&ze(`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,MA,bc,$r,TA,_2,bL=be(()=>{"use strict";Ms(),yd(),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}`)}},MA=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)},bc=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&ze(`Can't set a session config entry: ${e} - ${r}.`)},$r=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);t.push([n,o])},TA=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&&bc(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let m=n;if(m.device)if(typeof GPUDevice<"u"&&m.device instanceof GPUDevice)f=m.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&$r(a,"enableGraphCapture","1",r),typeof m.preferredLayout=="string"&&$r(a,"preferredLayout",m.preferredLayout,r),m.forceCpuNodeNames){let x=Array.isArray(m.forceCpuNodeNames)?m.forceCpuNodeNames:[m.forceCpuNodeNames];$r(a,"forceCpuNodeNames",x.join(` `),r)}m.validationMode&&$r(a,"validationMode",m.validationMode,r)}let _=De().webgpuRegisterDevice(f);if(_){let[m,w,x]=_;$r(a,"deviceId",m.toString(),r),$r(a,"webgpuInstance",w.toString(),r),$r(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=zt(o,r),l=a.length,c=0,p=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),p=De()._malloc(l*De().PTR_SIZE),r.push(p);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};MA(n);try{let o=EA(n.graphOptimizationLevel??"all"),a=AA(n.executionMode??"sequential"),i=typeof n.logId=="string"?zt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?zt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&ze("Can't create session options."),n.executionProviders&&await TA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);bc(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,_]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let m=zt(f,s);e._OrtAddFreeDimensionOverride(r,m,_)!==0&&ze(`Can't set a free dimension override: ${f} - ${_}.`)}return n.extra!==void 0&&Tc(n.extra,"",new WeakSet,(f,_)=>{bc(r,f,_,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&ze("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),bs,Ec,un,To,Sc,bd,vd,ud,pn=be(()=>{"use strict";bs=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}`)}},Ec=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},un=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},To=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}`)}},Sc=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}`)}},bd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",vd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",ud=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}`)}}}),kd,m2=be(()=>{"use strict";gd(),kd=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,vL=be(()=>{"use strict";pn(),h2=(t,e)=>new(To(e))(t)}),SA,OA,IA,CA,g2,PA,yt,w2=be(()=>{"use strict";pn(),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=Sc(t),s=Sc(IA);r>=s&&OA(r,typeof e=="function"?e():e)},yt=(...t)=>{CA&&PA(...t)}}),Zf,pd,ed,zA,td,LA,rd,sd,nd,NA,x2,kL=be(()=>{"use strict";pn(),w2(),Zf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),pd=(t,e)=>{if(e==="int32")return t;let r=Zf.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(To(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'`)}},ed=(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}`)}},zA=1,td=()=>zA++,LA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),rd=(t,e)=>{let r=Zf.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},sd=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 rd(this.dataType,this.tensorShape)}destroy(){yt("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=ed(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}},nd=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=LA.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);yt("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!==rd(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=pd(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 yt("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?ed(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=td();return this.tensorTrackersById.set(t,new nd(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){yt("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){yt("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=td(),a=new sd({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new nd(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){yt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}yt("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 sd({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,$A,b2,EL=be(()=>{"use strict";pn(),Ms(),vL(),kL(),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"]]),$A=(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){yt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){yt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)yt("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=>$A(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){yt("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){yt("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");yt("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 yt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let f=pd(new Uint8Array(c),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return yt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=ko.get(bs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),RA,Ed,Ad,Rr,DA,od,Oc,Md,Td,ad,Sd,Od,Id,v2=be(()=>{"use strict";As(),yL(),bL(),pn(),Ms(),yd(),m2(),RA=(t,e)=>{De()._OrtInit(t,e)!==0&&ze("Can't initialize onnxruntime.")},Ed=async t=>{RA(t.wasm.numThreads,Sc(t.logLevel))},Ad=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(EL(),Ac(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])}},Rr=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&&ze("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)}},od=(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&&ze("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],p=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},Md=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]=Oc(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await _2(e),e?.externalData&&n.mountExternalData){let T=[];for(let I of e.externalData){let O=typeof I=="string"?I:I.path;T.push(kd(typeof I=="string"?I:I.data).then(b=>{n.mountExternalData(O,b)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let I=T,O=I?.context,b=I?.gpuDevice,F=I?.deviceType,j=I?.powerPreference;O?n.currentContext=O:b?n.currentContext=await n.webnnCreateMLContext(b):n.currentContext=await n.webnnCreateMLContext({deviceType:F,powerPreference:j})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&ze("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,_]=DA(o),m=!!e?.enableGraphCapture,w=[],x=[],k=[],A=[],E=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&ze("Can't create IO binding."),S={handle:i,outputPreferredLocations:E,outputPreferredLocationsEncoded:E.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>ud(T))}),Rr.set(o,[o,c,p,S,m,!1]),[o,w,x,k,A]}catch(f){throw c.forEach(_=>n._OrtFree(_)),p.forEach(_=>n._OrtFree(_)),i!==0&&n._OrtReleaseBinding(i)!==0&&ze("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&ze("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&ze("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},Td=t=>{let e=De(),r=Rr.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&&ze("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&ze("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&&ze("Can't release session."),Rr.delete(t)},ad=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],p=t[1],f=t[3],_=f,m,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=un(bs(c),p);{let E=i.webgpuRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=E(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=un(bs(c),p);let E=i.webnnRegisterMLTensor;if(!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=E(s,A,bs(c),p)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,m=i._malloc(w),r.push(m);for(let E=0;Ei.setValue(k+S*l,E,l===4?"i32":"i64"));let A=i._OrtCreateTensor(bs(c),m,w,k,p.length,ud(_));A===0&&ze(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},Sd=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=Rr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],f=l[2],_=l[3],m=l[4],w=l[5],x=e.length,k=s.length,A=0,E=[],S=[],T=[],I=[],O=[],b=a.stackSave(),F=a.stackAlloc(x*i),j=a.stackAlloc(x*i),U=a.stackAlloc(k*i),X=a.stackAlloc(k*i);try{[A,E]=d2(o),Fr("wasm prepareInputOutputTensor");for(let C=0;CFe*Se,1);B=Ec(Ge);let At=_?.outputPreferredLocations[s[C]];if(B==="string"){if(At==="gpu-buffer"||At==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Fe=[];for(let Se=0;Se0){let Fe=a.webgpuGetBuffer;if(!Fe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Se=Fe(Q),rt=un(Ge,ct);if(rt===void 0||!bd(B))throw new Error(`Unsupported data type: ${B}`);$=!0;{a.webgpuRegisterBuffer(Se,t,Q);let tr=a.webgpuCreateDownloader(Se,rt,t);J.push([B,qe,{gpuBuffer:Se,download:async()=>{let Oe=await tr();return new(To(B))(Oe)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&ze("Can't release tensor.")}},"gpu-buffer"])}}else if(At==="ml-tensor"&&ct>0){let Fe=a.webnnEnsureTensor,Se=a.webnnIsGraphInputOutputTypeSupported;if(!Fe||!Se)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(un(Ge,ct)===void 0||!vd(B))throw new Error(`Unsupported data type: ${B}`);if(!Se(t,B,!1))throw new Error(`preferredLocation "ml-tensor" for ${B} output is not supported by current WebNN Context.`);let rt=await Fe(t,Q,Ge,qe,!1);$=!0,J.push([B,qe,{mlTensor:rt,download:a.webnnCreateMLTensorDownloader(Q,B),dispose:()=>{a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(At==="ml-tensor-cpu-output"&&ct>0){let Fe=a.webnnCreateMLTensorDownloader(Q,B)(),Se=J.length;$=!0,R.push((async()=>{let rt=[Se,await Fe];return a.webnnReleaseTensorId(Q),a._OrtReleaseTensor(se),rt})()),J.push([B,qe,[],"cpu"])}else{let Fe=To(B),Se=new Fe(ct);new Uint8Array(Se.buffer,Se.byteOffset,Se.byteLength).set(a.HEAPU8.subarray(Q,Q+Se.byteLength)),J.push([B,qe,Se,"cpu"])}}finally{a.stackRestore(Y),B==="string"&&Q&&a._free(Q),$||a._OrtReleaseTensor(se)}}_&&!m&&(a._OrtClearBoundOutputs(_.handle)!==0&&ze("Can't clear bound outputs."),Rr.set(t,[c,p,f,_,m,!1]));for(let[C,se]of await Promise.all(R))J[C][2]=se;return Br("wasm ProcessOutputTensor"),J}finally{a.webnnOnRunEnd?.(c),a.stackRestore(b),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),n.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),S.forEach(K=>a._OrtReleaseTensor(K)),T.forEach(K=>a._OrtReleaseTensor(K)),I.forEach(K=>a._free(K)),A!==0&&a._OrtReleaseRunOptions(A),E.forEach(K=>a._free(K))}},Od=t=>{let e=De(),r=Rr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&ze("Can't get an profile file name."),e._OrtFree(n)},Id=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Dr,Bt,cn,Eo,Ao,vc,id,kc,ws,xs,FA,k2,E2,A2,M2,T2,S2,O2,I2=be(()=>{"use strict";As(),v2(),Ms(),wd(),Dr=()=>!!Ye.wasm.proxy&&typeof document<"u",cn=!1,Eo=!1,Ao=!1,kc=new Map,ws=(t,e)=>{let r=kc.get(t);r?r.push(e):kc.set(t,[e])},xs=()=>{if(cn||!Eo||Ao||!Bt)throw new Error("worker not ready")},FA=t=>{switch(t.data.type){case"init-wasm":cn=!1,t.data.err?(Ao=!0,id[1](t.data.err)):(Eo=!0,id[0]()),vc&&(URL.revokeObjectURL(vc),vc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=kc.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(cn)throw new Error("multiple calls to 'initWasm()' detected.");if(Ao)throw new Error("previous call to 'initWasm()' failed.");if(cn=!0,Dr())return new Promise((t,e)=>{Bt?.terminate(),p2().then(([r,s])=>{try{Bt=s,Bt.onerror=o=>e(o),Bt.onmessage=FA,id=[t,e];let n={type:"init-wasm",in:Ye};!n.in.wasm.wasmPaths&&(r||cd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Bt.postMessage(n),vc=r}catch(n){e(n)}},e)});try{await xd(Ye.wasm),await Ed(Ye),Eo=!0}catch(t){throw Ao=!0,t}finally{cn=!1}}},E2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ye}};Bt.postMessage(s)});await Ad(Ye,t)},A2=async t=>Dr()?(xs(),new Promise((e,r)=>{ws("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Bt.postMessage(s,[t.buffer])})):Oc(t),M2=async(t,e)=>{if(Dr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xs(),new Promise((r,s)=>{ws("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Bt.postMessage(n,o)})}else return Md(t,e)},T2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("release",[e,r]);let s={type:"release",in:t};Bt.postMessage(s)});Td(t)},S2=async(t,e,r,s,n,o)=>{if(Dr()){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 xs(),new Promise((a,i)=>{ws("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Bt.postMessage(c,Id(l))})}else return Sd(t,e,r,s,n,o)},O2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Bt.postMessage(s)});Od(t)}}),ld,BA,C2,AL=be(()=>{"use strict";As(),I2(),pn(),gd(),m2(),ld=(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()}`)}},BA=t=>{switch(t[3]){case"cpu":return new Qt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!bd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Qt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!vd(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Qt.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 kd(t))}async loadModel(t,e){ks();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await M2(r,e),Es()}async dispose(){return T2(this.sessionId)}async run(t,e,r){ks();let s=[],n=[];Object.entries(t).forEach(f=>{let _=f[0],m=f[1],w=this.inputNames.indexOf(_);if(w===-1)throw new Error(`invalid input '${_}'`);s.push(m),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let _=f[0],m=f[1],w=this.outputNames.indexOf(_);if(w===-1)throw new Error(`invalid output '${_}'`);o.push(m),a.push(w)});let i=s.map((f,_)=>ld(f,()=>`input "${this.inputNames[n[_]]}"`)),l=o.map((f,_)=>f?ld(f,()=>`output "${this.outputNames[a[_]]}"`):null),c=await S2(this.sessionId,n,i,a,l,r),p={};for(let f=0;fdd,initializeFlags:()=>fd,wasmBackend:()=>z2});var fd,dd,z2,ML=be(()=>{"use strict";As(),I2(),AL(),fd=()=>{(typeof Ye.wasm.initTimeout!="number"||Ye.wasm.initTimeout<0)&&(Ye.wasm.initTimeout=0);let t=Ye.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.`),Ye.wasm.simd=!1),typeof Ye.wasm.proxy!="boolean"&&(Ye.wasm.proxy=!1),typeof Ye.wasm.trace!="boolean"&&(Ye.wasm.trace=!1),typeof Ye.wasm.numThreads!="number"||!Number.isInteger(Ye.wasm.numThreads)||Ye.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ye.wasm.numThreads=1;else{let e=typeof navigator>"u"?sL("node:os").cpus().length:navigator.hardwareConcurrency;Ye.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},dd=class{async init(t){fd(),await k2(),await E2(t)}async createInferenceSessionHandler(t,e){let r=new C2;return await r.loadModel(t,e),r}},z2=new dd});As();As();As();var TL="1.26.0-dev.20260416-b7804b056c",SL=o2;{let t=(ML(),Ac(P2)).wasmBackend;vs("webgpu",t,5),vs("webnn",t,5),vs("cpu",t,10),vs("wasm",t,10)}Object.defineProperty(Ye.versions,"web",{value:TL,enumerable:!0});async function L2(t){let e=t.split("/").pop(),r;try{if(r=await Yt(),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 me.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 L2(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 $2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await L2(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}}import{Tensor as j2}from"onnxruntime-common";var IL=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 B2(t){return t<=St.DEBUG?0:t<=St.INFO?2:t<=St.WARNING||t<=St.ERROR?3:4}var CL={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Ut=[],Pd,dn,R2=Symbol.for("onnxruntime");if(R2 in globalThis)dn=globalThis[R2];else if(ie.IS_NODE_ENV){switch(dn=OL,process.platform){case"win32":Ut.push("dml");break;case"linux":process.arch==="x64"&&Ut.push("cuda");break;case"darwin":Ut.push("coreml");break}Ut.push("webgpu"),Ut.push("cpu"),Pd=["cpu"]}else dn=Cd,ie.IS_WEBNN_AVAILABLE&&Ut.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&Ut.push("webgpu"),Ut.push("wasm"),Pd=["wasm"];var PL=dn.InferenceSession;function U2(t=null){if(!t)return Pd;switch(t){case"auto":return Ut;case"gpu":return Ut.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Ut.includes(t))return[IL[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Ut.join(", ")}.`)}var D2=Promise.resolve(),fn=null;async function zL(){if(fn)return fn;if(!(me.useWasmCache&&typeof it?.wasm?.wasmPaths=="object"&&it?.wasm?.wasmPaths?.wasm&&it?.wasm?.wasmPaths?.mjs)){if(ie.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return fn=Promise.resolve(),fn}return fn=(async()=>{let e=it.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!$f(e.wasm)?(async()=>{try{let s=await N2(Rf(e.wasm));s&&(it.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!$f(e.mjs)?(async()=>{try{let s=await $2(Rf(e.mjs));s&&(it.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(it.wasm.wasmPaths.mjs=e.mjs)})(),fn}async function Ic(t,e,r){await zL();let s=B2(me.logLevel??St.WARNING),n=()=>PL.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?D2=D2.then(n):n());return o.config=r,o}var F2=Promise.resolve();async function Cc(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?F2=F2.then(r):r()}function Pc(t){return t instanceof dn.Tensor}var it=dn?.env;function Oo(){return it?.wasm?.proxy}if(it){let t=function(e){let r=B2(e);it.logLevel=CL[r]};if(it.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&it.versions?.web&&!it.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${it.versions.web}/dist/`;it.wasm.wasmPaths=ie.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}it.wasm.proxy=!1}it.webgpu&&(it.webgpu.powerPreference="high-performance"),t(me.logLevel??St.WARNING),me.backends.onnx={...it,setLogLevel:t}}var Ur=async(t,e,r)=>{let s=await Ic(new Uint8Array(t),e);return(async n=>{let o=Oo(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Cc(s,a);return Array.isArray(r)?r.map(l=>new N(i[l])):new N(i[r])})},lr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Ur([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=Ur([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=Ur([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=Ur([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=Ur([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=Ur([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=Ur([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=Ur([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 G2=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 zc(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 V2=(function(){let t;return async function(){if(t===void 0)if(!ie.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),st=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),q2=st.fp32,W2=Object.freeze({[G2.wasm]:st.q8}),jr=Object.freeze({[st.fp32]:"",[st.fp16]:"_fp16",[st.int8]:"_int8",[st.uint8]:"_uint8",[st.q8]:"_quantized",[st.q4]:"_q4",[st.q2]:"_q2",[st.q1]:"_q1",[st.q4f16]:"_q4f16",[st.q2f16]:"_q2f16",[st.q1f16]:"_q1f16",[st.bnb4]:"_bnb4"});function Lc(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===st.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==st.auto&&st.hasOwnProperty(l))return l}i=W2[r]??q2}else o&&st.hasOwnProperty(o)?i=o:i=W2[r]??q2;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var Gr=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 Pc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new j2(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;sm)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(_,0),Math.min(m,this.dims[p])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([p,f])=>f-p),o=n.reduce((p,f)=>p*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let p=1;p=0;--_){let w=n[_];f+=(m%w+s[_][0])*l[_],m=Math.floor(m/w)}i[p]=a[f]}return new t(this.type,i,r)}permute(...e){return NL(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,_)=>f+_,i=0n):(a=(f,_)=>f+_**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,p]=Io(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let _=c%f;i+=_*p,p*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Ld(this.dims)}squeeze(e=null){return new t(this.type,this.data,H2(this.dims,e))}squeeze_(e=null){return this.dims=H2(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,X2(this.dims,e))}unsqueeze_(e){return this.dims=X2(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]=Io((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.lengthp===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,f=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((p,f)=>p*e[f]),o=n.reduce((p,f)=>p*f,1),a=this.data,i=new a.constructor(o),l=Ld(s),c=Ld(n);for(let p=0;pBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,dA(this.data),this.dims);return new t(e,Gr[e].from(this.data,r),this.dims)}};function LL(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 $c(t,e,r,s,n){return await(await lr.slice)({x:t,s:Nc(e),e:Nc(r),a:Nc(s),t:Nc(n??new Array(s.length).fill(1))})}function Y2(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;pr!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function X2(t,e){return e=cr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function cr(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=cr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--_){let x=c[_],k=m%x;_===e&&(k+=a),f+=k*w,w*=r[_],m=Math.floor(m/x)}n[f]=l[p]}a+=c[e]}}return new N(o,n,r)}function xt(t,e=0){return ve(t.map(r=>r.unsqueeze(e)),e)}function Io(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=cr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=_%w;p+=x*m,m*=i[f]}_=Math.floor(_/w)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function $d(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let m=n.reduce((A,E)=>A+E,0)/n.length,w=Math.sqrt(n.reduce((A,E)=>A+(E-m)**2,0)/(n.length-r)),x=new N(t.type,[m],[]);return[new N(t.type,[w],[]),x]}e=cr(e,o.length);let a=Rc(t,e,s),i=a.data,[l,c,p]=Io((_,m,w,x)=>_+(m-i[x])**2,t,e,s);for(let _=0;_c+p,0);return new N(t.type,[l/n.length],[])}e=cr(e,s.length);let[o,a,i]=Io((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 Rd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new N(r,new s(n).fill(e),t)}function Qe(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 Rd(t,e,r,s)}function Co(t,e){return Qe(t.dims,e)}function et(t){return Rd(t,1n,"int64",BigInt64Array)}function Dc(t){return et(t.dims)}function Dd(t){return Rd(t,0n,"int64",BigInt64Array)}function Fd(t){return Dd(t.dims)}function L4(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>hs.random()),t)}function Q2(t){let e=t.reduce((r,s)=>r*s,1);return new N("float32",Float32Array.from({length:e},()=>hs.gauss()),t)}function J2(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new N(s,a,[t.dims[0],t.dims[1]/8])}async function _n(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ot(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Bd(t,e){let r=await _n(t);return await Promise.all(r.map(s=>nt(t,s,!0,e)))}function Po(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 $L=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function RL(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"?gt(t[n],i):gt(i,t[n])}}function DL(t,e){for(let r of Object.keys(t))t[r].length=e}function Ts(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 FL(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 $E(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ts(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ts(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ts(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ts(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ts(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ts(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=FL(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 Bd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,p=Array.isArray(e),f;if(p){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((m,w)=>this._encode_plus(m,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(m=>this._encode_plus(m,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(Pe(f.map(m=>m.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let m=0;ml?i&&DL(f[m],l):o&&RL(f[m],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let _={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))_[w]=new N("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),m)}else{for(let m of Object.keys(f[0]))_[m]=f.map(w=>w[m]);if(!p)for(let m of Object.keys(_))_[m]=_[m][0]}return _}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof N&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof N&&(e=Po(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,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:p=null,return_tensor:f=!0,return_dict:_=!0,tokenizer_kwargs:m={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new XE(o),this._compiled_template_cache.set(o,x));let k=Object.create(null);for(let E of $L){let S=Ts(this.config,E);S&&(k[E]=S)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...k,...w});if(i){let E=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:p,return_tensor:f,...m});return _?E:E.input_ids}return A}};function mn(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 P_={};en(P_,{AlbertTokenizer:()=>Ud,AutoTokenizer:()=>ne,BartTokenizer:()=>jd,BertTokenizer:()=>Gd,BlenderbotSmallTokenizer:()=>qd,BlenderbotTokenizer:()=>Wd,BloomTokenizer:()=>Vd,CLIPTokenizer:()=>Xd,CamembertTokenizer:()=>Hd,CodeGenTokenizer:()=>Yd,CodeLlamaTokenizer:()=>Kd,CohereAsrTokenizer:()=>Jd,CohereTokenizer:()=>Qd,ConvBertTokenizer:()=>Zd,DebertaTokenizer:()=>t_,DebertaV2Tokenizer:()=>e_,DistilBertTokenizer:()=>r_,ElectraTokenizer:()=>s_,EsmTokenizer:()=>n_,FalconTokenizer:()=>o_,GPT2Tokenizer:()=>l_,GPTNeoXTokenizer:()=>i_,GemmaTokenizer:()=>a_,HerbertTokenizer:()=>c_,LlamaTokenizer:()=>u_,M2M100Tokenizer:()=>p_,MBart50Tokenizer:()=>d_,MBartTokenizer:()=>zo,MPNetTokenizer:()=>h_,MarianTokenizer:()=>f_,MgpstrTokenizer:()=>__,MobileBertTokenizer:()=>m_,NllbTokenizer:()=>g_,NougatTokenizer:()=>w_,PreTrainedTokenizer:()=>W,Qwen2Tokenizer:()=>x_,RoFormerTokenizer:()=>b_,RobertaTokenizer:()=>y_,SiglipTokenizer:()=>v_,SpeechT5Tokenizer:()=>k_,SqueezeBertTokenizer:()=>E_,T5Tokenizer:()=>A_,TokenizersBackend:()=>W,VitsTokenizer:()=>T_,Wav2Vec2CTCTokenizer:()=>S_,WhisperTokenizer:()=>O_,XLMRobertaTokenizer:()=>I_,XLMTokenizer:()=>C_});var Ud=class extends W{return_token_type_ids=!0};var jd=class extends W{};var Gd=class extends W{return_token_type_ids=!0};var qd=class extends W{};var Wd=class extends W{};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{return_token_type_ids=!0};var e_=class extends W{return_token_type_ids=!0};var t_=class extends W{return_token_type_ids=!0};var r_=class extends W{};var s_=class extends W{return_token_type_ids=!0};var n_=class extends W{};var o_=class extends W{};var a_=class extends W{};var i_=class extends W{};var l_=class extends W{};var c_=class extends W{return_token_type_ids=!0};var u_=class extends W{padding_side="left"};var p_=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 mn(this,e,r,s)}};var f_=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)}`),gt([n],super._encode_text(o))}}};var zo=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 mn(this,e,r,s)}};var d_=class extends zo{};var __=class extends W{};var m_=class extends W{return_token_type_ids=!0};var h_=class extends W{};var g_=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 mn(this,e,r,s)}};var w_=class extends W{};var x_=class extends W{};var y_=class extends W{};var b_=class extends W{return_token_type_ids=!0};var v_=class extends W{};var k_=class extends W{};var E_=class extends W{return_token_type_ids=!0};var A_=class extends W{};var M_=class extends Dt{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 eM(t){t=t.toLowerCase();let e=BL.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Lo.has(t))e=t;else{let n=t.length===2?Lo.keys():Lo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var UL="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",tM=new RegExp(`^[${UL}]+$`,"gu"),jL=.1,O_=class extends W{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],p=l(),f=0,_=this.timestamp_begin,w=_+1500,x=[],k=[],A=!1,E=null,S=new Set(this.all_special_ids);for(let O of e){let b=O.tokens,F=i?O.token_timestamps:null,j=null,U=_;if("stride"in O){let[J,R,C]=O.stride;if(f-=R,E=J-C,R&&(U=R/n+_),C)for(let se=b.length-1;se>=0;--se){let Y=Number(b[se]);if(Y>=_){if(j!==null&&(Y-_)*n=_&&R<=w){let C=(R-_)*n+f,se=gs(C,2);if(j!==null&&R>=j)A=!0;else if(A||x.length>0&&R0&&p.timestamp[1]!==null))for(let B of p.words)B.timestamp[1]>p.timestamp[1]&&p.timestamp[1]>=B.timestamp[0]&&(B.timestamp[1]=p.timestamp[1]);c.push(p),x=[],X=[],k=[],K=[],p=l()}}else if(X.push(R),i){let C=gs(F[J]+f,2),se;if(J+10?(x.push(X),i&&k.push(K)):x.every(J=>J.length===0)&&(p=l(),x=[],X=[],k=[],K=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[O,b]=this.findLongestCommonSequence(x,k),F=this.decode(O);p.text=F,i&&(p.words=this.collateWordTimestamps(O,b,a)),c.push(p)}let T=Object.create(null),I=c.map(O=>O.text).join("");if(r||s){for(let O=0;O0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cR===U[C]&&l[I+C][0]-jL<=r[c][F+C][0]).length:X=b.filter((R,C)=>R===U[C]).length;let K=T/1e4,J=X/T+K;X>1&&J>f&&(f=J,_=[I,O,F,j])}let[w,x,k,A]=_,E=Math.floor((x+w)/2),S=Math.floor((A+k)/2);if(a&&f===0&&n>0){let T=l[n-1][0],I=r[c].findIndex(O=>O[0]>=T);S=I===-1?p.length:I}o.push(...s.slice(0,E)),s=p.slice(S),n=s.length,a&&(i.push(...l.slice(0,E)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),m=c.startsWith(" "),w=c.trim(),x=tM.test(w);if(_||m||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let k=o.length-1;o[k]+=c,a[k].push(...p),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=gt(i[c],i[p]),l[p]=gt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;pf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var I_=class extends W{};var C_=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 Bd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=P_[c];return p||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=W),new p(i,l)}};var qr="https://github.com/huggingface/transformers.js/issues/new/choose";var No="preprocessor_config.json",yr=No,Fc="processor_config.json",Bc="chat_template.jinja";var re=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?nt(e,Fc,!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,Bc,!0,r):null]);return new this(s,n,o)}};var pu={};en(pu,{ChatterboxProcessor:()=>X_,CohereAsrProcessor:()=>K_,Florence2Processor:()=>jm,Gemma3Processor:()=>Gm,Gemma3nProcessor:()=>qm,Gemma4Processor:()=>Wm,Glm46VProcessor:()=>Vm,GraniteSpeechProcessor:()=>Hm,GroundingDinoProcessor:()=>Xm,Idefics3Processor:()=>iu,JinaCLIPProcessor:()=>Ym,Lfm2VlProcessor:()=>Qm,LlavaProcessor:()=>Jm,MgpstrProcessor:()=>Zm,MoonshineProcessor:()=>eh,OwlViTProcessor:()=>th,PaliGemmaProcessor:()=>rh,Phi3VProcessor:()=>sh,PixtralProcessor:()=>nh,Processor:()=>re,PyAnnoteProcessor:()=>oh,Qwen2VLProcessor:()=>Os,Qwen2_5_VLProcessor:()=>Ho,Qwen3VLProcessor:()=>ah,Sam2Processor:()=>lu,Sam2VideoProcessor:()=>ih,SamProcessor:()=>Xo,SmolVLMProcessor:()=>iu,SpeechT5Processor:()=>lh,UltravoxProcessor:()=>ch,VLChatProcessor:()=>Km,VoxtralProcessor:()=>uh,VoxtralRealtimeProcessor:()=>fh,Wav2Vec2Processor:()=>dh,Wav2Vec2ProcessorWithLM:()=>_h,WhisperProcessor:()=>mh});var Ee=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await nt(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 Go={};en(Go,{ASTFeatureExtractor:()=>N_,ChatterboxFeatureExtractor:()=>$_,ClapFeatureExtractor:()=>R_,CohereAsrFeatureExtractor:()=>D_,DacFeatureExtractor:()=>Fo,EncodecFeatureExtractor:()=>Ro,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Bo,Gemma4AudioFeatureExtractor:()=>Uo,GraniteSpeechFeatureExtractor:()=>F_,MoonshineFeatureExtractor:()=>B_,ParakeetFeatureExtractor:()=>Do,PyAnnoteFeatureExtractor:()=>jo,SeamlessM4TFeatureExtractor:()=>U_,SnacFeatureExtractor:()=>j_,SpeechT5FeatureExtractor:()=>G_,VoxtralRealtimeFeatureExtractor:()=>V_,Wav2Vec2FeatureExtractor:()=>q_,WeSpeakerFeatureExtractor:()=>W_,WhisperFeatureExtractor:()=>H_});import GL from"fs";import{Readable as qL}from"stream";import{pipeline as WL}from"stream/promises";async function Uc(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=qL.fromWeb(r),n=GL.createWriteStream(t);await WL(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function nM(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 Pr(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 z_(t,e="htk"){let r=HL[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 XL={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 KL(t,e="htk"){let r=XL[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 YL(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function lt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=z_(r,a),c=z_(s,a),p=sM(l,c,e+2),f=KL(p,a),_;if(i){let w=n/((t-1)*2);_=z_(Float64Array.from({length:t},(x,k)=>k*w),a),f=p}else _=sM(0,Math.floor(n/2),t);let m=YL(_,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(j!==r)throw new Error(`Length of the window (${j}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let Q=Math.floor(r/2);switch(i){case"reflect":{t=QL(t,Q,Q);break}case"constant":{let le=new t.constructor(t.length+2*Q);le.set(t,Q),t=le;break}case"semicausal":{let le=new t.constructor(t.length+Q);le.set(t,Q),t=le;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let U=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&UU?I&&(J=T):J=K=T);let R=new gc(n),C=new Float64Array(n),se=new Float64Array(R.outputBufferSize),Y=new Float32Array(X*J);for(let Q=0;Q=1;--ce)C[ce]-=c*C[ce-1];C[0]*=1-c}for(let ce=0;ceMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function eN(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return jc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),jc(n,8,"WAVE"),jc(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),jc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function jc(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]),eN(e,this.sampling_rate)}async save(e){return Uc(e,this.toBlob())}};var N_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){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(hs.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ot(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){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=p){l.push(e.slice(c,p));break}let f=Math.max(c,c+a-i),_=Math.min(c+a,p),m;_<=f?m=c+a:m=this._find_split_point_energy(e,f,_,n),m=Math.max(c+1,Math.min(m,p)),l.push(e.slice(c,m)),c=m}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let p=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Qe([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Uo=class extends Bo{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ot(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){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,p=Math.floor(l/2),f=l+1,_=new Uint8Array(s+p+(r.pad_to_multiple_of??128));_.fill(1,p,p+s);let m=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:p*s,confidence:f/(p-c)})))}return n}};var U_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Ae(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let A=0;A0){let E=new Float32Array(x*(w+A));E.set(k),E.fill(this.config.padding_value,k.length);let S=w+A;a=new N(a.type,E,[S,x]),o&&(i=new N("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let _=a.view(1,Math.floor(l/p),c*p),m={input_features:_};if(o){let w=_.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let A=1,E=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){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 W_=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=lt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ot(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){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 je=class{static async from_pretrained(e,r={}){let s=await nt(e,No,!0,r),n=s.feature_extractor_type,o=Go[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${qr}.`);return new o(s)}};var X_=class extends re{static tokenizer_class=ne;static feature_extractor_class=je;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var rN=new Set(["ja","zh"]),K_=class extends re{static tokenizer_class=ne;static feature_extractor_class=je;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=rN.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};import Y_ from"sharp";var Ss,iM,Wr;if(ie.IS_WEB_ENV)Ss=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Wr=self.createImageBitmap,iM=self.ImageData;else if(Y_)Wr=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 sN={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},nN=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 Pr(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 Wr(e),s=Ss(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=Y_(await e.arrayBuffer());return await Wr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:p=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Wr(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=Ss(e.width,e.height),s=new iM(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(ie.IS_WEB_ENV){if(ie.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=nN.get(r)??"image/png",n=await this.toBlob(s);return Uc(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 Y_(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},oN=Je.read.bind(Je);function lM(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&&A.push(S)}else{let S=Pe(k.data)[1];if(S===l-1||(E=$e(k.data),E[S]I*f[(O+1)%2])),_.boxes.push(T),_.classes.push(S),_.scores.push(E[S])}}c.push(_)}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[A]&&(f[A]=k[A],_[A]=x)}let m=new Array(i.dims[0]);for(let x=0;x<_.length;++x){let k=_[x];m[k]=k}let w=m.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function aN(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(_),a.push(p))}return[n,o,a]}function iN(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let p=0;p=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function lN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new N("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x_[E]&&(f[E]=x,_[E]=A[E])}let m=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=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,p=0,f=0,_=s.data;for(let m=0;mthis.preprocess(o)));return{pixel_values:xt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await nt(e,yr,!0,r);return new this(s)}};var bn={};en(bn,{BeitFeatureExtractor:()=>J_,BitImageProcessor:()=>Z_,CHMv2ImageProcessor:()=>tm,CLIPFeatureExtractor:()=>rm,CLIPImageProcessor:()=>Vc,ChineseCLIPFeatureExtractor:()=>em,ConvNextFeatureExtractor:()=>sm,ConvNextImageProcessor:()=>Hc,DINOv3ViTImageProcessor:()=>am,DPTFeatureExtractor:()=>lm,DPTImageProcessor:()=>Yc,DeiTFeatureExtractor:()=>nm,DeiTImageProcessor:()=>Xc,DetrFeatureExtractor:()=>om,DetrImageProcessor:()=>Kc,DonutFeatureExtractor:()=>im,DonutImageProcessor:()=>gn,EfficientNetImageProcessor:()=>cm,GLPNFeatureExtractor:()=>fm,Gemma3ImageProcessor:()=>um,Gemma4ImageProcessor:()=>qo,Glm46VImageProcessor:()=>pm,GroundingDinoImageProcessor:()=>dm,Idefics3ImageProcessor:()=>Qc,ImageFeatureExtractor:()=>H,ImageProcessor:()=>H,JinaCLIPImageProcessor:()=>mm,Lfm2VlImageProcessor:()=>hm,LlavaOnevisionImageProcessor:()=>gm,Mask2FormerImageProcessor:()=>xm,MaskFormerFeatureExtractor:()=>wm,MaskFormerImageProcessor:()=>wn,MobileNetV1FeatureExtractor:()=>ym,MobileNetV1ImageProcessor:()=>Jc,MobileNetV2FeatureExtractor:()=>bm,MobileNetV2ImageProcessor:()=>Zc,MobileNetV3FeatureExtractor:()=>vm,MobileNetV3ImageProcessor:()=>eu,MobileNetV4FeatureExtractor:()=>km,MobileNetV4ImageProcessor:()=>tu,MobileViTFeatureExtractor:()=>Em,MobileViTImageProcessor:()=>ru,NougatImageProcessor:()=>Am,OwlViTFeatureExtractor:()=>Mm,OwlViTImageProcessor:()=>xn,Owlv2ImageProcessor:()=>Tm,Phi3VImageProcessor:()=>Im,PixtralImageProcessor:()=>Cm,PvtImageProcessor:()=>Pm,Qwen2VLImageProcessor:()=>Wo,RTDetrImageProcessor:()=>zm,Sam2ImageProcessor:()=>Vo,Sam3ImageProcessor:()=>Vo,SamImageProcessor:()=>Vo,SapiensFeatureExtractor:()=>Lm,SapiensImageProcessor:()=>su,SegformerFeatureExtractor:()=>Nm,SegformerImageProcessor:()=>nu,SiglipImageProcessor:()=>$m,SmolVLMImageProcessor:()=>Qc,Swin2SRImageProcessor:()=>Rm,VLMImageProcessor:()=>_m,ViTFeatureExtractor:()=>Dm,ViTImageProcessor:()=>ou,VitMatteImageProcessor:()=>Fm,VitPoseImageProcessor:()=>Bm,YolosFeatureExtractor:()=>Um,YolosImageProcessor:()=>au});var J_=class extends H{};var Z_=class extends H{};var em=class extends H{};var tm=class extends H{};var Vc=class extends H{},rm=class extends Vc{};var Hc=class extends H{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},sm=class extends Hc{};var Xc=class extends H{},nm=class extends Xc{};var Kc=class extends H{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Qe(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Vr(...e)}post_process_panoptic_segmentation(...e){return qc(...e)}post_process_instance_segmentation(...e){return Wc(...e)}},om=class extends Kc{};var am=class extends H{};var gn=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((f,_)=>-f/c[_]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},im=class extends gn{};var Yc=class extends H{},lm=class extends Yc{};var cm=class extends H{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var um=class extends H{};function cN(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let p=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,p)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,p)),[l,c]}function uN(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,p=n*n*s,f=new Float32Array(o*p),_=0;for(let x=0;xa),0));let p=a.dims[0]/i,f=a.dims[1],_=Math.floor(a.dims[2]/c),m=Math.floor(a.dims[3]/c),w=a.view(p,i,f,Math.floor(_/l),l,c,Math.floor(m/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*_*m,f*i*c*c),x=new N("int64",[p,_,m],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var pm=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 hn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var fm=class extends H{};var dm=class extends H{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 Qc=class extends H{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let E=await Promise.all(A.map(I=>this.preprocess(I)));l.push(...E.map(I=>I.original_size)),c.push(...E.map(I=>I.reshaped_input_size)),E.forEach(I=>I.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,T;if(r??this.do_image_splitting){let I=new Array(E.length),O=new Array(E.length);T=await Promise.all(E.map(async(b,F)=>{let j=this.get_resize_for_vision_encoder(b.pixel_values,S),U=await bt(b.pixel_values,{size:[j.height,j.width]}),{frames:X,num_splits_h:K,num_splits_w:J}=await this.split_image(U,this.max_image_size);return I[F]=K,O[F]=J,ve(X,0)})),a.push(I),i.push(O)}else{let I=[S,S];T=await Promise.all(E.map(O=>bt(O.pixel_values,{size:I}))),a.push(new Array(E.length).fill(0)),i.push(new Array(E.length).fill(0))}o.push(ve(T,0))}let p=o.length,[f,_,m,w]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=Qe([p,f,m,w],!0);else{let A=Math.max(...o.map(T=>T.dims.at(0)));k=Qe([p,A,m,w],!0);let E=k.data,S=A*m*w;for(let T=0;Ts||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var mm=class extends H{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function uM(t,e){return Math.round(t/e)*e}function pN(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 fN(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 dN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,p=new Float32Array(r*a*i*l),f=n*o;for(let _=0;_this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=fN(this.min_tiles,this.max_tiles),[n,o]=pN(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let _=await Promise.all(f.map(m=>this.preprocess(m,{do_pad:!1})));for(let{pixel_values:m}of _){let[,w,x]=m.dims,k=m.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,E=A**2,[S,T]=hn(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*E,this.max_image_tokens*E).map(U=>Math.max(A,U)),I,O=1,b=1,F=this._is_image_too_large(w,x),j=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(F&&j){let{grid_width:U,grid_height:X,target_width:K,target_height:J}=this._get_grid_layout(w,x);O=X,b=U;let R=await bt(k,{size:[J,K]});I=[];for(let C=0;C(p-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||Om(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(_=>this.preprocess(_))),o=n.map(_=>_.original_size),a=n.map(_=>_.reshaped_input_size),i=[];for(let{pixel_values:_}of n){_.unsqueeze_(0);let[m,w]=_.dims.slice(-2),x=await bt(_,{size:[Nt,Nt],mode:"bicubic"});if(r>0){let k=[],A=Om(r),E=yn(w/A),S=yn(m/A);for(let I=0;I_.map(m=>Nt*Sm(m/Nt))),p=new N("int64",c.flat(),[s,2]),f=c.map(([_,m])=>this.calc_num_image_tokens_from_image_size(m,_));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:f}}};var Cm=class extends H{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=c*p,_=Math.floor((i-1)/f)+1,m=Math.floor((l-1)/f)+1;return[_*f,m*f]}};var Pm=class extends H{};var zm=class extends H{post_process_object_detection(...e){return Vr(...e)}};var Vo=class extends H{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Cf(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new N("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);_=new N("bool",w,_.dims)}i.push(_)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var su=class extends H{post_process_semantic_segmentation(...e){return Gc(...e)}},Lm=class extends su{};var nu=class extends H{post_process_semantic_segmentation(...e){return Gc(...e)}},Nm=class extends nu{};var $m=class extends H{};var Rm=class extends H{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var ou=class extends H{},Dm=class extends ou{};var Fm=class extends H{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:xt(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 Bm=class extends H{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[p,f,..._]of i)l.push(f?f.trim():l.at(-1)??""),c.push(_.map((m,w)=>(Number(m)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Gm=class extends re{static tokenizer_class=ne;static image_processor_class=Me;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 qm=class extends re{static image_processor_class=Me;static feature_extractor_class=je;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:p,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let _=a.repeat(this.audio_seq_length);this.full_audio_sequence=` ${o}${_}${i} `,this.image_token_id=l,this.boi_token=c,this.image_token=p;let m=p.repeat(this.image_seq_length);this.full_image_sequence=` ${c}${m}${f} `}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;s&&(o=await this.feature_extractor(s,n),e=e.map(l=>l.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return r&&(a=await this.image_processor(r,n),e=e.map(l=>l.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...o}}};var Wm=class extends re{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:n,boa_token:o,eoa_token:a,image_token:i,boi_token:l,eoi_token:c}=this.tokenizer.config;this.audio_token=n,this.boa_token=o,this.eoa_token=a,this.image_token=i,this.boi_token=l,this.eoi_token=c}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([nt(e,Fc,!0,r),ne.from_pretrained(e,r),xo(e,Bc,!1,r)]),a={tokenizer:n};return s.image_processor&&(a.image_processor=new qo(s.image_processor)),s.feature_extractor&&(a.feature_extractor=new Uo(s.feature_extractor)),new this(s,a,o)}_compute_audio_num_tokens(e,r){let s=Math.round(r*20/1e3),n=Math.round(r*10/1e3),o=Math.floor(s/2),a=Math.floor((e+o-s-1)/n)+1;if(a<=0)return 0;for(let i=0;i<2;++i)a=Math.floor((a-1)/2)+1;return Math.min(a,this.audio_seq_length)}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;if(r){o=await this.image_processor(r,n);let i=o.num_soft_tokens_per_image,l=0;e=e.map(c=>c.replaceAll(this.image_token,()=>` ${this.boi_token}${this.image_token.repeat(i[l++])}${this.eoi_token} `))}let a;if(s){let i=Array.isArray(s)?s:[s];a=await this.feature_extractor(i[0],n);let l=this.feature_extractor.config.sampling_rate??16e3,c=0;e=e.map(p=>p.replaceAll(this.audio_token,()=>` ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[c++].length,l))}${this.eoa_token} `))}return{...this.tokenizer(e,n),...o,...a}}};var Os=class extends re{static image_processor_class=Me;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,p=o.tolist();e=e.map(f=>{for(;f.includes(c);){let _=Number(p[l++].reduce((m,w)=>m*w,1n));f=f.replace(c,"<|placeholder|>".repeat(Math.floor(_/i)))}return f.replaceAll("<|placeholder|>",c)})}return{...this.tokenizer(e),...n}}};var Vm=class extends Os{static image_token="<|image|>"};var Hm=class extends re{static tokenizer_class=ne;static feature_extractor_class=je;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:r}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:n}=this.feature_extractor.config,o=Math.floor(s/n),a=Math.floor(e/r)+1,i=Math.floor(a/2);return Math.ceil(i/s)*o}async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let{input_features:a}=await this.feature_extractor(r);n.input_features=a;let i=this._get_num_audio_features(r.length),l=new Uint8Array(i).fill(1);n.input_features_mask=new N("bool",l,[1,i]);let c=this.config.audio_token??"<|audio|>";if(!e.includes(c))throw new Error(`The input text does not contain the audio token ${c}.`);e=e.replaceAll(c,c.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};function hN(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 Xm=class extends re{static tokenizer_class=ne;static image_processor_class=Me;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=a.dims.at(1),p=a.sigmoid(),f=p.max(-1).tolist(),_=i.tolist().map(w=>w.map(x=>Q_(x))),m=[];for(let w=0;wT.map((I,O)=>I*x[(O+1)%2])));let k=f[w],A=[],E=[],S=[];for(let T=0;T`+n.repeat(t);a+=` `}return a+=` ${s}${o}`+n.repeat(t)+`${s}`,a}function wN(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function xN(t,e,r,s,n,o){return t===0&&e===0?wN(r,s,n,o):gN(r,t,e,s,n,o)}var iu=class extends re{static image_processor_class=Me;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;fxN(E,w[S],i,this.fake_image_token,this.image_token,this.global_img_token)),k=_.split(this.image_token);if(k.length===0)throw new Error("The image token should be present in the text.");let A=k[0];for(let E=0;Ek.images).flatMap(k=>k.images).map(k=>Je.read(k)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=k=>n.encode(k,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[c,p,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),_=a(i[0]),m=new Array(_.length).fill(!1);for(let k=1;k0){let k=await this.image_processor(r);return k.pixel_values.unsqueeze_(0),{...x,...k}}return x}};var Ym=class extends re{static tokenizer_class=ne;static image_processor_class=Me;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 Qm=class extends re{static tokenizer_class=ne;static image_processor_class=Me;async _call(e,r=null,s={}){let{image_rows:n,image_cols:o,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(r){let l=this.config.image_token??"",{tile_size:c=512,downsample_factor:p=2,encoder_patch_size:f=16,use_thumbnail:_=!0}=this.image_processor.config,m=S=>Math.ceil(Math.floor(S/f)/p),w=m(c)**2,x=this.config.image_start_token??"<|image_start|>",k=this.config.image_end_token??"<|image_end|>",A=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(r)||(r=[r]);let E=0;r=r.map(S=>{let T=S.split(l);return T[0]+T.slice(1).map(I=>{let O=E++,[b,F]=a[O],j=n[O],U=o[O],X=m(b)*m(F),K=x;if(j>1||U>1){let J=l.repeat(w);for(let R=0;R`+J;_&&(K+=A+l.repeat(X))}else K+=l.repeat(X);return K+k+I}).join("")})}return{...i,...r?this.tokenizer(r,s):{}}}};var Jm=class extends re{static tokenizer_class=ne;static image_processor_class=Me;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:c,num_additional_image_tokens:p}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+p;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let _=0;_0?x.reduce((A,E)=>A*E,1):0;c.push(w),l.push(k)}return[o(c),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,c]=this._decode_helper(s,"wp"),p=[],f=[];for(let _=0;_c.includes(vn))?a=r.map(c=>{let p=c.replaceAll(vn,vn.repeat(o)),f=p.lastIndexOf(vn),_=f===-1?0:f+vn.length;return p.slice(0,_)+n+p.slice(_)+` `}):(ee.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(c=>yN(c,n,o,vn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var fM="<|image|>",bN=/<\|image_\d+\|>/g,sh=class extends re{static image_processor_class=Me;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,_)=>f.split(bN).join(fM.repeat(l[_])));a=this.tokenizer(c,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id(fM);a.input_ids.map_(f=>f==p?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var nh=class extends re{static tokenizer_class=ne;static image_processor_class=Me;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:c,image_end_token:p,patch_size:f,spatial_merge_size:_}=this.config,m=f*_,w=Math.floor(a/m),x=Math.floor(i/m);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let k=0;kEN(w,l)),p=c.map(w=>w.length),f=c.flat(),_=(await Promise.all(f.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=_.length>1?ve(_,0):_[0];let m=a[0];for(let w=0;w0){if(c>fc)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${fc}).`);let p=gh(a,c);for(let f of p){let _=`${s.subfolder??""}/${f}`;l.push(new Promise(async(m,w)=>{let x=await wo(t,_,!0,s,i);m(x instanceof Uint8Array?{path:f,data:x}:f)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async p=>{if(typeof p.data=="string"){let f=await wo(t,p.data,!0,s);return{...p,data:f}}return p}));return Promise.all(l)}async function ON(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=zc(r.device??o.device,e,{warn:E=>ee.info(E)}),i=U2(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=Lc(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:E=>ee.info(E)});if(jr.hasOwnProperty(c)){if(a==="webgpu"&&!ie.IS_NODE_ENV&&c===st.fp16&&!await V2())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(st).join(", ")}`);let p=jr[c],f={...r.session_options};f.executionProviders??=i;let _=o.free_dimension_overrides;_?f.freeDimensionOverrides??=_:a.startsWith("webnn")&&!f.freeDimensionOverrides&&ee.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${a}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let m=_M(t,e,r,p),w=r.use_external_data_format??o.use_external_data_format,x=await mM(t,e,p,r,w,f);if(x.length>0&&(!ie.IS_NODE_ENV||x.some(E=>typeof E!="string"))&&(f.externalData=x),s&&a==="webgpu"){let E=Is(r.config,{prefix:"present",session_name:n});if(E.size>0&&!Oo()){let S={};for(let T of E)S[T]="gpu-buffer";f.preferredOutputLocation=S}}return{buffer_or_path:await m,session_options:f,session_config:{dtype:c,device:a}}}async function hM(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 ON(t,e[n],r,o,n),c=await Ic(a,i,l);return[n,c]})))}function gM(t){for(let e in t)Pc(t[e])?t[e]=new N(t[e]):typeof t[e]=="object"&&gM(t[e]);return t}async function ue(t,e){let r=IN(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 Cc(t,s);return gM(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 IN(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]=Oo()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(e).length,o=t.inputNames.length;if(n>o){let a=Object.keys(e).filter(i=>!t.inputNames.includes(i));ee.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Re=class{};var q=class extends Re{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},ge=class extends Re{constructor({logits:e}){super(),this.logits=e}},we=class extends Re{constructor({logits:e}){super(),this.logits=e}},Te=class extends Re{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},vt=class extends Re{constructor({logits:e}){super(),this.logits=e}};var du=class extends Re{constructor({alphas:e}){super(),this.alphas=e}};var $t=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")}},Cs=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()}},_u=class extends $t{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=Uf(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,_)=>f+_)),p=Pe(l.subarray(0,this.timestamp_begin))[0];c>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},wu=class extends $t{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}},xM=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 Mn=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,Ve(e,Object.getOwnPropertyNames(this)))}};var Hr=class extends We{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Tn=class t extends We{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof Hr&&(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)}},Mu=class extends Hr{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)})}},yM=class extends Hr{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 Ps=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 xh(e);if(e.num_beams>1)return new yh(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 wh(e)}},wh=class extends Ps{async sample(e){let r=Pe(e.data)[1];return[[BigInt(r),0]]}},xh=class extends Ps{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 Jt(e,r),o=$e(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},yh=class extends Ps{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 Jt(e,r),o=$e(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var bh=class{constructor(e){if(e)for(let r in e){if(r in this)throw new TypeError(`Key "${r}" conflicts with an existing property on DynamicCache`);let s=e[r];if(!(s instanceof N))throw new TypeError(`Expected a Tensor for key "${r}", got ${typeof s}`);this[r]=s}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let r in e)if(r.startsWith("past_key_values."))return e[r].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(let r in e){let s=this[r],n=e[r];s&&s!==n&&s.location==="gpu-buffer"&&s.dispose(),this[r]=n}}async dispose(){let e=[];for(let r of Object.values(this))r.location==="gpu-buffer"&&e.push(r.dispose());await Promise.all(e)}},Sn=bh;var V={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},ur={[V.DecoderOnly]:{sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[V.DecoderOnlyWithoutHead]:{sessions:(t,e)=>({model:e.model_file_name??"model"})},[V.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[V.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[V.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...ur[V.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),t.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...ur[V.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[V.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...ur[V.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},optional_configs:{generation_config:"generation_config.json"}},[V.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[V.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[V.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[V.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[V.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[V.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...ur[V.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(t,e)=>({model:e.model_file_name??"model"})}};function vh(t){return ur[t]?.text_only_sessions??null}function Yo(t,e,r={}){let s=ur[t]??ur.default;return{sessions:s.sessions(e,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function On(t,{warn:e=!0}={}){let r=t.architectures||[];for(let s of r){let n=Zt.get(s);if(n!==void 0)return n}if(t.model_type){let s=Zt.get(t.model_type);if(s!==void 0)return s;for(let n of Object.values(zs))if(n.has(t.model_type)){let o=Zt.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: ${qr}`)}return V.EncoderOnly}function Qo(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return jt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=JSON.stringify([t,r,s,n]);return _c(o,()=>jt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n}))}async function In(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await Qo(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,p=r??a.dtype,f=On(e),_=(x,k=null)=>{k=k??x;let A=zc(c,x),E=Lc(p,x,A),S=jr[E]??"",T=`${k}${S}.onnx`,I=l?`${l}/${T}`:T;o.push(I);let O=hh(i,T,x);for(let b of gh(T,O)){let F=l?`${l}/${b}`:b;o.push(F)}},{sessions:m,optional_configs:w}=Yo(f,e,{model_file_name:n});for(let[x,k]of Object.entries(m))_(x,k);if(w)for(let x of Object.values(w))o.push(x);return o}var zs=null;function kM(t){zs=t}function kh(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 Eh(t){return new N("bool",[t],[1])}var bM={[V.DecoderOnly]:{can_generate:!0,forward:It,prepare_inputs:Cn},[V.DecoderOnlyWithoutHead]:{can_generate:!1,forward:It,prepare_inputs:Cn},[V.Seq2Seq]:{can_generate:!0,forward:Tu,prepare_inputs:Jo},[V.Vision2Seq]:{can_generate:!0,forward:Tu,prepare_inputs:Jo},[V.Musicgen]:{can_generate:!0,forward:Tu},[V.EncoderDecoder]:{can_generate:!1,forward:Tu},[V.ImageTextToText]:{can_generate:!0,forward:LN,prepare_inputs:Su},[V.AudioTextToText]:{can_generate:!0,forward:zN,prepare_inputs:Su},[V.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Su},[V.Phi3V]:{can_generate:!0,prepare_inputs:Su},[V.MultiModality]:{can_generate:!0},[V.AutoEncoder]:{can_generate:!1,forward:CN},[V.Chatterbox]:{can_generate:!0,forward:Gt},[V.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Cn},default:{can_generate:!1,forward:Gt}};function vM(t,e){let r=Zt.get(t),s=!1,n=e?.architectures?.[0];if(n&&n!==t&&t?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let i=Zt.get(n);i!==void 0&&(r=i,s=!0)}let o=bM[r]??bM.default,a=ur[r]??ur.default;return{typeConfig:{...o,...a},textOnly:s,modelType:r}}var Zt=new Map,Iu=new Map,Ls=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=Ls.get(this.constructor),{typeConfig:o}=vM(n,e);this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:p=null,use_external_data_format:f=null,session_options:_={}}={}){let m={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:p,use_external_data_format:f,session_options:_},w=Ls.get(this);s=m.config=await jt.from_pretrained(e,m);let{typeConfig:x,textOnly:k,modelType:A}=vM(w,s);if(A===void 0){let I=w??s?.model_type;I!=="custom"&&ee.warn(`Model type for '${I}' not found, assuming encoder-only architecture. Please report this at ${qr}.`)}if(r&&!(r instanceof ds)){let I={};try{let O=await In(e,{config:s,dtype:p,device:c,model_file_name:i});(await Promise.all(O.map(F=>Ot(e,F,m)))).forEach((F,j)=>{if(F.exists){let U=O[j]==="config.json";I[O[j]]={loaded:U?F.size??0:0,total:F.size??0}}})}catch(O){ee.warn(`Unable to fetch model file metadata for total progress tracking: ${O}`)}Object.keys(I).length>0&&(m.progress_callback=new ds(r,I))}let E=x.sessions(s,m,k),S=[hM(e,E,m,x.cache_sessions)];x.optional_configs&&S.push($N(e,x.optional_configs,m));let T=await Promise.all(S);return new this(s,...T)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new Cs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new xu(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new wu(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new vu(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new yu(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 bu(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new _u(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 hu(e.suppress_tokens)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new An(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new ku(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 Eu(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=Mn){let n={...this.config};for(let a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);let o=new s(n);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),r&&Object.assign(o,Ve(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Tn;return e.max_length!==null&&s.push(new Au(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new Mu(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[zs.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,zs.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,zs.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,zs.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Ls.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=Ou(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=Ve(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...c}=r,p=await this._prepare_inputs_embeds(r);r={...c,...Ve(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Gt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=ve([o,Co(o,0)],0),"attention_mask"in r&&(r.attention_mask=ve([r.attention_mask,Fd(r.attention_mask)],0));else if(r.decoder_input_ids){let a=kh(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=kh(i)}return l.decoder_attention_mask=Dc(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),p=this.config.is_encoder_decoder;p&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let f;p?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];let _=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=_+r.max_new_tokens);let m=this._get_logits_processor(r,_,s),w=this._get_stopping_criteria(r,n),x=l[c].dims.at(0),k=Ps.getSampler(r),A=new Array(x).fill(0),E=f.tolist();o&&o.put(E);let S,T={},I={};for(;;){if(l=this.prepare_inputs_for_generation(E,l,r),S=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let R=PN(S);for(let C in R)C in T||(T[C]=[]),T[C].push(R[C])}else this._return_dict_in_generate_keys&&Object.assign(I,Ve(S,this._return_dict_in_generate_keys));let U=S.logits.slice(null,-1,null).to("float32"),X=m(E,U),K=[];for(let R=0;RR))break;l=this._update_model_kwargs_for_generation({generated_input_ids:K,outputs:S,model_inputs:l,is_encoder_decoder:p})}o&&o.end();let O=new N("int64",E.flat(),[E.length,E[0].length]),b=Ou(S,l.past_key_values),F=new Set(Object.values(b));for(let U of Object.values(S))U.location==="gpu-buffer"&&!F.has(U)&&U.dispose();return"past_key_values"in a||r.return_dict_in_generate||await b.dispose(),r.return_dict_in_generate?{sequences:O,past_key_values:b,...T,...I}:O}async _encode_input(e,r,s){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);let n=this.sessions[e];return(await ue(n,Ve(r,n.inputNames)))[s]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function Tu(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:o,...a}=e;if(!r){let i=Ve(e,t.sessions.model.inputNames);r=(await Gt(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 It(t,a,!0)}async function Gt(t,e){let r=t.sessions.model,s=Ve(e,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Fd(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let n=s.pixel_values.dims;s.pixel_mask=et([n[0],n[2],n[3]])}return await ue(r,s)}async function CN(t,e){let r=await t.encode(e);return await t.decode(r)}function Ou(t,e){let r=Object.create(null);for(let s in t)if(s.startsWith("present")){let n=s.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");s.includes("encoder")&&e?r[n]=e[n]:r[n]=t[s]}return e?(e.update(r),e):new Sn(r)}function PN(t){let e={};for(let r of["cross_attentions","encoder_attentions","decoder_attentions"])for(let s in t)s.startsWith(r)&&(r in e||(e[r]=[]),e[r].push(t[s]));return e}function Ah(t,e){return t.map(r=>typeof r=="number"?r:e[r]??0)}function Zo(t,e,r){if(r&&Object.keys(r).length>0)return Object.assign(e,r),r;let s=t.sessions.decoder_model_merged??t.sessions.model,n=(e[t.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=Is(t.config),a=t.config?.normalized_config?.num_heads,i={batch_size:n};typeof a=="number"&&(i["batch_size x num_heads"]=n*a);let l=Object.create(null);for(let c of s.inputMetadata){if(!o.has(c.name))continue;let p=Ah(c.shape,i),f=p.reduce((w,x)=>w*x,1),_=Gr[c.type],m=new N(c.type,new _(f),p);e[c.name]=m,l[c.name]=m}return r?(r.update(l),r):new Sn(l)}async function It(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=Eh(n!=null&&Object.keys(n).length>0)),s.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(t.config.model_type)?1:0;o.position_ids=NN(o,n,i)}s.inputNames.includes("num_logits_to_keep")&&!o.num_logits_to_keep&&(o.num_logits_to_keep=new N("int64",[0n],[])),Zo(t,o,n);let a=Ve(o,s.inputNames);return await ue(s,a)}async function EM(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:f=null,..._}){if(!l){l=await t.encode_text({input_ids:o,..._});let w=Ve(_,s);if(Object.keys(w).length>0){if(o.dims[1]!==1){let x=await e({...w,..._});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&o.dims[1]===1){let x=o.dims[1],k=c.get_seq_length();a=ve([et([o.dims[0],k]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(t.config.model_type)){let{image_grid_thw:w,video_grid_thw:x}=_;[i]=t.get_rope_index(o,w,x,a)}return await It(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:p,logits_processor:f},!0)}async function zN(t,e){return await EM(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 LN(t,e){return await EM(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 Mh(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:kh(e)}}function Su(t,...e){return t.config.is_encoder_decoder?Jo(t,...e):Cn(t,...e)}function AM({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((p,f,_)=>(f==t&&p.push(_),p),[])),a=o.reduce((c,p)=>c+p.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let c=0;c{let n=await nt(t,e[s],!1,r);return[s,n]})))}var hl={};en(hl,{ASTForAudioClassification:()=>Dh,ASTModel:()=>Rh,ASTPreTrainedModel:()=>sa,AfmoeForCausalLM:()=>Lh,AfmoeModel:()=>zh,AfmoePreTrainedModel:()=>ta,AlbertForMaskedLM:()=>Ih,AlbertForQuestionAnswering:()=>Oh,AlbertForSequenceClassification:()=>Sh,AlbertModel:()=>Th,AlbertPreTrainedModel:()=>Ns,ApertusForCausalLM:()=>Ph,ApertusModel:()=>Ch,ApertusPreTrainedModel:()=>ea,ArceeForCausalLM:()=>$h,ArceeModel:()=>Nh,ArceePreTrainedModel:()=>ra,BartForConditionalGeneration:()=>Bh,BartForSequenceClassification:()=>Uh,BartModel:()=>Fh,BartPretrainedModel:()=>zn,BeitForImageClassification:()=>Gh,BeitModel:()=>jh,BeitPreTrainedModel:()=>na,BertForMaskedLM:()=>Wh,BertForQuestionAnswering:()=>Xh,BertForSequenceClassification:()=>Vh,BertForTokenClassification:()=>Hh,BertModel:()=>qh,BertPreTrainedModel:()=>Xr,BlenderbotForConditionalGeneration:()=>Yh,BlenderbotModel:()=>Kh,BlenderbotPreTrainedModel:()=>oa,BlenderbotSmallForConditionalGeneration:()=>Jh,BlenderbotSmallModel:()=>Qh,BlenderbotSmallPreTrainedModel:()=>aa,BloomForCausalLM:()=>eg,BloomModel:()=>Zh,BloomPreTrainedModel:()=>ia,CHMv2ForDepthEstimation:()=>ig,CHMv2PreTrainedModel:()=>Lu,CLIPModel:()=>cg,CLIPPreTrainedModel:()=>pr,CLIPSegForImageSegmentation:()=>_g,CLIPSegModel:()=>dg,CLIPSegPreTrainedModel:()=>fa,CLIPTextModel:()=>ug,CLIPTextModelWithProjection:()=>pa,CLIPVisionModel:()=>pg,CLIPVisionModelWithProjection:()=>fg,CamembertForMaskedLM:()=>rg,CamembertForQuestionAnswering:()=>og,CamembertForSequenceClassification:()=>sg,CamembertForTokenClassification:()=>ng,CamembertModel:()=>tg,CamembertPreTrainedModel:()=>Kr,ChatterboxModel:()=>la,ChatterboxPreTrainedModel:()=>Pu,ChineseCLIPModel:()=>ag,ChineseCLIPPreTrainedModel:()=>zu,ClapAudioModelWithProjection:()=>ua,ClapModel:()=>lg,ClapPreTrainedModel:()=>Ln,ClapTextModelWithProjection:()=>ca,CodeGenForCausalLM:()=>hg,CodeGenModel:()=>mg,CodeGenPreTrainedModel:()=>da,Cohere2ForCausalLM:()=>yg,Cohere2Model:()=>xg,Cohere2PreTrainedModel:()=>ma,CohereAsrForConditionalGeneration:()=>vg,CohereAsrModel:()=>bg,CohereAsrPreTrainedModel:()=>ha,CohereForCausalLM:()=>wg,CohereModel:()=>gg,CoherePreTrainedModel:()=>_a,ConvBertForMaskedLM:()=>Eg,ConvBertForQuestionAnswering:()=>Tg,ConvBertForSequenceClassification:()=>Ag,ConvBertForTokenClassification:()=>Mg,ConvBertModel:()=>kg,ConvBertPreTrainedModel:()=>Yr,ConvNextForImageClassification:()=>Og,ConvNextModel:()=>Sg,ConvNextPreTrainedModel:()=>ga,ConvNextV2ForImageClassification:()=>Cg,ConvNextV2Model:()=>Ig,ConvNextV2PreTrainedModel:()=>wa,DFineForObjectDetection:()=>Ng,DFineModel:()=>Lg,DFinePreTrainedModel:()=>ya,DINOv3ConvNextModel:()=>iw,DINOv3ConvNextPreTrainedModel:()=>Uu,DINOv3ViTModel:()=>lw,DINOv3ViTPreTrainedModel:()=>ju,DPTForDepthEstimation:()=>hw,DPTModel:()=>mw,DPTPreTrainedModel:()=>Ta,DacDecoderModel:()=>va,DacDecoderOutput:()=>$u,DacEncoderModel:()=>ba,DacEncoderOutput:()=>Nu,DacModel:()=>$g,DacPreTrainedModel:()=>Nn,DebertaForMaskedLM:()=>Dg,DebertaForQuestionAnswering:()=>Ug,DebertaForSequenceClassification:()=>Fg,DebertaForTokenClassification:()=>Bg,DebertaModel:()=>Rg,DebertaPreTrainedModel:()=>Qr,DebertaV2ForMaskedLM:()=>Wg,DebertaV2ForQuestionAnswering:()=>Xg,DebertaV2ForSequenceClassification:()=>Vg,DebertaV2ForTokenClassification:()=>Hg,DebertaV2Model:()=>qg,DebertaV2PreTrainedModel:()=>Jr,DecisionTransformerModel:()=>Kg,DecisionTransformerPreTrainedModel:()=>Ru,DeepseekV3ForCausalLM:()=>Gg,DeepseekV3Model:()=>jg,DeepseekV3PreTrainedModel:()=>ka,DeiTForImageClassification:()=>Qg,DeiTModel:()=>Yg,DeiTPreTrainedModel:()=>Ea,DepthAnythingForDepthEstimation:()=>Jg,DepthAnythingPreTrainedModel:()=>Du,DepthProForDepthEstimation:()=>Zg,DepthProPreTrainedModel:()=>Fu,DetrForObjectDetection:()=>tw,DetrForSegmentation:()=>rw,DetrModel:()=>ew,DetrObjectDetectionOutput:()=>Rn,DetrPreTrainedModel:()=>$n,DetrSegmentationOutput:()=>Bu,Dinov2ForImageClassification:()=>nw,Dinov2Model:()=>sw,Dinov2PreTrainedModel:()=>Aa,Dinov2WithRegistersForImageClassification:()=>aw,Dinov2WithRegistersModel:()=>ow,Dinov2WithRegistersPreTrainedModel:()=>Ma,DistilBertForMaskedLM:()=>dw,DistilBertForQuestionAnswering:()=>fw,DistilBertForSequenceClassification:()=>uw,DistilBertForTokenClassification:()=>pw,DistilBertModel:()=>cw,DistilBertPreTrainedModel:()=>Zr,DonutSwinModel:()=>_w,DonutSwinPreTrainedModel:()=>Gu,EdgeTamModel:()=>Tb,EfficientNetForImageClassification:()=>ww,EfficientNetModel:()=>gw,EfficientNetPreTrainedModel:()=>Sa,ElectraForMaskedLM:()=>yw,ElectraForQuestionAnswering:()=>kw,ElectraForSequenceClassification:()=>bw,ElectraForTokenClassification:()=>vw,ElectraModel:()=>xw,ElectraPreTrainedModel:()=>es,Ernie4_5ForCausalLM:()=>Aw,Ernie4_5Model:()=>Ew,Ernie4_5PretrainedModel:()=>Oa,EsmForMaskedLM:()=>Tw,EsmForSequenceClassification:()=>Sw,EsmForTokenClassification:()=>Ow,EsmModel:()=>Mw,EsmPreTrainedModel:()=>$s,EuroBertForMaskedLM:()=>Cw,EuroBertForSequenceClassification:()=>Pw,EuroBertForTokenClassification:()=>zw,EuroBertModel:()=>Iw,EuroBertPreTrainedModel:()=>Rs,ExaoneForCausalLM:()=>Nw,ExaoneModel:()=>Lw,ExaonePreTrainedModel:()=>Ia,FalconForCausalLM:()=>Rw,FalconH1ForCausalLM:()=>Fw,FalconH1Model:()=>Dw,FalconH1PreTrainedModel:()=>Pa,FalconModel:()=>$w,FalconPreTrainedModel:()=>Ca,FastViTForImageClassification:()=>Uw,FastViTModel:()=>Bw,FastViTPreTrainedModel:()=>za,Florence2ForConditionalGeneration:()=>jw,Florence2PreTrainedModel:()=>qu,GLPNForDepthEstimation:()=>ox,GLPNModel:()=>nx,GLPNPreTrainedModel:()=>Ba,GPT2LMHeadModel:()=>mx,GPT2Model:()=>_x,GPT2PreTrainedModel:()=>Wa,GPTBigCodeForCausalLM:()=>ix,GPTBigCodeModel:()=>ax,GPTBigCodePreTrainedModel:()=>Ua,GPTJForCausalLM:()=>gx,GPTJModel:()=>hx,GPTJPreTrainedModel:()=>Va,GPTNeoForCausalLM:()=>cx,GPTNeoModel:()=>lx,GPTNeoPreTrainedModel:()=>ja,GPTNeoXForCausalLM:()=>px,GPTNeoXModel:()=>ux,GPTNeoXPreTrainedModel:()=>Ga,Gemma2ForCausalLM:()=>Vw,Gemma2Model:()=>Ww,Gemma2PreTrainedModel:()=>Na,Gemma3ForCausalLM:()=>Yw,Gemma3ForConditionalGeneration:()=>Hu,Gemma3Model:()=>Kw,Gemma3PreTrainedModel:()=>Vu,Gemma3nForCausalLM:()=>Qw,Gemma3nForConditionalGeneration:()=>ts,Gemma3nPreTrainedModel:()=>Xu,Gemma4ForCausalLM:()=>Jw,Gemma4ForConditionalGeneration:()=>Dn,GemmaForCausalLM:()=>qw,GemmaModel:()=>Gw,GemmaPreTrainedModel:()=>La,GlmForCausalLM:()=>ex,GlmModel:()=>Zw,GlmMoeDsaForCausalLM:()=>rx,GlmMoeDsaModel:()=>tx,GlmMoeDsaPreTrainedModel:()=>Ra,GlmOcrForConditionalGeneration:()=>sx,GlmPreTrainedModel:()=>$a,GptOssForCausalLM:()=>dx,GptOssModel:()=>fx,GptOssPreTrainedModel:()=>qa,GraniteForCausalLM:()=>xx,GraniteModel:()=>wx,GraniteMoeHybridForCausalLM:()=>bx,GraniteMoeHybridModel:()=>yx,GraniteMoeHybridPreTrainedModel:()=>Xa,GranitePreTrainedModel:()=>Ha,GraniteSpeechForConditionalGeneration:()=>vx,GroundingDinoForObjectDetection:()=>kx,GroundingDinoPreTrainedModel:()=>Qu,GroupViTModel:()=>Ex,GroupViTPreTrainedModel:()=>Ju,HeliumForCausalLM:()=>Mx,HeliumModel:()=>Ax,HeliumPreTrainedModel:()=>Ka,HieraForImageClassification:()=>Sx,HieraModel:()=>Tx,HieraPreTrainedModel:()=>Ya,HubertForCTC:()=>Nx,HubertForSequenceClassification:()=>$x,HubertModel:()=>Lx,HubertPreTrainedModel:()=>zx,HunYuanDenseV1ForCausalLM:()=>Dx,HunYuanDenseV1Model:()=>Rx,HunYuanDenseV1PreTrainedModel:()=>Qa,IJepaForImageClassification:()=>Bx,IJepaModel:()=>Fx,IJepaPreTrainedModel:()=>Za,Idefics3ForConditionalGeneration:()=>Ja,JAISLMHeadModel:()=>jx,JAISModel:()=>Ux,JAISPreTrainedModel:()=>ei,JinaCLIPModel:()=>Gx,JinaCLIPPreTrainedModel:()=>Bn,JinaCLIPTextModel:()=>ti,JinaCLIPVisionModel:()=>qx,Lfm2ForCausalLM:()=>Vx,Lfm2Model:()=>Wx,Lfm2MoeForCausalLM:()=>Kx,Lfm2MoeModel:()=>Xx,Lfm2MoePreTrainedModel:()=>si,Lfm2PreTrainedModel:()=>ri,Lfm2VlForConditionalGeneration:()=>Yx,LightOnOcrForConditionalGeneration:()=>Hx,LiteWhisperForConditionalGeneration:()=>G1,Llama4ForCausalLM:()=>Zx,Llama4PreTrainedModel:()=>Zu,LlamaForCausalLM:()=>Jx,LlamaModel:()=>Qx,LlamaPreTrainedModel:()=>ni,LlavaForConditionalGeneration:()=>kt,LlavaOnevisionForConditionalGeneration:()=>kt,LlavaPreTrainedModel:()=>Wu,LlavaQwen2ForCausalLM:()=>Xw,LongT5ForConditionalGeneration:()=>ty,LongT5Model:()=>ey,LongT5PreTrainedModel:()=>oi,M2M100ForConditionalGeneration:()=>sy,M2M100Model:()=>ry,M2M100PreTrainedModel:()=>ai,MBartForCausalLM:()=>py,MBartForConditionalGeneration:()=>cy,MBartForSequenceClassification:()=>uy,MBartModel:()=>ly,MBartPreTrainedModel:()=>Bs,MPNetForMaskedLM:()=>Qy,MPNetForQuestionAnswering:()=>e0,MPNetForSequenceClassification:()=>Jy,MPNetForTokenClassification:()=>Zy,MPNetModel:()=>Yy,MPNetPreTrainedModel:()=>rs,MT5ForConditionalGeneration:()=>n0,MT5Model:()=>s0,MT5PreTrainedModel:()=>xi,MarianMTModel:()=>oy,MarianModel:()=>ny,MarianPreTrainedModel:()=>ii,MaskFormerForInstanceSegmentation:()=>iy,MaskFormerModel:()=>ay,MaskFormerPreTrainedModel:()=>li,Metric3DForDepthEstimation:()=>fy,Metric3DPreTrainedModel:()=>ep,Metric3Dv2ForDepthEstimation:()=>dy,Metric3Dv2PreTrainedModel:()=>tp,MgpstrForSceneTextRecognition:()=>_y,MgpstrModelOutput:()=>rp,MgpstrPreTrainedModel:()=>sp,MimiDecoderModel:()=>ui,MimiDecoderOutput:()=>op,MimiEncoderModel:()=>ci,MimiEncoderOutput:()=>np,MimiModel:()=>my,MimiPreTrainedModel:()=>Un,Mistral4ForCausalLM:()=>xy,Mistral4Model:()=>wy,Mistral4PreTrainedModel:()=>fi,MistralForCausalLM:()=>gy,MistralModel:()=>hy,MistralPreTrainedModel:()=>pi,MobileBertForMaskedLM:()=>by,MobileBertForQuestionAnswering:()=>ky,MobileBertForSequenceClassification:()=>vy,MobileBertModel:()=>yy,MobileBertPreTrainedModel:()=>Us,MobileLLMForCausalLM:()=>Ay,MobileLLMModel:()=>Ey,MobileLLMPreTrainedModel:()=>di,MobileNetV1ForImageClassification:()=>Ty,MobileNetV1ForSemanticSegmentation:()=>Sy,MobileNetV1Model:()=>My,MobileNetV1PreTrainedModel:()=>jn,MobileNetV2ForImageClassification:()=>Iy,MobileNetV2ForSemanticSegmentation:()=>Cy,MobileNetV2Model:()=>Oy,MobileNetV2PreTrainedModel:()=>Gn,MobileNetV3ForImageClassification:()=>zy,MobileNetV3ForSemanticSegmentation:()=>Ly,MobileNetV3Model:()=>Py,MobileNetV3PreTrainedModel:()=>qn,MobileNetV4ForImageClassification:()=>$y,MobileNetV4ForSemanticSegmentation:()=>Ry,MobileNetV4Model:()=>Ny,MobileNetV4PreTrainedModel:()=>Wn,MobileViTForImageClassification:()=>Fy,MobileViTModel:()=>Dy,MobileViTPreTrainedModel:()=>_i,MobileViTV2ForImageClassification:()=>Uy,MobileViTV2Model:()=>By,MobileViTV2PreTrainedModel:()=>mi,ModernBertDecoderForCausalLM:()=>Hy,ModernBertDecoderModel:()=>Vy,ModernBertDecoderPreTrainedModel:()=>hi,ModernBertForMaskedLM:()=>Gy,ModernBertForSequenceClassification:()=>qy,ModernBertForTokenClassification:()=>Wy,ModernBertModel:()=>jy,ModernBertPreTrainedModel:()=>js,Moondream1ForConditionalGeneration:()=>Hw,MoonshineForConditionalGeneration:()=>Ky,MoonshineModel:()=>Xy,MoonshinePreTrainedModel:()=>gi,MptForCausalLM:()=>r0,MptModel:()=>t0,MptPreTrainedModel:()=>wi,MultiModalityCausalLM:()=>o0,MultiModalityPreTrainedModel:()=>ap,MusicgenForCausalLM:()=>i0,MusicgenForConditionalGeneration:()=>bi,MusicgenModel:()=>a0,MusicgenPreTrainedModel:()=>yi,NanoChatForCausalLM:()=>c0,NanoChatModel:()=>l0,NanoChatPreTrainedModel:()=>vi,NemotronHForCausalLM:()=>p0,NemotronHModel:()=>u0,NemotronHPreTrainedModel:()=>ki,NeoBertForMaskedLM:()=>d0,NeoBertForQuestionAnswering:()=>h0,NeoBertForSequenceClassification:()=>_0,NeoBertForTokenClassification:()=>m0,NeoBertModel:()=>f0,NeoBertPreTrainedModel:()=>ss,NomicBertModel:()=>g0,NomicBertPreTrainedModel:()=>ip,OPTForCausalLM:()=>C0,OPTModel:()=>I0,OPTPreTrainedModel:()=>Ii,Olmo2ForCausalLM:()=>b0,Olmo2Model:()=>y0,Olmo2PreTrainedModel:()=>Ai,Olmo3ForCausalLM:()=>k0,Olmo3Model:()=>v0,Olmo3PreTrainedModel:()=>Mi,OlmoForCausalLM:()=>x0,OlmoHybridForCausalLM:()=>A0,OlmoHybridModel:()=>E0,OlmoHybridPreTrainedModel:()=>Ti,OlmoModel:()=>w0,OlmoPreTrainedModel:()=>Ei,OpenAIPrivacyFilterForTokenClassification:()=>T0,OpenAIPrivacyFilterModel:()=>M0,OpenAIPrivacyFilterPreTrainedModel:()=>Si,OpenELMForCausalLM:()=>O0,OpenELMModel:()=>S0,OpenELMPreTrainedModel:()=>Oi,OwlViTForObjectDetection:()=>N0,OwlViTModel:()=>L0,OwlViTPreTrainedModel:()=>Pi,Owlv2ForObjectDetection:()=>z0,Owlv2Model:()=>P0,Owlv2PreTrainedModel:()=>Ci,PaliGemmaForConditionalGeneration:()=>$0,ParakeetForCTC:()=>R0,ParakeetPreTrainedModel:()=>lp,PatchTSMixerForPrediction:()=>F0,PatchTSMixerModel:()=>D0,PatchTSMixerPreTrainedModel:()=>zi,PatchTSTForPrediction:()=>U0,PatchTSTModel:()=>B0,PatchTSTPreTrainedModel:()=>Li,Phi3ForCausalLM:()=>W0,Phi3Model:()=>q0,Phi3PreTrainedModel:()=>$i,Phi3VForCausalLM:()=>Ri,Phi3VPreTrainedModel:()=>cp,PhiForCausalLM:()=>G0,PhiModel:()=>j0,PhiPreTrainedModel:()=>Ni,PreTrainedModel:()=>y,PvtForImageClassification:()=>H0,PvtModel:()=>V0,PvtPreTrainedModel:()=>Di,PyAnnoteForAudioFrameClassification:()=>K0,PyAnnoteModel:()=>X0,PyAnnotePreTrainedModel:()=>Fi,Qwen2ForCausalLM:()=>Q0,Qwen2Model:()=>Y0,Qwen2MoeForCausalLM:()=>Z0,Qwen2MoeModel:()=>J0,Qwen2MoePreTrainedModel:()=>Ui,Qwen2PreTrainedModel:()=>Bi,Qwen2VLForCausalLM:()=>Da,Qwen2VLForConditionalGeneration:()=>Fn,Qwen2VLPreTrainedModel:()=>Ku,Qwen2_5_VLForCausalLM:()=>Fa,Qwen2_5_VLForConditionalGeneration:()=>Ds,Qwen3ForCausalLM:()=>tb,Qwen3Model:()=>eb,Qwen3MoeForCausalLM:()=>sb,Qwen3MoeModel:()=>rb,Qwen3MoePreTrainedModel:()=>Gi,Qwen3NextForCausalLM:()=>ob,Qwen3NextModel:()=>nb,Qwen3NextPreTrainedModel:()=>qi,Qwen3PreTrainedModel:()=>ji,Qwen3VLForCausalLM:()=>Wi,Qwen3VLForConditionalGeneration:()=>Gs,Qwen3VLMoeForCausalLM:()=>ib,Qwen3VLMoeForConditionalGeneration:()=>ab,Qwen3_5ForCausalLM:()=>Vi,Qwen3_5ForConditionalGeneration:()=>Vn,Qwen3_5MoeForCausalLM:()=>cb,Qwen3_5MoeForConditionalGeneration:()=>lb,RFDetrForObjectDetection:()=>db,RFDetrModel:()=>fb,RFDetrObjectDetectionOutput:()=>up,RFDetrPreTrainedModel:()=>Xi,RTDetrForObjectDetection:()=>zg,RTDetrModel:()=>Pg,RTDetrObjectDetectionOutput:()=>fr,RTDetrPreTrainedModel:()=>xa,RTDetrV2ForObjectDetection:()=>Ab,RTDetrV2Model:()=>Eb,RTDetrV2ObjectDetectionOutput:()=>pp,RTDetrV2PreTrainedModel:()=>Ki,ResNetForImageClassification:()=>pb,ResNetModel:()=>ub,ResNetPreTrainedModel:()=>Hi,RoFormerForMaskedLM:()=>yb,RoFormerForQuestionAnswering:()=>kb,RoFormerForSequenceClassification:()=>bb,RoFormerForTokenClassification:()=>vb,RoFormerModel:()=>xb,RoFormerPreTrainedModel:()=>os,RobertaForMaskedLM:()=>mb,RobertaForQuestionAnswering:()=>wb,RobertaForSequenceClassification:()=>hb,RobertaForTokenClassification:()=>gb,RobertaModel:()=>_b,RobertaPreTrainedModel:()=>ns,Sam2ImageSegmentationOutput:()=>_p,Sam2Model:()=>Yi,Sam2PreTrainedModel:()=>mp,Sam3TrackerModel:()=>Sb,SamImageSegmentationOutput:()=>fp,SamModel:()=>Mb,SamPreTrainedModel:()=>dp,SapiensForDepthEstimation:()=>Ib,SapiensForNormalEstimation:()=>Cb,SapiensForSemanticSegmentation:()=>Ob,SapiensPreTrainedModel:()=>Hn,SegformerForImageClassification:()=>zb,SegformerForSemanticSegmentation:()=>Lb,SegformerModel:()=>Pb,SegformerPreTrainedModel:()=>Xn,SiglipModel:()=>Nb,SiglipPreTrainedModel:()=>Qi,SiglipTextModel:()=>Ji,SiglipVisionModel:()=>$b,SmolLM3ForCausalLM:()=>Db,SmolLM3Model:()=>Rb,SmolLM3PreTrainedModel:()=>Zi,SmolVLMForConditionalGeneration:()=>Fb,SnacDecoderModel:()=>tl,SnacEncoderModel:()=>el,SnacModel:()=>Bb,SnacPreTrainedModel:()=>Kn,SolarOpenForCausalLM:()=>jb,SolarOpenModel:()=>Ub,SolarOpenPreTrainedModel:()=>rl,SpeechT5ForSpeechToText:()=>qb,SpeechT5ForTextToSpeech:()=>Wb,SpeechT5HifiGan:()=>Vb,SpeechT5Model:()=>Gb,SpeechT5PreTrainedModel:()=>Yn,SqueezeBertForMaskedLM:()=>Xb,SqueezeBertForQuestionAnswering:()=>Yb,SqueezeBertForSequenceClassification:()=>Kb,SqueezeBertModel:()=>Hb,SqueezeBertPreTrainedModel:()=>qs,StableLmForCausalLM:()=>Jb,StableLmModel:()=>Qb,StableLmPreTrainedModel:()=>sl,Starcoder2ForCausalLM:()=>e1,Starcoder2Model:()=>Zb,Starcoder2PreTrainedModel:()=>nl,StyleTextToSpeech2Model:()=>t1,StyleTextToSpeech2PreTrainedModel:()=>hp,SupertonicForConditionalGeneration:()=>ol,SupertonicPreTrainedModel:()=>gp,Swin2SRForImageSuperResolution:()=>a1,Swin2SRModel:()=>o1,Swin2SRPreTrainedModel:()=>al,SwinForImageClassification:()=>s1,SwinForSemanticSegmentation:()=>n1,SwinModel:()=>r1,SwinPreTrainedModel:()=>Qn,T5ForConditionalGeneration:()=>l1,T5Model:()=>i1,T5PreTrainedModel:()=>il,TableTransformerForObjectDetection:()=>u1,TableTransformerModel:()=>c1,TableTransformerObjectDetectionOutput:()=>wp,TableTransformerPreTrainedModel:()=>ll,TrOCRForCausalLM:()=>p1,TrOCRPreTrainedModel:()=>xp,UltravoxModel:()=>Fs,UltravoxPreTrainedModel:()=>Yu,UniSpeechForCTC:()=>d1,UniSpeechForSequenceClassification:()=>_1,UniSpeechModel:()=>f1,UniSpeechPreTrainedModel:()=>Jn,UniSpeechSatForAudioFrameClassification:()=>w1,UniSpeechSatForCTC:()=>h1,UniSpeechSatForSequenceClassification:()=>g1,UniSpeechSatModel:()=>m1,UniSpeechSatPreTrainedModel:()=>Ws,VaultGemmaForCausalLM:()=>y1,VaultGemmaModel:()=>x1,VaultGemmaPreTrainedModel:()=>cl,ViTForImageClassification:()=>k1,ViTMAEModel:()=>E1,ViTMAEPreTrainedModel:()=>yp,ViTMSNForImageClassification:()=>M1,ViTMSNModel:()=>A1,ViTMSNPreTrainedModel:()=>pl,ViTModel:()=>v1,ViTPreTrainedModel:()=>ul,VisionEncoderDecoderModel:()=>b1,VitMatteForImageMatting:()=>T1,VitMattePreTrainedModel:()=>bp,VitPoseForPoseEstimation:()=>S1,VitPosePreTrainedModel:()=>vp,VitsModel:()=>O1,VitsModelOutput:()=>kp,VitsPreTrainedModel:()=>Ep,VoxtralForConditionalGeneration:()=>I1,VoxtralRealtimeForConditionalGeneration:()=>fl,VoxtralRealtimePreTrainedModel:()=>Ap,Wav2Vec2BertForCTC:()=>L1,Wav2Vec2BertForSequenceClassification:()=>N1,Wav2Vec2BertModel:()=>z1,Wav2Vec2BertPreTrainedModel:()=>Zn,Wav2Vec2ForAudioFrameClassification:()=>Px,Wav2Vec2ForCTC:()=>Ix,Wav2Vec2ForSequenceClassification:()=>Cx,Wav2Vec2Model:()=>Ox,Wav2Vec2PreTrainedModel:()=>er,WavLMForAudioFrameClassification:()=>B1,WavLMForCTC:()=>R1,WavLMForSequenceClassification:()=>D1,WavLMForXVector:()=>F1,WavLMModel:()=>$1,WavLMPreTrainedModel:()=>as,WeSpeakerResNetModel:()=>U1,WeSpeakerResNetPreTrainedModel:()=>Tp,WhisperForConditionalGeneration:()=>Op,WhisperModel:()=>j1,WhisperPreTrainedModel:()=>dl,XLMForQuestionAnswering:()=>X1,XLMForSequenceClassification:()=>V1,XLMForTokenClassification:()=>H1,XLMModel:()=>q1,XLMPreTrainedModel:()=>is,XLMRobertaForMaskedLM:()=>Y1,XLMRobertaForQuestionAnswering:()=>Z1,XLMRobertaForSequenceClassification:()=>Q1,XLMRobertaForTokenClassification:()=>J1,XLMRobertaModel:()=>K1,XLMRobertaPreTrainedModel:()=>ls,XLMWithLMHeadModel:()=>W1,XVectorOutput:()=>Mp,YolosForObjectDetection:()=>tv,YolosModel:()=>ev,YolosObjectDetectionOutput:()=>Ip,YolosPreTrainedModel:()=>_l,YoutuForCausalLM:()=>sv,YoutuModel:()=>rv,YoutuPreTrainedModel:()=>ml});var Ns=class extends y{},Th=class extends Ns{},Sh=class extends Ns{async _call(e){return new q(await super._call(e))}},Oh=class extends Ns{async _call(e){return new Te(await super._call(e))}},Ih=class extends Ns{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{},zh=class extends ta{},Lh=class extends ta{};var ra=class extends y{},Nh=class extends ra{},$h=class extends ra{};var sa=class extends y{},Rh=class extends sa{},Dh=class extends sa{};var zn=class extends y{},Fh=class extends zn{},Bh=class extends zn{},Uh=class extends zn{async _call(e){return new q(await super._call(e))}};var na=class extends y{},jh=class extends na{},Gh=class extends na{async _call(e){return new q(await super._call(e))}};var Xr=class extends y{},qh=class extends Xr{},Wh=class extends Xr{async _call(e){return new we(await super._call(e))}},Vh=class extends Xr{async _call(e){return new q(await super._call(e))}},Hh=class extends Xr{async _call(e){return new ge(await super._call(e))}},Xh=class extends Xr{async _call(e){return new Te(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 Kr=class extends y{},tg=class extends Kr{},rg=class extends Kr{async _call(e){return new we(await super._call(e))}},sg=class extends Kr{async _call(e){return new q(await super._call(e))}},ng=class extends Kr{async _call(e){return new ge(await super._call(e))}},og=class extends Kr{async _call(e){return new Te(await super._call(e))}};var RN=4299n,MM=6561n,Pu=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 Pu{async encode_speech(e){return ue(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,audio_features:p=null,audio_tokens:f=null,speaker_embeddings:_=null,speaker_features:m=null,...w}){let x;if(!a){let A=this.sessions.embed_tokens.inputNames,E={input_ids:e};if(A.includes("exaggeration")){if(!(n instanceof N)){let S=e.dims[0];if(n==null)n=Qe([S],.5);else if(typeof n=="number")n=Qe([S],n);else if(Array.isArray(n))n=new N("float32",n,[S]);else throw new Error("Unsupported type for `exaggeration` input")}E.exaggeration=n}if(A.includes("position_ids")&&(E.position_ids=o),{inputs_embeds:a}=await ue(this.sessions.embed_tokens,E),p&&f&&_&&m&&(x={audio_features:p,audio_tokens:f,speaker_embeddings:_,speaker_features:m}),x||s)x??=await this.encode_speech(s),a=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 T=i.get_seq_length();r=et([a.dims[0],T+S])}}return{...await It(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==MM)-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>=MM?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),Cn(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=Qe([a.dims[0],3],RN),l=ve([s,a,i],1),{waveform:c}=await ue(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var zu=class extends y{},ag=class extends zu{};var Lu=class extends y{},ig=class extends Lu{};var Ln=class extends y{},lg=class extends Ln{},ca=class extends Ln{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},ua=class extends Ln{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var pr=class extends y{},cg=class extends pr{},ug=class extends pr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},pa=class extends pr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},pg=class extends pr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},fg=class extends pr{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{},_g=class extends fa{};var da=class extends y{},mg=class extends da{},hg=class extends da{};var _a=class extends y{},gg=class extends _a{},wg=class extends _a{};var ma=class extends y{},xg=class extends ma{},yg=class extends ma{};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 Yr=class extends y{},kg=class extends Yr{},Eg=class extends Yr{async _call(e){return new we(await super._call(e))}},Ag=class extends Yr{async _call(e){return new q(await super._call(e))}},Mg=class extends Yr{async _call(e){return new ge(await super._call(e))}},Tg=class extends Yr{async _call(e){return new Te(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{},zg=class extends xa{async _call(e){return new fr(await super._call(e))}},fr=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var ya=class extends y{},Lg=class extends ya{},Ng=class extends ya{async _call(e){return new fr(await super._call(e))}};var Nu=class extends Re{constructor({audio_codes:e}){super(),this.audio_codes=e}},$u=class extends Re{constructor({audio_values:e}){super(),this.audio_values=e}},Nn=class extends y{main_input_name="input_values";forward_params=["input_values"]},$g=class extends Nn{async encode(e){return new Nu(await ue(this.sessions.encoder_model,e))}async decode(e){return new $u(await ue(this.sessions.decoder_model,e))}},ba=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},va=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Qr=class extends y{},Rg=class extends Qr{},Dg=class extends Qr{async _call(e){return new we(await super._call(e))}},Fg=class extends Qr{async _call(e){return new q(await super._call(e))}},Bg=class extends Qr{async _call(e){return new ge(await super._call(e))}},Ug=class extends Qr{async _call(e){return new Te(await super._call(e))}};var ka=class extends y{},jg=class extends ka{},Gg=class extends ka{};var Jr=class extends y{},qg=class extends Jr{},Wg=class extends Jr{async _call(e){return new we(await super._call(e))}},Vg=class extends Jr{async _call(e){return new q(await super._call(e))}},Hg=class extends Jr{async _call(e){return new ge(await super._call(e))}},Xg=class extends Jr{async _call(e){return new Te(await super._call(e))}};var Ru=class extends y{},Kg=class extends Ru{};var Ea=class extends y{},Yg=class extends Ea{},Qg=class extends Ea{async _call(e){return new q(await super._call(e))}};var Du=class extends y{},Jg=class extends Du{};var Fu=class extends y{},Zg=class extends Fu{};var $n=class extends y{},ew=class extends $n{},tw=class extends $n{async _call(e){return new Rn(await super._call(e))}},rw=class extends $n{async _call(e){return new Bu(await super._call(e))}},Rn=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},Bu=class extends Re{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var Aa=class extends y{},sw=class extends Aa{},nw=class extends Aa{async _call(e){return new q(await super._call(e))}};var Ma=class extends y{},ow=class extends Ma{},aw=class extends Ma{async _call(e){return new q(await super._call(e))}};var Uu=class extends y{},iw=class extends Uu{};var ju=class extends y{},lw=class extends ju{};var Zr=class extends y{},cw=class extends Zr{},uw=class extends Zr{async _call(e){return new q(await super._call(e))}},pw=class extends Zr{async _call(e){return new ge(await super._call(e))}},fw=class extends Zr{async _call(e){return new Te(await super._call(e))}},dw=class extends Zr{async _call(e){return new we(await super._call(e))}};var Gu=class extends y{},_w=class extends Gu{};var Ta=class extends y{},mw=class extends Ta{},hw=class extends Ta{};var Sa=class extends y{},gw=class extends Sa{},ww=class extends Sa{async _call(e){return new q(await super._call(e))}};var es=class extends y{},xw=class extends es{},yw=class extends es{async _call(e){return new we(await super._call(e))}},bw=class extends es{async _call(e){return new q(await super._call(e))}},vw=class extends es{async _call(e){return new ge(await super._call(e))}},kw=class extends es{async _call(e){return new Te(await super._call(e))}};var Oa=class extends y{},Ew=class extends Oa{},Aw=class extends Oa{};var $s=class extends y{},Mw=class extends $s{},Tw=class extends $s{async _call(e){return new we(await super._call(e))}},Sw=class extends $s{async _call(e){return new q(await super._call(e))}},Ow=class extends $s{async _call(e){return new ge(await super._call(e))}};var Rs=class extends y{},Iw=class extends Rs{},Cw=class extends Rs{async _call(e){return new we(await super._call(e))}},Pw=class extends Rs{async _call(e){return new q(await super._call(e))}},zw=class extends Rs{async _call(e){return new ge(await super._call(e))}};var Ia=class extends y{},Lw=class extends Ia{},Nw=class extends Ia{};var Ca=class extends y{},$w=class extends Ca{},Rw=class extends Ca{};var Pa=class extends y{},Dw=class extends Pa{},Fw=class extends Pa{};var za=class extends y{},Bw=class extends za{},Uw=class extends za{async _call(e){return new q(await super._call(e))}};var qu=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"},jw=class extends qu{_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 Gt(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 It(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var La=class extends y{},Gw=class extends La{},qw=class extends La{};var Na=class extends y{},Ww=class extends Na{},Vw=class extends Na{};var Wu=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},kt=class extends Wu{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Pn({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},Hw=class extends kt{},Xw=class extends kt{};var Vu=class extends y{},Kw=class extends Vu{},Hu=class extends kt{},Yw=class extends Hu{};var Xu=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"]},ts=class extends Xu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:f=null,..._}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await ue(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:w}=await this._encode_vision({pixel_values:s,..._});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:w}=await ue(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await It(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,attention_mask:r,position_ids:a,generation_config:p,logits_processor:f},!0)}_encode_vision(e){return ue(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Pn({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 Cu({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},Qw=class extends ts{};var Dn=class extends ts{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(e){return ue(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},Jw=class extends Dn{};var $a=class extends y{},Zw=class extends $a{},ex=class extends $a{};var Ra=class extends y{},tx=class extends Ra{},rx=class extends Ra{};var Ku=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Fn=class extends Ku{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,r){if(r){let{data:s,dims:n}=Mh(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]),Dd([s,1])]}}_reorder_and_write_positions(e,r,s,n){let o=e.reduce((c,p)=>c+p.length,0),a=new Array(o),i=0;for(let c=0;c<3;++c)for(let p of e){let f=p.length/3;for(let _=c*f;_<(c+1)*f;++_)a[i++]=p[_]}let l=0;for(let c=0;c(S==l&&E.push(T),E),[]).map(E=>c[E+1]),_=f.filter(E=>E==a).length,m=f.filter(E=>E==i).length,w=[],x=0,k=_,A=m;for(let E=0;Ele>x&&Q==a),T=c.findIndex((Q,le)=>le>x&&Q==i),I=k>0&&S!==-1?S:c.length+1,O=A>0&&T!==-1?T:c.length+1,b,F,j,U;I0?Pe(w.at(-1))[0]+1:0;w.push(Array.from({length:3*R},(Q,le)=>C+le%R));let se=R+C,Y=X*K*J,z=Array.from({length:Y},(Q,le)=>se+Math.floor(le/(K*J))),$=Array.from({length:Y},(Q,le)=>se+Math.floor(le/J)%K),B=Array.from({length:Y},(Q,le)=>se+le%J);w.push([z,$,B].flat()),x=b+Y}if(x0?Pe(w.at(-1))[0]+1:0,S=c.length-x;w.push(Array.from({length:3*S},(T,I)=>E+I%S))}return w}get_rope_index(e,r,s,n){let{vision_config:o}=this.config,a=o.spatial_merge_size??2;if(r||s){let i=e.tolist();n||(n=Dc(e));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),p=r?r.tolist():[],f=s?s.tolist():[],_={image_index:0,video_index:0},m=[];for(let w=0;wl[w][S]==1),k=this._get_multimodal_rope_positions({filtered_ids:x,image_grid_thw_list:p,video_grid_thw_list:f,spatial_merge_size:a,state:_}),A=this._reorder_and_write_positions(k,l[w],c,w);m.push(Pe(A)[0]+1-i[w].length)}return[new N("int64",c.flat(1/0),[3,e.dims[0],e.dims[1]]),new N("int64",m,[m.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:r}){return(await ue(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(e){return Pn({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=xt([i,i,i],0)}}return r}},Da=class extends Fn{};var Ds=class extends Fn{image_grid_thw_name="image_grid_thw"},Fa=class extends Da{image_grid_thw_name="image_grid_thw"};var sx=class extends Ds{get_vision_position_ids(e,r,s,n){let o=Math.floor(r[0]/s),a=Math.floor(r[1]/n),i=Math.floor(r[2]/n),l=a*i*o,c=Array.from({length:l},()=>e),p=Array.from({length:l},(_,m)=>e+Math.floor(m/(i*o))),f=Array.from({length:l},(_,m)=>e+m%i);return[...c,...p,...f]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:o}){let{image_token_id:a}=this.config,i=[],l=0,c=e[0]==a?1:0;for(let _=1;_<=e.length;++_){let m=_p+A%x)),p+=x}else{let x=r[o.image_index++].map(Number),k=x[0];f.push(this.get_vision_position_ids(p,x,k,n)),p+=Math.max(x[1],x[2])/n}return f}};var Ba=class extends y{},nx=class extends Ba{},ox=class extends Ba{};var Ua=class extends y{},ax=class extends Ua{},ix=class extends Ua{};var ja=class extends y{},lx=class extends ja{},cx=class extends ja{};var Ga=class extends y{},ux=class extends Ga{},px=class extends Ga{};var qa=class extends y{},fx=class extends qa{},dx=class extends qa{};var Wa=class extends y{},_x=class extends Wa{},mx=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 Yu=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Fs=class extends Yu{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return Cu({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 Fs{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var Qu=class extends y{},kx=class extends Qu{};var Ju=class extends y{},Ex=class extends Ju{};var Ka=class extends y{},Ax=class extends Ka{},Mx=class extends Ka{};var Ya=class extends y{},Tx=class extends Ya{},Sx=class extends Ya{async _call(e){return new q(await super._call(e))}};var er=class extends y{},Ox=class extends er{},Ix=class extends er{async _call(e){return new vt(await super._call(e))}},Cx=class extends er{async _call(e){return new q(await super._call(e))}},Px=class extends er{async _call(e){return new ge(await super._call(e))}};var zx=class extends y{},Lx=class extends er{},Nx=class extends er{async _call(e){return new vt(await super._call(e))}},$x=class extends er{async _call(e){return new q(await super._call(e))}};var Qa=class extends y{},Rx=class extends Qa{},Dx=class extends Qa{};var Ja=class extends kt{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var Za=class extends y{},Fx=class extends Za{},Bx=class extends Za{async _call(e){return new q(await super._call(e))}};var ei=class extends y{},Ux=class extends ei{},jx=class extends ei{};var Bn=class extends y{},Gx=class extends Bn{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=Qe([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}},ti=class extends Bn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},qx=class extends Bn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var ri=class extends y{},Wx=class extends ri{},Vx=class extends ri{};var Hx=class extends kt{};var si=class extends y{},Xx=class extends si{},Kx=class extends si{};var Yx=class extends kt{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var ni=class extends y{},Qx=class extends ni{},Jx=class extends ni{};var Zu=class extends y{},Zx=class extends Zu{};var oi=class extends y{},ey=class extends oi{},ty=class extends oi{};var ai=class extends y{},ry=class extends ai{},sy=class extends ai{};var ii=class extends y{},ny=class extends ii{},oy=class extends ii{};var li=class extends y{},ay=class extends li{},iy=class extends li{};var Bs=class extends y{},ly=class extends Bs{},cy=class extends Bs{},uy=class extends Bs{async _call(e){return new q(await super._call(e))}},py=class extends Bs{};var ep=class extends y{},fy=class extends ep{};var tp=class extends y{},dy=class extends tp{};var rp=class extends Re{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},sp=class extends y{},_y=class extends sp{async _call(e){return new rp(await super._call(e))}};var np=class extends Re{constructor({audio_codes:e}){super(),this.audio_codes=e}},op=class extends Re{constructor({audio_values:e}){super(),this.audio_values=e}},Un=class extends y{main_input_name="input_values";forward_params=["input_values"]},my=class extends Un{async encode(e){return new np(await ue(this.sessions.encoder_model,e))}async decode(e){return new op(await ue(this.sessions.decoder_model,e))}},ci=class extends Un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ui=class extends Un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var pi=class extends y{},hy=class extends pi{},gy=class extends pi{};var fi=class extends y{},wy=class extends fi{},xy=class extends fi{};var Us=class extends y{},yy=class extends Us{},by=class extends Us{async _call(e){return new we(await super._call(e))}},vy=class extends Us{async _call(e){return new q(await super._call(e))}},ky=class extends Us{async _call(e){return new Te(await super._call(e))}};var di=class extends y{},Ey=class extends di{},Ay=class extends di{};var jn=class extends y{},My=class extends jn{},Ty=class extends jn{async _call(e){return new q(await super._call(e))}},Sy=class extends jn{};var Gn=class extends y{},Oy=class extends Gn{},Iy=class extends Gn{async _call(e){return new q(await super._call(e))}},Cy=class extends Gn{};var qn=class extends y{},Py=class extends qn{},zy=class extends qn{async _call(e){return new q(await super._call(e))}},Ly=class extends qn{};var Wn=class extends y{},Ny=class extends Wn{},$y=class extends Wn{async _call(e){return new q(await super._call(e))}},Ry=class extends Wn{};var _i=class extends y{},Dy=class extends _i{},Fy=class extends _i{async _call(e){return new q(await super._call(e))}};var mi=class extends y{},By=class extends mi{},Uy=class extends mi{async _call(e){return new q(await super._call(e))}};var js=class extends y{},jy=class extends js{},Gy=class extends js{async _call(e){return new we(await super._call(e))}},qy=class extends js{async _call(e){return new q(await super._call(e))}},Wy=class extends js{async _call(e){return new ge(await super._call(e))}};var hi=class extends y{},Vy=class extends hi{},Hy=class extends hi{};var gi=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Xy=class extends gi{},Ky=class extends gi{};var rs=class extends y{},Yy=class extends rs{},Qy=class extends rs{async _call(e){return new we(await super._call(e))}},Jy=class extends rs{async _call(e){return new q(await super._call(e))}},Zy=class extends rs{async _call(e){return new ge(await super._call(e))}},e0=class extends rs{async _call(e){return new Te(await super._call(e))}};var wi=class extends y{},t0=class extends wi{},r0=class extends wi{};var xi=class extends y{},s0=class extends xi{},n0=class extends xi{};var ap=class extends y{},o0=class extends ap{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){let r=this._generation_mode??"text",s;if(r==="text"||!e.past_key_values){let l=this.sessions.prepare_inputs_embeds,c=Ve(e,l.inputNames);s=await ue(l,c)}else{let l=this.sessions.gen_img_embeds,c=Ve({image_ids:e.input_ids},l.inputNames);s=await ue(l,c)}let n={...e,...s},o=await It(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await ue(a,Ve(o,a.inputNames));return{...s,...o,...i}}prepare_inputs_for_generation(e,r,s){let n=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=ve([r.input_ids,r.input_ids],0):(r.input_ids=ve([r.input_ids,Co(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=ve([r.attention_mask,Co(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Qe([0,0,3,384,384],1)),n&&(r.images_seq_mask=new N("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new N("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let r=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[r,null]),o=this.sessions.image_decode,{decoded_image:a}=await ue(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let p=Je.fromTensor(c);l.push(p)}return l}};var yi=class extends y{},a0=class extends yi{},i0=class extends yi{},bi=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[r,s]=e.dims,n=this.config.decoder.num_codebooks,o=s-n,a=0;for(let c=0;c0&&_<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new N(e.type,e.data.slice(0,a),[i,n,l])}prepare_inputs_for_generation(e,r,s){let n=BigInt(this.config.decoder.pad_token_id),o=structuredClone(e);for(let a=0;a=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),Jo(this,o,r,s)}async generate(e){let r=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await ue(this.sessions.encodec_decode,{audio_codes:s});return n}};var vi=class extends y{},l0=class extends vi{},c0=class extends vi{};var ki=class extends y{},u0=class extends ki{},p0=class extends ki{};var ss=class extends y{},f0=class extends ss{},d0=class extends ss{async _call(e){return new we(await super._call(e))}},_0=class extends ss{async _call(e){return new q(await super._call(e))}},m0=class extends ss{async _call(e){return new ge(await super._call(e))}},h0=class extends ss{async _call(e){return new Te(await super._call(e))}};var ip=class extends y{},g0=class extends ip{};var Ei=class extends y{},w0=class extends Ei{},x0=class extends Ei{};var Ai=class extends y{},y0=class extends Ai{},b0=class extends Ai{};var Mi=class extends y{},v0=class extends Mi{},k0=class extends Mi{};var Ti=class extends y{},E0=class extends Ti{},A0=class extends Ti{};var Si=class extends y{},M0=class extends Si{},T0=class extends Si{async _call(e){return new q(await super._call(e))}};var Oi=class extends y{},S0=class extends Oi{},O0=class extends Oi{};var Ii=class extends y{},I0=class extends Ii{},C0=class extends Ii{};var Ci=class extends y{},P0=class extends Ci{},z0=class extends Ci{};var Pi=class extends y{},L0=class extends Pi{},N0=class extends Pi{};var $0=class extends kt{};var lp=class extends y{},R0=class extends lp{async _call(e){return new vt(await super._call(e))}};var zi=class extends y{},D0=class extends zi{},F0=class extends zi{};var Li=class extends y{},B0=class extends Li{},U0=class extends Li{};var Ni=class extends y{},j0=class extends Ni{},G0=class extends Ni{};var $i=class extends y{},q0=class extends $i{},W0=class extends $i{};var cp=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Ri=class extends cp{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,...p}){if(!a){let _;if(s&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:_}=await ue(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let m=this.config.normalized_config.hidden_size;_=new N("float32",[],[0,m])}({inputs_embeds:a}=await ue(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:_}))}return await It(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var Di=class extends y{},V0=class extends Di{},H0=class extends Di{async _call(e){return new q(await super._call(e))}};var Fi=class extends y{},X0=class extends Fi{},K0=class extends Fi{async _call(e){return new ge(await super._call(e))}};var Bi=class extends y{},Y0=class extends Bi{},Q0=class extends Bi{};var Ui=class extends y{},J0=class extends Ui{},Z0=class extends Ui{};var ji=class extends y{},eb=class extends ji{},tb=class extends ji{};var Gi=class extends y{},rb=class extends Gi{},sb=class extends Gi{};var qi=class extends y{},nb=class extends qi{},ob=class extends qi{};var Gs=class extends Ds{},Wi=class extends Fa{};var ab=class extends Gs{},ib=class extends Wi{};var Vn=class extends Gs{},Vi=class extends Vn{};var lb=class extends Vn{},cb=class extends Vi{};var Hi=class extends y{},ub=class extends Hi{},pb=class extends Hi{async _call(e){return new q(await super._call(e))}};var Xi=class extends y{},fb=class extends Xi{},db=class extends Xi{async _call(e){return new up(await super._call(e))}},up=class extends fr{};var ns=class extends y{},_b=class extends ns{},mb=class extends ns{async _call(e){return new we(await super._call(e))}},hb=class extends ns{async _call(e){return new q(await super._call(e))}},gb=class extends ns{async _call(e){return new ge(await super._call(e))}},wb=class extends ns{async _call(e){return new Te(await super._call(e))}};var os=class extends y{},xb=class extends os{},yb=class extends os{async _call(e){return new we(await super._call(e))}},bb=class extends os{async _call(e){return new q(await super._call(e))}},vb=class extends os{async _call(e){return new ge(await super._call(e))}},kb=class extends os{async _call(e){return new Te(await super._call(e))}};var Ki=class extends y{},Eb=class extends Ki{},Ab=class extends Ki{async _call(e){return new pp(await super._call(e))}},pp=class extends fr{};var fp=class extends Re{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},dp=class extends y{},Mb=class extends dp{async get_image_embeddings({pixel_values:e}){return await Gt(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 ue(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new fp(await super._call(e))}};var _p=class extends Re{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},mp=class extends y{},Yi=class extends mp{async get_image_embeddings({pixel_values:e}){return await Gt(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??=Qe([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Qe([a[0],a[1],0],-1n),e.input_points=Qe([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,o=Ve(e,n.inputNames);return await ue(n,o)}async _call(e){return new _p(await super._call(e))}},Tb=class extends Yi{},Sb=class extends Yi{};var Hn=class extends y{},Ob=class extends Hn{},Ib=class extends Hn{},Cb=class extends Hn{};var Xn=class extends y{},Pb=class extends Xn{},zb=class extends Xn{},Lb=class extends Xn{};var Qi=class extends y{},Nb=class extends Qi{},Ji=class extends Qi{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},$b=class extends pr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Zi=class extends y{},Rb=class extends Zi{},Db=class extends Zi{};var Fb=class extends Ja{};var Kn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Bb=class extends Kn{async encode(e){return await ue(this.sessions.encoder_model,e)}async decode(e){return await ue(this.sessions.decoder_model,e)}},el=class extends Kn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},tl=class extends Kn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var rl=class extends y{},Ub=class extends rl{},jb=class extends rl{};var Yn=class extends y{},Gb=class extends Yn{},qb=class extends Yn{},Wb=class extends Yn{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 Gt(this,i),p=l.dims[1]/this.config.reduction_factor,f=Math.floor(p*o),_=Math.floor(p*n),m=this.config.num_mel_bins,w=[],x=null,k=null,A=0;for(;;){++A;let T=Eh(!!k),I;k?I=k.output_sequence_out:I=new N("float32",new Float32Array(m),[1,1,m]);let O={use_cache_branch:T,output_sequence:I,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};Zo(this,O,x),k=await ue(this.sessions.decoder_model_merged,O),x=Ou(k,x);let{prob:b,spectrum:F}=k;if(w.push(F),A>=_&&(Array.from(b.data).filter(j=>j>=s).length>0||A>=f))break}let E=ve(w),{waveform:S}=await ue(a.sessions.model,{spectrogram:E});return{spectrogram:E,waveform:S}}},Vb=class extends y{main_input_name="spectrogram"};var qs=class extends y{},Hb=class extends qs{},Xb=class extends qs{async _call(e){return new we(await super._call(e))}},Kb=class extends qs{async _call(e){return new q(await super._call(e))}},Yb=class extends qs{async _call(e){return new Te(await super._call(e))}};var sl=class extends y{},Qb=class extends sl{},Jb=class extends sl{};var nl=class extends y{},Zb=class extends nl{},e1=class extends nl{};var hp=class extends y{},t1=class extends hp{};var gp=class extends y{},ol=class extends gp{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:c}=this.config,{last_hidden_state:p,durations:f}=await ue(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),_=f.div(o).mul_(a),m=l*i,w=_.data,x=Int32Array.from(w,U=>Math.ceil(U/m)),k=Math.max(...x),A=e.dims[0],E=new BigInt64Array(A*k);for(let U=0;US*T,1),E=Gr[x.type];l[x.name]=new N(x.type,new E(A),k)}let _=Gr[f],m=new N(f,new _(i*TM),[1,i,TM]),w=e[Symbol.asyncIterator]?.()??e[Symbol.iterator]?.();if(!w)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:m,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:w,text_hidden_size:r.hidden_size}}async function BN(t,e){let r=e.dims[2],s=Math.floor((DN+r-3)/2)+1,n=new N("int64",BigInt64Array.from({length:s},(p,f)=>BigInt(t.enc_past_seq_len+f)),[1,s]),o=t.enc_past_seq_len+s,a=et([1,o]),{audio_embeds:i,present_padding_cache:l,...c}=await ue(t.encoder_session,{input_features:e,attention_mask:a,position_ids:n,past_padding_cache:t.enc_padding_cache,...t.enc_kv_cache});t.enc_padding_cache.location==="gpu-buffer"&&t.enc_padding_cache.dispose(),t.enc_padding_cache=l;for(let p in c)if(p.startsWith("present.")){let f=p.replace("present","past_key_values"),_=t.enc_kv_cache[f];_?.location==="gpu-buffer"&&_.dispose(),t.enc_kv_cache[f]=c[p]}return t.enc_past_seq_len=o,i}async function UN(t,e){for(;t.audio_embed_total_tokens0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let p=0;p=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var P1=class extends Hr{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)}},Ap=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},fl=class extends Ap{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=C1.get(this);o&&await UN(o,o.audio_consumed+n);let{inputs_embeds:a}=await ue(this.sessions.embed_tokens,{input_ids:e});o&&jN(o,a,n);let i={inputs_embeds:a,...s};Zo(this,i,r);let l=this.sessions.decoder_model_merged,c=Ve(i,l.inputNames);return await ue(l,c)}async generate({input_features:e,stopping_criteria:r,...s}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let n=FN(this,e);C1.set(this,n);let o=new Tn;o.push(new P1(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),C1.delete(this)}}};var Zn=class extends y{},z1=class extends Zn{},L1=class extends Zn{async _call(e){return new vt(await super._call(e))}},N1=class extends Zn{async _call(e){return new q(await super._call(e))}};var Mp=class extends Re{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},as=class extends y{},$1=class extends as{},R1=class extends as{async _call(e){return new vt(await super._call(e))}},D1=class extends as{async _call(e){return new q(await super._call(e))}},F1=class extends as{async _call(e){return new Mp(await super._call(e))}},B1=class extends as{async _call(e){return new ge(await super._call(e))}};var Tp=class extends y{},U1=class extends Tp{};var Sp=class extends Mn{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 dl=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"]},j1=class extends dl{},Op=class extends dl{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,Sp)}_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=`<|${eM(s)}|>`;r.push(e.lang_to_id[a]),r.push(e.task_to_id[n??"transcribe"])}else if(s||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(ee.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,...o}){r=this._prepare_generation_config(r,o);let a=o.decoder_input_ids instanceof N?Po(o.decoder_input_ids):o.decoder_input_ids??this._retrieve_init_tokens(r);if(r.return_timestamps&&(s??=new Cs,s.push(new gu(r,a))),r.begin_suppress_tokens&&(s??=new Cs,s.push(new An(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");r.task==="translate"&&ee.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}if(r.return_timestamps&&!o.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:a,kwargs:o});let i=await super.generate({inputs:e,generation_config:r,logits_processor:s,decoder_input_ids:a,...o});return r.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,r.alignment_heads,r.num_frames,.02,a.length)),i}async _generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:n,kwargs:o}){let a=r.no_timestamps_token_id+1,i=Array.isArray(r.eos_token_id)?r.eos_token_id[0]:r.eos_token_id,l=r.return_token_timestamps,c=e,p=c.dims[2],f=2,_=this.config.max_source_positions,m=f*_,w=0,x=[],k=[];for(;wz+Y)}if(F.length>0&&F.at(-1)===i&&F.pop(),F.length===0)break;let U=F.map(Y=>Y>=a),X=F.length>=2&&U[F.length-1]&&!U[F.length-2],K=[];for(let Y=0;Y0)if(X)J=E-w;else{let Y=K.at(-1);J=(F[Y-1]-a)*f,R=Y}else J=E-w;let C=Math.floor(w/f),se=a+1500;for(let Y=0;Y=a&&(F[Y]=Math.min(F[Y]+C,se));x.push(...F.slice(0,R)),j&&k.push(...j.slice(0,R)),w+=J}x.push(i);let A=[...n,...x];if(l){let E=new N("int64",A.map(BigInt),[1,A.length]),S=[...new Array(n.length).fill(0),...k,0],T=new N("float32",new Float32Array(S),[1,S.length]);return{sequences:E,token_timestamps:T}}return new N("int64",A.map(BigInt),[1,A.length])}_extract_token_timestamps(e,r,s=null,n=.02,o=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");s==null&&ee.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(ee.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let i=e.cross_attentions,l=Array.from({length:this.config.decoder_layers},(A,E)=>ve(i.map(S=>S[E]),2)),c=xt(r.map(([A,E])=>{if(A>=l.length)throw new Error(`Layer index ${A} is out of bounds for cross attentions (length ${l.length}).`);return s?l[A].slice(null,E,null,[0,s]):l[A].slice(null,E)})).transpose(1,0,2,3),[p,f]=$d(c,-2,0,!0),_=c.clone();for(let A=0;A<_.dims[0];++A){let E=_[A];for(let S=0;S0?_.slice(null,null,[o,_.dims[2]],null):_,w=[Rc(m,1)],x=e.sequences.dims,k=new N("float32",new Float32Array(x[0]*x[1]),x);for(let A=0;AS[U+1]-S[U]),O=gt([1],I).map(j=>!!j),b=[];for(let j=0;j0&&F.push(b.at(-1)),k[A].data.set(F)}return k}},G1=class extends Op{};var is=class extends y{},q1=class extends is{},W1=class extends is{async _call(e){return new we(await super._call(e))}},V1=class extends is{async _call(e){return new q(await super._call(e))}},H1=class extends is{async _call(e){return new ge(await super._call(e))}},X1=class extends is{async _call(e){return new Te(await super._call(e))}};var ls=class extends y{},K1=class extends ls{},Y1=class extends ls{async _call(e){return new we(await super._call(e))}},Q1=class extends ls{async _call(e){return new q(await super._call(e))}},J1=class extends ls{async _call(e){return new ge(await super._call(e))}},Z1=class extends ls{async _call(e){return new Te(await super._call(e))}};var _l=class extends y{},ev=class extends _l{},tv=class extends _l{async _call(e){return new Ip(await super._call(e))}},Ip=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var ml=class extends y{},rv=class extends ml{},sv=class extends ml{};var GN=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"]]),qN=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"]]),WN=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),VN=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"]]),SM=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),OM=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),IM=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),CM=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"]]),PM=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),zM=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),LM=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"]]),HN=new Map([["multi_modality","MultiModalityCausalLM"]]),NM=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"]]),$M=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"]]),RM=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),DM=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"]]),FM=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),XN=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),BM=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"]]),UM=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),jM=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),eo=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),GM=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),qM=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),WM=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),VM=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),HM=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),XM=new Map([["wavlm","WavLMForXVector"]]),KM=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),YM=new Map([["vitmatte","VitMatteForImageMatting"]]),KN=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),QM=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),JM=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),ZM=new Map([["sapiens","SapiensForNormalEstimation"]]),eT=new Map([["vitpose","VitPoseForPoseEstimation"]]),tT=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),nv=[[GN,V.EncoderOnly],[qN,V.EncoderDecoder],[VN,V.DecoderOnlyWithoutHead],[WN,V.AutoEncoder],[CM,V.EncoderOnly],[PM,V.EncoderOnly],[zM,V.Seq2Seq],[SM,V.Seq2Seq],[LM,V.DecoderOnly],[HN,V.MultiModality],[NM,V.EncoderOnly],[$M,V.EncoderOnly],[RM,V.Vision2Seq],[DM,V.ImageTextToText],[FM,V.AudioTextToText],[BM,V.EncoderOnly],[eo,V.EncoderOnly],[qM,V.EncoderOnly],[GM,V.EncoderOnly],[YM,V.EncoderOnly],[KN,V.EncoderOnly],[QM,V.EncoderOnly],[JM,V.EncoderOnly],[ZM,V.EncoderOnly],[eT,V.EncoderOnly],[UM,V.EncoderOnly],[jM,V.EncoderOnly],[WM,V.MaskGeneration],[VM,V.EncoderOnly],[HM,V.EncoderOnly],[OM,V.Seq2Seq],[IM,V.EncoderOnly],[XM,V.EncoderOnly],[KM,V.EncoderOnly],[tT,V.EncoderOnly]];for(let[t,e]of nv)for(let r of t.values()){Zt.set(r,e);let s=hl[r];Ls.set(s,r),Iu.set(r,s)}var YN=[["MusicgenForConditionalGeneration",bi,V.Musicgen],["Phi3VForCausalLM",Ri,V.Phi3V],["CLIPTextModelWithProjection",pa,V.EncoderOnly],["SiglipTextModel",Ji,V.EncoderOnly],["JinaCLIPTextModel",ti,V.EncoderOnly],["ClapTextModelWithProjection",ca,V.EncoderOnly],["ClapAudioModelWithProjection",ua,V.EncoderOnly],["DacEncoderModel",ba,V.EncoderOnly],["DacDecoderModel",va,V.EncoderOnly],["MimiEncoderModel",ci,V.EncoderOnly],["MimiDecoderModel",ui,V.EncoderOnly],["SnacEncoderModel",el,V.EncoderOnly],["SnacDecoderModel",tl,V.EncoderOnly],["Gemma3nForConditionalGeneration",ts,V.ImageAudioTextToText],["Gemma4ForConditionalGeneration",Dn,V.ImageAudioTextToText],["SupertonicForConditionalGeneration",ol,V.Supertonic],["ChatterboxModel",la,V.Chatterbox],["VoxtralRealtimeForConditionalGeneration",fl,V.VoxtralRealtime]];for(let[t,e,r]of YN)Zt.set(t,r),Ls.set(e,t),Iu.set(t,e);var rT=new Map([["modnet",eo],["birefnet",eo],["isnet",eo],["ben",eo]]);for(let[t,e]of rT.entries())e.set(t,"PreTrainedModel"),Zt.set(t,V.EncoderOnly),Iu.set(t,y);var sT=new Set(rT.keys());Zt.set("PreTrainedModel",V.EncoderOnly);Ls.set(y,"PreTrainedModel");var Le={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:CM,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:PM,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:OM,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:IM,MODEL_FOR_MASKED_LM_MAPPING_NAMES:NM,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:$M,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:BM,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:eo,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:GM,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:qM,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:UM,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:jM,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:WM,MODEL_FOR_CTC_MAPPING_NAMES:VM,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:HM,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:XM,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:KM,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:XN,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:YM,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:QM,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:JM,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:ZM,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:eT,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:tT,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:DM,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:FM,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:zM,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:SM,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:LM,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:RM};kM(Le);var Ce=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let r of this.MODEL_CLASS_MAPPINGS)if(r.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:p=null,use_external_data_format:f=null,session_options:_={}}={}){let m={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:p,use_external_data_format:f,session_options:_};if(m.config=await jt.from_pretrained(e,m),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:w}=m.config;for(let x of this.MODEL_CLASS_MAPPINGS){let k=x.get(w);if(!k){for(let A of x.values())if(A[0]===w){k=A;break}if(!k)continue}return await hl[k].from_pretrained(e,m)}if(this.BASE_IF_FAIL)return sT.has(w)||ee.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,m);throw Error(`Unsupported model type: ${w}`)}},br=class extends Ce{static MODEL_CLASS_MAPPINGS=nv.map(e=>e[0]);static BASE_IF_FAIL=!0},gl=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},Cp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},to=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},Pp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},zp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},Lp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},Np=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},$p=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},Rp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},Dp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},Fp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},wl=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},xl=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},yl=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},Bp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Up=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},nT=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},jp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_CTC_MAPPING_NAMES]},Gp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},oT=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},aT=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},qp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},iT=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},Wp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},Vp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},lT=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},cT=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},Hp=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},uT=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},pT=class extends Ce{static MODEL_CLASS_MAPPINGS=[Le.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 vr(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?L_(r,e):r instanceof Float64Array?new Float32Array(r):r))}function bl(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 _e=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 vl=class extends _e{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",$e(c.data),c.dims),l=[];for(let c of n.logits){let p=i(c),f=await Jt(p,r),_=f[0].tolist(),w=f[1].tolist().map((x,k)=>({label:a?a[x]:`LABEL_${x}`,score:_[k]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var kl=class extends _e{async _call(e,{ignore_labels:r=["O"],aggregation_strategy:s="none"}={}){if(s!=="none"&&s!=="simple")throw new Error(`Invalid aggregation_strategy: "${s}". Must be one of "none" or "simple".`);let n=Array.isArray(e),o=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(o)).logits,l=this.model.config.id2label,c=[];for(let p=0;p{let l=0,c=[];for(let p=a;pO==f),k=a[m].tolist(),A=i[m].tolist();for(let O=1;Ob==w[O])!==-1)&&(k[O]=-1/0,A[O]=-1/0);let E=$e(k).map((O,b)=>[O,b]),S=$e(A).map((O,b)=>[O,b]);E[0][0]=0,S[0][0]=0;let T=xE(E,S).filter(O=>O[0][1]<=O[1][1]).map(O=>[O[0][1],O[1][1],O[0][0]*O[1][0]]).sort((O,b)=>b[2]-O[2]),I=[];for(let O=0;Ok==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let _=a[c][f],m=await Jt(new N("float32",$e(_.data),_.dims),r),w=m[0].tolist(),x=m[1].tolist();i.push(x.map((k,A)=>{let E=p.slice();return E[f]=k,{score:w[A],token:Number(k),token_str:this.tokenizer.decode([k]),sequence:this.tokenizer.decode(E,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var kr=class extends _e{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,r={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(l=>s[this.task].prefix+l));let n=this.tokenizer,o={padding:!0,truncation:!0},a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,o,r):a=n(e,o);let i=await this.model.generate({...a,...this._default_generation_config,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}};var Ml=class extends kr{_key="summary_text"};var Tl=class extends kr{_key="translation_text"};function fT(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Sl=class extends _e{_default_generation_config={max_new_tokens:256};async _call(e,r={}){let{add_special_tokens:s,return_full_text:n,tools:o,documents:a,chat_template:i,tokenizer_encode_kwargs:l,...c}=r,p=!1,f=!1,_=s??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,m=l,w;if(typeof e=="string")w=e=[e];else if(Array.isArray(e)&&e.every(I=>typeof I=="string"))p=!0,w=e;else{if(fT(e))e=[e];else if(Array.isArray(e)&&e.every(fT))p=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");f=!0;let I={tokenize:!1,add_generation_prompt:!0,...Ve({tools:o,documents:a,chat_template:i},["tools","documents","chat_template"]),...m};w=e.map(O=>this.tokenizer.apply_chat_template(O,I)),_=!1,m=void 0}let x=f?!1:n??!0;this.tokenizer.padding_side="left";let k=this.tokenizer(w,{add_special_tokens:_,padding:!0,truncation:!0,...m}),A=await this.model.generate({...k,...this._default_generation_config,...c}),E=this.tokenizer.batch_decode(A,{skip_special_tokens:!0}),S;!x&&k.input_ids.dims.at(-1)>0&&(S=this.tokenizer.batch_decode(k.input_ids,{skip_special_tokens:!0}).map(I=>I.length));let T=Array.from({length:e.length},I=>[]);for(let I=0;I[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(ee.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(ee.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let p=[];for(let m of a){let w=this.tokenizer(c,{text_pair:m,padding:!0,truncation:!0}),x=await this.model(w);i?p.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):p.push(x.logits.data[this.entailment_id])}let _=(i?p.map(m=>$e(m)[1]):$e(p)).map((m,w)=>[m,w]).sort((m,w)=>w[0]-m[0]);l.push({sequence:c,labels:_.map(m=>r[m[1]]),scores:_.map(m=>m[0])})}return o?l:l[0]}};var Il=class extends _e{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await vr(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),p=(await this.model(l)).logits[0],f=await Jt(new N("float32",$e(p.data),p.dims),r),_=f[0].tolist(),w=f[1].tolist().map((x,k)=>({label:o?o[x]:`LABEL_${x}`,score:_[k]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var Cl=class extends _e{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(p=>s.replace("{}",p)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await vr(e,i),c=[];for(let p of l){let f=await this.processor(p),_=await this.model({...a,...f}),m=$e(_.logits_per_audio.data);c.push([...m].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var Pl=class extends _e{_default_generation_config={};async _call(e,r={}){switch(r={...this._default_generation_config,...r},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,r);case"moonshine":return this._call_moonshine(e,r);case"cohere_asr":return this._call_cohere_asr(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&ee.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&ee.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await vr(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).logits[0],_=[];for(let w of f)_.push(Pe(w.data)[1]);let m=this.tokenizer.decode(_,{skip_special_tokens:!0}).trim();i.push({text:m})}return s?i[0]:i}async _call_whisper(e,r){let s=r.return_timestamps??!1,n=r.chunk_length_s??0,o=r.force_full_sequences??!1,a=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);let l=!Array.isArray(e),c=l?[e]:e,p=this.processor.feature_extractor.config,f=p.chunk_length/this.model.config.max_source_positions,_=p.hop_length,m=p.sampling_rate,w=await vr(c,m),x=[];for(let k of w){let A=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let T=m*n,I=m*a,O=T-2*I,b=0;for(;;){let F=b+T,j=k.subarray(b,F),U=await this.processor(j),X=b===0,K=F>=k.length;if(A.push({stride:[j.length,X?0:I,K?0:I],input_features:U.input_features,is_last:K}),K)break;b+=O}}else A=[{stride:[k.length,0,0],input_features:(await this.processor(k)).input_features,is_last:!0}];for(let T of A){i.num_frames=Math.floor(T.stride[0]/_);let I=await this.model.generate({inputs:T.input_features,...i});if(s==="word"){let O=I.sequences.tolist()[0],b=I.token_timestamps.tolist()[0],F=this.tokenizer.timestamp_begin,j=Math.max(O.findIndex(U=>Number(U)>=F),0);T.tokens=O.slice(j),T.token_timestamps=b.slice(j).map(U=>gs(U,2))}else T.tokens=I[0].tolist();T.stride=T.stride.map(O=>O/m)}let[E,S]=this.tokenizer._decode_asr(A,{time_precision:f,return_timestamps:s,force_full_sequences:o});x.push({text:E,...S})}return l?x[0]:x}async _call_moonshine(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await vr(n,o),i=[];for(let l of a){let c=await this.processor(l),p=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:p,...r,...c}),_=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:_})}return s?i[0]:i}async _call_cohere_asr(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor,a=o.config.sampling_rate,i=await vr(n,a),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),p=[];for(let f of i){let _=o.split_audio(f),m=[];for(let x of _){let k=await this.processor(x),A=await this.model.generate({...k,decoder_input_ids:c,...r}),E=this.tokenizer.decode(A[0].tolist(),{skip_special_tokens:!0}).trim();m.push(E)}let w=this.processor.constructor.join_chunks(m,l);p.push({text:w})}return s?p[0]:p}};var zl=class extends _e{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 me.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new N("float32",e,[e.length]);else if(!(e instanceof N))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,c=[];for(let p=0;p({generated_text:p.trim()}));a.push(c)}return s?a:a[0]}};var Nl=class extends _e{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 Jt(new N("float32",$e(l.data),l.dims),r),p=c[0].tolist(),_=c[1].tolist().map((m,w)=>({label:a?a[m]:`LABEL_${m}`,score:p[w]}));i.push(_)}return Array.isArray(e)?i:i[0]}};var dT={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Vs=class extends _e{async _call(e,{threshold:r=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:o=null,target_sizes:a=null,subtask:i=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let c=await tt(e),p=c.map(E=>[E.height,E.width]),f=await this.processor(c),{inputNames:_,outputNames:m}=this.model.sessions.model;if(!_.includes("pixel_values")){if(_.length!==1)throw Error(`Expected a single input name, but got ${_.length} inputs: ${_}.`);let E=_[0];if(E in f)throw Error(`Input name ${E} already exists in the inputs.`);f[E]=f.pixel_values}let w=await this.model(f),x=null;if(i!==null)x=dT[i];else if(this.processor.image_processor){for(let[E,S]of Object.entries(dT))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=E;break}}let k=this.model.config.id2label,A=[];if(i)if(i==="panoptic"||i==="instance"){let E=x(w,r,s,n,o,a??p)[0],S=E.segmentation;for(let T of E.segments_info){let I=new Uint8ClampedArray(S.data.length);for(let b=0;bF<-1e-5||F>1+1e-5)&&O.sigmoid_();let b=await Je.fromTensor(O.mul_(255).to("uint8")).resize(I[1],I[0]);A.push({label:null,score:null,mask:b})}}return A}};var $l=class extends Vs{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 Rl=class extends _e{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await tt(e),a=r.map(_=>s.replace("{}",_)),i=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(o),c=await this.model({...i,pixel_values:l}),p=this.model.config.model_type==="siglip"?_=>_.sigmoid().data:_=>$e(_.data),f=[];for(let _ of c.logits_per_image){let w=[...p(_)].map((x,k)=>({score:x,label:r[k]}));w.sort((x,k)=>k.score-x.score),f.push(w)}return n?f:f[0]}};var Dl=class extends _e{async _call(e,{threshold:r=.9,percentage:s=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let o=await tt(e),a=s?null:o.map(m=>[m.height,m.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),c=await this.model({pixel_values:i,pixel_mask:l}),p=this.processor.image_processor.post_process_object_detection(c,r,a),{id2label:f}=this.model.config,_=p.map(m=>m.boxes.map((w,x)=>({score:m.scores[x],label:f[m.classes[x]],box:bl(w,!s)})));return n?_:_[0]}};var Fl=class extends _e{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await tt(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=await this.processor(i),p=[];for(let f=0;f({score:A.scores[S],label:A.labels[S],box:bl(E,!o)}))}else{let A=this.processor.image_processor.post_process_object_detection(x,s,m,!0)[0];k=A.boxes.map((E,S)=>({score:A.scores[S],label:r[A.classes[S]],box:bl(E,!o)}))}k.sort((A,E)=>E.score-A.score),n!==null&&(k=k.slice(0,n)),p.push(k)}return a?p:p[0]}};var Bl=class extends _e{_default_generation_config={max_new_tokens:256};async _call(e,r,s={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await tt(e))[0],{pixel_values:o}=await this.processor(n),a=`${r}`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...s}),p=this.tokenizer.batch_decode(l)[0].match(/(.*?)<\/s_answer>/),f=null;return p&&p.length>=2&&(f=p[1].trim()),[{answer:f}]}};var Ul=class extends _e{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 jl=class extends _e{async _call(e){let r=await tt(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a`onnx/${_}`);return i.filter(_=>!_.startsWith("onnx/")||f.some(m=>_.startsWith(m)))}}return i}async function Rle(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:p=null,model_file_name:f=null,session_options:_={}}={}){t=Xp[t]??t;let m=ro[t.split("_",1)[0]];if(!m)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(ro)}]`);e||(e=m.default.model,ee.info(`No model specified. Using default model: "${e}".`),!l&&m.default.dtype&&(l=m.default.dtype));let w=await Ar(t,e,{device:i,dtype:l}),x={};r&&(await Promise.all(w.map(async X=>Ot(e,X)))).forEach((X,K)=>{X.exists&&(x[w[K]]={loaded:0,total:X.size??0})});let k={progress_callback:r?new ds(r,x):void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:p,model_file_name:f,session_options:_},A=w.includes("tokenizer.json"),E=w.includes("preprocessor_config.json"),S=m.model,T;if(Array.isArray(S)){let U=s??await jt.from_pretrained(e,k),{model_type:X}=U,K=S.find(J=>J.supports(X));if(!K)throw Error(`Unsupported model type "${X}" for task "${t}". None of the candidate model classes support this type.`);T=K.from_pretrained(e,{...k,config:U})}else T=S.from_pretrained(e,k);let[I,O,b]=await Promise.all([A?ne.from_pretrained(e,k):null,E?fu.from_pretrained(e,k):null,T]),F={task:t,model:b};I&&(F.tokenizer=I),O&&(F.processor=O),or(r,{status:"ready",task:t,model:e});let j=m.pipeline;return new j(F)}var ZN=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,ov=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},_T=ie.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),av=class extends ov{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??_T,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=gt(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&&ZN(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===_T&&ie.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}},mT=class extends av{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:c=!0,decode_kwargs:p={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,callback_function:s,token_callback_function:n,decode_kwargs:p}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var Wl=class{constructor(e,r){this.image=e,this.timestamp=r}},Yp=class{constructor(e,r){e.length>0&&e[0]instanceof Je&&(e=e.map((s,n)=>new Wl(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 e3(t,{num_frames:e=null,fps:r=null}={}){if(!ie.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(e==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let s=[],n=document.createElement("video");if(n.crossOrigin="anonymous",n.muted=!0,typeof t=="string")n.src=t;else if(t instanceof Blob)n.src=URL.createObjectURL(t);else if(t instanceof HTMLVideoElement)n.src=t.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(f=>n.onloadedmetadata=f),n.seekable.start(0)===n.seekable.end(0)){let _=await(await me.fetch(n.src)).blob();n.src=URL.createObjectURL(_),await new Promise(m=>n.onloadedmetadata=m)}let o=n.duration,a,i;e!=null?(a=e,i=e===1?0:o/(e-1)):(i=1/r,a=Math.floor(o/i));let l=[];for(let f=0;f{n.onseeked=x}),p.drawImage(n,0,0,c.width,c.height);let _=p.getImageData(0,0,c.width,c.height),m=new Je(_.data,c.width,c.height,4),w=new Wl(m,f);s.push(w)}return n.remove(),new Yp(s,o)}async function Qp(t,e,r={}){let s=await Yt(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}=zr(t,o,r,s),l=await Lr(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function hT(t,e,r={}){let s=await Yt(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=zr(t,e,r,s);return!!await Lr(s,n,o)}async function gT(t,e={}){if(!t)throw new Error("modelId is required");if(!await hT(t,"config.json",e))return!1;let r=await Er(t,e);return(await Qp(t,r,e)).allCached}async function wT(t,e={}){if(!t)throw new Error("modelId is required");let r=await Er(t,e);return await Qp(t,r,e)}async function xT(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await hT(e,"config.json",r))return!1;let s=await Ar(t,e,r);return(await Qp(e,s,r)).allCached}async function yT(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Ar(t,e,r);return await Qp(e,s,r)}async function bT(t,e,r={}){let s=await Yt(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}=zr(t,o,r,s),c=!!await Lr(s,a,i),p=!1;if(c){let f=await s.delete(i),_=!f&&i!==a?await s.delete(a):!1;p=f||_}return{file:o,deleted:p,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function vT(t,e={}){if(!t)throw new Error("modelId is required");let r=await Er(t,e);return await bT(t,r,e)}async function kT(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Ar(t,e,r);return await bT(e,s,r)}var t3=Object.keys(jr);async function ET(t,{config:e=null,model_file_name:r=null,revision:s="main",cache_dir:n=null,local_files_only:o=!1}={}){e=await Qo(t,{config:e,cache_dir:n,local_files_only:o,revision:s});let a="onnx",i=On(e),{sessions:l}=Yo(i,e,{model_file_name:r}),c=Object.values(l),p={revision:s,cache_dir:n,local_files_only:o};return(await Promise.all(t3.map(async _=>{let m=jr[_]??"",w=await Promise.all(c.map(async x=>{let k=`${a}/${x}${m}.onnx`;return(await Ot(t,k,p)).exists}));return{dtype:_,available:w.every(Boolean)}}))).filter(_=>_.available).map(_=>_.dtype)}var iv=class{static async get_files(e,r={}){return Er(e,r)}static async get_pipeline_files(e,r,s={}){return Ar(e,r,s)}static async get_model_files(e,r={}){return In(e,r)}static async get_tokenizer_files(e){return _n(e)}static async get_processor_files(e){return Kp(e)}static async get_available_dtypes(e,r={}){return ET(e,r)}static async is_cached(e,r={}){return gT(e,r)}static async is_cached_files(e,r={}){return wT(e,r)}static async is_pipeline_cached(e,r,s={}){return xT(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return yT(e,r,s)}static async get_file_metadata(e,r,s={}){return Ot(e,r,s)}static async clear_cache(e,r={}){return vT(e,r)}static async clear_pipeline_cache(e,r,s={}){return kT(e,r,s)}};export{N_ as ASTFeatureExtractor,Dh as ASTForAudioClassification,Rh as ASTModel,sa as ASTPreTrainedModel,Lh as AfmoeForCausalLM,zh as AfmoeModel,ta as AfmoePreTrainedModel,Ih as AlbertForMaskedLM,Oh as AlbertForQuestionAnswering,Sh as AlbertForSequenceClassification,Th as AlbertModel,Ns as AlbertPreTrainedModel,Ud as AlbertTokenizer,Ph as ApertusForCausalLM,Ch as ApertusModel,ea as ApertusPreTrainedModel,$h as ArceeForCausalLM,Nh as ArceeModel,ra as ArceePreTrainedModel,Il as AudioClassificationPipeline,jt as AutoConfig,je as AutoFeatureExtractor,Me as AutoImageProcessor,br as AutoModel,Gp as AutoModelForAudioClassification,aT as AutoModelForAudioFrameClassification,pT as AutoModelForAudioTextToText,jp as AutoModelForCTC,Np as AutoModelForCausalLM,Vp as AutoModelForDepthEstimation,qp as AutoModelForDocumentQuestionAnswering,Fp as AutoModelForImageClassification,Hp as AutoModelForImageFeatureExtraction,iT as AutoModelForImageMatting,wl as AutoModelForImageSegmentation,uT as AutoModelForImageTextToText,Wp as AutoModelForImageToImage,nT as AutoModelForMaskGeneration,$p as AutoModelForMaskedLM,lT as AutoModelForNormalEstimation,Bp as AutoModelForObjectDetection,cT as AutoModelForPoseEstimation,Rp as AutoModelForQuestionAnswering,xl as AutoModelForSemanticSegmentation,to as AutoModelForSeq2SeqLM,gl as AutoModelForSequenceClassification,Pp as AutoModelForSpeechSeq2Seq,zp as AutoModelForTextToSpectrogram,Lp as AutoModelForTextToWaveform,Cp as AutoModelForTokenClassification,yl as AutoModelForUniversalSegmentation,Dp as AutoModelForVision2Seq,oT as AutoModelForXVector,Up as AutoModelForZeroShotObjectDetection,fu as AutoProcessor,ne as AutoTokenizer,Pl as AutomaticSpeechRecognitionPipeline,$l as BackgroundRemovalPipeline,Bh as BartForConditionalGeneration,Uh as BartForSequenceClassification,Fh as BartModel,zn as BartPretrainedModel,jd as BartTokenizer,ov as BaseStreamer,J_ as BeitFeatureExtractor,Gh as BeitForImageClassification,jh as BeitModel,na as BeitPreTrainedModel,Wh as BertForMaskedLM,Xh as BertForQuestionAnswering,Vh as BertForSequenceClassification,Hh as BertForTokenClassification,qh as BertModel,Xr as BertPreTrainedModel,Gd as BertTokenizer,Z_ as BitImageProcessor,Yh as BlenderbotForConditionalGeneration,Kh as BlenderbotModel,oa as BlenderbotPreTrainedModel,Jh as BlenderbotSmallForConditionalGeneration,Qh as BlenderbotSmallModel,aa as BlenderbotSmallPreTrainedModel,qd as BlenderbotSmallTokenizer,Wd as BlenderbotTokenizer,eg as BloomForCausalLM,Zh as BloomModel,ia as BloomPreTrainedModel,Vd as BloomTokenizer,ig as CHMv2ForDepthEstimation,tm as CHMv2ImageProcessor,Lu as CHMv2PreTrainedModel,rm as CLIPFeatureExtractor,Vc as CLIPImageProcessor,cg as CLIPModel,pr as CLIPPreTrainedModel,_g as CLIPSegForImageSegmentation,dg as CLIPSegModel,fa as CLIPSegPreTrainedModel,ug as CLIPTextModel,pa as CLIPTextModelWithProjection,Xd as CLIPTokenizer,pg as CLIPVisionModel,fg as CLIPVisionModelWithProjection,rg as CamembertForMaskedLM,og as CamembertForQuestionAnswering,sg as CamembertForSequenceClassification,ng as CamembertForTokenClassification,tg as CamembertModel,Kr as CamembertPreTrainedModel,Hd as CamembertTokenizer,$_ as ChatterboxFeatureExtractor,la as ChatterboxModel,Pu as ChatterboxPreTrainedModel,X_ as ChatterboxProcessor,em as ChineseCLIPFeatureExtractor,ag as ChineseCLIPModel,zu as ChineseCLIPPreTrainedModel,ua as ClapAudioModelWithProjection,R_ as ClapFeatureExtractor,lg as ClapModel,Ln as ClapPreTrainedModel,ca as ClapTextModelWithProjection,ku as ClassifierFreeGuidanceLogitsProcessor,hg as CodeGenForCausalLM,mg as CodeGenModel,da as CodeGenPreTrainedModel,Yd as CodeGenTokenizer,Kd as CodeLlamaTokenizer,yg as Cohere2ForCausalLM,xg as Cohere2Model,ma as Cohere2PreTrainedModel,D_ as CohereAsrFeatureExtractor,vg as CohereAsrForConditionalGeneration,bg as CohereAsrModel,ha as CohereAsrPreTrainedModel,K_ as CohereAsrProcessor,Jd as CohereAsrTokenizer,wg as CohereForCausalLM,gg as CohereModel,_a as CoherePreTrainedModel,Qd as CohereTokenizer,Eg as ConvBertForMaskedLM,Tg as ConvBertForQuestionAnswering,Ag as ConvBertForSequenceClassification,Mg as ConvBertForTokenClassification,kg as ConvBertModel,Yr as ConvBertPreTrainedModel,Zd as ConvBertTokenizer,sm as ConvNextFeatureExtractor,Og as ConvNextForImageClassification,Hc as ConvNextImageProcessor,Sg as ConvNextModel,ga as ConvNextPreTrainedModel,Cg as ConvNextV2ForImageClassification,Ig as ConvNextV2Model,wa as ConvNextV2PreTrainedModel,Ng as DFineForObjectDetection,Lg as DFineModel,ya as DFinePreTrainedModel,iw as DINOv3ConvNextModel,Uu as DINOv3ConvNextPreTrainedModel,am as DINOv3ViTImageProcessor,lw as DINOv3ViTModel,ju as DINOv3ViTPreTrainedModel,lm as DPTFeatureExtractor,hw as DPTForDepthEstimation,Yc as DPTImageProcessor,mw as DPTModel,Ta as DPTPreTrainedModel,va as DacDecoderModel,$u as DacDecoderOutput,ba as DacEncoderModel,Nu as DacEncoderOutput,Fo as DacFeatureExtractor,$g as DacModel,Nn as DacPreTrainedModel,Dg as DebertaForMaskedLM,Ug as DebertaForQuestionAnswering,Fg as DebertaForSequenceClassification,Bg as DebertaForTokenClassification,Rg as DebertaModel,Qr as DebertaPreTrainedModel,t_ as DebertaTokenizer,Wg as DebertaV2ForMaskedLM,Xg as DebertaV2ForQuestionAnswering,Vg as DebertaV2ForSequenceClassification,Hg as DebertaV2ForTokenClassification,qg as DebertaV2Model,Jr as DebertaV2PreTrainedModel,e_ as DebertaV2Tokenizer,Kg as DecisionTransformerModel,Ru as DecisionTransformerPreTrainedModel,Gg as DeepseekV3ForCausalLM,jg as DeepseekV3Model,ka as DeepseekV3PreTrainedModel,nm as DeiTFeatureExtractor,Qg as DeiTForImageClassification,Xc as DeiTImageProcessor,Yg as DeiTModel,Ea as DeiTPreTrainedModel,Jg as DepthAnythingForDepthEstimation,Du as DepthAnythingPreTrainedModel,jl as DepthEstimationPipeline,Zg as DepthProForDepthEstimation,Fu as DepthProPreTrainedModel,om as DetrFeatureExtractor,tw as DetrForObjectDetection,rw as DetrForSegmentation,Kc as DetrImageProcessor,ew as DetrModel,Rn as DetrObjectDetectionOutput,$n as DetrPreTrainedModel,Bu as DetrSegmentationOutput,nw as Dinov2ForImageClassification,sw as Dinov2Model,Aa as Dinov2PreTrainedModel,aw as Dinov2WithRegistersForImageClassification,ow as Dinov2WithRegistersModel,Ma as Dinov2WithRegistersPreTrainedModel,dw as DistilBertForMaskedLM,fw as DistilBertForQuestionAnswering,uw as DistilBertForSequenceClassification,pw as DistilBertForTokenClassification,cw as DistilBertModel,Zr as DistilBertPreTrainedModel,r_ as DistilBertTokenizer,Bl as DocumentQuestionAnsweringPipeline,im as DonutFeatureExtractor,gn as DonutImageProcessor,_w as DonutSwinModel,Gu as DonutSwinPreTrainedModel,Sn as DynamicCache,Tb as EdgeTamModel,ww as EfficientNetForImageClassification,cm as EfficientNetImageProcessor,gw as EfficientNetModel,Sa as EfficientNetPreTrainedModel,yw as ElectraForMaskedLM,kw as ElectraForQuestionAnswering,bw as ElectraForSequenceClassification,vw as ElectraForTokenClassification,xw as ElectraModel,es as ElectraPreTrainedModel,s_ as ElectraTokenizer,Ro as EncodecFeatureExtractor,Mu as EosTokenCriteria,Aw as Ernie4_5ForCausalLM,Ew as Ernie4_5Model,Oa as Ernie4_5PretrainedModel,Tw as EsmForMaskedLM,Sw as EsmForSequenceClassification,Ow as EsmForTokenClassification,Mw as EsmModel,$s as EsmPreTrainedModel,n_ as EsmTokenizer,Cw as EuroBertForMaskedLM,Pw as EuroBertForSequenceClassification,zw as EuroBertForTokenClassification,Iw as EuroBertModel,Rs as EuroBertPreTrainedModel,Nw as ExaoneForCausalLM,Lw as ExaoneModel,Ia as ExaonePreTrainedModel,Rw as FalconForCausalLM,Fw as FalconH1ForCausalLM,Dw as FalconH1Model,Pa as FalconH1PreTrainedModel,$w as FalconModel,Ca as FalconPreTrainedModel,o_ as FalconTokenizer,Uw as FastViTForImageClassification,Bw as FastViTModel,za as FastViTPreTrainedModel,Gl as FeatureExtractionPipeline,Ee as FeatureExtractor,Al as FillMaskPipeline,jw as Florence2ForConditionalGeneration,qu as Florence2PreTrainedModel,jm as Florence2Processor,_u as ForcedBOSTokenLogitsProcessor,mu as ForcedEOSTokenLogitsProcessor,fm as GLPNFeatureExtractor,ox as GLPNForDepthEstimation,nx as GLPNModel,Ba as GLPNPreTrainedModel,mx as GPT2LMHeadModel,_x as GPT2Model,Wa as GPT2PreTrainedModel,l_ as GPT2Tokenizer,ix as GPTBigCodeForCausalLM,ax as GPTBigCodeModel,Ua as GPTBigCodePreTrainedModel,gx as GPTJForCausalLM,hx as GPTJModel,Va as GPTJPreTrainedModel,cx as GPTNeoForCausalLM,lx as GPTNeoModel,ja as GPTNeoPreTrainedModel,px as GPTNeoXForCausalLM,ux as GPTNeoXModel,Ga as GPTNeoXPreTrainedModel,i_ as GPTNeoXTokenizer,Vw as Gemma2ForCausalLM,Ww as Gemma2Model,Na as Gemma2PreTrainedModel,Yw as Gemma3ForCausalLM,Hu as Gemma3ForConditionalGeneration,um as Gemma3ImageProcessor,Kw as Gemma3Model,Vu as Gemma3PreTrainedModel,Gm as Gemma3Processor,Bo as Gemma3nAudioFeatureExtractor,Qw as Gemma3nForCausalLM,ts as Gemma3nForConditionalGeneration,Xu as Gemma3nPreTrainedModel,qm as Gemma3nProcessor,Uo as Gemma4AudioFeatureExtractor,Jw as Gemma4ForCausalLM,Dn as Gemma4ForConditionalGeneration,qo as Gemma4ImageProcessor,Wm as Gemma4Processor,qw as GemmaForCausalLM,Gw as GemmaModel,La as GemmaPreTrainedModel,a_ as GemmaTokenizer,pm as Glm46VImageProcessor,Vm as Glm46VProcessor,ex as GlmForCausalLM,Zw as GlmModel,rx as GlmMoeDsaForCausalLM,tx as GlmMoeDsaModel,Ra as GlmMoeDsaPreTrainedModel,sx as GlmOcrForConditionalGeneration,$a 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,F_ as GraniteSpeechFeatureExtractor,vx as GraniteSpeechForConditionalGeneration,Hm as GraniteSpeechProcessor,kx as GroundingDinoForObjectDetection,dm as GroundingDinoImageProcessor,Qu as GroundingDinoPreTrainedModel,Xm as GroundingDinoProcessor,Ex as GroupViTModel,Ju as GroupViTPreTrainedModel,Mx as HeliumForCausalLM,Ax as HeliumModel,Ka as HeliumPreTrainedModel,c_ as HerbertTokenizer,Sx as HieraForImageClassification,Tx as HieraModel,Ya as HieraPreTrainedModel,Nx as HubertForCTC,$x as HubertForSequenceClassification,Lx as HubertModel,zx as HubertPreTrainedModel,Dx as HunYuanDenseV1ForCausalLM,Rx as HunYuanDenseV1Model,Qa as HunYuanDenseV1PreTrainedModel,Bx as IJepaForImageClassification,Fx as IJepaModel,Za as IJepaPreTrainedModel,Ja as Idefics3ForConditionalGeneration,Qc as Idefics3ImageProcessor,iu as Idefics3Processor,Nl as ImageClassificationPipeline,ql as ImageFeatureExtractionPipeline,H as ImageFeatureExtractor,H as ImageProcessor,Vs as ImageSegmentationPipeline,Ul as ImageToImagePipeline,Ll as ImageToTextPipeline,yM as InterruptableStoppingCriteria,jx as JAISLMHeadModel,Ux as JAISModel,ei as JAISPreTrainedModel,mm as JinaCLIPImageProcessor,Gx as JinaCLIPModel,Bn as JinaCLIPPreTrainedModel,Ym as JinaCLIPProcessor,ti as JinaCLIPTextModel,qx as JinaCLIPVisionModel,Vx as Lfm2ForCausalLM,Wx as Lfm2Model,Kx as Lfm2MoeForCausalLM,Xx as Lfm2MoeModel,si as Lfm2MoePreTrainedModel,ri as Lfm2PreTrainedModel,Yx as Lfm2VlForConditionalGeneration,hm as Lfm2VlImageProcessor,Qm as Lfm2VlProcessor,Hx as LightOnOcrForConditionalGeneration,G1 as LiteWhisperForConditionalGeneration,Zx as Llama4ForCausalLM,Zu as Llama4PreTrainedModel,Jx as LlamaForCausalLM,Qx as LlamaModel,ni as LlamaPreTrainedModel,u_ as LlamaTokenizer,kt as LlavaForConditionalGeneration,kt as LlavaOnevisionForConditionalGeneration,gm as LlavaOnevisionImageProcessor,Wu as LlavaPreTrainedModel,Jm as LlavaProcessor,Xw as LlavaQwen2ForCausalLM,St as LogLevel,$t as LogitsProcessor,Cs as LogitsProcessorList,Ko as LogitsWarper,ty as LongT5ForConditionalGeneration,ey as LongT5Model,oi as LongT5PreTrainedModel,sy as M2M100ForConditionalGeneration,ry as M2M100Model,ai as M2M100PreTrainedModel,p_ as M2M100Tokenizer,d_ as MBart50Tokenizer,py as MBartForCausalLM,cy as MBartForConditionalGeneration,uy as MBartForSequenceClassification,ly as MBartModel,Bs as MBartPreTrainedModel,zo as MBartTokenizer,Qy as MPNetForMaskedLM,e0 as MPNetForQuestionAnswering,Jy as MPNetForSequenceClassification,Zy as MPNetForTokenClassification,Yy as MPNetModel,rs as MPNetPreTrainedModel,h_ as MPNetTokenizer,n0 as MT5ForConditionalGeneration,s0 as MT5Model,xi as MT5PreTrainedModel,oy as MarianMTModel,ny as MarianModel,ii as MarianPreTrainedModel,f_ as MarianTokenizer,xm as Mask2FormerImageProcessor,wm as MaskFormerFeatureExtractor,iy as MaskFormerForInstanceSegmentation,wn as MaskFormerImageProcessor,ay as MaskFormerModel,li as MaskFormerPreTrainedModel,Au as MaxLengthCriteria,fy as Metric3DForDepthEstimation,ep as Metric3DPreTrainedModel,dy as Metric3Dv2ForDepthEstimation,tp as Metric3Dv2PreTrainedModel,_y as MgpstrForSceneTextRecognition,rp as MgpstrModelOutput,sp as MgpstrPreTrainedModel,Zm as MgpstrProcessor,__ as MgpstrTokenizer,ui as MimiDecoderModel,op as MimiDecoderOutput,ci as MimiEncoderModel,np as MimiEncoderOutput,my as MimiModel,Un as MimiPreTrainedModel,yu as MinLengthLogitsProcessor,bu as MinNewTokensLengthLogitsProcessor,xy as Mistral4ForCausalLM,wy as Mistral4Model,fi as Mistral4PreTrainedModel,gy as MistralForCausalLM,hy as MistralModel,pi as MistralPreTrainedModel,by as MobileBertForMaskedLM,ky as MobileBertForQuestionAnswering,vy as MobileBertForSequenceClassification,yy as MobileBertModel,Us as MobileBertPreTrainedModel,m_ as MobileBertTokenizer,Ay as MobileLLMForCausalLM,Ey as MobileLLMModel,di as MobileLLMPreTrainedModel,ym as MobileNetV1FeatureExtractor,Ty as MobileNetV1ForImageClassification,Sy as MobileNetV1ForSemanticSegmentation,Jc as MobileNetV1ImageProcessor,My as MobileNetV1Model,jn as MobileNetV1PreTrainedModel,bm as MobileNetV2FeatureExtractor,Iy as MobileNetV2ForImageClassification,Cy as MobileNetV2ForSemanticSegmentation,Zc as MobileNetV2ImageProcessor,Oy as MobileNetV2Model,Gn as MobileNetV2PreTrainedModel,vm as MobileNetV3FeatureExtractor,zy as MobileNetV3ForImageClassification,Ly as MobileNetV3ForSemanticSegmentation,eu as MobileNetV3ImageProcessor,Py as MobileNetV3Model,qn as MobileNetV3PreTrainedModel,km as MobileNetV4FeatureExtractor,$y as MobileNetV4ForImageClassification,Ry as MobileNetV4ForSemanticSegmentation,tu as MobileNetV4ImageProcessor,Ny as MobileNetV4Model,Wn as MobileNetV4PreTrainedModel,Em as MobileViTFeatureExtractor,Fy as MobileViTForImageClassification,ru as MobileViTImageProcessor,Dy as MobileViTModel,_i as MobileViTPreTrainedModel,Uy as MobileViTV2ForImageClassification,By as MobileViTV2Model,mi as MobileViTV2PreTrainedModel,iv as ModelRegistry,Hy as ModernBertDecoderForCausalLM,Vy as ModernBertDecoderModel,hi as ModernBertDecoderPreTrainedModel,Gy as ModernBertForMaskedLM,qy as ModernBertForSequenceClassification,Wy as ModernBertForTokenClassification,jy as ModernBertModel,js as ModernBertPreTrainedModel,Hw as Moondream1ForConditionalGeneration,B_ as MoonshineFeatureExtractor,Ky as MoonshineForConditionalGeneration,Xy as MoonshineModel,gi as MoonshinePreTrainedModel,eh as MoonshineProcessor,r0 as MptForCausalLM,t0 as MptModel,wi as MptPreTrainedModel,o0 as MultiModalityCausalLM,ap as MultiModalityPreTrainedModel,i0 as MusicgenForCausalLM,bi as MusicgenForConditionalGeneration,a0 as MusicgenModel,yi as MusicgenPreTrainedModel,c0 as NanoChatForCausalLM,l0 as NanoChatModel,vi as NanoChatPreTrainedModel,p0 as NemotronHForCausalLM,u0 as NemotronHModel,ki as NemotronHPreTrainedModel,d0 as NeoBertForMaskedLM,h0 as NeoBertForQuestionAnswering,_0 as NeoBertForSequenceClassification,m0 as NeoBertForTokenClassification,f0 as NeoBertModel,ss as NeoBertPreTrainedModel,g_ as NllbTokenizer,vu as NoBadWordsLogitsProcessor,wu as NoRepeatNGramLogitsProcessor,g0 as NomicBertModel,ip as NomicBertPreTrainedModel,Am as NougatImageProcessor,w_ as NougatTokenizer,C0 as OPTForCausalLM,I0 as OPTModel,Ii as OPTPreTrainedModel,Dl as ObjectDetectionPipeline,b0 as Olmo2ForCausalLM,y0 as Olmo2Model,Ai as Olmo2PreTrainedModel,k0 as Olmo3ForCausalLM,v0 as Olmo3Model,Mi as Olmo3PreTrainedModel,x0 as OlmoForCausalLM,A0 as OlmoHybridForCausalLM,E0 as OlmoHybridModel,Ti as OlmoHybridPreTrainedModel,w0 as OlmoModel,Ei as OlmoPreTrainedModel,T0 as OpenAIPrivacyFilterForTokenClassification,M0 as OpenAIPrivacyFilterModel,Si as OpenAIPrivacyFilterPreTrainedModel,O0 as OpenELMForCausalLM,S0 as OpenELMModel,Oi as OpenELMPreTrainedModel,Mm as OwlViTFeatureExtractor,N0 as OwlViTForObjectDetection,xn as OwlViTImageProcessor,L0 as OwlViTModel,Pi as OwlViTPreTrainedModel,th as OwlViTProcessor,z0 as Owlv2ForObjectDetection,Tm as Owlv2ImageProcessor,P0 as Owlv2Model,Ci as Owlv2PreTrainedModel,$0 as PaliGemmaForConditionalGeneration,rh as PaliGemmaProcessor,Do as ParakeetFeatureExtractor,R0 as ParakeetForCTC,lp as ParakeetPreTrainedModel,F0 as PatchTSMixerForPrediction,D0 as PatchTSMixerModel,zi as PatchTSMixerPreTrainedModel,U0 as PatchTSTForPrediction,B0 as PatchTSTModel,Li as PatchTSTPreTrainedModel,W0 as Phi3ForCausalLM,q0 as Phi3Model,$i as Phi3PreTrainedModel,Ri as Phi3VForCausalLM,Im as Phi3VImageProcessor,cp as Phi3VPreTrainedModel,sh as Phi3VProcessor,G0 as PhiForCausalLM,j0 as PhiModel,Ni as PhiPreTrainedModel,Cm as PixtralImageProcessor,nh as PixtralProcessor,y as PreTrainedModel,W as PreTrainedTokenizer,En as PretrainedConfig,re as Processor,H0 as PvtForImageClassification,Pm as PvtImageProcessor,V0 as PvtModel,Di as PvtPreTrainedModel,jo as PyAnnoteFeatureExtractor,K0 as PyAnnoteForAudioFrameClassification,X0 as PyAnnoteModel,Fi as PyAnnotePreTrainedModel,oh as PyAnnoteProcessor,El as QuestionAnsweringPipeline,Q0 as Qwen2ForCausalLM,Y0 as Qwen2Model,Z0 as Qwen2MoeForCausalLM,J0 as Qwen2MoeModel,Ui as Qwen2MoePreTrainedModel,Bi as Qwen2PreTrainedModel,x_ as Qwen2Tokenizer,Da as Qwen2VLForCausalLM,Fn as Qwen2VLForConditionalGeneration,Wo as Qwen2VLImageProcessor,Ku as Qwen2VLPreTrainedModel,Os as Qwen2VLProcessor,Fa as Qwen2_5_VLForCausalLM,Ds as Qwen2_5_VLForConditionalGeneration,Ho as Qwen2_5_VLProcessor,tb as Qwen3ForCausalLM,eb as Qwen3Model,sb as Qwen3MoeForCausalLM,rb as Qwen3MoeModel,Gi as Qwen3MoePreTrainedModel,ob as Qwen3NextForCausalLM,nb as Qwen3NextModel,qi as Qwen3NextPreTrainedModel,ji as Qwen3PreTrainedModel,Wi as Qwen3VLForCausalLM,Gs as Qwen3VLForConditionalGeneration,ib as Qwen3VLMoeForCausalLM,ab as Qwen3VLMoeForConditionalGeneration,ah as Qwen3VLProcessor,Vi as Qwen3_5ForCausalLM,Vn as Qwen3_5ForConditionalGeneration,cb as Qwen3_5MoeForCausalLM,lb as Qwen3_5MoeForConditionalGeneration,db as RFDetrForObjectDetection,fb as RFDetrModel,up as RFDetrObjectDetectionOutput,Xi as RFDetrPreTrainedModel,zg as RTDetrForObjectDetection,zm as RTDetrImageProcessor,Pg as RTDetrModel,fr as RTDetrObjectDetectionOutput,xa as RTDetrPreTrainedModel,Ab as RTDetrV2ForObjectDetection,Eb as RTDetrV2Model,pp as RTDetrV2ObjectDetectionOutput,Ki as RTDetrV2PreTrainedModel,$o as RawAudio,Je as RawImage,Yp as RawVideo,Wl as RawVideoFrame,xu as RepetitionPenaltyLogitsProcessor,pb as ResNetForImageClassification,ub as ResNetModel,Hi as ResNetPreTrainedModel,yb as RoFormerForMaskedLM,kb as RoFormerForQuestionAnswering,bb as RoFormerForSequenceClassification,vb as RoFormerForTokenClassification,xb as RoFormerModel,os as RoFormerPreTrainedModel,b_ as RoFormerTokenizer,mb as RobertaForMaskedLM,wb as RobertaForQuestionAnswering,hb as RobertaForSequenceClassification,gb as RobertaForTokenClassification,_b as RobertaModel,ns as RobertaPreTrainedModel,y_ as RobertaTokenizer,Vo as Sam2ImageProcessor,_p as Sam2ImageSegmentationOutput,Yi as Sam2Model,mp as Sam2PreTrainedModel,lu as Sam2Processor,ih as Sam2VideoProcessor,Vo as Sam3ImageProcessor,Sb as Sam3TrackerModel,Vo as SamImageProcessor,fp as SamImageSegmentationOutput,Mb as SamModel,dp as SamPreTrainedModel,Xo as SamProcessor,Lm as SapiensFeatureExtractor,Ib as SapiensForDepthEstimation,Cb as SapiensForNormalEstimation,Ob as SapiensForSemanticSegmentation,su as SapiensImageProcessor,Hn as SapiensPreTrainedModel,U_ as SeamlessM4TFeatureExtractor,Nm as SegformerFeatureExtractor,zb as SegformerForImageClassification,Lb as SegformerForSemanticSegmentation,nu as SegformerImageProcessor,Pb as SegformerModel,Xn as SegformerPreTrainedModel,$m as SiglipImageProcessor,Nb as SiglipModel,Qi as SiglipPreTrainedModel,Ji as SiglipTextModel,v_ as SiglipTokenizer,$b as SiglipVisionModel,Db as SmolLM3ForCausalLM,Rb as SmolLM3Model,Zi as SmolLM3PreTrainedModel,Fb as SmolVLMForConditionalGeneration,Qc as SmolVLMImageProcessor,iu as SmolVLMProcessor,tl as SnacDecoderModel,el as SnacEncoderModel,j_ as SnacFeatureExtractor,Bb as SnacModel,Kn as SnacPreTrainedModel,jb as SolarOpenForCausalLM,Ub as SolarOpenModel,rl as SolarOpenPreTrainedModel,G_ as SpeechT5FeatureExtractor,qb as SpeechT5ForSpeechToText,Wb as SpeechT5ForTextToSpeech,Vb as SpeechT5HifiGan,Gb as SpeechT5Model,Yn as SpeechT5PreTrainedModel,lh as SpeechT5Processor,k_ as SpeechT5Tokenizer,Xb as SqueezeBertForMaskedLM,Yb as SqueezeBertForQuestionAnswering,Kb as SqueezeBertForSequenceClassification,Hb as SqueezeBertModel,qs as SqueezeBertPreTrainedModel,E_ as SqueezeBertTokenizer,Jb as StableLmForCausalLM,Qb as StableLmModel,sl as StableLmPreTrainedModel,e1 as Starcoder2ForCausalLM,Zb as Starcoder2Model,nl as Starcoder2PreTrainedModel,Hr as StoppingCriteria,Tn as StoppingCriteriaList,t1 as StyleTextToSpeech2Model,hp as StyleTextToSpeech2PreTrainedModel,Ml as SummarizationPipeline,ol as SupertonicForConditionalGeneration,gp as SupertonicPreTrainedModel,An as SuppressTokensAtBeginLogitsProcessor,hu as SuppressTokensLogitsProcessor,a1 as Swin2SRForImageSuperResolution,Rm as Swin2SRImageProcessor,o1 as Swin2SRModel,al as Swin2SRPreTrainedModel,s1 as SwinForImageClassification,n1 as SwinForSemanticSegmentation,r1 as SwinModel,Qn as SwinPreTrainedModel,l1 as T5ForConditionalGeneration,i1 as T5Model,il as T5PreTrainedModel,A_ as T5Tokenizer,u1 as TableTransformerForObjectDetection,c1 as TableTransformerModel,wp as TableTransformerObjectDetectionOutput,ll as TableTransformerPreTrainedModel,Eu as TemperatureLogitsWarper,N as Tensor,kr as Text2TextGenerationPipeline,vl as TextClassificationPipeline,Sl as TextGenerationPipeline,av as TextStreamer,zl as TextToAudioPipeline,kl as TokenClassificationPipeline,W as TokenizersBackend,xM as TopKLogitsWarper,wM as TopPLogitsWarper,p1 as TrOCRForCausalLM,xp as TrOCRPreTrainedModel,Tl as TranslationPipeline,Fs as UltravoxModel,Yu as UltravoxPreTrainedModel,ch as UltravoxProcessor,d1 as UniSpeechForCTC,_1 as UniSpeechForSequenceClassification,f1 as UniSpeechModel,Jn as UniSpeechPreTrainedModel,w1 as UniSpeechSatForAudioFrameClassification,h1 as UniSpeechSatForCTC,g1 as UniSpeechSatForSequenceClassification,m1 as UniSpeechSatModel,Ws as UniSpeechSatPreTrainedModel,Km as VLChatProcessor,_m as VLMImageProcessor,y1 as VaultGemmaForCausalLM,x1 as VaultGemmaModel,cl as VaultGemmaPreTrainedModel,Dm as ViTFeatureExtractor,k1 as ViTForImageClassification,ou as ViTImageProcessor,E1 as ViTMAEModel,yp as ViTMAEPreTrainedModel,M1 as ViTMSNForImageClassification,A1 as ViTMSNModel,pl as ViTMSNPreTrainedModel,v1 as ViTModel,ul as ViTPreTrainedModel,b1 as VisionEncoderDecoderModel,T1 as VitMatteForImageMatting,Fm as VitMatteImageProcessor,bp as VitMattePreTrainedModel,S1 as VitPoseForPoseEstimation,Bm as VitPoseImageProcessor,vp as VitPosePreTrainedModel,O1 as VitsModel,kp as VitsModelOutput,Ep as VitsPreTrainedModel,T_ as VitsTokenizer,I1 as VoxtralForConditionalGeneration,uh as VoxtralProcessor,V_ as VoxtralRealtimeFeatureExtractor,fl as VoxtralRealtimeForConditionalGeneration,Ap as VoxtralRealtimePreTrainedModel,fh as VoxtralRealtimeProcessor,L1 as Wav2Vec2BertForCTC,N1 as Wav2Vec2BertForSequenceClassification,z1 as Wav2Vec2BertModel,Zn as Wav2Vec2BertPreTrainedModel,S_ as Wav2Vec2CTCTokenizer,q_ as Wav2Vec2FeatureExtractor,Px as Wav2Vec2ForAudioFrameClassification,Ix as Wav2Vec2ForCTC,Cx as Wav2Vec2ForSequenceClassification,Ox as Wav2Vec2Model,er as Wav2Vec2PreTrainedModel,dh as Wav2Vec2Processor,_h as Wav2Vec2ProcessorWithLM,B1 as WavLMForAudioFrameClassification,R1 as WavLMForCTC,D1 as WavLMForSequenceClassification,F1 as WavLMForXVector,$1 as WavLMModel,as as WavLMPreTrainedModel,W_ as WeSpeakerFeatureExtractor,U1 as WeSpeakerResNetModel,Tp as WeSpeakerResNetPreTrainedModel,H_ as WhisperFeatureExtractor,Op as WhisperForConditionalGeneration,j1 as WhisperModel,dl as WhisperPreTrainedModel,mh as WhisperProcessor,mT as WhisperTextStreamer,gu as WhisperTimeStampLogitsProcessor,O_ as WhisperTokenizer,X1 as XLMForQuestionAnswering,V1 as XLMForSequenceClassification,H1 as XLMForTokenClassification,q1 as XLMModel,is as XLMPreTrainedModel,Y1 as XLMRobertaForMaskedLM,Z1 as XLMRobertaForQuestionAnswering,Q1 as XLMRobertaForSequenceClassification,J1 as XLMRobertaForTokenClassification,K1 as XLMRobertaModel,ls as XLMRobertaPreTrainedModel,I_ as XLMRobertaTokenizer,C_ as XLMTokenizer,W1 as XLMWithLMHeadModel,Mp as XVectorOutput,Um as YolosFeatureExtractor,tv as YolosForObjectDetection,au as YolosImageProcessor,ev as YolosModel,Ip as YolosObjectDetectionOutput,_l as YolosPreTrainedModel,sv as YoutuForCausalLM,rv as YoutuModel,ml as YoutuPreTrainedModel,Cl as ZeroShotAudioClassificationPipeline,Ol as ZeroShotClassificationPipeline,Rl as ZeroShotImageClassificationPipeline,Fl as ZeroShotObjectDetectionPipeline,ve as cat,Zz as cos_sim,lA as dot,me as env,Qe as full,Co as full_like,Nd as interpolate,bt as interpolate_4d,z4 as layer_norm,nM as load_audio,oN as load_image,e3 as load_video,Uf as log_softmax,K2 as matmul,Rc as mean,Y2 as mean_pooling,et as ones,Dc as ones_like,NL as permute,Rle as pipeline,J2 as quantize_embeddings,L4 as rand,Q2 as randn,hs as random,L_ as read_audio,P4 as rfft,$c as slice,$e as softmax,xt as stack,$d as std_mean,Jt as topk,Dd as zeros,Fd as zeros_like};