var LI=Object.defineProperty;var ms=(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 _s=(t,e)=>{for(var r in e)LI(t,r,{get:e[r],enumerable:!0})};var ht={};var Ut={};var nE={};var NI="4.0.0-next.11",gf=typeof self<"u",nn=!uE(ht),iE=!uE(Ut),Yl=gf&&"caches"in self,zI=typeof globalThis.Deno<"u",c3=typeof globalThis.Bun<"u",Jl=zI&&Yl&&!nn,lE=typeof process<"u",cE=lE&&process?.release?.name==="node"&&!Jl,wf=typeof window<"u"&&typeof window.document<"u",xf=gf&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),RI=wf||xf||Jl,$I=cE||typeof navigator<"u"&&"gpu"in navigator,DI=typeof navigator<"u"&&"ml"in navigator,BI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",UI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",FI=typeof ServiceWorkerGlobalScope<"u"&&gf&&self instanceof ServiceWorkerGlobalScope,GI=()=>{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},jI=GI(),ie=Object.freeze({IS_BROWSER_ENV:wf,IS_WEBWORKER_ENV:xf,IS_WEB_ENV:RI,IS_SERVICE_WORKER_ENV:FI,IS_DENO_WEB_RUNTIME:Jl,IS_WEB_CACHE_AVAILABLE:Yl,IS_WEBGPU_AVAILABLE:$I,IS_WEBNN_AVAILABLE:DI,IS_SAFARI:jI,IS_PROCESS_AVAILABLE:lE,IS_NODE_ENV:cE,IS_FS_AVAILABLE:nn,IS_PATH_AVAILABLE:iE,IS_CRYPTO_AVAILABLE:BI,IS_CHROME_AVAILABLE:UI}),yf=nn&&iE,Ql="./";if(yf){let t=Object(import.meta).url;t?Ql=Ut.dirname(Ut.dirname(nE.fileURLToPath(t))):typeof __dirname<"u"&&(Ql=Ut.dirname(__dirname))}var qI=yf?Ut.join(Ql,"/.cache/"):null,oE="/models/",WI=yf?Ut.join(Ql,oE):oE,VI=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ot=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),aE=Ot.WARNING,me={version:NI,backends:{onnx:{}},get logLevel(){return aE},set logLevel(t){aE=t,me.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(wf||xf||Jl),localModelPath:WI,useFS:nn,useBrowserCache:Yl,useFSCache:nn,cacheDir:qI,useCustomCache:!1,customCache:null,useWasmCache:Yl||nn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:VI};function uE(t){return Object.keys(t).length===0}var Ke=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function lr(t,e){t&&t(e)}var hs=class extends Ke{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 pE(t){return Number.isInteger(t)||typeof t=="bigint"}function bf(t){return t==null||t===-1}function vf(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 fE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function on(t,e){return Math.abs((t+e)%(2*e)-e)}function Ye(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function dE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var ee={error(...t){me.logLevel<=Ot.ERROR&&console.error(...t)},warn(...t){me.logLevel<=Ot.WARNING&&console.warn(...t)},info(...t){me.logLevel<=Ot.INFO&&console.log(...t)},debug(...t){me.logLevel<=Ot.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var HI=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]]))})(),YI=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),QI=YI(bE),_E=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",JI=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|[${_E}])]+`,` ?[^\\s${_E}]+`]]),Zl="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Ef=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"),ec=(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 JI)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=ZI(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},ZI=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),eC=(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,rC=t=>Number.isInteger(t)||typeof t=="bigint",sC=t=>{let e=0;for(let r of t)++e;return e},nC=t=>vE(t.toLowerCase()),Kt=(...t)=>Array.prototype.concat.apply([],t),Af=t=>new Map(Object.entries(t)),oC=(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,""),hE=(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},aC=t=>t.match(/\S+/g)||[],iC=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},co=iC,lC=class extends co{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},vr=lC,cC=class extends vr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},fC=pC,dC=class extends vr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>kE(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},mC=dC,_C=class extends vr{normalize(t){let e=ec(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},hC=_C,gC=class extends vr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},tc=gC,wC=class extends tc{constructor(){super(...arguments),this.form="NFC"}},xC=wC,yC=class extends tc{constructor(){super(...arguments),this.form="NFD"}},bC=yC,vC=class extends tc{constructor(){super(...arguments),this.form="NFKC"}},kC=vC,EC=class extends tc{constructor(){super(...arguments),this.form="NFKD"}},AC=EC,TC=class extends vr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},MC=TC,SC=class extends vr{normalize(t){return vE(t)}},OC=SC,IC=class extends vr{normalize(t){return t.toLowerCase()}},CC=IC,PC=class extends vr{normalize(t){return t=this.config.prepend+t,t}},LC=PC;function NC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new uC(t);case"Precompiled":return new fC(t);case"Sequence":return new mC(t);case"Replace":return new hC(t);case"NFC":return new xC(t);case"NFD":return new bC(t);case"NFKC":return new kC(t);case"NFKD":return new AC(t);case"Strip":return new MC(t);case"StripAccents":return new OC(t);case"Lowercase":return new CC(t);case"Prepend":return new LC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var kE=NC,zC=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)}},Yt=zC,RC=class extends Yt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=bE,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(""))}},$C=RC,DC=class extends Yt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},BC=DC,UC=class extends Yt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},FC=UC,GC=class extends Yt{constructor(t){super(),this.config=t,this.pattern=ec(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):oC(t,this.pattern)}},jC=GC,qC=class extends Yt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Zl}]+|[${Zl}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},WC=qC,VC=class extends Yt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},HC=VC,XC=class extends Yt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Zl}]+|[${Zl}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},KC=XC,YC=class extends Yt{constructor(t){super(),this.config=t,this.pattern=ec(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},QC=YC,JC=class extends Yt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>EE(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},ZC=JC,eP=class extends Yt{pre_tokenize_text(t){return aC(t)}},tP=eP,rP=class extends Yt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;rthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},gE=aP,wE=class AE{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new AE(!1,new Map)}},iP=class{constructor(){this.root=wE.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=wE.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)}}},lP=iP,kf=class TE{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 TE(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},cP=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 kf(this.bos_token_id??0,0,0,0,0),n=new kf(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 kf(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let u=c.backtrace_score+a.score;(l===null||u>i)&&(l=c.clone(),i=u)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},uP=cP;function pP(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=pP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new lP,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()}},hP=_P,gP=class extends rc{constructor(t){super(t),this.tokens_to_ids=Af(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 hP(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 mP((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}},yE=gP,wP=class extends rc{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=Af(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}},xP=wP;function yP(t,e){switch(t.type){case"WordPiece":return new gE(t);case"Unigram":return new xE(t,e.eos_token);case"BPE":return new yE(t);default:if(t.vocab)return Array.isArray(t.vocab)?new xE(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new yE(t):new gE(t):new xP(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 bP=yP,vP=class extends co{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},uo=vP,kP=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=Kt(n,t),o=Kt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Kt(n,e),o=Kt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},EP=kP,AP=class extends uo{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},TP=AP,MP=class extends uo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Kt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Kt(t,n,e,o),s=Kt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},SP=MP,OP=class extends uo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Kt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Kt(t,n,e,o),s=Kt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},IP=OP,CP=class extends uo{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>ME(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}},PP=CP;function LP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new EP(t);case"ByteLevel":return new TP(t);case"BertProcessing":return new SP(t);case"RobertaProcessing":return new IP(t);case"Sequence":return new PP(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var ME=LP,NP=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("")}},Ft=NP,zP=class extends Ft{constructor(t){super(t),this.byte_decoder=QI,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}},RP=zP,$P=class extends Ft{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=Ef(e)),e})}},DP=$P,BP=class extends Ft{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;re.replaceAll(this.suffix,r===t.length-1?"":" "))}},GP=FP,jP=class extends Ft{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(s=Ef(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},qP=jP,WP=class extends Ft{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>SE(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},VP=WP,HP=class extends Ft{decode_chain(t){let e=ec(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},XP=HP,KP=class extends Ft{decode_chain(t){return[t.join("")]}},YP=KP,QP=class extends Ft{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},eL=ZP;function tL(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new RP(t);case"WordPiece":return new DP(t);case"Metaspace":return new UP(t);case"BPEDecoder":return new GP(t);case"CTC":return new qP(t);case"Sequence":return new VP(t);case"Replace":return new XP(t);case"Fuse":return new YP(t);case"Strip":return new JP(t);case"ByteFallback":return new eL(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var SE=tL,rL=class{constructor(t,e){let r=hE(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=hE(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=kE(this.tokenizer.normalizer),this.pre_tokenizer=EE(this.tokenizer.pre_tokenizer),this.model=bP(this.tokenizer.model,this.config),this.post_processor=ME(this.tokenizer.post_processor),this.decoder=SE(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 KI(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 mE(n),this.splitter_normalized=new mE(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||!rC(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=Ef(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=nC(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Kt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r=",U.ComparisonBinaryOperator],["==",U.ComparisonBinaryOperator],["!=",U.ComparisonBinaryOperator],["<",U.ComparisonBinaryOperator],[">",U.ComparisonBinaryOperator],["+",U.AdditiveBinaryOperator],["-",U.AdditiveBinaryOperator],["~",U.AdditiveBinaryOperator],["*",U.MultiplicativeBinaryOperator],["/",U.MultiplicativeBinaryOperator],["%",U.MultiplicativeBinaryOperator],["=",U.Equals]],nL=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function oL(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 aL(t,e={}){let r=[],s=oL(t,e),n=0,o=0,a=c=>{let u="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=nL.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);u+=m;continue}if(u+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return u},i=()=>{let c=r.at(-1);c&&c.type===U.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new Gt(f,U.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let m="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");m+=s[n++]}let _=m.endsWith("-");_&&(m=m.slice(0,-1)),f&&i(),r.push(new Gt(m,U.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Gt("{%",U.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Gt("{{",U.OpenExpression)),o=0,n+=3;continue}if(a(CE),s.slice(n,n+3)==="-%}"){r.push(new Gt("%}",U.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Gt("}}",U.CloseExpression)),n+=3,l();continue}let u=s[n];if(u==="-"||u==="+"){let f=r.at(-1)?.type;if(f===U.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${u}`);switch(f){case U.Identifier:case U.NumericLiteral:case U.StringLiteral:case U.CloseParen:case U.CloseSquareBracket:break;default:{++n;let m=a(po);r.push(new Gt(`${u}${m}`,m.length>0?U.NumericLiteral:U.UnaryOperator));continue}}}for(let[f,m]of sL){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Gt(f,m)),m===U.OpenExpression?o=0:m===U.OpenCurlyBracket?++o:m===U.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(u==="'"||u==='"'){++n;let f=a(m=>m!==u);r.push(new Gt(f,U.StringLiteral)),++n;continue}if(po(u)){let f=a(po);if(s[n]==="."&&po(s[n+1])){++n;let m=a(po);f=`${f}.${m}`}r.push(new Gt(f,U.NumericLiteral));continue}if(IE(u)){let f=a(IE);r.push(new Gt(f,U.Identifier));continue}throw new SyntaxError(`Unexpected character: ${u}`)}return r}var Jt=class{type="Statement"},iL=class extends Jt{constructor(t){super(),this.body=t}type="Program"},lL=class extends Jt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},cL=class extends Jt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},uL=class extends Jt{type="Break"},pL=class extends Jt{type="Continue"},fL=class extends Jt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},dL=class extends Jt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},mL=class extends Jt{constructor(t){super(),this.value=t}type="Comment"},Lt=class extends Jt{type="Expression"},_L=class extends Lt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},PE=class extends Lt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},an=class extends Lt{constructor(t){super(),this.value=t}type="Identifier"},ln=class extends Lt{constructor(t){super(),this.value=t}type="Literal"},hL=class extends ln{type="IntegerLiteral"},gL=class extends ln{type="FloatLiteral"},LE=class extends ln{type="StringLiteral"},wL=class extends ln{type="ArrayLiteral"},NE=class extends ln{type="TupleLiteral"},xL=class extends ln{type="ObjectLiteral"},fo=class extends Lt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},yL=class extends Lt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},bL=class extends Jt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},vL=class extends Lt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},kL=class extends Lt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},EL=class extends Lt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},AL=class extends Lt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},TL=class extends Lt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},ML=class extends Lt{constructor(t){super(),this.argument=t}type="SpreadExpression"},SL=class extends Jt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},OL=class extends Lt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function IL(t){let e=new iL([]),r=0;function s(L,R){let D=t[r++];if(!D||D.type!==L)throw new Error(`Parser Error: ${R}. ${D.type} !== ${L}.`);return D}function n(L){if(!l(L))throw new SyntaxError(`Expected ${L}`);++r}function o(){switch(t[r].type){case U.Comment:return new mL(t[r++].value);case U.Text:return c();case U.OpenStatement:return u();case U.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...L){return r+L.length<=t.length&&L.every((R,D)=>R===t[r+D].type)}function i(...L){return t[r]?.type===U.OpenStatement&&t[r+1]?.type===U.Identifier&&L.includes(t[r+1]?.value)}function l(...L){return r+L.length<=t.length&&L.every((R,D)=>t[r+D].type==="Identifier"&&R===t[r+D].value)}function c(){return new LE(s(U.Text,"Expected text token").value)}function u(){if(s(U.OpenStatement,"Expected opening statement token"),t[r].type!==U.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let L=t[r].value,R;switch(L){case"set":++r,R=m();break;case"if":++r,R=_(),s(U.OpenStatement,"Expected {% token"),n("endif"),s(U.CloseStatement,"Expected %} token");break;case"macro":++r,R=w(),s(U.OpenStatement,"Expected {% token"),n("endmacro"),s(U.CloseStatement,"Expected %} token");break;case"for":++r,R=E(),s(U.OpenStatement,"Expected {% token"),n("endfor"),s(U.CloseStatement,"Expected %} token");break;case"call":{++r;let D=null;a(U.OpenParen)&&(D=F());let Z=Y();if(Z.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let xe=F();s(U.CloseStatement,"Expected closing statement token");let ue=[];for(;!i("endcall");)ue.push(o());s(U.OpenStatement,"Expected '{%'"),n("endcall"),s(U.CloseStatement,"Expected closing statement token");let We=new PE(Z,xe);R=new SL(We,D,ue);break}case"break":++r,s(U.CloseStatement,"Expected closing statement token"),R=new uL;break;case"continue":++r,s(U.CloseStatement,"Expected closing statement token"),R=new pL;break;case"filter":{++r;let D=Y();D instanceof an&&a(U.OpenParen)&&(D=G(D)),s(U.CloseStatement,"Expected closing statement token");let Z=[];for(;!i("endfilter");)Z.push(o());s(U.OpenStatement,"Expected '{%'"),n("endfilter"),s(U.CloseStatement,"Expected '%}'"),R=new bL(D,Z);break}default:throw new SyntaxError(`Unknown statement type: ${L}`)}return R}function f(){s(U.OpenExpression,"Expected opening expression token");let L=b();return s(U.CloseExpression,"Expected closing expression token"),L}function m(){let L=x(),R=null,D=[];if(a(U.Equals))++r,R=x();else{for(s(U.CloseStatement,"Expected %} token");!i("endset");)D.push(o());s(U.OpenStatement,"Expected {% token"),n("endset")}return s(U.CloseStatement,"Expected closing statement token"),new fL(L,R,D)}function _(){let L=b();s(U.CloseStatement,"Expected closing statement token");let R=[],D=[];for(;!i("elif","else","endif");)R.push(o());if(i("elif")){++r,++r;let Z=_();D.push(Z)}else if(i("else"))for(++r,++r,s(U.CloseStatement,"Expected closing statement token");!i("endif");)D.push(o());return new lL(L,R,D)}function w(){let L=Y();if(L.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let R=F();s(U.CloseStatement,"Expected closing statement token");let D=[];for(;!i("endmacro");)D.push(o());return new dL(L,R,D)}function x(L=!1){let R=L?Y:b,D=[R()],Z=a(U.Comma);for(;Z&&(++r,D.push(R()),!!a(U.Comma)););return Z?new NE(D):D[0]}function E(){let L=x(!0);if(!(L instanceof an||L instanceof NE))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${L.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let R=b();s(U.CloseStatement,"Expected closing statement token");let D=[];for(;!i("endfor","else");)D.push(o());let Z=[];if(i("else"))for(++r,++r,s(U.CloseStatement,"Expected closing statement token");!i("endfor");)Z.push(o());return new cL(L,R,D,Z)}function b(){return A()}function A(){let L=S();if(l("if")){++r;let R=S();if(l("else")){++r;let D=A();return new OL(R,L,D)}else return new vL(L,R)}return L}function S(){let L=M();for(;l("or");){let R=t[r];++r;let D=M();L=new fo(R,L,D)}return L}function M(){let L=I();for(;l("and");){let R=t[r];++r;let D=I();L=new fo(R,L,D)}return L}function I(){let L;for(;l("not");){let R=t[r];++r;let D=I();L=new EL(R,D)}return L??O()}function O(){let L=v();for(;;){let R;if(l("not","in"))R=new Gt("not in",U.Identifier),r+=2;else if(l("in"))R=t[r++];else if(a(U.ComparisonBinaryOperator))R=t[r++];else break;let D=v();L=new fo(R,L,D)}return L}function v(){let L=B();for(;a(U.AdditiveBinaryOperator);){let R=t[r];++r;let D=B();L=new fo(R,L,D)}return L}function $(){let L=Q(Y());return a(U.OpenParen)?G(L):L}function G(L){let R=new PE(L,F());return R=Q(R),a(U.OpenParen)&&(R=G(R)),R}function F(){s(U.OpenParen,"Expected opening parenthesis for arguments list");let L=K();return s(U.CloseParen,"Expected closing parenthesis for arguments list"),L}function K(){let L=[];for(;!a(U.CloseParen);){let R;if(t[r].type===U.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let D=b();R=new ML(D)}else if(R=b(),a(U.Equals)){if(++r,!(R instanceof an))throw new SyntaxError("Expected identifier for keyword argument");let D=b();R=new TL(R,D)}L.push(R),a(U.Comma)&&++r}return L}function W(){let L=[],R=!1;for(;!a(U.CloseSquareBracket);)a(U.Colon)?(L.push(void 0),++r,R=!0):(L.push(b()),a(U.Colon)&&(++r,R=!0));if(L.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(R){if(L.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new AL(...L)}return L[0]}function Q(L){for(;a(U.Dot)||a(U.OpenSquareBracket);){let R=t[r];++r;let D,Z=R.type===U.OpenSquareBracket;if(Z)D=W(),s(U.CloseSquareBracket,"Expected closing square bracket");else if(D=Y(),D.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");L=new _L(L,D,Z)}return L}function B(){let L=P();for(;a(U.MultiplicativeBinaryOperator);){let R=t[r++],D=P();L=new fo(R,L,D)}return L}function P(){let L=re();for(;l("is");){++r;let R=l("not");R&&++r;let D=Y();if(!(D instanceof an))throw new SyntaxError("Expected identifier for the test");L=new kL(L,R,D)}return L}function re(){let L=$();for(;a(U.Pipe);){++r;let R=Y();if(!(R instanceof an))throw new SyntaxError("Expected identifier for the filter");a(U.OpenParen)&&(R=G(R)),L=new yL(L,R)}return L}function Y(){let L=t[r++];switch(L.type){case U.NumericLiteral:{let R=L.value;return R.includes(".")?new gL(Number(R)):new hL(Number(R))}case U.StringLiteral:{let R=L.value;for(;a(U.StringLiteral);)R+=t[r++].value;return new LE(R)}case U.Identifier:return new an(L.value);case U.OpenParen:{let R=x();return s(U.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),R}case U.OpenSquareBracket:{let R=[];for(;!a(U.CloseSquareBracket);)R.push(b()),a(U.Comma)&&++r;return++r,new wL(R)}case U.OpenCurlyBracket:{let R=new Map;for(;!a(U.CloseCurlyBracket);){let D=b();s(U.Colon,"Expected colon between key and value in object literal");let Z=b();R.set(D,Z),a(U.Comma)&&++r}return++r,new xL(R)}default:throw new SyntaxError(`Unexpected token: ${L.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function zE(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 LL(t){return NL(new Date,t)}function NL(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 zL(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RL(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(zL(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var RE=class extends Error{},$E=class extends Error{},cr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new pe(!!this.value)}toString(){return String(this.value)}},_e=class extends cr{type="IntegerValue"},Je=class extends cr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},te=class extends cr{type="StringValue";builtins=new Map([["upper",new qe(()=>new te(this.value.toUpperCase()))],["lower",new qe(()=>new te(this.value.toLowerCase()))],["strip",new qe(()=>new te(this.value.trim()))],["title",new qe(()=>new te(PL(this.value)))],["capitalize",new qe(()=>new te(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new _e(this.value.length)],["rstrip",new qe(()=>new te(this.value.trimEnd()))],["lstrip",new qe(()=>new te(this.value.trimStart()))],["startswith",new qe(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof te)return new pe(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 pe(!0)}return new pe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new qe(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof te)return new pe(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 pe(!0)}return new pe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new qe(t=>{let e=t[0]??new Ve;if(!(e instanceof te||e instanceof Ve))throw new Error("sep argument must be a string or null");let r=t[1]??new _e(-1);if(!(r instanceof _e))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Ve){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 qe(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 Ve:s=t[2]:s=new Ve,!(s instanceof _e||s instanceof Ve))throw new Error("replace() count argument must be a number or null");return new te(RL(this.value,e.value,r.value,s.value))})]])},pe=class extends cr{type="BooleanValue"},$L=/[\x7f-\uffff]/g;function DE(t){return t.replace($L,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function ws(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let u=JSON.stringify(t.value);return o&&(u=DE(u)),u}case"ArrayValue":case"ObjectValue":{let u=n?" ".repeat(n):"",f=` `+u.repeat(r),m=f+u;if(t.type==="ArrayValue"){let _=t.value.map(w=>ws(w,e,r+1,s));return n?`[${m}${_.join(`${l}${m}`)}${f}]`:`[${_.join(l)}]`}else{let _=Array.from(t.value.entries());i&&(_=_.sort(([x],[E])=>x.localeCompare(E)));let w=_.map(([x,E])=>{let b=JSON.stringify(x);o&&(b=DE(b));let A=`${b}${c}${ws(E,e,r+1,s)}`;return n?`${m}${A}`:A});return n?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var ct=class extends cr{type="ObjectValue";__bool__(){return new pe(this.value.size>0)}builtins=new Map([["get",new qe(([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 Ve})],["items",new qe(()=>this.items())],["keys",new qe(()=>this.keys())],["values",new qe(()=>this.values())],["dictsort",new qe(t=>{let e=new Map,r=t.filter(i=>i instanceof mo?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new pe(!1);if(!(s instanceof pe))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 pe(!1);if(!(o instanceof pe))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new ye([new te(i),l])).sort((i,l)=>{let c=n.value==="key"?0:1,u=i.value[c],f=l.value[c],m=Tf(u,f,s.value);return o.value?-m:m});return new ye(a)})]]);items(){return new ye(Array.from(this.value.entries()).map(([t,e])=>new ye([new te(t),e])))}keys(){return new ye(Array.from(this.value.keys()).map(t=>new te(t)))}values(){return new ye(Array.from(this.value.values()))}toString(){return ws(this,{},0,!1)}},mo=class extends ct{type="KeywordArgumentsValue"},ye=class extends cr{type="ArrayValue";builtins=new Map([["length",new _e(this.value.length)]]);__bool__(){return new pe(this.value.length>0)}toString(){return ws(this,{},0,!1)}},BE=class extends ye{type="TupleValue"},qe=class extends cr{type="FunctionValue"},Ve=class extends cr{type="NullValue"},je=class extends cr{type="UndefinedValue"},gs=class{constructor(t){this.parent=t}variables=new Map([["namespace",new qe(t=>{if(t.length===0)return new ct(new Map);if(t.length!==1||!(t[0]instanceof ct))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 qe],["odd",t=>{if(!(t instanceof _e))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof _e))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 _e||t instanceof Je],["integer",t=>t instanceof _e],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t instanceof ct],["sequence",t=>t instanceof ye||t instanceof ct||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,sc(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 je}catch{return new je}}};function DL(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",CL),t.set("strftime_now",LL),t.set("True",!0),t.set("False",!1),t.set("None",null)}function UE(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof ct)s=s.value.get(n)??new je;else if(s instanceof ye){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&oo instanceof _e||o instanceof Je||o instanceof pe,n=o=>o instanceof pe?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 BL=class{global;constructor(t){this.global=t??new gs}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 pe(r.value==s.value);case"!=":return new pe(r.value!=s.value)}if(r instanceof je||s instanceof je){if(s instanceof je&&["in","not in"].includes(t.operator.value))return new pe(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof Ve||s instanceof Ve)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 _e||r instanceof Je)&&(s instanceof _e||s instanceof Je)){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 Je||s instanceof Je?new Je(a):new _e(a)}case"/":return new Je(n/o);case"%":{let a=n%o;return r instanceof Je||s instanceof Je?new Je(a):new _e(a)}case"<":return new pe(n":return new pe(n>o);case">=":return new pe(n>=o);case"<=":return new pe(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 pe(n);case"not in":return new pe(!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 pe(s.value.includes(r.value));case"not in":return new pe(!s.value.includes(r.value))}if(r instanceof te&&s instanceof ct)switch(t.operator.value){case"in":return new pe(s.value.has(r.value));case"not in":return new pe(!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(ws(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 _e(t.value.length);case"reverse":return new ye(t.value.slice().reverse());case"sort":return new ye(t.value.slice().sort((n,o)=>Tf(n,o,!1)));case"join":return new te(t.value.map(n=>n.value).join(""));case"string":return new te(ws(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 qe)return n.value([],r);if(n instanceof _e)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 _e(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Je(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof _e||t instanceof Je)switch(s.value){case"abs":return t instanceof _e?new _e(Math.abs(t.value)):new Je(Math.abs(t.value));case"int":return new _e(Math.floor(t.value));case"float":return new Je(t.value);case"string":return new te(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof ct)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 _e(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof qe?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof pe)switch(s.value){case"bool":return new pe(t.value);case"int":return new _e(t.value?1:0);case"float":return new Je(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 Ve;if(!(a instanceof _e||a instanceof Ve))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new pe(!1);if(!(i instanceof pe))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new pe(!1);if(!(l instanceof pe))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Ve,u=null;if(c instanceof ye||c instanceof BE){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.value;if(!(f instanceof te)||!(m instanceof te))throw new Error("separators must be a tuple of two strings");u=[f.value,m.value]}else if(!(c instanceof Ve))throw new Error("If set, separators must be a tuple of two strings");return new te(ws(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:u}))}else if(n==="join"){let o;if(t instanceof te)o=Array.from(t.value);else if(t instanceof ye)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new te("");if(!(l instanceof te))throw new Error("separator must be a string");return new te(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new _e(0):new Je(0));if(t instanceof te){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new _e(l):new Je(l)}else{if(t instanceof _e||t instanceof Je)return t;if(t instanceof pe)return n==="int"?new _e(t.value?1:0):new Je(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 pe(!1);if(!(l instanceof pe))throw new Error("`default` filter flag must be a boolean");return t instanceof je||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 pe(!1);if(!(i instanceof pe))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new pe(!1);if(!(l instanceof pe))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Ve;if(!(c instanceof te||c instanceof _e||c instanceof Ve))throw new Error("attribute must be a string, integer, or null");let u=f=>{if(c instanceof Ve)return f;let m=c instanceof _e?String(c.value):c.value;return UE(f,m)};return new ye(t.value.slice().sort((f,m)=>{let _=u(f),w=u(m),x=Tf(_,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ct)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let u=t.value.filter(f=>{let m=f.value.get(a.value),_=m?c(m,l):!1;return o?_:!_});return new ye(u)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof te))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof ct))throw new Error("items in map must be an object");let u=UE(c,a.value);return u instanceof je?i??new je:u});return new ye(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof te){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new _e(4);if(!(i instanceof _e))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new pe(!1),c=o.at(2)??a.get("blank")??new pe(!1),u=t.value.split(` `),f=" ".repeat(i.value),m=u.map((_,w)=>!l.value&&w===0||!c.value&&_.length===0?_:f+_);return new te(m.join(` `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof qe))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new mo(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ct){let o=t.builtins.get(n);if(o&&o instanceof qe){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new mo(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 pe(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new je}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new pe(!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 mo(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 _e||s instanceof je))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof _e||n instanceof je))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof _e||o instanceof je))throw new Error("Slice step must be numeric or undefined");return t instanceof ye?new ye(zE(t.value,s.value,n.value,o.value)):new te(zE(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 ct){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 _e)n=r.value.at(s.value),r instanceof te&&(n=new te(r.value.at(s.value)));else if(s instanceof te)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof te))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof cr?n:new je}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ye))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o_.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let _=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(_.value.length!==w.value.length)throw new Error(`Too ${_.value.length>w.value.length?"few":"many"} items to unpack`);m=x=>{for(let E=0;E<_.value.length;++E){if(_.value[E].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_.value[E].type}`);x.setVariable(_.value[E].value,w.value[E])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(u),!this.evaluate(s,u).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let c=0;c0?o[c-1]:new je],["nextitem",c{let n=new gs(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a{let c=new gs(l);if(t.callerArgs)for(let u=0;uthis.evaluate(r,e)));case"TupleLiteral":return new BE(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 ct(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 Ve;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function sc(t){switch(typeof t){case"number":return Number.isInteger(t)?new _e(t):new Je(t);case"string":return new te(t);case"boolean":return new pe(t);case"undefined":return new je;case"object":return t===null?new Ve:Array.isArray(t)?new ye(t.map(sc)):new ct(new Map(Object.entries(t).map(([e,r])=>[e,sc(r)])));case"function":return new qe((e,r)=>{let s=t(...e.map(n=>n.value))??null;return sc(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var rt=` `,UL="{%- ",FL=" -%}";function GL(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 jL(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Qt(t.body,0,r).replace(/\n$/,"")}function wt(...t){return UL+t.join(" ")+FL}function Qt(t,e,r){return t.map(s=>qL(s,e,r)).join(rt)}function qL(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Qt(t.body,e,r);case"If":return WL(t,e,r);case"For":return VL(t,e,r);case"Set":return HL(t,e,r);case"Macro":return XL(t,e,r);case"Break":return s+wt("break");case"Continue":return s+wt("continue");case"CallStatement":return KL(t,e,r);case"FilterStatement":return YL(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function WL(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))+rt+Qt(n[0].body,e+1,r);for(let i=1;i0&&(a+=rt+s+wt("else")+rt+Qt(o.alternate,e+1,r)),a+=rt+s+wt("endif"),a}function VL(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)+rt+Qt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=rt+s+wt("else")+rt+Qt(t.defaultBlock,e+1,r)),o+=rt+s+wt("endfor"),o}function HL(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+rt+Qt(t.body,e+1,r)+rt+s+wt("endset")}function XL(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+wt("macro",`${t.name.value}(${n})`)+rt+Qt(t.body,e+1,r)+rt+s+wt("endmacro")}function KL(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)+rt;return a+=Qt(t.body,e+1,r)+rt,a+=s+wt("endcall"),a}function YL(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+wt("filter",n)+rt;return o+=Qt(t.body,e+1,r)+rt,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=GL(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 FE=class{parsed;constructor(t){let e=aL(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=IL(e)}render(t){let e=new gs;if(DL(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new BL(e).run(this.parsed).value}format(t){return jL(this.parsed,t?.indent||" ")}};var QL={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"},Lr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=ht.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=ht.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=ht.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",QL[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 ht.promises.readFile(this.filePath)).buffer}async blob(){let e=await ht.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await ht.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Nr=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[GE(this._random_fn,r)]}};function GE(t,e){let r=0;for(let n=0;nGE(xs.random,t);var JL=new Nr,cn=class{constructor(e){this.path=e}async match(e){let r=Ut.join(this.path,e),s=new Lr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Ut.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=JL._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),u=0;await ht.promises.mkdir(Ut.dirname(n),{recursive:!0});let f=ht.createWriteStream(i),m=r.body.getReader();for(;;){let{done:_,value:w}=await m.read();if(_)break;await new Promise((E,b)=>{f.write(w,A=>{if(A){b(A);return}E()})}),u+=w.length;let x=c?u/c*100:0;s?.({progress:x,loaded:u,total:c})}await new Promise((_,w)=>{f.close(x=>x?w(x):_())}),await ht.promises.rename(i,n)}catch(l){try{await ht.promises.unlink(i)}catch{}throw l}}async delete(e){let r=Ut.join(this.path,e);try{return await ht.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"},nc=100,WE=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function _o(...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 zr(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 VE(t){return!(!WE.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function HE(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 XE(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&ee.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:u}=await i.read();if(c)return;let f=a+u.length;if(f>n){n=f;let _=new Uint8Array(n);_.set(o),o=_}o.set(u,a),a=f;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}function Mf(t){return zr(t,["blob:"])}function Sf(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 YE="SHA-256",ZL="experimental_transformers-hash-cache",KE=t=>({algorithm:YE,value:t}),ho=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(ZL),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([KE(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([KE(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(YE,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Zt(t=null){let e=null;if(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&&ho.isAvailable()&&(e=new ho),!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 cn(t??me.cacheDir)}return e}async function QE(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var oc=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 eN=100,Of=new oc(eN);function ac(t,e){let r=Of.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(Of.delete(t),Promise.reject(n)));return Of.put(t,s),s}async function tN(t){if(!zr(t,["http:","https:"]))return null;let e=If(t);return e.set("Range","bytes=0-0"),me.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function It(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return ac(s,()=>rN(t,e,r))}async function rN(t,e,r){let s=await Zt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=$r(t,e,r,s),l=await Dr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),u=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:u||void 0,fromCache:!0}}if(me.allowLocalModels&&!zr(n,["http:","https:"]))try{let u=await Rr(n);if(typeof u!="string"&&u.status!==404){let f=u.headers.get("content-length"),m=u.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(me.allowRemoteModels&&!r.local_files_only&&i)try{let c=await tN(o);if(c&&c.status>=200&&c.status<300){let u,f=c.headers.get("content-type");if(c.status===206){let m=c.headers.get("content-range");if(m){let _=m.match(/bytes \d+-\d+\/(\d+)/);_&&(u=parseInt(_[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(u===void 0){let m=c.headers.get("content-length");u=m?parseInt(m,10):void 0}return{exists:!0,size:u,contentType:f||void 0,fromCache:!1}}}catch(c){ee.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Rr(t){return me.useFS&&!zr(t,["http:","https:","blob:"])?new Lr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):me.fetch(t,{headers:If(t)})}function If(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};`),zr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function $r(t,e,r={},s=null){let n=r.revision??"main",o=_o(t,e),a=VE(t),i=a?_o(me.localModelPath,o):o,l=_o(me.remoteHost,me.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof cn?n==="main"?o:_o(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Dr(t,e,r){if(t)return await QE(t,e,r)}async function sN(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{ee.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>lr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function nN(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:u}=$r(t,e,s,o),f,m=!1,_;_=await Dr(o,i,c);let w=_!==void 0;if(w)f=c;else{if(me.allowLocalModels)if(zr(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{_=await Rr(i),f=i}catch(A){ee.warn(`Unable to load from local path "${i}": "${A}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!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(!u)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Rr(l),_.status!==200)return HE(_.status,l,r);f=c}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}lr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let b;if(typeof _!="string")if(!s.progress_callback)b=new Uint8Array(await _.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))b=new Uint8Array(await _.arrayBuffer()),lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:b.length,total:b.length});else{let A,S=_.headers.get("content-length");if(S)A=parseInt(S,10);else try{let M=await It(t,e,s);M.size&&(A=M.size)}catch{}b=await XE(_,M=>{lr(s.progress_callback,{status:"progress",name:t,file:e,...M})},A)}x=b}if(m&&f&&typeof _!="string"&&await sN(t,e,o,f,_,x,s),ie.IS_NODE_ENV&&n&&s.progress_callback&&typeof _!="string"){let b=parseInt(_.headers.get("content-length"),10)||0;lr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:b,total:b})}if(lr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!ie.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof Lr)return _.filePath;let E=await o?.match(f);if(E instanceof Lr)return E.filePath;if(E instanceof Response)return new Uint8Array(await E.arrayBuffer());if(typeof E=="string")return E;throw new Error("Unable to get model file path or buffer.")}var ic=new Map;async function go(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`.")}lr(s.progress_callback,{status:"initiate",name:t,file:e});let o=`${t}::${e}`,a=ic.get(o);if(!a){let i=await Zt(s?.cache_dir);a=nN(t,e,r,s,n,i).then(l=>(ic.delete(o),l),l=>{throw ic.delete(o),l}),ic.set(o,a)}return await a}async function Cf(t,e,r=!0,s={}){let n=await go(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function ut(t,e,r=!0,s={}){let n=await Cf(t,e,r,s);return n===null?{}:JSON.parse(n)}function ZE(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,u=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=u%e[c]*o[c],u=Math.floor(u/e[c]);a[l]=t[i]}return[a,s]}function Re(t){let e=Ce(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 Lf(t){let e=Ce(t)[0],r=0;for(let o=0;oo-e-s)}function tA(t,e){let r=0;for(let s=0;se+r*r,0))}function wo(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 rA(t){return t>0&&(t&t-1)===0}var lc=class{constructor(e){if(this.size=e|0,this.size<=1||!rA(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l>>1;for(let _=2;_>1;++u){let f=(u+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,_=f*Math.atan2(c,l),w=2*u;o[w]=m*Math.cos(_),o[w+1]=m*Math.sin(_),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new lc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,u=this._a;if(s)for(let f=0;f>1,w=r[_];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function ys(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function nA(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function oA(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let u=1;u0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var aA=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,m=l&1023;if(f===31)c=u|2139095040|m<<13;else if(f===0)if(m===0)c=u;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,c=u|_<<23|m<<13}else c=u|f+112<<23|m<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;oaN});var aN={};var Ed={};_s(Ed,{InferenceSession:()=>cd,TRACE:()=>wc,TRACE_EVENT_BEGIN:()=>jr,TRACE_EVENT_END:()=>qr,TRACE_FUNC_BEGIN:()=>Ts,TRACE_FUNC_END:()=>Ms,Tensor:()=>er,default:()=>zN,env:()=>He,registerBackend:()=>As});var id=Object.defineProperty,iN=Object.getOwnPropertyDescriptor,lN=Object.getOwnPropertyNames,cN=Object.prototype.hasOwnProperty,uN=(t=>typeof ms<"u"?ms:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof ms<"u"?ms:e)[r]}):t)(function(t){if(typeof ms<"u")return ms.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>()=>(t&&(e=t(t=0)),e),To=(t,e)=>{for(var r in e)id(t,r,{get:e[r],enumerable:!0})},pN=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lN(e))!cN.call(t,n)&&n!==r&&id(t,n,{get:()=>e[n],enumerable:!(s=iN(e,n))||s.enumerable});return t},gc=t=>pN(id({},"__esModule",{value:!0}),t),xo,Br,As,iA,NA,zA=be(()=>{"use strict";xo=new Map,Br=[],As=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=xo.get(t);if(s===void 0)xo.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Br.indexOf(t);n!==-1&&Br.splice(n,1);for(let o=0;o{let e=xo.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}}},NA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Br:r,n,o=[],a=new Set;for(let l of s){let c=await iA(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)})]}}),fN=be(()=>{"use strict";zA()}),RA,dN=be(()=>{"use strict";RA="1.24.0-dev.20251116-b39e144322"}),zf,pt,$A=be(()=>{"use strict";dN(),zf="warning",pt={wasm:{},webgl:{},webgpu:{},versions:{common:RA},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}`);zf=t}},get logLevel(){return zf}},Object.defineProperty(pt,"logLevel",{enumerable:!0})}),He,mN=be(()=>{"use strict";$A(),He=pt}),DA,BA,_N=be(()=>{"use strict";DA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,E=3,b=0,A=f,S=f*2,M=-1;i==="RGBA"?(b=0,A=f,S=f*2,M=f*3):i==="RGB"?(b=0,A=f,S=f*2):i==="RBG"&&(b=0,S=f,A=f*2),s=r.createImageData(n,o);for(let I=0;I{"use strict";ld(),uc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,E=0,b=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(E=0,A=c,b=c*2):l==="BGR"&&(A=0,b=c,E=c*2);for(let M=0;M{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,uc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(uc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return uc(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},FA=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Rt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},GA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Rt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},jA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Rt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},qA=(t,e,r)=>new Rt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ks,Eo,Rf,WA,gN=be(()=>{"use strict";ks=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Eo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Rf=!1,WA=()=>{if(!Rf){Rf=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(ks.set("int64",BigInt64Array),Eo.set(BigInt64Array,"int64")),e&&(ks.set("uint64",BigUint64Array),Eo.set(BigUint64Array,"uint64")),s?(ks.set("float16",r),Eo.set(r,"float16")):ks.set("float16",Uint16Array)}}}),VA,HA,wN=be(()=>{"use strict";ld(),VA=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new Rt(t.type,t.data,e);case"cpu-pinned":return new Rt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Rt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Rt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Rt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Rt,ld=be(()=>{"use strict";_N(),hN(),gN(),wN(),Rt=class{constructor(t,e,r){WA();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=ks.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=ks.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=Eo.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=VA(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 UA(t,e)}static fromTexture(t,e){return FA(t,e)}static fromGpuBuffer(t,e){return GA(t,e)}static fromMLTensor(t,e){return jA(t,e)}static fromPinnedBuffer(t,e,r){return qA(t,e,r)}toDataURL(t){return DA(this,t)}toImageData(t){return BA(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 HA(this,t)}}}),er,XA=be(()=>{"use strict";ld(),er=Rt}),wc,$f,Ts,Ms,jr,qr,KA=be(()=>{"use strict";$A(),wc=(t,e)=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeStamp(`${t}::ORT::${e}`)},$f=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||$f("BEGIN",t)},Ms=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||$f("END",t)},jr=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.time(`ORT::${t}`)},qr=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeEnd(`ORT::${t}`)}}),YA,xN=be(()=>{"use strict";zA(),XA(),KA(),YA=class QA{constructor(e){this.handler=e}async run(e,r,s){Ts(),jr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof er||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,u=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(u.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof er)&&(c=!0,a=!1,n[f]=m)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let u=i[c];u instanceof er?l[c]=u:l[c]=new er(u.type,u.data,u.dims)}return qr("InferenceSession.run"),Ms(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Ts(),jr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,f=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(m=e.byteLength-f,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||f+m>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(u,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await NA(a),c=await i.createInferenceSessionHandler(o,l);return qr("InferenceSession.create"),Ms(),new QA(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}}}),cd,yN=be(()=>{"use strict";xN(),cd=YA}),bN=be(()=>{"use strict"}),vN=be(()=>{"use strict"}),kN=be(()=>{"use strict"}),EN=be(()=>{"use strict"}),JA={};To(JA,{InferenceSession:()=>cd,TRACE:()=>wc,TRACE_EVENT_BEGIN:()=>jr,TRACE_EVENT_END:()=>qr,TRACE_FUNC_BEGIN:()=>Ts,TRACE_FUNC_END:()=>Ms,Tensor:()=>er,env:()=>He,registerBackend:()=>As});var Ss=be(()=>{"use strict";fN(),mN(),yN(),XA(),bN(),vN(),KA(),kN(),EN()}),ud=be(()=>{"use strict"}),ZA={};To(ZA,{default:()=>e2});var Df,Bf,e2,AN=be(()=>{"use strict";_2(),Os(),pd(),Df="ort-wasm-proxy-worker",Bf=globalThis.self?.name===Df,Bf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":fd(r.wasm).then(()=>{gd(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;wd(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=bc(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;xd(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":yd(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;bd(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},kd([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":vd(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),e2=Bf?null:t=>new Worker(t??Nt,{type:"module",name:Df})}),t2={};To(t2,{default:()=>r2});async function lA(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(p,d)=>{p.startsWith("./")&&(p=p.substring(2)),(e.Uc||(e.Uc=new Map)).set(p,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let o=()=>{let p=d=>(...h)=>{let g=ar;return h=d(...h),ar!=g?new Promise((k,T)=>{Jp={resolve:k,reject:T}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=p(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(p,d)=>{throw d},c=import.meta.url,u="";if(r||s){try{u=new URL(".",c).href}catch{}s&&(i=p=>{var d=new XMLHttpRequest;return d.open("GET",p,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async p=>{if(O(p))return new Promise((h,g)=>{var k=new XMLHttpRequest;k.open("GET",p,!0),k.responseType="arraybuffer",k.onload=()=>{k.status==200||k.status==0&&k.response?h(k.response):g(k.status)},k.onerror=g,k.send(null)});var d=await fetch(p,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,_,w,x,E,b=console.log.bind(console),A=console.error.bind(console),S=b,M=A,I=!1,O=p=>p.startsWith("file://");function v(){Cr.buffer!=F.buffer&&xe()}if(n){let p=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let k=[];self.onmessage=T=>k.push(T),E=()=>{postMessage({Oc:"loaded"});for(let T of k)p(T);self.onmessage=p};for(let T of h.de)e[T]&&!e[T].proxy||(e[T]=(...C)=>{postMessage({Oc:"callHandler",ce:T,args:C})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));Cr=h.je,xe(),m=h.ke,mt(),Kl()}else if(g==="run"){(function(k){var T=(v(),P)[k+52>>>2>>>0];k=(v(),P)[k+56>>>2>>>0],mk(T,T-k),le(T)})(h.Nc),pf(h.Nc,0,0,1,0,0),tv(),Kp(h.Nc),G||(Yv(),G=!0);try{LM(h.he,h.Wc)}catch(k){if(k!="unwind")throw k}}else h.target!=="setimmediate"&&(g==="checkMailbox"?G&&Fl():g&&(M(`worker: received unknown command ${g}`),M(h)))}catch(k){throw ck(),k}};var $=p,G=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=p}var F,K,W,Q,B,P,re,Y,L,R,D,Z=!1;function xe(){var p=Cr.buffer;e.HEAP8=F=new Int8Array(p),W=new Int16Array(p),e.HEAPU8=K=new Uint8Array(p),Q=new Uint16Array(p),e.HEAP32=B=new Int32Array(p),e.HEAPU32=P=new Uint32Array(p),re=new Float32Array(p),Y=new Float64Array(p),L=new BigInt64Array(p),R=new BigUint64Array(p)}function ue(){Z=!0,n?E():br._b()}function We(p){throw M(p="Aborted("+p+")"),I=!0,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),x?.(p),p}function ot(){return{a:{f:NM,J:zM,k:RM,p:$M,l:DM,ta:BM,b:UM,ca:FM,Ka:iv,q:GM,da:pv,_a:fv,Ga:dv,Ia:mv,$a:_v,Ya:hv,Ra:gv,Xa:wv,pa:xv,Ha:yv,Yb:bv,Za:vv,Fa:kv,eb:jM,Da:WM,Tb:VM,Rb:XM,Ca:YM,M:QM,I:JM,Sb:ZM,ka:aS,Ub:iS,Ua:lS,Wb:uS,La:pS,Pb:fS,la:dS,Ta:Kp,bb:mS,U:wS,n:kS,c:Hp,sb:ES,w:AS,L:TS,z:MS,j:SS,o:Cv,tb:OS,G:IS,T:CS,h:PS,u:LS,m:NS,i:zS,Oa:RS,Pa:$S,Qa:DS,Ma:zv,Na:Rv,Qb:$v,fb:US,db:jS,Y:qS,rb:WS,ma:VS,cb:FS,gb:HS,ab:XS,Xb:KS,N:BS,hb:YS,X:QS,Vb:JS,ob:iO,C:lO,sa:cO,ra:uO,qb:pO,W:fO,v:dO,nb:mO,mb:_O,lb:hO,pb:gO,kb:wO,jb:xO,ib:yO,Va:jv,Wa:qv,Ja:Js,ea:Wv,oa:Vv,Sa:Hv,na:Xv,Db:II,xa:vI,Eb:OI,ya:bI,F:pI,e:JO,s:YO,x:KO,D:lI,Ib:wI,ba:hI,B:tI,za:xI,$:kI,ha:gI,Fb:MI,Gb:TI,Ba:fI,Aa:_I,Jb:dI,wa:SI,aa:yI,d:QO,A:eI,r:ZO,Cb:CI,t:sI,y:cI,H:rI,E:nI,K:uI,S:EI,ja:iI,_:AI,Kb:aI,Lb:oI,P:mI,g:vO,a:Cr,Ob:Qs,Hb:kO,ia:EO,O:AO,qa:TO,Mb:MO,Q:SO,zb:OO,Ab:IO,ua:CO,fa:PO,R:LO,Ea:NO,va:zO,Z:RO,xb:$O,Zb:DO,V:BO,Bb:UO,ub:FO,vb:jO,wb:qO,ga:WO,yb:VO,Nb:HO}}}async function mt(){function p(g,k){var T=br=g.exports;g={};for(let[C,N]of Object.entries(T))typeof N=="function"?(T=_S(N),g[C]=T):g[C]=N;return br=g,br=(function(){var C=br,N=J=>Oe=>J(Oe)>>>0,j=J=>()=>J()>>>0;return(C=Object.assign({},C)).$b=N(C.$b),C.Cc=j(C.Cc),C.Ec=N(C.Ec),C.rd=(J=>(Oe,ze)=>J(Oe,ze)>>>0)(C.rd),C.wd=N(C.wd),C.xd=j(C.xd),C.Bd=N(C.Bd),C})(),Z1.push(br.id),Kv=(g=br).$b,Yv=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,nf=e._OrtGetWebGpuDevice=g.Bc,Hl=g.Cc,Xt=e._free=g.Dc,sn=e._malloc=g.Ec,Qv=e._wgpuBufferRelease=g.Fc,Jv=e._wgpuCreateInstance=g.Gc,Zv=g.Hc,ek=g.Ic,tk=g.Jc,rk=g.Kc,sk=g.Lc,nk=g.Pc,ok=g.Zc,ak=g._c,ik=g.$c,of=g.bd,af=g.cd,lf=g.dd,cf=g.ed,io=g.fd,uf=g.gd,lk=g.hd,pf=g.kd,ck=g.ld,uk=g.md,pk=g.nd,ff=g.od,fk=g.pd,dk=g.qd,df=g.rd,we=g.sd,lo=g.td,mk=g.ud,le=g.vd,Xl=g.wd,ce=g.xd,_k=g.yd,mf=g.zd,hk=g.Ad,gk=g.Bd,wk=g.Cd,_f=g.Dd,xk=g.Ed,yk=g.Fd,bk=g.Gd,vk=g.Hd,kk=g.Id,Ek=g.Jd,Ak=g.Kd,Tk=g.Ld,Mk=g.Md,Sk=g.Nd,Ok=g.Od,Ik=g.Pd,Ck=g.Qd,Pk=g.Rd,Lk=g.Td,Nk=g.Ud,zk=g.Vd,Rk=g.Wd,$k=g.Yd,Dk=g.Zd,Bk=g._d,Uk=g.$d,Fk=g.ae,Gk=g.be,jk=g.pe,qk=g.qe,Wk=g.re,Vk=g.se,Hk=g.te,Xk=g.ue,Kk=g.ve,Yk=g.we,Qk=g.xe,Jk=g.ye,Zk=g.ze,eE=g.Xe,tE=g.Ye,rE=g.Ze,sE=g._e,m=k,br}var d,h=ot();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(k,T)=>{g(p(k,T))})}):n?p(new WebAssembly.Instance(m,ot()),m):(D??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",u):u+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var k=D;if(!f&&!O(k))try{var T=fetch(k,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(C){M(`wasm streaming compile failed: ${C}`),M("falling back to ArrayBuffer instantiation")}return(async function(C,N){try{var j=await(async function(J){if(!f)try{var Oe=await a(J);return new Uint8Array(Oe)}catch{}if(J==D&&f)J=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";J=i(J)}return J})(C);return await WebAssembly.instantiate(j,N)}catch(J){M(`failed to asynchronously prepare wasm: ${J}`),We(J)}})(k,g)})(h),p(d.instance,d.module))}class at{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var At=p=>{p.terminate(),p.onmessage=()=>{}},Be=[],Me=0,tt=null,nr=p=>{Ir.length==0&&(sv(),rv(Ir[0]));var d=Ir.pop();if(!d)return 6;no.push(d),ps[p.Nc]=d,d.Nc=p.Nc;var h={Oc:"run",he:p.ge,Wc:p.Wc,Nc:p.Nc};return d.postMessage(h,p.Yc),0},Se=0,Ue=(p,d,...h)=>{var g,k=16*h.length,T=ce(),C=Xl(k),N=C>>>3;for(g of h)typeof g=="bigint"?((v(),L)[N++>>>0]=1n,(v(),L)[N++>>>0]=g):((v(),L)[N++>>>0]=0n,(v(),Y)[N++>>>0]=g);return p=uk(p,0,k,C,d),le(T),p};function Qs(p){if(n)return Ue(0,1,p);if(_=p,!(0{if(_=p,n)throw so(p),"unwind";Qs(p)},Ir=[],no=[],Z1=[],ps={},ev=p=>{var d=p.Nc;delete ps[d],Ir.push(p),no.splice(no.indexOf(p),1),p.Nc=0,pk(d)};function tv(){Z1.forEach(p=>p())}var rv=p=>new Promise(d=>{p.onmessage=k=>{var T=k.data;if(k=T.Oc,T.Vc&&T.Vc!=Hl()){var C=ps[T.Vc];C?C.postMessage(T,T.Yc):M(`Internal error! Worker sent a message "${k}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else k==="checkMailbox"?Fl():k==="spawnThread"?nr(T):k==="cleanupThread"?Mt(()=>{ev(ps[T.ie])}):k==="loaded"?(p.loaded=!0,d(p)):T.target==="setimmediate"?p.postMessage(T):k==="uncaughtException"?p.onerror(T.error):k==="callHandler"?e[T.ce](...T.args):k&&M(`worker sent an unknown command ${k}`)},p.onerror=k=>{throw M(`worker sent an error! ${k.filename}:${k.lineno}: ${k.message}`),k};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);p.postMessage({Oc:"load",de:g,je:Cr,ke:m})});function sv(){var p=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ir.push(p)}var Cr,LM=(p,d)=>{Se=0,p=_f(p,d),0-9007199254740992>p||9007199254740992>>=0);return(v(),F)[d.Qc+12>>>0]==0&&(nv(d,!0),Ul--),ov(d,!1),Bl.push(d),gk(p)}var Zs=0,zM=()=>{we(0,0);var p=Bl.pop();_k(p.Xc),Zs=0};function nv(p,d){d=d?1:0,(v(),F)[p.Qc+12>>>0]=d}function ov(p,d){d=d?1:0,(v(),F)[p.Qc+13>>>0]=d}class jp{constructor(d){this.Xc=d,this.Qc=d-24}}var qp=p=>{var d=Zs;if(!d)return lo(0),0;var h=new jp(d);(v(),P)[h.Qc+16>>>2>>>0]=d;var g=(v(),P)[h.Qc+4>>>2>>>0];if(!g)return lo(0),d;for(var k of p){if(k===0||k===g)break;if(hk(k,g,h.Qc+16))return lo(k),d}return lo(g),d};function RM(){return qp([])}function $M(p){return qp([p>>>0])}function DM(p,d,h,g){return qp([p>>>0,d>>>0,h>>>0,g>>>0])}var BM=()=>{var p=Bl.pop();p||We("no exception to throw");var d=p.Xc;throw(v(),F)[p.Qc+13>>>0]==0&&(Bl.push(p),ov(p,!0),nv(p,!1),Ul++),mf(d),Zs=d};function UM(p,d,h){var g=new jp(p>>>=0);throw d>>>=0,h>>>=0,(v(),P)[g.Qc+16>>>2>>>0]=0,(v(),P)[g.Qc+4>>>2>>>0]=d,(v(),P)[g.Qc+8>>>2>>>0]=h,mf(p),Ul++,Zs=p}var FM=()=>Ul;function av(p,d,h,g){return n?Ue(2,1,p,d,h,g):iv(p,d,h,g)}function iv(p,d,h,g){if(p>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var k=[];return n&&k.length===0?av(p,d,h,g):(p={ge:h,Nc:p,Wc:g,Yc:k},n?(p.Oc="spawnThread",postMessage(p,k),0):nr(p))}function GM(p){throw Zs||=p>>>0,Zs}var lv=globalThis.TextDecoder&&new TextDecoder,cv=(p,d,h,g)=>{if(h=d+h,g)return h;for(;p[d]&&!(d>=h);)++d;return d},uv=(p,d=0,h,g)=>{if(16<(h=cv(p,d>>>=0,h,g))-d&&p.buffer&&lv)return lv.decode(p.buffer instanceof ArrayBuffer?p.subarray(d,h):p.slice(d,h));for(g="";d(k=(240&k)==224?(15&k)<<12|T<<6|C:(7&k)<<18|T<<12|C<<6|63&p[d++])?g+=String.fromCharCode(k):(k-=65536,g+=String.fromCharCode(55296|k>>10,56320|1023&k))}}else g+=String.fromCharCode(k)}return g},en=(p,d,h)=>(p>>>=0)?uv((v(),K),p,d,h):"";function pv(p,d,h){return n?Ue(3,1,p,d,h):0}function fv(p,d){if(n)return Ue(4,1,p,d)}function dv(p,d){if(n)return Ue(5,1,p,d)}function mv(p,d,h){if(n)return Ue(6,1,p,d,h)}function _v(p,d,h){return n?Ue(7,1,p,d,h):0}function hv(p,d){if(n)return Ue(8,1,p,d)}function gv(p,d,h){if(n)return Ue(9,1,p,d,h)}function wv(p,d,h,g){if(n)return Ue(10,1,p,d,h,g)}function xv(p,d,h,g){if(n)return Ue(11,1,p,d,h,g)}function yv(p,d,h,g){if(n)return Ue(12,1,p,d,h,g)}function bv(p){if(n)return Ue(13,1,p)}function vv(p,d){if(n)return Ue(14,1,p,d)}function kv(p,d,h){if(n)return Ue(15,1,p,d,h)}var jM=()=>We(""),or=p=>{p>>>=0;for(var d="";;){var h=(v(),K)[p++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},Wp={},Vp={},qM={},tn=class extends Error{constructor(p){super(p),this.name="BindingError"}};function hr(p,d,h={}){return(function(g,k,T={}){var C=k.name;if(!g)throw new tn(`type "${C}" must have a positive integer typeid pointer`);if(Vp.hasOwnProperty(g)){if(T.ee)return;throw new tn(`Cannot register type '${C}' twice`)}Vp[g]=k,delete qM[g],Wp.hasOwnProperty(g)&&(k=Wp[g],delete Wp[g],k.forEach(N=>N()))})(p,d,h)}var Ev=(p,d,h)=>{switch(d){case 1:return h?g=>(v(),F)[g>>>0]:g=>(v(),K)[g>>>0];case 2:return h?g=>(v(),W)[g>>>1>>>0]:g=>(v(),Q)[g>>>1>>>0];case 4:return h?g=>(v(),B)[g>>>2>>>0]:g=>(v(),P)[g>>>2>>>0];case 8:return h?g=>(v(),L)[g>>>3>>>0]:g=>(v(),R)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${p}`)}};function WM(p,d,h,g,k){p>>>=0,h>>>=0,d=or(d>>>0);let T=C=>C;if(g=g===0n){let C=8*h;T=N=>BigInt.asUintN(C,N),k=T(k)}hr(p,{name:d,Mc:T,Sc:(C,N)=>(typeof N=="number"&&(N=BigInt(N)),N),Rc:Ev(d,h,!g),Tc:null})}function VM(p,d,h,g){hr(p>>>=0,{name:d=or(d>>>0),Mc:function(k){return!!k},Sc:function(k,T){return T?h:g},Rc:function(k){return this.Mc((v(),K)[k>>>0])},Tc:null})}var Av=[],fs=[0,1,,1,null,1,!0,1,!1,1];function Hp(p){9<(p>>>=0)&&--fs[p+1]==0&&(fs[p]=void 0,Av.push(p))}var Bt=p=>{if(!p)throw new tn(`Cannot use deleted val. handle = ${p}`);return fs[p]},Ht=p=>{switch(p){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Av.pop()||fs.length;return fs[d]=p,fs[d+1]=1,d}};function Xp(p){return this.Mc((v(),P)[p>>>2>>>0])}var HM={name:"emscripten::val",Mc:p=>{var d=Bt(p);return Hp(p),d},Sc:(p,d)=>Ht(d),Rc:Xp,Tc:null};function XM(p){return hr(p>>>0,HM)}var KM=(p,d)=>{switch(d){case 4:return function(h){return this.Mc((v(),re)[h>>>2>>>0])};case 8:return function(h){return this.Mc((v(),Y)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${p}`)}};function YM(p,d,h){h>>>=0,hr(p>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,k)=>k,Rc:KM(d,h),Tc:null})}function QM(p,d,h,g,k){p>>>=0,h>>>=0,d=or(d>>>0);let T=N=>N;if(g===0){var C=32-8*h;T=N=>N<>>C,k=T(k)}hr(p,{name:d,Mc:T,Sc:(N,j)=>j,Rc:Ev(d,h,g!==0),Tc:null})}function JM(p,d,h){function g(T){var C=(v(),P)[T>>>2>>>0];return T=(v(),P)[T+4>>>2>>>0],new k((v(),F).buffer,T,C)}var k=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];hr(p>>>=0,{name:h=or(h>>>0),Mc:g,Rc:g},{ee:!0})}var gr=(p,d,h)=>{var g=(v(),K);if(d>>>=0,0=C){if(d>=h)break;g[d++>>>0]=C}else if(2047>=C){if(d+1>=h)break;g[d++>>>0]=192|C>>6,g[d++>>>0]=128|63&C}else if(65535>=C){if(d+2>=h)break;g[d++>>>0]=224|C>>12,g[d++>>>0]=128|C>>6&63,g[d++>>>0]=128|63&C}else{if(d+3>=h)break;g[d++>>>0]=240|C>>18,g[d++>>>0]=128|C>>12&63,g[d++>>>0]=128|C>>6&63,g[d++>>>0]=128|63&C,T++}}g[d>>>0]=0,p=d-k}else p=0;return p},wr=p=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function ZM(p,d){hr(p>>>=0,{name:d=or(d>>>0),Mc(h){var g=(v(),P)[h>>>2>>>0];return g=en(h+4,g,!0),Xt(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var k=typeof g=="string";if(!(k||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new tn("Cannot pass non-string to std::string");var T=k?wr(g):g.length,C=sn(4+T+1),N=C+4;return(v(),P)[C>>>2>>>0]=T,k?gr(g,N,T+1):(v(),K).set(g,N>>>0),h!==null&&h.push(Xt,C),C},Rc:Xp,Tc(h){Xt(h)}})}var Tv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,eS=(p,d,h)=>{if(p>>>=1,16<(d=cv((v(),Q),p,d/2,h))-p&&Tv)return Tv.decode((v(),Q).slice(p,d));for(h="";p>>0];h+=String.fromCharCode(g)}return h},tS=(p,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*p.length?h/2:p.length;for(var k=0;k>>1>>>0]=T,d+=2}return(v(),W)[d>>>1>>>0]=0,d-g},rS=p=>2*p.length,sS=(p,d,h)=>{var g="";p>>>=2;for(var k=0;!(k>=d/4);k++){var T=(v(),P)[p+k>>>0];if(!T&&!h)break;g+=String.fromCodePoint(T)}return g},nS=(p,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var k=0;k>>2>>>0]=T,(d+=4)+4>h)break}return(v(),B)[d>>>2>>>0]=0,d-g},oS=p=>{for(var d=0,h=0;h>>=0,d>>>=0,h=or(h>>>=0),d===2)var g=eS,k=tS,T=rS;else g=sS,k=nS,T=oS;hr(p,{name:h,Mc:C=>{var N=(v(),P)[C>>>2>>>0];return N=g(C+4,N*d,!0),Xt(C),N},Sc:(C,N)=>{if(typeof N!="string")throw new tn(`Cannot pass non-string to C++ string type ${h}`);var j=T(N),J=sn(4+j+d);return(v(),P)[J>>>2>>>0]=j/d,k(N,J+4,j+d),C!==null&&C.push(Xt,J),J},Rc:Xp,Tc(C){Xt(C)}})}function iS(p,d){hr(p>>>=0,{fe:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function lS(p){pf(p>>>0,!s,1,!r,131072,!1),tv()}var Mt=p=>{if(!I)try{if(p(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Kp(p){p>>>=0,cS||(Atomics.waitAsync((v(),B),p>>>2,p).value.then(Fl),p+=128,Atomics.store((v(),B),p>>>2,1))}var Fl=()=>Mt(()=>{var p=Hl();p&&(Kp(p),dk())});function uS(p,d){(p>>>=0)==d>>>0?setTimeout(Fl):n?postMessage({Vc:p,Oc:"checkMailbox"}):(p=ps[p])&&p.postMessage({Oc:"checkMailbox"})}var Yp=[];function pS(p,d,h,g,k){for(d>>>=0,k>>>=0,Yp.length=0,h=k>>>3,g=k+g>>>3;h>>0]?(v(),L)[h++>>>0]:(v(),Y)[h++>>>0],Yp.push(T)}return(d?hf[d]:XO[p])(...Yp)}var fS=()=>{Se=0};function dS(p){p>>>=0,n?postMessage({Oc:"cleanupThread",ie:p}):ev(ps[p])}function mS(p){}var Gl=p=>{try{p()}catch(d){We(d)}};function _S(p){var d=(...h)=>{jl.push(p);try{return p(...h)}finally{I||(jl.pop(),ar&&Pr===1&&jl.length===0&&(Pr=0,Se+=1,Gl(tE),typeof Fibers<"u"&&Fibers.De()))}};return Ov.set(p,d),d}var Pr=0,ar=null,Mv=0,jl=[],Qp=new Map,Sv=new Map,Ov=new Map,hS=0,Jp=null,gS=[],Iv=p=>(function(d){if(!I){if(Pr===0){var h=!1,g=!1;d((k=0)=>{if(!I&&(Mv=k,h=!0,g)){Pr=2,Gl(()=>rE(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),k=!1;try{var T=(function(){var j=(v(),B)[ar+8>>>2>>>0];return j=Sv.get(j),j=Ov.get(j),--Se,j()})()}catch(j){T=j,k=!0}var C=!1;if(!ar){var N=Jp;N&&(Jp=null,(k?N.reject:N.resolve)(T),C=!0)}if(k&&!C)throw T}}),g=!0,h||(Pr=1,ar=(function(){var k=sn(65548),T=k+12;if((v(),P)[k>>>2>>>0]=T,(v(),P)[k+4>>>2>>>0]=T+65536,T=jl[0],!Qp.has(T)){var C=hS++;Qp.set(T,C),Sv.set(C,T)}return T=Qp.get(T),(v(),B)[k+8>>>2>>>0]=T,k})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Gl(()=>eE(ar)))}else Pr===2?(Pr=0,Gl(sE),Xt(ar),ar=null,gS.forEach(Mt)):We(`invalid state: ${Pr}`);return Mv}})(d=>{p().then(d)});function wS(p){return p>>>=0,Iv(async()=>{var d=await Bt(p);return Ht(d)})}var Zp=[],xS=p=>{var d=Zp.length;return Zp.push(p),d},yS=(p,d)=>{for(var h=Array(p),g=0;g>>2>>>0],C=Vp[T];if(C===void 0)throw p=`parameter ${g}`,T=Kv(T),d=or(T),Xt(T),new tn(`${p} has unknown type ${d}`);h[k]=C}return h},bS=(p,d,h)=>{var g=[];return p=p(g,h),g.length&&((v(),P)[d>>>2>>>0]=Ht(g)),p},vS={},ql=p=>{var d=vS[p];return d===void 0?or(p):d};function kS(p,d,h){var[g,...k]=yS(p,d>>>0);d=g.Sc.bind(g);var T=k.map(j=>j.Rc.bind(j));p--;var C={toValue:Bt};switch(p=T.map((j,J)=>{var Oe=`argFromPtr${J}`;return C[Oe]=j,`${Oe}(args${J?"+"+8*J:""})`}),h){case 0:var N="toValue(handle)";break;case 2:N="new (toValue(handle))";break;case 3:N="";break;case 1:C.getStringOrSymbol=ql,N="toValue(handle)[getStringOrSymbol(methodName)]"}return N+=`(${p})`,g.fe||(C.toReturnWire=d,C.emval_returnValue=bS,N=`return emval_returnValue(toReturnWire, destructorsRef, ${N})`),N=`return function (handle, methodName, destructorsRef, args) { ${N} }`,h=new Function(Object.keys(C),N)(...Object.values(C)),N=`methodCaller<(${k.map(j=>j.name)}) => ${g.name}>`,xS(Object.defineProperty(h,"name",{value:N}))}function ES(p,d){return d>>>=0,(p=Bt(p>>>0))==Bt(d)}function AS(p){return(p>>>=0)?(p=ql(p),Ht(globalThis[p])):Ht(globalThis)}function TS(p){return p=ql(p>>>0),Ht(e[p])}function MS(p,d){return d>>>=0,p=Bt(p>>>0),d=Bt(d),Ht(p[d])}function SS(p){9<(p>>>=0)&&(fs[p+1]+=1)}function Cv(p,d,h,g,k){return Zp[p>>>0](d>>>0,h>>>0,g>>>0,k>>>0)}function OS(p,d,h,g,k){return Cv(p>>>0,d>>>0,h>>>0,g>>>0,k>>>0)}function IS(){return Ht([])}function CS(p){p=Bt(p>>>0);for(var d=Array(p.length),h=0;h>>0))}function LS(){return Ht({})}function NS(p){for(var d=Bt(p>>>=0);d.length;){var h=d.pop();d.pop()(h)}Hp(p)}function zS(p,d,h){d>>>=0,h>>>=0,p=Bt(p>>>0),d=Bt(d),h=Bt(h),p[d]=h}function RS(p,d){p=Tt(p),d>>>=0,p=new Date(1e3*p),(v(),B)[d>>>2>>>0]=p.getUTCSeconds(),(v(),B)[d+4>>>2>>>0]=p.getUTCMinutes(),(v(),B)[d+8>>>2>>>0]=p.getUTCHours(),(v(),B)[d+12>>>2>>>0]=p.getUTCDate(),(v(),B)[d+16>>>2>>>0]=p.getUTCMonth(),(v(),B)[d+20>>>2>>>0]=p.getUTCFullYear()-1900,(v(),B)[d+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),B)[d+28>>>2>>>0]=p}var Pv=p=>p%4==0&&(p%100!=0||p%400==0),Lv=[0,31,60,91,121,152,182,213,244,274,305,335],Nv=[0,31,59,90,120,151,181,212,243,273,304,334];function $S(p,d){p=Tt(p),d>>>=0,p=new Date(1e3*p),(v(),B)[d>>>2>>>0]=p.getSeconds(),(v(),B)[d+4>>>2>>>0]=p.getMinutes(),(v(),B)[d+8>>>2>>>0]=p.getHours(),(v(),B)[d+12>>>2>>>0]=p.getDate(),(v(),B)[d+16>>>2>>>0]=p.getMonth(),(v(),B)[d+20>>>2>>>0]=p.getFullYear()-1900,(v(),B)[d+24>>>2>>>0]=p.getDay();var h=(Pv(p.getFullYear())?Lv:Nv)[p.getMonth()]+p.getDate()-1|0;(v(),B)[d+28>>>2>>>0]=h,(v(),B)[d+36>>>2>>>0]=-60*p.getTimezoneOffset(),h=new Date(p.getFullYear(),6,1).getTimezoneOffset();var g=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=0|(h!=g&&p.getTimezoneOffset()==Math.min(g,h)),(v(),B)[d+32>>>2>>>0]=p}function DS(p){p>>>=0;var d=new Date((v(),B)[p+20>>>2>>>0]+1900,(v(),B)[p+16>>>2>>>0],(v(),B)[p+12>>>2>>>0],(v(),B)[p+8>>>2>>>0],(v(),B)[p+4>>>2>>>0],(v(),B)[p>>>2>>>0],0),h=(v(),B)[p+32>>>2>>>0],g=d.getTimezoneOffset(),k=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),C=Math.min(T,k);return 0>h?(v(),B)[p+32>>>2>>>0]=+(k!=T&&C==g):0>>2>>>0]=d.getDay(),h=(Pv(d.getFullYear())?Lv:Nv)[d.getMonth()]+d.getDate()-1|0,(v(),B)[p+28>>>2>>>0]=h,(v(),B)[p>>>2>>>0]=d.getSeconds(),(v(),B)[p+4>>>2>>>0]=d.getMinutes(),(v(),B)[p+8>>>2>>>0]=d.getHours(),(v(),B)[p+12>>>2>>>0]=d.getDate(),(v(),B)[p+16>>>2>>>0]=d.getMonth(),(v(),B)[p+20>>>2>>>0]=d.getYear(),p=d.getTime(),BigInt(isNaN(p)?-1:p/1e3)}function zv(p,d,h,g,k,T,C){return n?Ue(16,1,p,d,h,g,k,T,C):-52}function Rv(p,d,h,g,k,T){if(n)return Ue(17,1,p,d,h,g,k,T)}var oo={},BS=()=>performance.timeOrigin+performance.now();function $v(p,d){if(n)return Ue(18,1,p,d);if(oo[p]&&(clearTimeout(oo[p].id),delete oo[p]),!d)return 0;var h=setTimeout(()=>{delete oo[p],Mt(()=>fk(p,performance.timeOrigin+performance.now()))},d);return oo[p]={id:h,Ce:d},0}function US(p,d,h,g){p>>>=0,d>>>=0,h>>>=0,g>>>=0;var k=new Date().getFullYear(),T=new Date(k,0,1).getTimezoneOffset();k=new Date(k,6,1).getTimezoneOffset();var C=Math.max(T,k);(v(),P)[p>>>2>>>0]=60*C,(v(),B)[d>>>2>>>0]=+(T!=k),p=(d=N=>{var j=Math.abs(N);return`UTC${0<=N?"-":"+"}${String(Math.floor(j/60)).padStart(2,"0")}${String(j%60).padStart(2,"0")}`})(T),d=d(k),kDate.now(),GS=1;function jS(p,d,h){if(h>>>=0,!(0<=p&&3>=p))return 28;if(p===0)p=Date.now();else{if(!GS)return 52;p=performance.timeOrigin+performance.now()}return p=Math.round(1e6*p),(v(),L)[h>>>3>>>0]=BigInt(p),0}var ef=[],Dv=(p,d)=>{ef.length=0;for(var h;h=(v(),K)[p++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,ef.push(h==112?(v(),P)[d>>>2>>>0]:h==106?(v(),L)[d>>>3>>>0]:h==105?(v(),B)[d>>>2>>>0]:(v(),Y)[d>>>3>>>0]),d+=g?8:4}return ef};function qS(p,d,h){return p>>>=0,d=Dv(d>>>0,h>>>0),hf[p](...d)}function WS(p,d,h){return p>>>=0,d=Dv(d>>>0,h>>>0),hf[p](...d)}var VS=()=>{};function HS(p,d){return M(en(p>>>0,d>>>0))}var XS=()=>{throw Se+=1,"unwind"};function KS(){return 4294901760}var YS=()=>1,QS=()=>navigator.hardwareConcurrency;function JS(p){p>>>=0;var d=(v(),K).length;if(p<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,p+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(p,g)/65536))-Cr.buffer.byteLength+65535)/65536|0;try{Cr.grow(g),xe();var k=1;break e}catch{}k=void 0}if(k)return!0}return!1}var ir=p=>{var d=wr(p)+1,h=Xl(d);return gr(p,h,d),h},tf=(p,d)=>{(v(),P)[p>>>2>>>0]=d;var h=(v(),P)[p>>>2>>>0];(v(),P)[p+4>>>2>>>0]=(d-h)/4294967296},ao=p=>(v(),P)[p>>>2>>>0]+4294967296*(v(),B)[p+4>>>2>>>0],_t=[],ZS=(p,d)=>{_t[p>>>0]=d},xr=[],Wl=[],rn=(p,d)=>{Wl[p]=new Promise(h=>d.finally(()=>h(p)))},oe=p=>{if(p)return _t[p>>>0]},eO=(p,d)=>{for(p=(v(),P)[p>>>2>>>0];p;p=(v(),P)[p>>>2>>>0])d[(v(),B)[p+4>>>2>>>0]](p)},Vl=(p,d,h)=>{(v(),P)[p>>>2>>>0]=d,(v(),P)[p+4>>>2>>>0]=h},Bv=p=>{var d=(v(),P)[p>>>2>>>0];return p=(v(),P)[p+4>>>2>>>0],en(d,p)},yr=p=>{var d=(v(),P)[p>>>2>>>0];return p=(v(),P)[p+4>>>2>>>0],d?en(d,p):p===0?"":void 0},tO=p=>{var d=yr(p+4),h=(h=(v(),P)[p+12>>>2>>>0])?oe(h):"auto";if(p+=16){var g=oe((v(),P)[p+4>>>2>>>0]),k=(v(),P)[p+16>>>2>>>0],T=(v(),P)[p+20>>>2>>>0];if(k){for(var C={},N=0;N>>3>>>0]}k=C}else k=void 0;p={module:g,constants:k,entryPoint:yr(p+8)}}else p=void 0;return{label:d,layout:h,compute:p}},Uv=(p,d)=>{function h(g,k){g=p[g],(v(),P)[d+k>>>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),tf(d+64,p.maxUniformBufferBindingSize),tf(d+72,p.maxStorageBufferBindingSize),h("maxVertexBuffers",88),tf(d+96,p.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),p.Ae!==void 0&&h("maxImmediateSize",148)},rO=[,"validation","out-of-memory","internal"],sO=[,"compatibility","core"],Fv={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"},nO=[,"low-power","high-performance"],oO=[,"occlusion","timestamp"],aO={undefined:1,unknown:1,destroyed:2};function iO(p,d,h,g,k,T){d=Tt(d),h=Tt(h),g>>>=0,k>>>=0,T>>>=0;var C=oe(p>>>0);if(p={},T){var N=(v(),P)[T+12>>>2>>>0];if(N){var j=(v(),P)[T+16>>>2>>>0];p.requiredFeatures=Array.from((v(),P).subarray(j>>>2>>>0,j+4*N>>>2>>>0),ae=>Fv[ae])}var J=(v(),P)[T+20>>>2>>>0];if(J){let ae=function(St,lt,ds=!1){lt=J+lt,(lt=(v(),P)[lt>>>2>>>0])==4294967295||ds&<==0||(Fe[St]=lt)},it=function(St,lt){lt=J+lt;var ds=(v(),P)[lt>>>2>>>0],PI=(v(),P)[lt+4>>>2>>>0];ds==4294967295&&PI==4294967295||(Fe[St]=ao(lt))};var Oe=ae,ze=it,Fe={};ae("maxTextureDimension1D",4),ae("maxTextureDimension2D",8),ae("maxTextureDimension3D",12),ae("maxTextureArrayLayers",16),ae("maxBindGroups",20),ae("maxBindGroupsPlusVertexBuffers",24),ae("maxDynamicUniformBuffersPerPipelineLayout",32),ae("maxDynamicStorageBuffersPerPipelineLayout",36),ae("maxSampledTexturesPerShaderStage",40),ae("maxSamplersPerShaderStage",44),ae("maxStorageBuffersPerShaderStage",48),ae("maxStorageTexturesPerShaderStage",52),ae("maxUniformBuffersPerShaderStage",56),ae("minUniformBufferOffsetAlignment",80),ae("minStorageBufferOffsetAlignment",84),it("maxUniformBufferBindingSize",64),it("maxStorageBufferBindingSize",72),ae("maxVertexBuffers",88),it("maxBufferSize",96),ae("maxVertexAttributes",104),ae("maxVertexBufferArrayStride",108),ae("maxInterStageShaderVariables",112),ae("maxColorAttachments",116),ae("maxColorAttachmentBytesPerSample",120),ae("maxComputeWorkgroupStorageSize",124),ae("maxComputeInvocationsPerWorkgroup",128),ae("maxComputeWorkgroupSizeX",132),ae("maxComputeWorkgroupSizeY",136),ae("maxComputeWorkgroupSizeZ",140),ae("maxComputeWorkgroupsPerDimension",144),ae("maxImmediateSize",148,!0),p.requiredLimits=Fe}(N=(v(),P)[T+24>>>2>>>0])&&(N={label:yr(N+4)},p.defaultQueue=N),p.label=yr(T+4)}Se+=1,rn(d,C.requestDevice(p).then(ae=>{--Se,Mt(()=>{_t[k>>>0]=ae.queue,_t[g>>>0]=ae,Se+=1,rn(h,ae.lost.then(it=>{Mt(()=>{ae.onuncapturederror=()=>{};var St=ce(),lt=ir(it.message);af(h,aO[it.reason],lt),le(St)}),--Se})),ae.onuncapturederror=it=>{var St=5;it.error instanceof GPUValidationError?St=2:it.error instanceof GPUOutOfMemoryError?St=3:it.error instanceof GPUInternalError&&(St=4);var lt=ce();it=ir(it.error.message),lk(g,St,it),le(lt)},"adapterInfo"in ae||(ae.adapterInfo=C.info),uf(d,1,g,0)})},ae=>{--Se,Mt(()=>{var it=ce(),St=ir(ae.message);uf(d,3,g,St),h&&af(h,4,St),le(it)})}))}function lO(p){var d=oe(p>>>=0),h=xr[p];if(h){for(var g=0;g>>=0;var g=oe(p>>>=0);h==4294967295&&(h=void 0);try{var k=g.getMappedRange(d>>>0,h)}catch{return 0}var T=df(16,k.byteLength);return(v(),K).set(new Uint8Array(k),T>>>0),xr[p].push(()=>Xt(T)),T}function uO(p,d,h){h>>>=0;var g=oe(p>>>=0);h==4294967295&&(h=void 0);try{var k=g.getMappedRange(d>>>0,h)}catch{return 0}var T=df(16,k.byteLength);return(v(),K).fill(0,T,k.byteLength),xr[p].push(()=>{new Uint8Array(k).set((v(),K).subarray(T>>>0,T+k.byteLength>>>0)),Xt(T)}),T}function pO(p,d,h,g,k){p>>>=0,d=Tt(d),h=Tt(h),k>>>=0;var T=oe(p);xr[p]=[],k==4294967295&&(k=void 0),Se+=1,rn(d,T.mapAsync(h,g>>>0,k).then(()=>{--Se,Mt(()=>{lf(d,1,0)})},C=>{--Se,Mt(()=>{ce();var N=ir(C.message);lf(d,C.name==="AbortError"?4:C.name==="OperationError"?3:0,N),delete xr[p]})}))}function fO(p){var d=oe(p>>>=0),h=xr[p];if(h){for(var g=0;g>>0]}function mO(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=!!(v(),P)[d+32>>>2>>>0];d={label:yr(d+4),usage:(v(),P)[d+16>>>2>>>0],size:ao(d+24),mappedAtCreation:g},p=oe(p);try{var k=p.createBuffer(d)}catch{return!1}return _t[h>>>0]=k,g&&(xr[h]=[]),!0}function _O(p,d,h,g){p>>>=0,d=Tt(d),g>>>=0,h=tO(h>>>0),p=oe(p),Se+=1,rn(d,p.createComputePipelineAsync(h).then(k=>{--Se,Mt(()=>{_t[g>>>0]=k,of(d,1,g,0)})},k=>{--Se,Mt(()=>{var T=ce(),C=ir(k.message);of(d,k.reason==="validation"?3:k.reason==="internal"?4:0,g,C),le(T)})}))}function hO(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=(v(),P)[d>>>2>>>0],k=(v(),B)[g+4>>>2>>>0];d={label:yr(d+4),code:""},k===2&&(d.code=Bv(g+8)),p=oe(p).createShaderModule(d),_t[h>>>0]=p}var gO=p=>{(p=oe(p)).onuncapturederror=null,p.destroy()};function wO(p,d){d=Tt(d),p=oe(p>>>0),Se+=1,rn(d,p.popErrorScope().then(h=>{--Se,Mt(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var k=ce(),T=h?ir(h.message):0;cf(d,1,g,T),le(k)})},h=>{--Se,Mt(()=>{var g=ce(),k=ir(h.message);cf(d,1,5,k),le(g)})}))}function xO(p,d,h,g){if(d=Tt(d),g>>>=0,h>>>=0){var k={featureLevel:sO[(v(),B)[h+4>>>2>>>0]],powerPreference:nO[(v(),B)[h+8>>>2>>>0]],forceFallbackAdapter:!!(v(),P)[h+12>>>2>>>0]};(p=(v(),P)[h>>>2>>>0])!==0&&(v(),k.Fe=!!(v(),P)[p+8>>>2>>>0])}"gpu"in navigator?(Se+=1,rn(d,navigator.gpu.requestAdapter(k).then(T=>{--Se,Mt(()=>{if(T)_t[g>>>0]=T,io(d,1,g,0);else{var C=ce(),N=ir("WebGPU not available on this browser (requestAdapter returned null)");io(d,3,g,N),le(C)}})},T=>{--Se,Mt(()=>{var C=ce(),N=ir(T.message);io(d,4,g,N),le(C)})}))):(k=ce(),p=ir("WebGPU not available on this browser (navigator.gpu is not available)"),io(d,3,g,p),le(k))}function yO(p,d,h){return p>>>=0,d>>>=0,h>>>=0,Iv(async()=>{var g=[];if(h){var k=(v(),B)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(N=>setTimeout(N,k,0))}else g.length=d;for(var T=0;T{if(!rf){var p,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(p in sf)sf[p]===void 0?delete d[p]:d[p]=sf[p];var h=[];for(p in d)h.push(`${p}=${d[p]}`);rf=h}return rf};function jv(p,d){if(n)return Ue(19,1,p,d);p>>>=0,d>>>=0;var h,g=0,k=0;for(h of Gv()){var T=d+g;(v(),P)[p+k>>>2>>>0]=T,g+=gr(h,T,1/0)+1,k+=4}return 0}function qv(p,d){if(n)return Ue(20,1,p,d);p>>>=0,d>>>=0;var h=Gv();for(var g of((v(),P)[p>>>2>>>0]=h.length,p=0,h))p+=wr(g)+1;return(v(),P)[d>>>2>>>0]=p,0}function Wv(p){return n?Ue(21,1,p):52}function Vv(p,d,h,g){return n?Ue(22,1,p,d,h,g):52}function Hv(p,d,h,g){return n?Ue(23,1,p,d,h,g):70}var bO=[null,[],[]];function Xv(p,d,h,g){if(n)return Ue(24,1,p,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var k=0,T=0;T>>2>>>0],N=(v(),P)[d+4>>>2>>>0];d+=8;for(var j=0;j>>0],ze=bO[J];Oe===0||Oe===10?((J===1?S:M)(uv(ze)),ze.length=0):ze.push(Oe)}k+=N}return(v(),P)[g>>>2>>>0]=k,0}function vO(p){return p>>>0}function kO(p,d){return Uv(oe(p>>>0).limits,d>>>0),1}function EO(p,d){return oe(p>>>0).features.has(Fv[d])}function AO(p){return BigInt(oe(p>>>0).size)}function TO(p){return BigInt(oe(p>>>0).usage)}function MO(p,d){if(p>>>=0,d>>>=0){var h=yr(d+4);h={label:h,timestampWrites:d=(d=(v(),P)[d+12>>>2>>>0])!==0?{querySet:oe((v(),P)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),P)[d+8>>>2>>>0],endOfPassWriteIndex:(v(),P)[d+12>>>2>>>0]}:void 0}}return d=oe(p),p=sk(0),h=d.beginComputePass(h),_t[p>>>0]=h,p}function SO(p,d,h,g,k,T){h=Tt(h),k=Tt(k),T=Tt(T),oe(p>>>0).copyBufferToBuffer(oe(d>>>0),h,oe(g>>>0),k,T)}function OO(p){var d=oe(p>>>0);return p=tk(0),d=d.finish(),_t[p>>>0]=d,p}function IO(p,d,h,g,k,T){T=Tt(T),oe(p>>>0).resolveQuerySet(oe(d>>>0),h,g,oe(k>>>0),T)}function CO(p,d,h,g){oe(p>>>0).dispatchWorkgroups(d,h,g)}function PO(p,d,h){h=Tt(h),oe(p>>>0).dispatchWorkgroupsIndirect(oe(d>>>0),h)}function LO(p){oe(p>>>0).end()}function NO(p,d,h,g,k){g>>>=0,k>>>=0,p=oe(p>>>0),h=oe(h>>>0),g==0?p.setBindGroup(d,h):p.setBindGroup(d,h,(v(),P),k>>>2,g)}function zO(p,d){oe(p>>>0).setPipeline(oe(d>>>0))}function RO(p,d,h){oe(p>>>0).Ee(oe(d>>>0),h)}function $O(p,d){var h=oe(p>>>0);return p=ek(0),d=h.getBindGroupLayout(d),_t[p>>>0]=d,p}function DO(p,d){function h(k){var T=(v(),P)[k+8>>>2>>>0],C=(v(),P)[k+32>>>2>>>0],N=(v(),P)[k+36>>>2>>>0],j=0;return eO(k,{327681:J=>{j=(v(),P)[J+8>>>2>>>0]}}),T?((C=ao(k+24))==-1&&(C=void 0),T={buffer:oe(T),offset:ao(k+16),size:C}):T=oe(C||N||j),{binding:(v(),P)[k+4>>>2>>>0],resource:T}}p>>>=0,d={label:yr(4+(d>>>=0)),layout:oe((v(),P)[d+12>>>2>>>0]),entries:(function(k,T){for(var C=[],N=0;N>>2>>>0],(v(),P)[d+20>>>2>>>0])},p=oe(p);var g=Zv(0);return ZS(g,p.createBindGroup(d)),g}function BO(p,d){var h;return p>>>=0,(d>>>=0)&&(h={label:yr(d+4)}),d=oe(p),p=rk(0),h=d.createCommandEncoder(h),_t[p>>>0]=h,p}function UO(p,d){p>>>=0,d>>>=0,d={type:oO[(v(),B)[d+12>>>2>>>0]],count:(v(),P)[d+16>>>2>>>0]};var h=oe(p);return p=nk(0),d=h.createQuerySet(d),_t[p>>>0]=d,p}function FO(p,d){p=oe(p>>>0).adapterInfo,d>>>=0,(v(),P)[d+52>>>2>>>0]=p.subgroupMinSize,(v(),P)[d+56>>>2>>>0]=p.subgroupMaxSize;var h=p.vendor+p.architecture+p.device+p.description,g=wr(h)+1,k=sn(g);return k&&gr(h,k,g),h=k,g=wr(p.vendor),Vl(d+4,h,g),h+=g,g=wr(p.architecture),Vl(d+12,h,g),h+=g,g=wr(p.device),Vl(d+20,h,g),Vl(d+28,h+g,wr(p.description)),(v(),B)[d+36>>>2>>>0]=2,p=p.isFallbackAdapter?3:4,(v(),B)[d+40>>>2>>>0]=p,(v(),P)[d+44>>>2>>>0]=0,(v(),P)[d+48>>>2>>>0]=0,1}var GO={"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 jO(p,d){d>>>=0;var h=oe(p>>>0);p=sn(4*h.features.size);var g=0,k=0;for(let T of h.features)0<=(h=GO[T])&&((v(),B)[p+g>>>2>>>0]=h,g+=4,k++);(v(),P)[d+4>>>2>>>0]=p,(v(),P)[d>>>2>>>0]=k}function qO(p,d){return Uv(oe(p>>>0).limits,d>>>0),1}function WO(p,d){oe(p>>>0).pushErrorScope(rO[d])}function VO(p,d,h){d>>>=0,h>>>=0,p=oe(p>>>0),d=Array.from((v(),B).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>oe(g)),p.submit(d)}function HO(p,d,h,g,k){h=Tt(h),g>>>=0,k>>>=0,p=oe(p>>>0),d=oe(d>>>0),g=(v(),K).subarray(g>>>0,g+k>>>0),p.writeBuffer(d,h,g,0,k)}n||(function(){for(var p=e.numThreads-1;p--;)sv();Be.push(async()=>{var d=(async function(){if(!n)return Promise.all(Ir.map(rv))})();Me++,await d,--Me==0&&tt&&(d=tt,tt=null,d())})})(),n||(Cr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),xe()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ce(),e.stackRestore=p=>le(p),e.stackAlloc=p=>Xl(p),e.setValue=function(p,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(v(),F)[p>>>0]=d;break;case"i16":(v(),W)[p>>>1>>>0]=d;break;case"i32":(v(),B)[p>>>2>>>0]=d;break;case"i64":(v(),L)[p>>>3>>>0]=BigInt(d);break;case"float":(v(),re)[p>>>2>>>0]=d;break;case"double":(v(),Y)[p>>>3>>>0]=d;break;case"*":(v(),P)[p>>>2>>>0]=d;break;default:We(`invalid type for setValue: ${h}`)}},e.getValue=function(p,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(v(),F)[p>>>0];case"i16":return(v(),W)[p>>>1>>>0];case"i32":return(v(),B)[p>>>2>>>0];case"i64":return(v(),L)[p>>>3>>>0];case"float":return(v(),re)[p>>>2>>>0];case"double":return(v(),Y)[p>>>3>>>0];case"*":return(v(),P)[p>>>2>>>0];default:We(`invalid type for getValue: ${d}`)}},e.UTF8ToString=en,e.stringToUTF8=gr,e.lengthBytesUTF8=wr;var Kv,Yv,nf,Hl,Xt,sn,Qv,Jv,Zv,ek,tk,rk,sk,nk,ok,ak,ik,of,af,lf,cf,io,uf,lk,pf,ck,uk,pk,ff,fk,dk,df,we,lo,mk,le,Xl,ce,_k,mf,hk,gk,wk,_f,xk,yk,bk,vk,kk,Ek,Ak,Tk,Mk,Sk,Ok,Ik,Ck,Pk,Lk,Nk,zk,Rk,$k,Dk,Bk,Uk,Fk,Gk,jk,qk,Wk,Vk,Hk,Xk,Kk,Yk,Qk,Jk,Zk,eE,tE,rE,sE,br,XO=[Qs,so,av,pv,fv,dv,mv,_v,hv,gv,wv,xv,yv,bv,vv,kv,zv,Rv,$v,jv,qv,Wv,Vv,Hv,Xv],hf={937076:(p,d,h,g,k)=>{if(e===void 0||!e.Uc)return 1;if((p=en(Number(p>>>0))).startsWith("./")&&(p=p.substring(2)),!(p=e.Uc.get(p)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>p.byteLength)return 3;try{let T=p.subarray(d,d+h);switch(k){case 0:(v(),K).set(T,g>>>0);break;case 1:e.ad?e.ad(g,T):e.oe(g,T);break;default:return 4}return 0}catch{return 4}},937900:(p,d,h)=>{e.Sd(p,(v(),K).subarray(d>>>0,d+h>>>0))},937964:()=>e.me(),938006:p=>{e.jd(p)},938043:()=>typeof wasmOffsetConverter<"u"};function KO(p,d,h,g){var k=ce();try{return Tk(p,d,h,g)}catch(T){if(le(k),T!==T+0)throw T;we(1,0)}}function YO(p,d,h){var g=ce();try{return kk(p,d,h)}catch(k){if(le(g),k!==k+0)throw k;we(1,0)}}function QO(p){var d=ce();try{xk(p)}catch(h){if(le(d),h!==h+0)throw h;we(1,0)}}function JO(p,d){var h=ce();try{return _f(p,d)}catch(g){if(le(h),g!==g+0)throw g;we(1,0)}}function ZO(p,d,h){var g=ce();try{wk(p,d,h)}catch(k){if(le(g),k!==k+0)throw k;we(1,0)}}function eI(p,d){var h=ce();try{Mk(p,d)}catch(g){if(le(h),g!==g+0)throw g;we(1,0)}}function tI(p,d,h,g,k,T,C){var N=ce();try{return vk(p,d,h,g,k,T,C)}catch(j){if(le(N),j!==j+0)throw j;we(1,0)}}function rI(p,d,h,g,k,T){var C=ce();try{yk(p,d,h,g,k,T)}catch(N){if(le(C),N!==N+0)throw N;we(1,0)}}function sI(p,d,h,g){var k=ce();try{Ak(p,d,h,g)}catch(T){if(le(k),T!==T+0)throw T;we(1,0)}}function nI(p,d,h,g,k,T,C){var N=ce();try{Ok(p,d,h,g,k,T,C)}catch(j){if(le(N),j!==j+0)throw j;we(1,0)}}function oI(p,d,h,g,k,T,C){var N=ce();try{Ik(p,d,h,g,k,T,C)}catch(j){if(le(N),j!==j+0)throw j;we(1,0)}}function aI(p,d,h,g,k,T,C,N){var j=ce();try{Bk(p,d,h,g,k,T,C,N)}catch(J){if(le(j),J!==J+0)throw J;we(1,0)}}function iI(p,d,h,g,k,T,C,N,j,J,Oe,ze){var Fe=ce();try{Ck(p,d,h,g,k,T,C,N,j,J,Oe,ze)}catch(ae){if(le(Fe),ae!==ae+0)throw ae;we(1,0)}}function lI(p,d,h,g,k){var T=ce();try{return Sk(p,d,h,g,k)}catch(C){if(le(T),C!==C+0)throw C;we(1,0)}}function cI(p,d,h,g,k){var T=ce();try{bk(p,d,h,g,k)}catch(C){if(le(T),C!==C+0)throw C;we(1,0)}}function uI(p,d,h,g,k,T,C,N){var j=ce();try{Ek(p,d,h,g,k,T,C,N)}catch(J){if(le(j),J!==J+0)throw J;we(1,0)}}function pI(p){var d=ce();try{return Uk(p)}catch(h){if(le(d),h!==h+0)throw h;we(1,0)}}function fI(p,d,h){var g=ce();try{return Fk(p,d,h)}catch(k){if(le(g),k!==k+0)throw k;we(1,0)}}function dI(p,d){var h=ce();try{return Zk(p,d)}catch(g){if(le(h),g!==g+0)throw g;return we(1,0),0n}}function mI(p,d,h,g,k){var T=ce();try{Gk(p,d,h,g,k)}catch(C){if(le(T),C!==C+0)throw C;we(1,0)}}function _I(p){var d=ce();try{return Pk(p)}catch(h){if(le(d),h!==h+0)throw h;return we(1,0),0n}}function hI(p,d,h,g,k,T){var C=ce();try{return $k(p,d,h,g,k,T)}catch(N){if(le(C),N!==N+0)throw N;we(1,0)}}function gI(p,d,h,g,k,T){var C=ce();try{return jk(p,d,h,g,k,T)}catch(N){if(le(C),N!==N+0)throw N;we(1,0)}}function wI(p,d,h,g,k,T){var C=ce();try{return qk(p,d,h,g,k,T)}catch(N){if(le(C),N!==N+0)throw N;we(1,0)}}function xI(p,d,h,g,k,T,C,N){var j=ce();try{return Dk(p,d,h,g,k,T,C,N)}catch(J){if(le(j),J!==J+0)throw J;we(1,0)}}function yI(p,d,h,g,k){var T=ce();try{return Wk(p,d,h,g,k)}catch(C){if(le(T),C!==C+0)throw C;return we(1,0),0n}}function bI(p,d,h,g){var k=ce();try{return Vk(p,d,h,g)}catch(T){if(le(k),T!==T+0)throw T;we(1,0)}}function vI(p,d,h,g){var k=ce();try{return Hk(p,d,h,g)}catch(T){if(le(k),T!==T+0)throw T;we(1,0)}}function kI(p,d,h,g,k,T,C,N,j,J,Oe,ze){var Fe=ce();try{return Xk(p,d,h,g,k,T,C,N,j,J,Oe,ze)}catch(ae){if(le(Fe),ae!==ae+0)throw ae;we(1,0)}}function EI(p,d,h,g,k,T,C,N,j,J,Oe){var ze=ce();try{Kk(p,d,h,g,k,T,C,N,j,J,Oe)}catch(Fe){if(le(ze),Fe!==Fe+0)throw Fe;we(1,0)}}function AI(p,d,h,g,k,T,C,N,j,J,Oe,ze,Fe,ae,it,St){var lt=ce();try{Yk(p,d,h,g,k,T,C,N,j,J,Oe,ze,Fe,ae,it,St)}catch(ds){if(le(lt),ds!==ds+0)throw ds;we(1,0)}}function TI(p,d,h,g){var k=ce();try{return Qk(p,d,h,g)}catch(T){if(le(k),T!==T+0)throw T;we(1,0)}}function MI(p,d,h,g,k){var T=ce();try{return Jk(p,d,h,g,k)}catch(C){if(le(T),C!==C+0)throw C;we(1,0)}}function SI(p,d,h){var g=ce();try{return Nk(p,d,h)}catch(k){if(le(g),k!==k+0)throw k;return we(1,0),0n}}function OI(p,d,h){var g=ce();try{return Lk(p,d,h)}catch(k){if(le(g),k!==k+0)throw k;we(1,0)}}function II(p,d,h){var g=ce();try{return zk(p,d,h)}catch(k){if(le(g),k!==k+0)throw k;we(1,0)}}function CI(p,d,h,g){var k=ce();try{Rk(p,d,h,g)}catch(T){if(le(k),T!==T+0)throw T;we(1,0)}}function Kl(){if(0{let d=new WeakMap,h,g,k=1;e.webgpuRegisterDevice=N=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(N){var j=d.get(N);if(!j){let J=((Oe,ze=0)=>{var Fe=ik(ze);return ze=ak(ze,Fe),_t[Fe>>>0]=Oe.queue,_t[ze>>>0]=Oe,ze})(N,j=Jv(0));j=[k++,j,J],d.set(N,j)}return h=N,g=j[0],j}h=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=N=>{if(g!==void 0){var j=g;if(g=void 0,N){let J=nf(j);T.set(N,J),j===0&&p(h??oe(J))}h=void 0}},e.webgpuOnReleaseSession=N=>{T.delete(N)};let C=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(N,j,J)=>{if(J)return N[C]=[J,NaN],J;if(J=N[C])return J[1]++,J[0];if((j=T.get(j))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return j=((Oe,ze=0)=>(Oe.mapState==="unmapped"||We(),ze=ok(ze),_t[ze>>>0]=Oe,ze))(N,j),N[C]=[j,1],j},e.webgpuUnregisterBuffer=N=>{let j=N[C];if(!j)throw Error("Buffer is not registered");j[1]--,j[1]===0&&(Qv(j[0]),delete N[C])},e.webgpuGetBuffer=N=>oe(N),e.webgpuCreateDownloader=(N,j,J)=>{if((J=T.get(J))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Oe=oe(J),ze=16*Math.ceil(Number(j)/16);return async()=>{let Fe=Oe.createBuffer({size:ze,usage:9});try{let ae=Oe.createCommandEncoder();return ae.copyBufferToBuffer(N,0,Fe,0,ze),Oe.queue.submit([ae.finish()]),await Fe.mapAsync(GPUMapMode.READ),Fe.getMappedRange().slice(0,j)}finally{Fe.destroy()}}},e.ad=(N,j)=>{var J=j.buffer;let Oe=j.byteOffset,ze=j.byteLength;if(j=16*Math.ceil(Number(ze)/16),N=oe(N),!h){var Fe=nf(g);h=oe(Fe)}let ae=(Fe=h.createBuffer({mappedAtCreation:!0,size:j,usage:6})).getMappedRange();new Uint8Array(ae).set(new Uint8Array(J,Oe,ze)),Fe.unmap(),(J=h.createCommandEncoder()).copyBufferToBuffer(Fe,0,N,0,j),h.queue.submit([J.finish()]),Fe.destroy()}},e.webnnInit=p=>{let d=p[0];[e.me,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.le,e.webnnEnableTraceEvent]=p.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.le,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,k,T)=>d.registerMLTensor(h,g,k,T),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,k,T,C,N)=>d.registerMLConstant(h,g,k,T,C,e.Uc,N),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)},Z?e:new Promise((p,d)=>{w=p,x=d})}var r2,cA,TN=be(()=>{"use strict";r2=lA,cA=globalThis.self?.name?.startsWith("em-pthread"),cA&&lA()}),Uf,rd,uA,Nt,s2,pc,pA,fA,Ff,dA,Gf,n2,jf,o2,pd=be(()=>{"use strict";ud(),Uf=typeof location>"u"?void 0:location.origin,rd=import.meta.url>"file:"&&import.meta.url<"file;",uA=()=>{if(rd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Uf).href}return import.meta.url},Nt=uA(),s2=()=>{if(Nt&&!Nt.startsWith("blob:"))return Nt.substring(0,Nt.lastIndexOf("/")+1)},pc=(t,e)=>{try{let r=e??Nt;return(r?new URL(t,r):new URL(t)).origin===Uf}catch{return!1}},pA=(t,e)=>{let r=e??Nt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},fA=(t,e)=>`${e??"./"}${t}`,Ff=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},dA=async t=>(await import(t)).default,Gf=(AN(),gc(ZA)).default,n2=async()=>{if(!Nt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(pc(Nt))return[void 0,Gf()];let t=await Ff(Nt);return[t,Gf(t)]},jf=(TN(),gc(t2)).default,o2=async(t,e,r,s)=>{let n=jf&&!(t||e);if(n)if(Nt)n=pc(Nt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,jf];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??pA(o,e),i=r&&a&&!pc(a,e),l=i?await Ff(a):a??fA(o,e);return[i?l:void 0,await dA(l)]}}}),qf,fc,yo,Wf,mA,_A,hA,fd,De,Os=be(()=>{"use strict";pd(),fc=!1,yo=!1,Wf=!1,mA=()=>{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}},_A=()=>{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}},hA=()=>{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}},fd=async t=>{if(fc)return Promise.resolve();if(yo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Wf)throw new Error("previous call to 'initializeWebAssembly()' failed.");yo=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!hA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!_A())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=mA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,u=t.wasmBinary,[f,m]=await o2(i,o,r>1,!!u||!!c),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,E)=>{let b={numThreads:r};if(u)b.wasmBinary=u,b.locateFile=A=>A;else if(c||o)b.locateFile=A=>c??o+A;else if(i&&i.indexOf("blob:")!==0)b.locateFile=A=>new URL(A,i).href;else if(f){let A=s2();A&&(b.locateFile=S=>A+S)}m(b).then(A=>{yo=!1,fc=!0,qf=A,x(),f&&URL.revokeObjectURL(f)},A=>{yo=!1,Wf=!0,E(A)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(fc&&qf)return qf;throw new Error("WebAssembly is not initialized yet.")}}),zt,xc,Pe,dd=be(()=>{"use strict";Os(),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},xc=(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")xc(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}`)})},Pe=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)}}}),a2,MN=be(()=>{"use strict";Os(),dd(),a2=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&&Pe("Can't create run options."),t?.extra!==void 0&&xc(t.extra,"",new WeakSet,(a,i)=>{let l=zt(a,s),c=zt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Pe(`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}}}),gA,wA,xA,dc,Ur,yA,i2,SN=be(()=>{"use strict";Os(),dd(),gA=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}`)}},wA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},xA=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)},dc=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&Pe(`Can't set a session config entry: ${e} - ${r}.`)},Ur=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);t.push([n,o])},yA=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&&dc(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let _=n;if(_.device)if(typeof GPUDevice<"u"&&_.device instanceof GPUDevice)f=_.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&Ur(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&Ur(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];Ur(a,"forceCpuNodeNames",x.join(` `),r)}_.validationMode&&Ur(a,"validationMode",_.validationMode,r)}let m=De().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;Ur(a,"deviceId",_.toString(),r),Ur(a,"webgpuInstance",w.toString(),r),Ur(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=zt(o,r),l=a.length,c=0,u=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),u=De()._malloc(l*De().PTR_SIZE),r.push(u);for(let f=0;f{let e=De(),r=0,s=[],n=t||{};xA(n);try{let o=gA(n.graphOptimizationLevel??"all"),a=wA(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 u=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,u),r===0&&Pe("Can't create session options."),n.executionProviders&&await yA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);dc(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,m]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let _=zt(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&Pe(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&xc(n.extra,"",new WeakSet,(f,m)=>{dc(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Pe("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),Es,hc,pn,Ao,yc,md,_d,sd,fn=be(()=>{"use strict";Es=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}`)}},hc=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}`)}},pn=(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},Ao=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}`)}},yc=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}`)}},md=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",_d=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",sd=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}`)}}}),hd,l2=be(()=>{"use strict";ud(),hd=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)}}),c2,ON=be(()=>{"use strict";fn(),c2=(t,e)=>new(Ao(e))(t)}),bA,vA,kA,EA,u2,AA,bt,p2=be(()=>{"use strict";fn(),bA=["V","I","W","E","F"],vA=(t,e)=>{console.log(`[${bA[t]},${new Date().toISOString()}]${e}`)},u2=(t,e)=>{kA=t,EA=e},AA=(t,e)=>{let r=yc(t),s=yc(kA);r>=s&&vA(r,typeof e=="function"?e():e)},bt=(...t)=>{EA&&AA(...t)}}),Vf,nd,Hf,TA,Xf,MA,Kf,Yf,Qf,SA,f2,IN=be(()=>{"use strict";fn(),p2(),Vf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),nd=(t,e)=>{if(e==="int32")return t;let r=Vf.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(Ao(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'`)}},Hf=(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}`)}},TA=1,Xf=()=>TA++,MA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Kf=(t,e)=>{let r=Vf.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},Yf=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 Kf(this.dataType,this.tensorShape)}destroy(){bt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=Hf(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}},Qf=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=MA.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);bt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Kf(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=nd(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else bt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?Hf(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()}},SA=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=Xf();return this.tensorTrackersById.set(t,new Qf(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){bt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){bt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=Xf(),a=new Yf({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new Qf(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,u]of this.freeTensors.entries())if(u.canReuseTensor(i,e,r)){bt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}bt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new Yf({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)}},f2=(...t)=>new SA(...t)}),d2={};To(d2,{WebNNBackend:()=>m2});var bo,OA,m2,CN=be(()=>{"use strict";fn(),Os(),ON(),IN(),p2(),bo=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),OA=(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])},m2=class{constructor(t){this.tensorManager=f2(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,u2(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){bt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){bt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)bt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>OA(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){bt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=bo.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){bt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=bo.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!De().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");bt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return c2(r,e)}}registerMLTensor(t,e,r,s){let n=bo.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return bt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(e,e+r).buffer,u;switch(n.dataType){case"float32":u=new Float32Array(c);break;case"float16":u=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":u=new Int32Array(c);break;case"uint32":u=new Uint32Array(c);break;case"int64":if(a){let f=nd(new Uint8Array(c),"int64");u=new Int32Array(f.buffer),n.dataType="int32"}else u=new BigInt64Array(c);break;case"uint64":u=new BigUint64Array(c);break;case"int8":u=new Int8Array(c);break;case"int4":case"uint4":case"uint8":u=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return bt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,u)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=bo.get(Es(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),IA,gd,wd,Fr,CA,Jf,bc,xd,yd,Zf,bd,vd,kd,_2=be(()=>{"use strict";Ss(),MN(),SN(),fn(),Os(),dd(),l2(),IA=(t,e)=>{De()._OrtInit(t,e)!==0&&Pe("Can't initialize onnxruntime.")},gd=async t=>{IA(t.wasm.numThreads,yc(t.logLevel))},wd=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(CN(),gc(d2)).WebNNBackend(t);De().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Fr=new Map,CA=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&&Pe("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)}},Jf=(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&&Pe("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],u=[];for(let f=0;f{let e=De(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},xd=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]=bc(t);let o=0,a=0,i=0,l=[],c=[],u=[];try{if([a,l]=await i2(e),e?.externalData&&n.mountExternalData){let M=[];for(let I of e.externalData){let O=typeof I=="string"?I:I.path;M.push(hd(typeof I=="string"?I:I.data).then(v=>{n.mountExternalData(O,v)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let I=M,O=I?.context,v=I?.gpuDevice,$=I?.deviceType,G=I?.powerPreference;O?n.currentContext=O:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:$,powerPreference:G})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Pe("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=CA(o),_=!!e?.enableGraphCapture,w=[],x=[],E=[],b=[],A=[];for(let M=0;MM==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Pe("Can't create IO binding."),S={handle:i,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>sd(M))}),Fr.set(o,[o,c,u,S,_,!1]),[o,w,x,E,b]}catch(f){throw c.forEach(m=>n._OrtFree(m)),u.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Pe("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Pe("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Pe("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},yd=t=>{let e=De(),r=Fr.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Pe("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Pe("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&&Pe("Can't release session."),Fr.delete(t)},Zf=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],u=t[1],f=t[3],m=f,_,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let b=t[2].gpuBuffer;w=pn(Es(c),u);{let A=i.webgpuRegisterBuffer;if(!A)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=A(b,s)}}else if(f==="ml-tensor"){let b=t[2].mlTensor;w=pn(Es(c),u);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=A(s,b,Es(c),u)}else{let b=t[2];if(Array.isArray(b)){w=l*b.length,_=i._malloc(w),r.push(_);for(let A=0;Ai.setValue(E+S*l,A,l===4?"i32":"i64"));let b=i._OrtCreateTensor(Es(c),_,w,E,u.length,sd(m));b===0&&Pe(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(b)}finally{i.stackRestore(x)}},bd=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=Fr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],u=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,E=s.length,b=0,A=[],S=[],M=[],I=[],O=[],v=a.stackSave(),$=a.stackAlloc(x*i),G=a.stackAlloc(x*i),F=a.stackAlloc(E*i),K=a.stackAlloc(E*i);try{[b,A]=a2(o),jr("wasm prepareInputOutputTensor");for(let P=0;PBe*Me,1);D=hc(ue);let At=m?.outputPreferredLocations[s[P]];if(D==="string"){if(At==="gpu-buffer"||At==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Be=[];for(let Me=0;Me0){let Be=a.webgpuGetBuffer;if(!Be)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Me=Be(Z),tt=pn(ue,at);if(tt===void 0||!md(D))throw new Error(`Unsupported data type: ${D}`);R=!0;{a.webgpuRegisterBuffer(Me,t,Z);let nr=a.webgpuCreateDownloader(Me,tt,t);Q.push([D,mt,{gpuBuffer:Me,download:async()=>{let Se=await nr();return new(Ao(D))(Se)},dispose:()=>{a._OrtReleaseTensor(re)!==0&&Pe("Can't release tensor.")}},"gpu-buffer"])}}else if(At==="ml-tensor"&&at>0){let Be=a.webnnEnsureTensor,Me=a.webnnIsGraphInputOutputTypeSupported;if(!Be||!Me)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(pn(ue,at)===void 0||!_d(D))throw new Error(`Unsupported data type: ${D}`);if(!Me(t,D,!1))throw new Error(`preferredLocation "ml-tensor" for ${D} output is not supported by current WebNN Context.`);let tt=await Be(t,Z,ue,mt,!1);R=!0,Q.push([D,mt,{mlTensor:tt,download:a.webnnCreateMLTensorDownloader(Z,D),dispose:()=>{a.webnnReleaseTensorId(Z),a._OrtReleaseTensor(re)}},"ml-tensor"])}else if(At==="ml-tensor-cpu-output"&&at>0){let Be=a.webnnCreateMLTensorDownloader(Z,D)(),Me=Q.length;R=!0,B.push((async()=>{let tt=[Me,await Be];return a.webnnReleaseTensorId(Z),a._OrtReleaseTensor(re),tt})()),Q.push([D,mt,[],"cpu"])}else{let Be=Ao(D),Me=new Be(at);new Uint8Array(Me.buffer,Me.byteOffset,Me.byteLength).set(a.HEAPU8.subarray(Z,Z+Me.byteLength)),Q.push([D,mt,Me,"cpu"])}}finally{a.stackRestore(Y),D==="string"&&Z&&a._free(Z),R||a._OrtReleaseTensor(re)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Pe("Can't clear bound outputs."),Fr.set(t,[c,u,f,m,_,!1]));for(let[P,re]of await Promise.all(B))Q[P][2]=re;return qr("wasm ProcessOutputTensor"),Q}finally{a.webnnOnRunEnd?.(c),a.stackRestore(v),r.forEach(W=>{W&&W[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(W[2].gpuBuffer)}),n.forEach(W=>{W&&W[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(W[2].gpuBuffer)}),S.forEach(W=>a._OrtReleaseTensor(W)),M.forEach(W=>a._OrtReleaseTensor(W)),I.forEach(W=>a._free(W)),b!==0&&a._OrtReleaseRunOptions(b),A.forEach(W=>a._free(W))}},vd=t=>{let e=De(),r=Fr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Pe("Can't get an profile file name."),e._OrtFree(n)},kd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Gr,jt,un,vo,ko,mc,ed,_c,bs,vs,PA,h2,g2,w2,x2,y2,b2,v2,k2=be(()=>{"use strict";Ss(),_2(),Os(),pd(),Gr=()=>!!He.wasm.proxy&&typeof document<"u",un=!1,vo=!1,ko=!1,_c=new Map,bs=(t,e)=>{let r=_c.get(t);r?r.push(e):_c.set(t,[e])},vs=()=>{if(un||!vo||ko||!jt)throw new Error("worker not ready")},PA=t=>{switch(t.data.type){case"init-wasm":un=!1,t.data.err?(ko=!0,ed[1](t.data.err)):(vo=!0,ed[0]()),mc&&(URL.revokeObjectURL(mc),mc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=_c.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},h2=async()=>{if(!vo){if(un)throw new Error("multiple calls to 'initWasm()' detected.");if(ko)throw new Error("previous call to 'initWasm()' failed.");if(un=!0,Gr())return new Promise((t,e)=>{jt?.terminate(),n2().then(([r,s])=>{try{jt=s,jt.onerror=o=>e(o),jt.onmessage=PA,ed=[t,e];let n={type:"init-wasm",in:He};!n.in.wasm.wasmPaths&&(r||rd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),jt.postMessage(n),mc=r}catch(n){e(n)}},e)});try{await fd(He.wasm),await gd(He),vo=!0}catch(t){throw ko=!0,t}finally{un=!1}}},g2=async t=>{if(Gr())return vs(),new Promise((e,r)=>{bs("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:He}};jt.postMessage(s)});await wd(He,t)},w2=async t=>Gr()?(vs(),new Promise((e,r)=>{bs("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};jt.postMessage(s,[t.buffer])})):bc(t),x2=async(t,e)=>{if(Gr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return vs(),new Promise((r,s)=>{bs("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),jt.postMessage(n,o)})}else return xd(t,e)},y2=async t=>{if(Gr())return vs(),new Promise((e,r)=>{bs("release",[e,r]);let s={type:"release",in:t};jt.postMessage(s)});yd(t)},b2=async(t,e,r,s,n,o)=>{if(Gr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return vs(),new Promise((a,i)=>{bs("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};jt.postMessage(c,kd(l))})}else return bd(t,e,r,s,n,o)},v2=async t=>{if(Gr())return vs(),new Promise((e,r)=>{bs("end-profiling",[e,r]);let s={type:"end-profiling",in:t};jt.postMessage(s)});vd(t)}}),td,LA,E2,PN=be(()=>{"use strict";Ss(),k2(),fn(),ud(),l2(),td=(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()}`)}},LA=t=>{switch(t[3]){case"cpu":return new er(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!md(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return er.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!_d(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return er.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},E2=class{async fetchModelAndCopyToWasmMemory(t){return w2(await hd(t))}async loadModel(t,e){Ts();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await x2(r,e),Ms()}async dispose(){return y2(this.sessionId)}async run(t,e,r){Ts();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],_=f[1],w=this.inputNames.indexOf(m);if(w===-1)throw new Error(`invalid input '${m}'`);s.push(_),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],_=f[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(_),a.push(w)});let i=s.map((f,m)=>td(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?td(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await b2(this.sessionId,n,i,a,l,r),u={};for(let f=0;fad,initializeFlags:()=>od,wasmBackend:()=>T2});var od,ad,T2,LN=be(()=>{"use strict";Ss(),k2(),PN(),od=()=>{(typeof He.wasm.initTimeout!="number"||He.wasm.initTimeout<0)&&(He.wasm.initTimeout=0);let t=He.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.`),He.wasm.simd=!1),typeof He.wasm.proxy!="boolean"&&(He.wasm.proxy=!1),typeof He.wasm.trace!="boolean"&&(He.wasm.trace=!1),typeof He.wasm.numThreads!="number"||!Number.isInteger(He.wasm.numThreads)||He.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)He.wasm.numThreads=1;else{let e=typeof navigator>"u"?uN("node:os").cpus().length:navigator.hardwareConcurrency;He.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},ad=class{async init(t){od(),await h2(),await g2(t)}async createInferenceSessionHandler(t,e){let r=new E2;return await r.loadModel(t,e),r}},T2=new ad});Ss();Ss();Ss();var NN="1.25.0-dev",zN=JA;{let t=(LN(),gc(A2)).wasmBackend;As("webgpu",t,5),As("webnn",t,5),As("cpu",t,10),As("wasm",t,10)}Object.defineProperty(He.versions,"web",{value:NN,enumerable:!0});async function M2(t){let e=t.split("/").pop(),r;try{if(r=await Zt(),r){let n=await r.match(t);if(n)return n}}catch(n){ee.warn(`Failed to load ${e} from cache:`,n)}let s=await 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 S2(t){let e=await M2(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 O2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await M2(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return ee.warn("Failed to read WASM factory:",r),null}}var I2="1.24.3";var C2="warning",Ad={wasm:{},webgl:{},webgpu:{},versions:{common:I2},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}`);C2=t}},get logLevel(){return C2}};Object.defineProperty(Ad,"logLevel",{enumerable:!0});var P2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,E=3,b=0,A=f,S=f*2,M=-1;i==="RGBA"?(b=0,A=f,S=f*2,M=f*3):i==="RGB"?(b=0,A=f,S=f*2):i==="RBG"&&(b=0,S=f,A=f*2),s=r.createImageData(n,o);for(let I=0;I{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,E=0,b=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(E=0,A=c,b=c*2):l==="BGR"&&(A=0,b=c,E=c*2);for(let I=0;I{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,Td(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(Td(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Td(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},z2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new xt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},R2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new xt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},$2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new xt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},D2=(t,e,r)=>new xt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Is=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"]]),B2=!1,U2=()=>{if(!B2){B2=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Is.set("int64",BigInt64Array),Mo.set(BigInt64Array,"int64")),e&&(Is.set("uint64",BigUint64Array),Mo.set(BigUint64Array,"uint64")),s?(Is.set("float16",r),Mo.set(r,"float16")):Is.set("float16",Uint16Array)}};var F2=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new xt(t.type,t.data,e);case"cpu-pinned":return new xt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new xt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new xt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new xt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var xt=class{constructor(e,r,s){U2();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Is.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof e=="string")if(n=e,l=s,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=Is.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let c=Mo.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}let a=F2(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,r){return N2(e,r)}static fromTexture(e,r){return z2(e,r)}static fromGpuBuffer(e,r){return R2(e,r)}static fromMLTensor(e,r){return $2(e,r)}static fromPinnedBuffer(e,r,s){return D2(e,r,s)}toDataURL(e){return P2(this,e)}toImageData(e){return L2(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return G2(this,e)}};var vc=xt;var RN=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 V2(t){return t<=Ot.DEBUG?0:t<=Ot.INFO?2:t<=Ot.WARNING||t<=Ot.ERROR?3:4}var $N={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},qt=[],Md,mn,j2=Symbol.for("onnxruntime");if(j2 in globalThis)mn=globalThis[j2];else if(ie.IS_NODE_ENV){switch(mn=Nf,process.platform){case"win32":qt.push("dml");break;case"linux":process.arch==="x64"&&qt.push("cuda");break;case"darwin":qt.push("coreml");break}qt.push("webgpu"),qt.push("cpu"),Md=["cpu"]}else mn=Ed,ie.IS_WEBNN_AVAILABLE&&qt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&qt.push("webgpu"),qt.push("wasm"),Md=["wasm"];var DN=mn.InferenceSession;function H2(t=null){if(!t)return Md;switch(t){case"auto":return qt;case"gpu":return qt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(qt.includes(t))return[RN[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${qt.join(", ")}.`)}var q2=Promise.resolve(),dn=null;async function BN(){if(dn)return dn;if(!(me.useWasmCache&&typeof st?.wasm?.wasmPaths=="object"&&st?.wasm?.wasmPaths?.wasm&&st?.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 dn=Promise.resolve(),dn}return dn=(async()=>{let e=st.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!Mf(e.wasm)?(async()=>{try{let s=await S2(Sf(e.wasm));s&&(st.wasm.wasmBinary=s,r=!0)}catch(s){ee.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!Mf(e.mjs)?(async()=>{try{let s=await O2(Sf(e.mjs));s&&(st.wasm.wasmPaths.mjs=s)}catch(s){ee.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(st.wasm.wasmPaths.mjs=e.mjs)})(),dn}async function kc(t,e,r){await BN();let s=V2(me.logLevel??Ot.WARNING),n=()=>DN.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?q2=q2.then(n):n());return o.config=r,o}var W2=Promise.resolve();async function Ec(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?W2=W2.then(r):r()}function Ac(t){return t instanceof mn.Tensor}var st=mn?.env;function So(){return st?.wasm?.proxy}if(st){let t=function(e){let r=V2(e);st.logLevel=$N[r]};if(st.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&st.versions?.web&&!st.wasm.wasmPaths){let e=`/assets/${st.versions.web}/dist/`;st.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`}}st.wasm.proxy=!1}st.webgpu&&(st.webgpu.powerPreference="high-performance"),t(me.logLevel??Ot.WARNING),me.backends.onnx={...st,setLogLevel:t}}var Wr=async(t,e,r)=>{let s=await kc(new Uint8Array(t),e);return(async n=>{let o=So(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await Ec(s,a);return Array.isArray(r)?r.map(l=>new z(i[l])):new z(i[r])})},pr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Wr([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=Wr([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=Wr([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=Wr([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=Wr([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=Wr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Wr([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=Wr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var X2=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"}),Sd=ie.IS_NODE_ENV?"cpu":"wasm";function Tc(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 (${Sd}).`),Sd):Sd}var Q2=(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}})(),yt=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),K2=yt.fp32,Y2=Object.freeze({[X2.wasm]:yt.q8}),Vr=Object.freeze({[yt.fp32]:"",[yt.fp16]:"_fp16",[yt.int8]:"_int8",[yt.uint8]:"_uint8",[yt.q8]:"_quantized",[yt.q4]:"_q4",[yt.q4f16]:"_q4f16",[yt.bnb4]:"_bnb4"});function Mc(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===yt.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==yt.auto&&yt.hasOwnProperty(l))return l}i=Y2[r]??K2}else o&&yt.hasOwnProperty(o)?i=o:i=Y2[r]??K2;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var kr=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var z=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 Ac(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new vc(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;s_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[u])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([u,f])=>f-u),o=n.reduce((u,f)=>u*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let u=1;u=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[u]=a[f]}return new t(this.type,i,r)}permute(...e){return FN(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,m)=>f+m,i=0n):(a=(f,m)=>f+m**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,u]=Oo(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*u,u*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return Od(this.dims)}squeeze(e=null){return new t(this.type,this.data,J2(this.dims,e))}squeeze_(e=null){return this.dims=J2(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,Z2(this.dims,e))}unsqueeze_(e){return this.dims=Z2(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=Ce(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Oo((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=wo(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=Ce(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthu===1)){if(e.length===this.dims.length)return this.clone();let u=e.length-this.dims.length,f=Array(u).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((u,f)=>u*e[f]),o=n.reduce((u,f)=>u*f,1),a=this.data,i=new a.constructor(o),l=Od(s),c=Od(n);for(let u=0;uBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,aA(this.data),this.dims);return new t(e,kr[e].from(this.data,r),this.dims)}};function UN(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 z("int64",t,[t.length]);async function Oc(t,e,r,s,n){return await(await pr.slice)({x:t,s:Sc(e),e:Sc(r),a:Sc(s),t:Sc(n??new Array(s.length).fill(1))})}function tT(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let u=0;ur!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function Z2(t,e){return e=fr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function fr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function ve(t,e=0){e=fr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--m){let x=c[m],E=_%x;m===e&&(E+=a),f+=E*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[u]}a+=c[e]}}return new z(o,n,r)}function Ct(t,e=0){return ve(t.map(r=>r.unsqueeze(e)),e)}function Oo(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=fr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=m%w;u+=x*_,_*=i[f]}m=Math.floor(m/w)}l[u]=t(l[u],o[c],c,u)}return s||i.splice(r,1),[e.type,l,i]}function Cd(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((b,A)=>b+A,0)/n.length,w=Math.sqrt(n.reduce((b,A)=>b+(A-_)**2,0)/(n.length-r)),x=new z(t.type,[_],[]);return[new z(t.type,[w],[]),x]}e=fr(e,o.length);let a=Ic(t,e,s),i=a.data,[l,c,u]=Oo((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;mc+u,0);return new z(t.type,[l/n.length],[])}e=fr(e,s.length);let[o,a,i]=Oo((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 Pd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new z(r,new s(n).fill(e),t)}function Xe(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 Pd(t,e,r,s)}function Io(t,e){return Xe(t.dims,e)}function Ze(t){return Pd(t,1n,"int64",BigInt64Array)}function Cc(t){return Ze(t.dims)}function Ld(t){return Pd(t,0n,"int64",BigInt64Array)}function Nd(t){return Ld(t.dims)}function OD(t){let e=t.reduce((r,s)=>r*s,1);return new z("float32",Float32Array.from({length:e},()=>xs.random()),t)}function rT(t){let e=t.reduce((r,s)=>r*s,1);return new z("float32",Float32Array.from({length:e},()=>xs.gauss()),t)}function sT(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),u=i%8;a[c]|=l<<7-u,r&&u===0&&(a[c]-=128)}return new z(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 It(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function zd(t,e){let r=await _n(t);return await Promise.all(r.map(s=>ut(t,s,!0,e)))}function Rd(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 GN=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function jN(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 qN(t,e){for(let r of Object.keys(t))t[r].length=e}function Cs(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 WN(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var V=class extends Ke{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new OE(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Cs(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Cs(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Cs(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Cs(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Cs(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Cs(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=WN(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 zd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,{text_pair:r=null,add_special_tokens:s=!0,padding:n=!1,truncation:o=null,max_length:a=null,return_tensor:i=!0,return_token_type_ids:l=null}={}){let c=Array.isArray(e),u;if(c){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");u=e.map((m,_)=>this._encode_plus(m,{text_pair:r[_],add_special_tokens:s,return_token_type_ids:l}))}else u=e.map(m=>this._encode_plus(m,{add_special_tokens:s,return_token_type_ids:l}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");u=[this._encode_plus(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:l})]}if(a===null?a=this.model_max_length:o===null&&(n===!0?(ee.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),a=this.model_max_length):n===!1&&(ee.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),n===!0&&(a=Math.min(Ce(u.map(m=>m.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),n||o)for(let m=0;ma?o&&qN(u[m],a):n&&jN(u[m],a,_=>_==="input_ids"?this.pad_token_id:0,this.padding_side));let f={};if(i){if(!(n&&o)&&u.some(_=>{for(let w of Object.keys(_))if(_[w].length!==u[0][w]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[u.length,u[0].input_ids.length];for(let _ of Object.keys(u[0]))f[_]=new z("int64",BigInt64Array.from(u.flatMap(w=>w[_]).map(BigInt)),m)}else{for(let m of Object.keys(u[0]))f[m]=u.map(_=>_[m]);if(!c)for(let m of Object.keys(f))f[m]=f[m][0]}return f}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof z&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof z&&(e=Rd(e)),!Array.isArray(e)||e.length===0||!pE(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,{tools:r=null,documents:s=null,chat_template:n=null,add_generation_prompt:o=!1,tokenize:a=!0,padding:i=!1,truncation:l=!1,max_length:c=null,return_tensor:u=!0,return_dict:f=!0,tokenizer_kwargs:m={},..._}={}){if(n=this.get_chat_template({chat_template:n,tools:r}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let w=this._compiled_template_cache.get(n);w===void 0&&(w=new FE(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let b of GN){let A=Cs(this.config,b);A&&(x[b]=A)}let E=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,..._});if(a){let b=this._call(E,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:u,...m});return f?b:b.input_ids}return E}};function hn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var Sm={};_s(Sm,{AlbertTokenizer:()=>$d,AutoTokenizer:()=>ne,BartTokenizer:()=>Dd,BertTokenizer:()=>Bd,BlenderbotSmallTokenizer:()=>Ud,BlenderbotTokenizer:()=>Fd,BloomTokenizer:()=>Gd,CLIPTokenizer:()=>qd,CamembertTokenizer:()=>jd,CodeGenTokenizer:()=>Vd,CodeLlamaTokenizer:()=>Wd,CohereAsrTokenizer:()=>Xd,CohereTokenizer:()=>Hd,ConvBertTokenizer:()=>Kd,DebertaTokenizer:()=>Qd,DebertaV2Tokenizer:()=>Yd,DistilBertTokenizer:()=>Jd,ElectraTokenizer:()=>Zd,EsmTokenizer:()=>em,FalconTokenizer:()=>tm,GPT2Tokenizer:()=>nm,GPTNeoXTokenizer:()=>sm,GemmaTokenizer:()=>rm,HerbertTokenizer:()=>om,LlamaTokenizer:()=>am,M2M100Tokenizer:()=>im,MBart50Tokenizer:()=>cm,MBartTokenizer:()=>Co,MPNetTokenizer:()=>fm,MarianTokenizer:()=>lm,MgpstrTokenizer:()=>um,MobileBertTokenizer:()=>pm,NllbTokenizer:()=>dm,NougatTokenizer:()=>mm,PreTrainedTokenizer:()=>V,Qwen2Tokenizer:()=>_m,RoFormerTokenizer:()=>gm,RobertaTokenizer:()=>hm,SiglipTokenizer:()=>wm,SpeechT5Tokenizer:()=>xm,SqueezeBertTokenizer:()=>ym,T5Tokenizer:()=>bm,TokenizersBackend:()=>V,VitsTokenizer:()=>km,Wav2Vec2CTCTokenizer:()=>Em,WhisperTokenizer:()=>Am,XLMRobertaTokenizer:()=>Tm,XLMTokenizer:()=>Mm});var $d=class extends V{return_token_type_ids=!0};var Dd=class extends V{};var Bd=class extends V{return_token_type_ids=!0};var Ud=class extends V{};var Fd=class extends V{};var Gd=class extends V{};var jd=class extends V{};var qd=class extends V{};var Wd=class extends V{};var Vd=class extends V{};var Hd=class extends V{};var Xd=class extends V{};var Kd=class extends V{return_token_type_ids=!0};var Yd=class extends V{return_token_type_ids=!0};var Qd=class extends V{return_token_type_ids=!0};var Jd=class extends V{};var Zd=class extends V{return_token_type_ids=!0};var em=class extends V{};var tm=class extends V{};var rm=class extends V{};var sm=class extends V{};var nm=class extends V{};var om=class extends V{return_token_type_ids=!0};var am=class extends V{padding_side="left"};var im=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return hn(this,e,r,s)}};var lm=class extends V{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 Co=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return hn(this,e,r,s)}};var cm=class extends Co{};var um=class extends V{};var pm=class extends V{return_token_type_ids=!0};var fm=class extends V{};var dm=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return hn(this,e,r,s)}};var mm=class extends V{};var _m=class extends V{};var hm=class extends V{};var gm=class extends V{return_token_type_ids=!0};var wm=class extends V{};var xm=class extends V{};var ym=class extends V{return_token_type_ids=!0};var bm=class extends V{};var vm=class extends Ft{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function oT(t){t=t.toLowerCase();let e=VN.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Po.has(t))e=t;else{let n=t.length===2?Po.keys():Po.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var HN="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",aT=new RegExp(`^[${HN}]+$`,"gu"),XN=.1,Am=class extends V{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],u=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],E=[],b=!1,A=null,S=new Set(this.all_special_ids);for(let O of e){let v=O.tokens,$=i?O.token_timestamps:null,G=null,F=m;if("stride"in O){let[Q,B,P]=O.stride;if(f-=B,A=Q-P,B&&(F=B/n+m),P)for(let re=v.length-1;re>=0;--re){let Y=Number(v[re]);if(Y>=m){if(G!==null&&(Y-m)*n=m&&B<=w){let P=(B-m)*n+f,re=ys(P,2);if(G!==null&&B>=G)b=!0;else if(b||x.length>0&&B0&&u.timestamp[1]!==null))for(let D of u.words)D.timestamp[1]>u.timestamp[1]&&u.timestamp[1]>=D.timestamp[0]&&(D.timestamp[1]=u.timestamp[1]);c.push(u),x=[],K=[],E=[],W=[],u=l()}}else if(K.push(B),i){let P=ys($[Q]+f,2),re;if(Q+1<$.length){re=ys($[Q+1]+f,2);let Y=this.decode([B]);aT.test(Y)&&(re=ys(Math.min(P+n,re),2))}else re=null;W.push([P,re])}}if("stride"in O){let[Q,B,P]=O.stride;f+=Q-P}K.length>0?(x.push(K),i&&E.push(W)):x.every(Q=>Q.length===0)&&(u=l(),x=[],K=[],E=[],W=[])}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,v]=this.findLongestCommonSequence(x,E),$=this.decode(O);u.text=$,i&&(u.words=this.collateWordTimestamps(O,v,a)),c.push(u)}let M=Object.create(null),I=c.map(O=>O.text).join("");if(r||s){for(let O=0;O0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cB===F[P]&&l[I+P][0]-XN<=r[c][$+P][0]).length:K=v.filter((B,P)=>B===F[P]).length;let W=M/1e4,Q=K/M+W;K>1&&Q>f&&(f=Q,m=[I,O,$,G])}let[w,x,E,b]=m,A=Math.floor((x+w)/2),S=Math.floor((b+E)/2);if(a&&f===0&&n>0){let M=l[n-1][0],I=r[c].findIndex(O=>O[0]>=M);S=I===-1?u.length:I}o.push(...s.slice(0,A)),s=u.slice(S),n=s.length,a&&(i.push(...l.slice(0,A)),l=r[c].slice(S))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let u=0;u=this._tokenizer.token_to_id("<|endoftext|>"),_=c.startsWith(" "),w=c.trim(),x=aT.test(w);if(m||_||x||o.length===0)o.push(c),a.push(u),i.push(f);else{let E=o.length-1;o[E]+=c,a[E].push(...u),i[E].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,u=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[u]=a[c]+a[u],i[u]=gt(i[c],i[u]),l[u]=gt(l[c],l[u]),a[c]="",i[c]=[],l[c]=[]):u=c,--c;for(c=0,u=1;uf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var Tm=class extends V{};var Mm=class extends V{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 zd(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",u=Sm[c];return u||(ee.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=V),new u(i,l)}};var Hr="https://github.com/huggingface/transformers.js/issues/new/choose";var Lo="preprocessor_config.json",Er=Lo,iT="processor_config.json",lT="chat_template.jinja";var se=class extends Ke{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?ut(e,iT,!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?Cf(e,lT,!0,r):null]);return new this(s,n,o)}};var su={};_s(su,{ChatterboxProcessor:()=>Wm,CohereAsrProcessor:()=>Vm,Florence2Processor:()=>D_,Gemma3Processor:()=>B_,Gemma3nProcessor:()=>U_,Glm46VProcessor:()=>F_,GraniteSpeechProcessor:()=>G_,GroundingDinoProcessor:()=>j_,Idefics3Processor:()=>Zc,JinaCLIPProcessor:()=>W_,Lfm2VlProcessor:()=>V_,LlavaProcessor:()=>H_,MgpstrProcessor:()=>X_,MoonshineProcessor:()=>K_,OwlViTProcessor:()=>Y_,PaliGemmaProcessor:()=>Q_,Phi3VProcessor:()=>J_,PixtralProcessor:()=>Z_,Processor:()=>se,PyAnnoteProcessor:()=>eh,Qwen2VLProcessor:()=>Ls,Qwen2_5_VLProcessor:()=>Go,Qwen3VLProcessor:()=>th,Sam2Processor:()=>eu,Sam2VideoProcessor:()=>rh,SamProcessor:()=>jo,SmolVLMProcessor:()=>Zc,SpeechT5Processor:()=>sh,UltravoxProcessor:()=>nh,VLChatProcessor:()=>q_,VoxtralProcessor:()=>oh,VoxtralRealtimeProcessor:()=>ih,Wav2Vec2Processor:()=>lh,Wav2Vec2ProcessorWithLM:()=>ch,WhisperProcessor:()=>uh});var Ee=class extends Ke{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await ut(e,Lo,!0,r);return new this(s)}};function Le(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 Bo={};_s(Bo,{ASTFeatureExtractor:()=>Cm,ChatterboxFeatureExtractor:()=>Pm,ClapFeatureExtractor:()=>Lm,CohereAsrFeatureExtractor:()=>Nm,DacFeatureExtractor:()=>$o,EncodecFeatureExtractor:()=>zo,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>zm,GraniteSpeechFeatureExtractor:()=>Rm,MoonshineFeatureExtractor:()=>$m,ParakeetFeatureExtractor:()=>Ro,PyAnnoteFeatureExtractor:()=>Do,SeamlessM4TFeatureExtractor:()=>Dm,SnacFeatureExtractor:()=>Bm,SpeechT5FeatureExtractor:()=>Um,VoxtralRealtimeFeatureExtractor:()=>jm,Wav2Vec2FeatureExtractor:()=>Fm,WeSpeakerFeatureExtractor:()=>Gm,WhisperFeatureExtractor:()=>qm});var KN=()=>{};var cT={fromWeb:KN};var YN=()=>{};var uT=YN;async function Pc(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=cT.fromWeb(r),n=ht.createWriteStream(t);await uT(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function Im(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await Rr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&ee.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function Om(t,e="htk"){let r=JN[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 ZN={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 ez(t,e="htk"){let r=ZN[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 tz(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 nt(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=Om(r,a),c=Om(s,a),u=fT(l,c,e+2),f=ez(u,a),m;if(i){let w=n/((t-1)*2);m=Om(Float64Array.from({length:t},(x,E)=>E*w),a),f=u}else m=fT(0,Math.floor(n/2),t);let _=tz(m,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if($!==r)throw new Error(`Length of the window (${$}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let D=Math.floor(r/2);switch(i){case"reflect":{t=rz(t,D,D);break}case"constant":{let Z=new t.constructor(t.length+2*D);Z.set(t,D),t=Z;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let G=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&GG?I&&(W=M):W=K=M);let Q=new cc(n),B=new Float64Array(n),P=new Float64Array(Q.outputBufferSize),re=new Float32Array(F*W);for(let D=0;D=1;--ue)B[ue]-=c*B[ue-1];B[0]*=1-c}for(let ue=0;ueMath.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 oz(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return Lc(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),Lc(n,8,"WAVE"),Lc(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),Lc(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function Lc(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]),oz(e,this.sampling_rate)}async save(e){return Pc(e,this.toBlob())}};var Cm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=nt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=dt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ft(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){Le(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(xs.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 ft(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){Le(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=u){l.push(e.slice(c,u));break}let f=Math.max(c,c+a-i),m=Math.min(c+a,u),_;m<=f?_=c+a:_=this._find_split_point_energy(e,f,m,n),_=Math.max(c+1,Math.min(_,u)),l.push(e.slice(c,_)),c=_}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let u=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Xe([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Rm=class extends Ee{constructor(e){super(e);let{n_fft:r,win_length:s,n_mels:n,sample_rate:o}=e.melspec_kwargs;this.mel_filters=nt(Math.floor(1+r/2),n,0,o/2,o,null,"htk");let a=dt(s,"hann");this.window=new Float64Array(r);let i=Math.floor((r-s)/2);this.window.set(a,i)}async _call(e){Le(e,"GraniteSpeechFeatureExtractor");let{n_fft:r,hop_length:s,n_mels:n}=this.config.melspec_kwargs,o=1+Math.floor((e.length-1)/s),a=o-o%2;return{input_features:(await ft(e,this.window,r,s,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*n).unsqueeze_(0)}}};var $m=class extends Ee{async _call(e){Le(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new z("float32",e,r)}}};var Do=class extends Ee{async _call(e){Le(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new z("float32",e,r)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,r){let s=r/this.samples_to_frames(r)/this.config.sampling_rate,n=[];for(let o of e.tolist()){let a=[],i=-1;for(let l=0;l({id:l,start:c*s,end:u*s,confidence:f/(u-c)})))}return n}};var Dm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=nt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=dt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ft(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}={}){Le(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,E=a.data;for(let b=0;b0){let A=new Float32Array(x*(w+b));A.set(E),A.fill(this.config.padding_value,E.length);let S=w+b;a=new z(a.type,A,[S,x]),o&&(i=new z("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,u=this.config.stride;if(l%u!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${u}).`);let m=a.view(1,Math.floor(l/u),c*u),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let E=i.data;for(let b=1,A=0;bo+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Le(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 z("float32",r,s),attention_mask:new z("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Gm=class extends Ee{constructor(e){super(e);let r=this.config.sampling_rate,s=nt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=dt(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ft(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){Le(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&ee.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var Ge=class{static async from_pretrained(e,r={}){let s=await ut(e,Lo,!0,r),n=s.feature_extractor_type,o=Bo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Hr}.`);return new o(s)}};var Wm=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ge;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var iz=new Set(["ja","zh"]),Vm=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ge;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=iz.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var Nc={};var Ps,_T,Xr;if(ie.IS_WEB_ENV)Ps=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Xr=self.createImageBitmap,_T=self.ImageData;else if(Nc)Xr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Qe(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 lz={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},cz=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Qe=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!ie.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await Rr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await Xr(e),s=Ps(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=Nc(await e.arrayBuffer());return await Xr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:u=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,u,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Xr(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new z("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=Ps(e.width,e.height),s=new _T(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=cz.get(r)??"image/png",n=await this.toBlob(s);return Pc(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 Nc(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},uz=Qe.read.bind(Qe);function hT(t,e,r=0,s=null){let n=t/e,o=nA(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),oe&&b.push(S)}else{let S=Ce(E.data)[1];if(S===l-1||(A=Re(E.data),A[S]I*f[(O+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(A[S])}}c.push(m)}return c}function zc(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[b]&&(f[b]=E[b],m[b]=x)}let _=new Array(i.dims[0]);for(let x=0;xx!==void 0);n.push({segmentation:u,labels:w})}return n}function pz(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(m),a.push(u))}return[n,o,a]}function fz(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let u=0;u=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function dz(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new z("int32",new Int32Array(i*l),[i,l]),u=[];if(a!==null)for(let x=0;xm[A]&&(f[A]=x,m[A]=b[A])}let _=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=wo(s.data)[0],a=Ce(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,u=0,f=0,m=s.data;for(let _=0;_this.preprocess(o)));return{pixel_values:Ct(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 ut(e,Er,!0,r);return new this(s)}};var vn={};_s(vn,{BeitFeatureExtractor:()=>Xm,BitImageProcessor:()=>Km,CHMv2ImageProcessor:()=>Qm,CLIPFeatureExtractor:()=>Jm,CLIPImageProcessor:()=>Dc,ChineseCLIPFeatureExtractor:()=>Ym,ConvNextFeatureExtractor:()=>Zm,ConvNextImageProcessor:()=>Bc,DINOv3ViTImageProcessor:()=>r_,DPTFeatureExtractor:()=>n_,DPTImageProcessor:()=>Gc,DeiTFeatureExtractor:()=>e_,DeiTImageProcessor:()=>Uc,DetrFeatureExtractor:()=>t_,DetrImageProcessor:()=>Fc,DonutFeatureExtractor:()=>s_,DonutImageProcessor:()=>wn,EfficientNetImageProcessor:()=>o_,GLPNFeatureExtractor:()=>l_,Gemma3ImageProcessor:()=>a_,Glm46VImageProcessor:()=>i_,GroundingDinoImageProcessor:()=>c_,Idefics3ImageProcessor:()=>jc,ImageFeatureExtractor:()=>X,ImageProcessor:()=>X,JinaCLIPImageProcessor:()=>p_,Lfm2VlImageProcessor:()=>f_,LlavaOnevisionImageProcessor:()=>d_,Mask2FormerImageProcessor:()=>__,MaskFormerFeatureExtractor:()=>m_,MaskFormerImageProcessor:()=>xn,MobileNetV1FeatureExtractor:()=>h_,MobileNetV1ImageProcessor:()=>qc,MobileNetV2FeatureExtractor:()=>g_,MobileNetV2ImageProcessor:()=>Wc,MobileNetV3FeatureExtractor:()=>w_,MobileNetV3ImageProcessor:()=>Vc,MobileNetV4FeatureExtractor:()=>x_,MobileNetV4ImageProcessor:()=>Hc,MobileViTFeatureExtractor:()=>y_,MobileViTImageProcessor:()=>Xc,NougatImageProcessor:()=>b_,OwlViTFeatureExtractor:()=>v_,OwlViTImageProcessor:()=>yn,Owlv2ImageProcessor:()=>k_,Phi3VImageProcessor:()=>T_,PixtralImageProcessor:()=>M_,PvtImageProcessor:()=>S_,Qwen2VLImageProcessor:()=>Uo,RTDetrImageProcessor:()=>O_,Sam2ImageProcessor:()=>Fo,Sam3ImageProcessor:()=>Fo,SamImageProcessor:()=>Fo,SapiensFeatureExtractor:()=>I_,SapiensImageProcessor:()=>Kc,SegformerFeatureExtractor:()=>C_,SegformerImageProcessor:()=>Yc,SiglipImageProcessor:()=>P_,SmolVLMImageProcessor:()=>jc,Swin2SRImageProcessor:()=>L_,VLMImageProcessor:()=>u_,ViTFeatureExtractor:()=>N_,ViTImageProcessor:()=>Qc,VitMatteImageProcessor:()=>z_,VitPoseImageProcessor:()=>R_,YolosFeatureExtractor:()=>$_,YolosImageProcessor:()=>Jc});var Xm=class extends X{};var Km=class extends X{};var Ym=class extends X{};var Qm=class extends X{};var Dc=class extends X{},Jm=class extends Dc{};var Bc=class extends X{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},Zm=class extends Bc{};var Uc=class extends X{},e_=class extends Uc{};var Fc=class extends X{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Xe(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Kr(...e)}post_process_panoptic_segmentation(...e){return Rc(...e)}post_process_instance_segmentation(...e){return $c(...e)}},t_=class extends Fc{};var r_=class extends X{};var wn=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let u=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:u,...n})}},s_=class extends wn{};var Gc=class extends X{},n_=class extends Gc{};var o_=class extends X{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var a_=class extends X{};var Uo=class extends X{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size;return gn(e.height,e.width,s,this.min_pixels,this.max_pixels)}async _call(e,...r){let{pixel_values:s,original_sizes:n,reshaped_input_sizes:o}=await super._call(e,...r),a=s,{temporal_patch_size:i,merge_size:l,patch_size:c}=this.config;a.dims[0]===1&&(a=ve(Array.from({length:i},()=>a),0));let u=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/c),_=Math.floor(a.dims[3]/c),w=a.view(u,i,f,Math.floor(m/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(u*m*_,f*i*c*c),x=new z("int64",[u,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var i_=class extends Uo{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return gn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var l_=class extends X{};var c_=class extends X{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=Ze([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var jc=class extends X{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let b of n){let A=await Promise.all(b.map(I=>this.preprocess(I)));l.push(...A.map(I=>I.original_size)),c.push(...A.map(I=>I.reshaped_input_size)),A.forEach(I=>I.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let I=new Array(A.length),O=new Array(A.length);M=await Promise.all(A.map(async(v,$)=>{let G=this.get_resize_for_vision_encoder(v.pixel_values,S),F=await vt(v.pixel_values,{size:[G.height,G.width]}),{frames:K,num_splits_h:W,num_splits_w:Q}=await this.split_image(F,this.max_image_size);return I[$]=W,O[$]=Q,ve(K,0)})),a.push(I),i.push(O)}else{let I=[S,S];M=await Promise.all(A.map(O=>vt(O.pixel_values,{size:I}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(ve(M,0))}let u=o.length,[f,m,_,w]=o[0].dims,x,E;if(u===1)x=o[0].unsqueeze_(0),E=Xe([u,f,_,w],!0);else{let b=Math.max(...o.map(M=>M.dims.at(0)));E=Xe([u,b,_,w],!0);let A=E.data,S=b*_*w;for(let M=0;Ms||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let u=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var p_=class extends X{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function wT(t,e){return Math.round(t/e)*e}function mz(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 _z(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 hz(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,u=new Float32Array(r*a*i*l),f=n*o;for(let m=0;mthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=_z(this.min_tiles,this.max_tiles),[n,o]=mz(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let m=await Promise.all(f.map(_=>this.preprocess(_,{do_pad:!1})));for(let{pixel_values:_}of m){let[,w,x]=_.dims,E=_.unsqueeze_(0),b=this.encoder_patch_size*this.downsample_factor,A=b**2,[S,M]=gn(Math.max(b,w),Math.max(b,x),b,this.min_image_tokens*A,this.max_image_tokens*A).map(F=>Math.max(b,F)),I,O=1,v=1,$=this._is_image_too_large(w,x),G=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if($&&G){let{grid_width:F,grid_height:K,target_width:W,target_height:Q}=this._get_grid_layout(w,x);O=K,v=F;let B=await vt(E,{size:[Q,W]});I=[];for(let P=0;P(u-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||A_(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(m=>this.preprocess(m))),o=n.map(m=>m.original_size),a=n.map(m=>m.reshaped_input_size),i=[];for(let{pixel_values:m}of n){m.unsqueeze_(0);let[_,w]=m.dims.slice(-2),x=await vt(m,{size:[$t,$t],mode:"bicubic"});if(r>0){let E=[],b=A_(r),A=bn(w/b),S=bn(_/b);for(let I=0;Im.map(_=>$t*E_(_/$t))),u=new z("int64",c.flat(),[s,2]),f=c.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:f}}};var M_=class extends X{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");let f=c*u,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var S_=class extends X{};var O_=class extends X{post_process_object_detection(...e){return Kr(...e)}};var Fo=class extends X{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=vf(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 z("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);m=new z("bool",w,m.dims)}i.push(m)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var Kc=class extends X{post_process_semantic_segmentation(...e){return zc(...e)}},I_=class extends Kc{};var Yc=class extends X{post_process_semantic_segmentation(...e){return zc(...e)}},C_=class extends Yc{};var P_=class extends X{};var L_=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var Qc=class extends X{},N_=class extends Qc{};var z_=class extends X{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Ct(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 R_=class extends X{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let u=0;u/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[u,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),c.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var B_=class extends se{static tokenizer_class=ne;static image_processor_class=Ae;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` ${n}${i}${a} `}async _call(e,r=null,s={}){typeof e=="string"&&(e=[e]);let n;return r&&(n=await this.image_processor(r,s),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,s),...n}}};var U_=class extends se{static image_processor_class=Ae;static feature_extractor_class=Ge;static tokenizer_class=ne;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:c,image_token:u,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=` ${o}${m}${i} `,this.image_token_id=l,this.boi_token=c,this.image_token=u;let _=u.repeat(this.image_seq_length);this.full_image_sequence=` ${c}${_}${f} `}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;s&&(o=await this.feature_extractor(s,n),e=e.map(l=>l.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return r&&(a=await this.image_processor(r,n),e=e.map(l=>l.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...o}}};var Ls=class extends se{static image_processor_class=Ae;static tokenizer_class=ne;static image_token="<|image_pad|>";async _call(e,r=null,...s){Array.isArray(e)||(e=[e]);let n,o;if(r&&(n=await this.image_processor(r),o=n.image_grid_thw),o){let i=this.image_processor.config.merge_size**2,l=0,c=this.constructor.image_token,u=o.tolist();e=e.map(f=>{for(;f.includes(c);){let m=Number(u[l++].reduce((_,w)=>_*w,1n));f=f.replace(c,"<|placeholder|>".repeat(Math.floor(m/i)))}return f.replaceAll("<|placeholder|>",c)})}return{...this.tokenizer(e),...n}}};var F_=class extends Ls{static image_token="<|image|>"};var G_=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ge;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:r}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:n}=this.feature_extractor.config,o=Math.floor(s/n),a=Math.floor(e/r)+1,i=Math.floor(a/2);return Math.ceil(i/s)*o}async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let{input_features:a}=await this.feature_extractor(r);n.input_features=a;let i=this._get_num_audio_features(r.length),l=new Uint8Array(i).fill(1);n.input_features_mask=new z("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 xz(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 j_=class extends se{static tokenizer_class=ne;static image_processor_class=Ae;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=a.dims.at(1),u=a.sigmoid(),f=u.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>Hm(x))),_=[];for(let w=0;wM.map((I,O)=>I*x[(O+1)%2])));let E=f[w],b=[],A=[],S=[];for(let M=0;M`+n.repeat(t);a+=` `}return a+=` ${s}${o}`+n.repeat(t)+`${s}`,a}function bz(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function vz(t,e,r,s,n,o){return t===0&&e===0?bz(r,s,n,o):yz(r,t,e,s,n,o)}var Zc=class extends se{static image_processor_class=Ae;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;fvz(A,w[S],i,this.fake_image_token,this.image_token,this.global_img_token)),E=m.split(this.image_token);if(E.length===0)throw new Error("The image token should be present in the text.");let b=E[0];for(let A=0;AE.images).flatMap(E=>E.images).map(E=>Qe.read(E)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=E=>n.encode(E,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[c,u,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),m=a(i[0]),_=new Array(m.length).fill(!1);for(let E=1;E0){let E=await this.image_processor(r);return E.pixel_values.unsqueeze_(0),{...x,...E}}return x}};var W_=class extends se{static tokenizer_class=ne;static image_processor_class=Ae;async _call(e=null,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},o=r?await this.image_processor(r,s):{};return{...n,...o}}};var V_=class extends se{static tokenizer_class=ne;static image_processor_class=Ae;async _call(e,r=null,s={}){let{image_rows:n,image_cols:o,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(r){let l=this.config.image_token??"",{tile_size:c=512,downsample_factor:u=2,encoder_patch_size:f=16,use_thumbnail:m=!0}=this.image_processor.config,_=S=>Math.ceil(Math.floor(S/f)/u),w=_(c)**2,x=this.config.image_start_token??"<|image_start|>",E=this.config.image_end_token??"<|image_end|>",b=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(r)||(r=[r]);let A=0;r=r.map(S=>{let M=S.split(l);return M[0]+M.slice(1).map(I=>{let O=A++,[v,$]=a[O],G=n[O],F=o[O],K=_(v)*_($),W=x;if(G>1||F>1){let Q=l.repeat(w);for(let B=0;B`+Q;m&&(W+=b+l.repeat(K))}else W+=l.repeat(K);return W+E+I}).join("")})}return{...i,...r?this.tokenizer(r,s):{}}}};var H_=class extends se{static tokenizer_class=ne;static image_processor_class=Ae;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:c,num_additional_image_tokens:u}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+u;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let m=0;m0?x.reduce((b,A)=>b*A,1):0;c.push(w),l.push(E)}return[o(c),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,c]=this._decode_helper(s,"wp"),u=[],f=[];for(let m=0;mc.includes(kn))?a=r.map(c=>{let u=c.replaceAll(kn,kn.repeat(o)),f=u.lastIndexOf(kn),m=f===-1?0:f+kn.length;return u.slice(0,m)+n+u.slice(m)+` `}):(ee.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(c=>kz(c,n,o,kn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var yT="<|image|>",Ez=/<\|image_\d+\|>/g,J_=class extends se{static image_processor_class=Ae;static tokenizer_class=ne;async _call(e,r=null,{padding:s=!0,truncation:n=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(r){i=await this.image_processor(r,{num_crops:o});let{num_img_tokens:l}=i,c=e.map((f,m)=>f.split(Ez).join(yT.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let u=this.tokenizer._tokenizer.token_to_id(yT);a.input_ids.map_(f=>f==u?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var Z_=class extends se{static tokenizer_class=ne;static image_processor_class=Ae;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:c,image_end_token:u,patch_size:f,spatial_merge_size:m}=this.config,_=f*m,w=Math.floor(a/_),x=Math.floor(i/_);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let E=0;EMz(w,l)),u=c.map(w=>w.length),f=c.flat(),m=(await Promise.all(f.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=m.length>1?ve(m,0):m[0];let _=a[0];for(let w=0;w0){if(c>nc)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${nc}).`);let u=fh(a,c);for(let f of u){let m=`${s.subfolder??""}/${f}`;l.push(new Promise(async(_,w)=>{let x=await go(t,m,!0,s,i);_(x instanceof Uint8Array?{path:f,data:x}:f)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async u=>{if(typeof u.data=="string"){let f=await go(t,u.data,!0,s);return{...u,data:f}}return u}));return Promise.all(l)}async function Pz(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=Tc(r.device??o.device,e,{warn:M=>ee.info(M)}),i=H2(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=Mc(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:M=>ee.info(M)});if(Vr.hasOwnProperty(c)){if(a==="webgpu"&&!ie.IS_NODE_ENV&&c===yt.fp16&&!await Q2())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(yt).join(", ")}`);let u=o.kv_cache_dtype,f=u?typeof u=="string"?u:u[c]??"float32":void 0;if(f&&!["float32","float16"].includes(f))throw new Error(`Invalid kv_cache_dtype: ${f}. Should be one of: float32, float16`);let m=Vr[c],_={...r.session_options};_.executionProviders??=i;let w=o.free_dimension_overrides;w?_.freeDimensionOverrides??=w:a.startsWith("webnn")&&!_.freeDimensionOverrides&&ee.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${a}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let x=vT(t,e,r,m),E=r.use_external_data_format??o.use_external_data_format,b=await kT(t,e,m,r,E,_);if(b.length>0&&(!ie.IS_NODE_ENV||b.some(M=>typeof M!="string"))&&(_.externalData=b),s&&a==="webgpu"&&u!==!1){let M=Ns(r.config,{prefix:"present",session_name:n});if(Object.keys(M).length>0&&!So()){let I={};for(let O in M)I[O]="gpu-buffer";_.preferredOutputLocation=I}}return{buffer_or_path:await x,session_options:_,session_config:{dtype:c,kv_cache_dtype:f,device:a}}}async function ET(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 Pz(t,e[n],r,o,n),c=await kc(a,i,l);return[n,c]})))}function AT(t){for(let e in t)Ac(t[e])?t[e]=new z(t[e]):typeof t[e]=="object"&&AT(t[e]);return t}async function fe(t,e){let r=Lz(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 Ec(t,s);return AT(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 Lz(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof z)){s.push(a);continue}r[a]=So()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(e).length,o=t.inputNames.length;if(n>o){let a=Object.keys(e).filter(i=>!t.inputNames.includes(i));ee.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var $e=class{};var q=class extends $e{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},he=class extends $e{constructor({logits:e}){super(),this.logits=e}},ge=class extends $e{constructor({logits:e}){super(),this.logits=e}},Te=class extends $e{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},kt=class extends $e{constructor({logits:e}){super(),this.logits=e}};var ou=class extends $e{constructor({alphas:e}){super(),this.alphas=e}};var Dt=class extends Ke{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},qo=class extends Ke{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},zs=class extends Ke{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()}},au=class extends Dt{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s=1&&o[o.length-1]>=this.timestamp_begin,i=o.length<2||o[o.length-2]>=this.timestamp_begin;if(a&&(i?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&this.max_initial_timestamp_index!==null){let f=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(f+1).fill(-1/0)}let l=Lf(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),u=Ce(l.subarray(0,this.timestamp_begin))[0];c>u&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},uu=class extends Dt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);let s=e.length,n=r.slice([0,s],null),o=r.slice([s,r.dims[0]],null);for(let a=0;a1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=s}},MT=class extends qo{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,Ye(e,Object.getOwnPropertyNames(this)))}};var Yr=class extends Ke{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Sn=class t extends Ke{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof Yr&&(e=[e]),this.criteria.push(...e)}_call(e,r){let s=new Array(e.length).fill(!1);for(let n of this.criteria){let o=n(e,r);for(let a=0;ar.length>=this.max_length)}},wu=class extends Yr{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(s=>{let n=s.at(-1);return this.eos_token_id.some(o=>n==o)})}},ST=class extends Yr{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var Rs=class extends Ke{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 jE(e)}static getSampler(e){if(e.do_sample)return new mh(e);if(e.num_beams>1)return new _h(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 dh(e)}},dh=class extends Rs{async sample(e){let r=Ce(e.data)[1];return[[BigInt(r),0]]}},mh=class extends Rs{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await tr(e,r),o=Re(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},_h=class extends Rs{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await tr(e,r),o=Re(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var hh=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 z))throw new TypeError(`Expected a Tensor for key "${r}", got ${typeof s}`);this[r]=s}}get_seq_length(){let e=this;for(let r in e)if(r.startsWith("past_key_values."))return e[r].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}async dispose(){let e=[];for(let r of Object.values(this))r.location==="gpu-buffer"&&e.push(r.dispose());await Promise.all(e)}},Wo=hh;var H={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},dr={[H.DecoderOnly]:{sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[H.DecoderOnlyWithoutHead]:{sessions:(t,e)=>({model:e.model_file_name??"model"})},[H.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[H.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[H.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[H.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),t.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[H.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[H.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[H.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},optional_configs:{generation_config:"generation_config.json"}},[H.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[H.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[H.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[H.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[H.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[H.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...dr[H.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(t,e)=>({model:e.model_file_name??"model"})}};function gh(t){return dr[t]?.text_only_sessions??null}function Vo(t,e,r={}){let s=dr[t]??dr.default;return{sessions:s.sessions(e,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function On(t,{warn:e=!0}={}){let r=t.architectures||[];for(let s of r){let n=rr.get(s);if(n!==void 0)return n}if(t.model_type){let s=rr.get(t.model_type);if(s!==void 0)return s;for(let n of Object.values($s))if(n.has(t.model_type)){let o=rr.get(n.get(t.model_type));if(o!==void 0)return o}}if(e){let s=r.length>0?r.join(", "):"(none)";ee.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Hr}`)}return H.EncoderOnly}function Ho(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return Wt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=JSON.stringify([t,r,s,n]);return ac(o,()=>Wt.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 Ho(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,u=r??a.dtype,f=On(e),m=(x,E=null)=>{E=E??x;let b=Tc(c,x),A=Mc(u,x,b),S=Vr[A]??"",M=`${E}${S}.onnx`,I=l?`${l}/${M}`:M;o.push(I);let O=ph(i,M,x);for(let v of fh(M,O)){let $=l?`${l}/${v}`:v;o.push($)}},{sessions:_,optional_configs:w}=Vo(f,e,{model_file_name:n});for(let[x,E]of Object.entries(_))m(x,E);if(w)for(let x of Object.values(w))o.push(x);return o}var $s=null;function CT(t){$s=t}function wh(t){if(t instanceof z)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 z("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new z("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function xh(t){return new z("bool",[t],[1])}var OT={[H.DecoderOnly]:{can_generate:!0,forward:Pt,prepare_inputs:Cn},[H.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Pt,prepare_inputs:Cn},[H.Seq2Seq]:{can_generate:!0,forward:xu,prepare_inputs:Xo},[H.Vision2Seq]:{can_generate:!0,forward:xu,prepare_inputs:Xo},[H.Musicgen]:{can_generate:!0,forward:xu},[H.EncoderDecoder]:{can_generate:!1,forward:xu},[H.ImageTextToText]:{can_generate:!0,forward:Rz,prepare_inputs:yu},[H.AudioTextToText]:{can_generate:!0,forward:zz,prepare_inputs:yu},[H.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:yu},[H.Phi3V]:{can_generate:!0,prepare_inputs:yu},[H.MultiModality]:{can_generate:!0},[H.AutoEncoder]:{can_generate:!1,forward:Nz},[H.Chatterbox]:{can_generate:!0,forward:Vt},[H.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Cn},default:{can_generate:!1,forward:Vt}};function IT(t,e){let r=rr.get(t),s=!1,n=e?.architectures?.[0];if(n&&n!==t&&t?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let i=rr.get(n);i!==void 0&&(r=i,s=!0)}let o=OT[r]??OT.default,a=dr[r]??dr.default;return{typeConfig:{...o,...a},textOnly:s,modelType:r}}var rr=new Map,bu=new Map,Ds=new Map,y=class extends Ke{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=Ds.get(this.constructor),{typeConfig:o}=IT(n,e);this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:f,session_options:m},w=Ds.get(this);s=_.config=await Wt.from_pretrained(e,_);let{typeConfig:x,textOnly:E,modelType:b}=IT(w,s);if(b===void 0){let I=w??s?.model_type;I!=="custom"&&ee.warn(`Model type for '${I}' not found, assuming encoder-only architecture. Please report this at ${Hr}.`)}if(r&&!(r instanceof hs)){let I={};try{let O=await In(e,{config:s,dtype:u,device:c,model_file_name:i});(await Promise.all(O.map($=>It(e,$,_)))).forEach(($,G)=>{if($.exists){let F=O[G]==="config.json";I[O[G]]={loaded:F?$.size??0:0,total:$.size??0}}})}catch(O){ee.warn(`Unable to fetch model file metadata for total progress tracking: ${O}`)}Object.keys(I).length>0&&(_.progress_callback=new hs(r,I))}let A=x.sessions(s,_,E),S=[ET(e,A,_,x.cache_sessions)];x.optional_configs&&S.push(Dz(e,x.optional_configs,_));let M=await Promise.all(S);return new this(s,...M)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new zs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new pu(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new uu(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new mu(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new fu(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 du(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new au(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new iu(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&n.push(new lu(e.suppress_tokens)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new Tn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new _u(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 hu(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,Ye(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Sn;return e.max_length!==null&&s.push(new gu(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new wu(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[$s.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,$s.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,$s.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,$s.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Ds.get(this.constructor),s=new Set,n=this.config.model_type;for(let a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new z("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=ve([s.decoder_attention_mask,Ze([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=ve([s.attention_mask,Ze([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:r,model_kwargs:s}){let n=Ye(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...c}=r,u=await this._prepare_inputs_embeds(r);r={...c,...Ye(u,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Vt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=ve([o,Io(o,0)],0),"attention_mask"in r&&(r.attention_mask=ve([r.attention_mask,Nd(r.attention_mask)],0));else if(r.decoder_input_ids){let a=wh(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 z)){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=wh(i)}return l.decoder_attention_mask=Cc(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),u=this.config.is_encoder_decoder;u&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let f;u?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];let m=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=m+r.max_new_tokens);let _=this._get_logits_processor(r,m,s),w=this._get_stopping_criteria(r,n),x=l[c].dims.at(0),E=Rs.getSampler(r),b=new Array(x).fill(0),A=f.tolist();o&&o.put(A);let S,M={},I={};for(;;){if(l=this.prepare_inputs_for_generation(A,l,r),S=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let W=this.getAttentions(S);for(let Q in W)Q in M||(M[Q]=[]),M[Q].push(W[Q])}else this._return_dict_in_generate_keys&&Object.assign(I,Ye(S,this._return_dict_in_generate_keys));let $=S.logits.slice(null,-1,null).to("float32"),G=_(A,$),F=[];for(let W=0;WW))break;l=this._update_model_kwargs_for_generation({generated_input_ids:F,outputs:S,model_inputs:l,is_encoder_decoder:u})}o&&o.end();let O=this.getPastKeyValues(S,l.past_key_values,!0),v=new z("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:v,past_key_values:O,...M,...I};for(let $ of Object.values(S))$.location==="gpu-buffer"&&$.dispose();return v}getPastKeyValues(e,r,s=!1){let n=Object.create(null);for(let o in e)if(o.startsWith("present")){let a=o.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values"),i=o.includes("encoder");if(i&&r?n[a]=r[a]:n[a]=e[o],r&&(!i||s)){let l=r[a];l.location==="gpu-buffer"&&l.dispose()}}return new Wo(n)}getAttentions(e){let r={};for(let s of["cross_attentions","encoder_attentions","decoder_attentions"])for(let n in e)n.startsWith(s)&&(s in r||(r[s]=[]),r[s].push(e[n]));return r}addPastKeyValues(e,r){if(r)Object.assign(e,r);else{let s=this.sessions.decoder_model_merged??this.sessions.model,n=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=s?.config?.kv_cache_dtype??"float32",a=o==="float16"?kr.float16:kr.float32,i=Ns(this.config,{batch_size:n});for(let l in i){let c=i[l].reduce((u,f)=>u*f,1);e[l]=new z(o,new a(c),i[l])}}}async _encode_input(e,r,s){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);let n=this.sessions[e];return(await fe(n,Ye(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 xu(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:o,...a}=e;if(!r){let i=Ye(e,t.sessions.model.inputNames);r=(await Vt(t,i)).last_hidden_state}return a.input_ids=n,a.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=e.attention_mask),o&&!a.attention_mask&&(a.attention_mask=o),await Pt(t,a,!0)}async function Vt(t,e){let r=t.sessions.model,s=Ye(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=Nd(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let n=s.pixel_values.dims;s.pixel_mask=Ze([n[0],n[2],n[3]])}return await fe(r,s)}async function Nz(t,e){let r=await t.encode(e);return await t.decode(r)}async function Pt(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=xh(!!n)),s.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(t.config.model_type)?1:0;o.position_ids=$z(o,n,i)}s.inputNames.includes("num_logits_to_keep")&&!o.num_logits_to_keep&&(o.num_logits_to_keep=new z("int64",[0n],[])),t.addPastKeyValues(o,n);let a=Ye(o,s.inputNames);return await fe(s,a)}async function PT(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:f=null,...m}){if(!l){l=await t.encode_text({input_ids:o,...m});let w=Ye(m,s);if(Object.keys(w).length>0){if(o.dims[1]!==1){let x=await e({...w,...m});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&o.dims[1]===1){let x=o.dims[1],E=c.get_seq_length();a=ve([Ze([o.dims[0],E]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(t.config.model_type)){let{image_grid_thw:w,video_grid_thw:x}=m;[i]=t.get_rope_index(o,w,x,a)}return await Pt(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:u,logits_processor:f},!0)}async function zz(t,e){return await PT(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 Rz(t,e){return await PT(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 yh(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:wh(e)}}function yu(t,...e){return t.config.is_encoder_decoder?Xo(t,...e):Cn(t,...e)}function LT({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((u,f,m)=>(f==t&&u.push(m),u),[])),a=o.reduce((c,u)=>c+u.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let c=0;c{let n=await ut(t,e[s],!1,r);return[s,n]})))}var cl={};_s(cl,{ASTForAudioClassification:()=>Ph,ASTModel:()=>Ch,ASTPreTrainedModel:()=>Jo,AfmoeForCausalLM:()=>Sh,AfmoeModel:()=>Mh,AfmoePreTrainedModel:()=>Yo,AlbertForMaskedLM:()=>Eh,AlbertForQuestionAnswering:()=>kh,AlbertForSequenceClassification:()=>vh,AlbertModel:()=>bh,AlbertPreTrainedModel:()=>Bs,ApertusForCausalLM:()=>Th,ApertusModel:()=>Ah,ApertusPreTrainedModel:()=>Ko,ArceeForCausalLM:()=>Ih,ArceeModel:()=>Oh,ArceePreTrainedModel:()=>Qo,BartForConditionalGeneration:()=>Nh,BartForSequenceClassification:()=>zh,BartModel:()=>Lh,BartPretrainedModel:()=>Ln,BeitForImageClassification:()=>$h,BeitModel:()=>Rh,BeitPreTrainedModel:()=>Zo,BertForMaskedLM:()=>Bh,BertForQuestionAnswering:()=>Gh,BertForSequenceClassification:()=>Uh,BertForTokenClassification:()=>Fh,BertModel:()=>Dh,BertPreTrainedModel:()=>Qr,BlenderbotForConditionalGeneration:()=>qh,BlenderbotModel:()=>jh,BlenderbotPreTrainedModel:()=>ea,BlenderbotSmallForConditionalGeneration:()=>Vh,BlenderbotSmallModel:()=>Wh,BlenderbotSmallPreTrainedModel:()=>ta,BloomForCausalLM:()=>Xh,BloomModel:()=>Hh,BloomPreTrainedModel:()=>ra,CHMv2ForDepthEstimation:()=>tg,CHMv2PreTrainedModel:()=>Au,CLIPModel:()=>sg,CLIPPreTrainedModel:()=>mr,CLIPSegForImageSegmentation:()=>lg,CLIPSegModel:()=>ig,CLIPSegPreTrainedModel:()=>ia,CLIPTextModel:()=>ng,CLIPTextModelWithProjection:()=>aa,CLIPVisionModel:()=>og,CLIPVisionModelWithProjection:()=>ag,CamembertForMaskedLM:()=>Yh,CamembertForQuestionAnswering:()=>Zh,CamembertForSequenceClassification:()=>Qh,CamembertForTokenClassification:()=>Jh,CamembertModel:()=>Kh,CamembertPreTrainedModel:()=>Jr,ChatterboxModel:()=>sa,ChatterboxPreTrainedModel:()=>ku,ChineseCLIPModel:()=>eg,ChineseCLIPPreTrainedModel:()=>Eu,ClapAudioModelWithProjection:()=>oa,ClapModel:()=>rg,ClapPreTrainedModel:()=>Nn,ClapTextModelWithProjection:()=>na,CodeGenForCausalLM:()=>ug,CodeGenModel:()=>cg,CodeGenPreTrainedModel:()=>la,Cohere2ForCausalLM:()=>mg,Cohere2Model:()=>dg,Cohere2PreTrainedModel:()=>ua,CohereAsrForConditionalGeneration:()=>hg,CohereAsrModel:()=>_g,CohereAsrPreTrainedModel:()=>pa,CohereForCausalLM:()=>fg,CohereModel:()=>pg,CoherePreTrainedModel:()=>ca,ConvBertForMaskedLM:()=>wg,ConvBertForQuestionAnswering:()=>bg,ConvBertForSequenceClassification:()=>xg,ConvBertForTokenClassification:()=>yg,ConvBertModel:()=>gg,ConvBertPreTrainedModel:()=>Zr,ConvNextForImageClassification:()=>kg,ConvNextModel:()=>vg,ConvNextPreTrainedModel:()=>fa,ConvNextV2ForImageClassification:()=>Ag,ConvNextV2Model:()=>Eg,ConvNextV2PreTrainedModel:()=>da,DFineForObjectDetection:()=>Og,DFineModel:()=>Sg,DFinePreTrainedModel:()=>_a,DINOv3ConvNextModel:()=>tw,DINOv3ConvNextPreTrainedModel:()=>Pu,DINOv3ViTModel:()=>rw,DINOv3ViTPreTrainedModel:()=>Lu,DPTForDepthEstimation:()=>uw,DPTModel:()=>cw,DPTPreTrainedModel:()=>va,DacDecoderModel:()=>ga,DacDecoderOutput:()=>Mu,DacEncoderModel:()=>ha,DacEncoderOutput:()=>Tu,DacModel:()=>Ig,DacPreTrainedModel:()=>zn,DebertaForMaskedLM:()=>Pg,DebertaForQuestionAnswering:()=>zg,DebertaForSequenceClassification:()=>Lg,DebertaForTokenClassification:()=>Ng,DebertaModel:()=>Cg,DebertaPreTrainedModel:()=>es,DebertaV2ForMaskedLM:()=>Bg,DebertaV2ForQuestionAnswering:()=>Gg,DebertaV2ForSequenceClassification:()=>Ug,DebertaV2ForTokenClassification:()=>Fg,DebertaV2Model:()=>Dg,DebertaV2PreTrainedModel:()=>ts,DecisionTransformerModel:()=>jg,DecisionTransformerPreTrainedModel:()=>Su,DeepseekV3ForCausalLM:()=>$g,DeepseekV3Model:()=>Rg,DeepseekV3PreTrainedModel:()=>wa,DeiTForImageClassification:()=>Wg,DeiTModel:()=>qg,DeiTPreTrainedModel:()=>xa,DepthAnythingForDepthEstimation:()=>Vg,DepthAnythingPreTrainedModel:()=>Ou,DepthProForDepthEstimation:()=>Hg,DepthProPreTrainedModel:()=>Iu,DetrForObjectDetection:()=>Kg,DetrForSegmentation:()=>Yg,DetrModel:()=>Xg,DetrObjectDetectionOutput:()=>$n,DetrPreTrainedModel:()=>Rn,DetrSegmentationOutput:()=>Cu,Dinov2ForImageClassification:()=>Jg,Dinov2Model:()=>Qg,Dinov2PreTrainedModel:()=>ya,Dinov2WithRegistersForImageClassification:()=>ew,Dinov2WithRegistersModel:()=>Zg,Dinov2WithRegistersPreTrainedModel:()=>ba,DistilBertForMaskedLM:()=>iw,DistilBertForQuestionAnswering:()=>aw,DistilBertForSequenceClassification:()=>nw,DistilBertForTokenClassification:()=>ow,DistilBertModel:()=>sw,DistilBertPreTrainedModel:()=>rs,DonutSwinModel:()=>lw,DonutSwinPreTrainedModel:()=>Nu,EdgeTamModel:()=>xb,EfficientNetForImageClassification:()=>fw,EfficientNetModel:()=>pw,EfficientNetPreTrainedModel:()=>ka,ElectraForMaskedLM:()=>mw,ElectraForQuestionAnswering:()=>gw,ElectraForSequenceClassification:()=>_w,ElectraForTokenClassification:()=>hw,ElectraModel:()=>dw,ElectraPreTrainedModel:()=>ss,Ernie4_5ForCausalLM:()=>xw,Ernie4_5Model:()=>ww,Ernie4_5PretrainedModel:()=>Ea,EsmForMaskedLM:()=>bw,EsmForSequenceClassification:()=>vw,EsmForTokenClassification:()=>kw,EsmModel:()=>yw,EsmPreTrainedModel:()=>Us,EuroBertForMaskedLM:()=>Aw,EuroBertForSequenceClassification:()=>Tw,EuroBertForTokenClassification:()=>Mw,EuroBertModel:()=>Ew,EuroBertPreTrainedModel:()=>Fs,ExaoneForCausalLM:()=>Ow,ExaoneModel:()=>Sw,ExaonePreTrainedModel:()=>Aa,FalconForCausalLM:()=>Cw,FalconH1ForCausalLM:()=>Lw,FalconH1Model:()=>Pw,FalconH1PreTrainedModel:()=>Ma,FalconModel:()=>Iw,FalconPreTrainedModel:()=>Ta,FastViTForImageClassification:()=>zw,FastViTModel:()=>Nw,FastViTPreTrainedModel:()=>Sa,Florence2ForConditionalGeneration:()=>Rw,Florence2PreTrainedModel:()=>zu,GLPNForDepthEstimation:()=>Jw,GLPNModel:()=>Qw,GLPNPreTrainedModel:()=>za,GPT2LMHeadModel:()=>lx,GPT2Model:()=>ix,GPT2PreTrainedModel:()=>Ua,GPTBigCodeForCausalLM:()=>ex,GPTBigCodeModel:()=>Zw,GPTBigCodePreTrainedModel:()=>Ra,GPTJForCausalLM:()=>ux,GPTJModel:()=>cx,GPTJPreTrainedModel:()=>Fa,GPTNeoForCausalLM:()=>rx,GPTNeoModel:()=>tx,GPTNeoPreTrainedModel:()=>$a,GPTNeoXForCausalLM:()=>nx,GPTNeoXModel:()=>sx,GPTNeoXPreTrainedModel:()=>Da,Gemma2ForCausalLM:()=>Uw,Gemma2Model:()=>Bw,Gemma2PreTrainedModel:()=>Ia,Gemma3ForCausalLM:()=>qw,Gemma3ForConditionalGeneration:()=>Du,Gemma3Model:()=>jw,Gemma3PreTrainedModel:()=>$u,Gemma3nForCausalLM:()=>Ww,Gemma3nForConditionalGeneration:()=>Dn,Gemma3nPreTrainedModel:()=>Bu,GemmaForCausalLM:()=>Dw,GemmaModel:()=>$w,GemmaPreTrainedModel:()=>Oa,GlmForCausalLM:()=>Hw,GlmModel:()=>Vw,GlmMoeDsaForCausalLM:()=>Kw,GlmMoeDsaModel:()=>Xw,GlmMoeDsaPreTrainedModel:()=>Pa,GlmOcrForConditionalGeneration:()=>Yw,GlmPreTrainedModel:()=>Ca,GptOssForCausalLM:()=>ax,GptOssModel:()=>ox,GptOssPreTrainedModel:()=>Ba,GraniteForCausalLM:()=>fx,GraniteModel:()=>px,GraniteMoeHybridForCausalLM:()=>mx,GraniteMoeHybridModel:()=>dx,GraniteMoeHybridPreTrainedModel:()=>ja,GranitePreTrainedModel:()=>Ga,GraniteSpeechForConditionalGeneration:()=>_x,GroundingDinoForObjectDetection:()=>hx,GroundingDinoPreTrainedModel:()=>Gu,GroupViTModel:()=>gx,GroupViTPreTrainedModel:()=>ju,HeliumForCausalLM:()=>xx,HeliumModel:()=>wx,HeliumPreTrainedModel:()=>qa,HieraForImageClassification:()=>bx,HieraModel:()=>yx,HieraPreTrainedModel:()=>Wa,HubertForCTC:()=>Sx,HubertForSequenceClassification:()=>Ox,HubertModel:()=>Mx,HubertPreTrainedModel:()=>Tx,HunYuanDenseV1ForCausalLM:()=>Cx,HunYuanDenseV1Model:()=>Ix,HunYuanDenseV1PreTrainedModel:()=>Va,IJepaForImageClassification:()=>Nx,IJepaModel:()=>Lx,IJepaPreTrainedModel:()=>Ha,Idefics3ForConditionalGeneration:()=>Px,JAISLMHeadModel:()=>Rx,JAISModel:()=>zx,JAISPreTrainedModel:()=>Xa,JinaCLIPModel:()=>$x,JinaCLIPPreTrainedModel:()=>Un,JinaCLIPTextModel:()=>Ka,JinaCLIPVisionModel:()=>Dx,Lfm2ForCausalLM:()=>Ux,Lfm2Model:()=>Bx,Lfm2MoeForCausalLM:()=>jx,Lfm2MoeModel:()=>Gx,Lfm2MoePreTrainedModel:()=>Qa,Lfm2PreTrainedModel:()=>Ya,Lfm2VlForConditionalGeneration:()=>qx,LightOnOcrForConditionalGeneration:()=>Fx,LiteWhisperForConditionalGeneration:()=>N1,Llama4ForCausalLM:()=>Hx,Llama4PreTrainedModel:()=>qu,LlamaForCausalLM:()=>Vx,LlamaModel:()=>Wx,LlamaPreTrainedModel:()=>Ja,LlavaForConditionalGeneration:()=>Et,LlavaOnevisionForConditionalGeneration:()=>Et,LlavaPreTrainedModel:()=>Ru,LlavaQwen2ForCausalLM:()=>Gw,LongT5ForConditionalGeneration:()=>Kx,LongT5Model:()=>Xx,LongT5PreTrainedModel:()=>Za,M2M100ForConditionalGeneration:()=>Qx,M2M100Model:()=>Yx,M2M100PreTrainedModel:()=>ei,MBartForCausalLM:()=>oy,MBartForConditionalGeneration:()=>sy,MBartForSequenceClassification:()=>ny,MBartModel:()=>ry,MBartPreTrainedModel:()=>qs,MPNetForMaskedLM:()=>Wy,MPNetForQuestionAnswering:()=>Xy,MPNetForSequenceClassification:()=>Vy,MPNetForTokenClassification:()=>Hy,MPNetModel:()=>qy,MPNetPreTrainedModel:()=>ns,MT5ForConditionalGeneration:()=>Jy,MT5Model:()=>Qy,MT5PreTrainedModel:()=>di,MarianMTModel:()=>Zx,MarianModel:()=>Jx,MarianPreTrainedModel:()=>ti,MaskFormerForInstanceSegmentation:()=>ty,MaskFormerModel:()=>ey,MaskFormerPreTrainedModel:()=>ri,Metric3DForDepthEstimation:()=>ay,Metric3DPreTrainedModel:()=>Wu,Metric3Dv2ForDepthEstimation:()=>iy,Metric3Dv2PreTrainedModel:()=>Vu,MgpstrForSceneTextRecognition:()=>ly,MgpstrModelOutput:()=>Hu,MgpstrPreTrainedModel:()=>Xu,MimiDecoderModel:()=>ni,MimiDecoderOutput:()=>Yu,MimiEncoderModel:()=>si,MimiEncoderOutput:()=>Ku,MimiModel:()=>cy,MimiPreTrainedModel:()=>Fn,Mistral4ForCausalLM:()=>dy,Mistral4Model:()=>fy,Mistral4PreTrainedModel:()=>ai,MistralForCausalLM:()=>py,MistralModel:()=>uy,MistralPreTrainedModel:()=>oi,MobileBertForMaskedLM:()=>_y,MobileBertForQuestionAnswering:()=>gy,MobileBertForSequenceClassification:()=>hy,MobileBertModel:()=>my,MobileBertPreTrainedModel:()=>Ws,MobileLLMForCausalLM:()=>xy,MobileLLMModel:()=>wy,MobileLLMPreTrainedModel:()=>ii,MobileNetV1ForImageClassification:()=>by,MobileNetV1ForSemanticSegmentation:()=>vy,MobileNetV1Model:()=>yy,MobileNetV1PreTrainedModel:()=>Gn,MobileNetV2ForImageClassification:()=>Ey,MobileNetV2ForSemanticSegmentation:()=>Ay,MobileNetV2Model:()=>ky,MobileNetV2PreTrainedModel:()=>jn,MobileNetV3ForImageClassification:()=>My,MobileNetV3ForSemanticSegmentation:()=>Sy,MobileNetV3Model:()=>Ty,MobileNetV3PreTrainedModel:()=>qn,MobileNetV4ForImageClassification:()=>Iy,MobileNetV4ForSemanticSegmentation:()=>Cy,MobileNetV4Model:()=>Oy,MobileNetV4PreTrainedModel:()=>Wn,MobileViTForImageClassification:()=>Ly,MobileViTModel:()=>Py,MobileViTPreTrainedModel:()=>li,MobileViTV2ForImageClassification:()=>zy,MobileViTV2Model:()=>Ny,MobileViTV2PreTrainedModel:()=>ci,ModernBertDecoderForCausalLM:()=>Fy,ModernBertDecoderModel:()=>Uy,ModernBertDecoderPreTrainedModel:()=>ui,ModernBertForMaskedLM:()=>$y,ModernBertForSequenceClassification:()=>Dy,ModernBertForTokenClassification:()=>By,ModernBertModel:()=>Ry,ModernBertPreTrainedModel:()=>Vs,Moondream1ForConditionalGeneration:()=>Fw,MoonshineForConditionalGeneration:()=>jy,MoonshineModel:()=>Gy,MoonshinePreTrainedModel:()=>pi,MptForCausalLM:()=>Yy,MptModel:()=>Ky,MptPreTrainedModel:()=>fi,MultiModalityCausalLM:()=>Zy,MultiModalityPreTrainedModel:()=>Qu,MusicgenForCausalLM:()=>t0,MusicgenForConditionalGeneration:()=>_i,MusicgenModel:()=>e0,MusicgenPreTrainedModel:()=>mi,NanoChatForCausalLM:()=>s0,NanoChatModel:()=>r0,NanoChatPreTrainedModel:()=>hi,NemotronHForCausalLM:()=>o0,NemotronHModel:()=>n0,NemotronHPreTrainedModel:()=>gi,NeoBertForMaskedLM:()=>i0,NeoBertForQuestionAnswering:()=>u0,NeoBertForSequenceClassification:()=>l0,NeoBertForTokenClassification:()=>c0,NeoBertModel:()=>a0,NeoBertPreTrainedModel:()=>os,NomicBertModel:()=>p0,NomicBertPreTrainedModel:()=>Ju,OPTForCausalLM:()=>k0,OPTModel:()=>v0,OPTPreTrainedModel:()=>ki,Olmo2ForCausalLM:()=>_0,Olmo2Model:()=>m0,Olmo2PreTrainedModel:()=>xi,Olmo3ForCausalLM:()=>g0,Olmo3Model:()=>h0,Olmo3PreTrainedModel:()=>yi,OlmoForCausalLM:()=>d0,OlmoHybridForCausalLM:()=>x0,OlmoHybridModel:()=>w0,OlmoHybridPreTrainedModel:()=>bi,OlmoModel:()=>f0,OlmoPreTrainedModel:()=>wi,OpenELMForCausalLM:()=>b0,OpenELMModel:()=>y0,OpenELMPreTrainedModel:()=>vi,OwlViTForObjectDetection:()=>M0,OwlViTModel:()=>T0,OwlViTPreTrainedModel:()=>Ai,Owlv2ForObjectDetection:()=>A0,Owlv2Model:()=>E0,Owlv2PreTrainedModel:()=>Ei,PaliGemmaForConditionalGeneration:()=>S0,ParakeetForCTC:()=>O0,ParakeetPreTrainedModel:()=>Zu,PatchTSMixerForPrediction:()=>C0,PatchTSMixerModel:()=>I0,PatchTSMixerPreTrainedModel:()=>Ti,PatchTSTForPrediction:()=>L0,PatchTSTModel:()=>P0,PatchTSTPreTrainedModel:()=>Mi,Phi3ForCausalLM:()=>$0,Phi3Model:()=>R0,Phi3PreTrainedModel:()=>Oi,Phi3VForCausalLM:()=>Ii,Phi3VPreTrainedModel:()=>ep,PhiForCausalLM:()=>z0,PhiModel:()=>N0,PhiPreTrainedModel:()=>Si,PreTrainedModel:()=>y,PvtForImageClassification:()=>B0,PvtModel:()=>D0,PvtPreTrainedModel:()=>Ci,PyAnnoteForAudioFrameClassification:()=>F0,PyAnnoteModel:()=>U0,PyAnnotePreTrainedModel:()=>Pi,Qwen2ForCausalLM:()=>j0,Qwen2Model:()=>G0,Qwen2MoeForCausalLM:()=>W0,Qwen2MoeModel:()=>q0,Qwen2MoePreTrainedModel:()=>Ni,Qwen2PreTrainedModel:()=>Li,Qwen2VLForCausalLM:()=>La,Qwen2VLForConditionalGeneration:()=>Bn,Qwen2VLPreTrainedModel:()=>Uu,Qwen2_5_VLForCausalLM:()=>Na,Qwen2_5_VLForConditionalGeneration:()=>Gs,Qwen3ForCausalLM:()=>H0,Qwen3Model:()=>V0,Qwen3MoeForCausalLM:()=>K0,Qwen3MoeModel:()=>X0,Qwen3MoePreTrainedModel:()=>Ri,Qwen3NextForCausalLM:()=>Q0,Qwen3NextModel:()=>Y0,Qwen3NextPreTrainedModel:()=>$i,Qwen3PreTrainedModel:()=>zi,Qwen3VLForCausalLM:()=>Di,Qwen3VLForConditionalGeneration:()=>Hs,Qwen3VLMoeForCausalLM:()=>Z0,Qwen3VLMoeForConditionalGeneration:()=>J0,Qwen3_5ForCausalLM:()=>Bi,Qwen3_5ForConditionalGeneration:()=>Vn,Qwen3_5MoeForCausalLM:()=>tb,Qwen3_5MoeForConditionalGeneration:()=>eb,RFDetrForObjectDetection:()=>ob,RFDetrModel:()=>nb,RFDetrObjectDetectionOutput:()=>tp,RFDetrPreTrainedModel:()=>Fi,RTDetrForObjectDetection:()=>Mg,RTDetrModel:()=>Tg,RTDetrObjectDetectionOutput:()=>_r,RTDetrPreTrainedModel:()=>ma,RTDetrV2ForObjectDetection:()=>gb,RTDetrV2Model:()=>hb,RTDetrV2ObjectDetectionOutput:()=>rp,RTDetrV2PreTrainedModel:()=>Gi,ResNetForImageClassification:()=>sb,ResNetModel:()=>rb,ResNetPreTrainedModel:()=>Ui,RoFormerForMaskedLM:()=>fb,RoFormerForQuestionAnswering:()=>_b,RoFormerForSequenceClassification:()=>db,RoFormerForTokenClassification:()=>mb,RoFormerModel:()=>pb,RoFormerPreTrainedModel:()=>is,RobertaForMaskedLM:()=>ib,RobertaForQuestionAnswering:()=>ub,RobertaForSequenceClassification:()=>lb,RobertaForTokenClassification:()=>cb,RobertaModel:()=>ab,RobertaPreTrainedModel:()=>as,Sam2ImageSegmentationOutput:()=>op,Sam2Model:()=>ji,Sam2PreTrainedModel:()=>ap,Sam3TrackerModel:()=>yb,SamImageSegmentationOutput:()=>sp,SamModel:()=>wb,SamPreTrainedModel:()=>np,SapiensForDepthEstimation:()=>vb,SapiensForNormalEstimation:()=>kb,SapiensForSemanticSegmentation:()=>bb,SapiensPreTrainedModel:()=>Hn,SegformerForImageClassification:()=>Ab,SegformerForSemanticSegmentation:()=>Tb,SegformerModel:()=>Eb,SegformerPreTrainedModel:()=>Xn,SiglipModel:()=>Mb,SiglipPreTrainedModel:()=>qi,SiglipTextModel:()=>Wi,SiglipVisionModel:()=>Sb,SmolLM3ForCausalLM:()=>Ib,SmolLM3Model:()=>Ob,SmolLM3PreTrainedModel:()=>Vi,SnacDecoderModel:()=>Xi,SnacEncoderModel:()=>Hi,SnacModel:()=>Cb,SnacPreTrainedModel:()=>Kn,SolarOpenForCausalLM:()=>Lb,SolarOpenModel:()=>Pb,SolarOpenPreTrainedModel:()=>Ki,SpeechT5ForSpeechToText:()=>zb,SpeechT5ForTextToSpeech:()=>Rb,SpeechT5HifiGan:()=>$b,SpeechT5Model:()=>Nb,SpeechT5PreTrainedModel:()=>Yn,SqueezeBertForMaskedLM:()=>Bb,SqueezeBertForQuestionAnswering:()=>Fb,SqueezeBertForSequenceClassification:()=>Ub,SqueezeBertModel:()=>Db,SqueezeBertPreTrainedModel:()=>Xs,StableLmForCausalLM:()=>jb,StableLmModel:()=>Gb,StableLmPreTrainedModel:()=>Yi,Starcoder2ForCausalLM:()=>Wb,Starcoder2Model:()=>qb,Starcoder2PreTrainedModel:()=>Qi,StyleTextToSpeech2Model:()=>Vb,StyleTextToSpeech2PreTrainedModel:()=>ip,SupertonicForConditionalGeneration:()=>Ji,SupertonicPreTrainedModel:()=>lp,Swin2SRForImageSuperResolution:()=>Qb,Swin2SRModel:()=>Yb,Swin2SRPreTrainedModel:()=>Zi,SwinForImageClassification:()=>Xb,SwinForSemanticSegmentation:()=>Kb,SwinModel:()=>Hb,SwinPreTrainedModel:()=>Qn,T5ForConditionalGeneration:()=>Zb,T5Model:()=>Jb,T5PreTrainedModel:()=>el,TableTransformerForObjectDetection:()=>t1,TableTransformerModel:()=>e1,TableTransformerObjectDetectionOutput:()=>cp,TableTransformerPreTrainedModel:()=>tl,TrOCRForCausalLM:()=>r1,TrOCRPreTrainedModel:()=>up,UltravoxModel:()=>js,UltravoxPreTrainedModel:()=>Fu,UniSpeechForCTC:()=>n1,UniSpeechForSequenceClassification:()=>o1,UniSpeechModel:()=>s1,UniSpeechPreTrainedModel:()=>Jn,UniSpeechSatForAudioFrameClassification:()=>c1,UniSpeechSatForCTC:()=>i1,UniSpeechSatForSequenceClassification:()=>l1,UniSpeechSatModel:()=>a1,UniSpeechSatPreTrainedModel:()=>Ks,VaultGemmaForCausalLM:()=>p1,VaultGemmaModel:()=>u1,VaultGemmaPreTrainedModel:()=>rl,ViTForImageClassification:()=>m1,ViTMAEModel:()=>_1,ViTMAEPreTrainedModel:()=>pp,ViTMSNForImageClassification:()=>g1,ViTMSNModel:()=>h1,ViTMSNPreTrainedModel:()=>nl,ViTModel:()=>d1,ViTPreTrainedModel:()=>sl,VisionEncoderDecoderModel:()=>f1,VitMatteForImageMatting:()=>w1,VitMattePreTrainedModel:()=>fp,VitPoseForPoseEstimation:()=>x1,VitPosePreTrainedModel:()=>dp,VitsModel:()=>y1,VitsModelOutput:()=>mp,VitsPreTrainedModel:()=>_p,VoxtralForConditionalGeneration:()=>b1,VoxtralRealtimeForConditionalGeneration:()=>ol,VoxtralRealtimePreTrainedModel:()=>hp,Wav2Vec2BertForCTC:()=>A1,Wav2Vec2BertForSequenceClassification:()=>T1,Wav2Vec2BertModel:()=>E1,Wav2Vec2BertPreTrainedModel:()=>Zn,Wav2Vec2ForAudioFrameClassification:()=>Ax,Wav2Vec2ForCTC:()=>kx,Wav2Vec2ForSequenceClassification:()=>Ex,Wav2Vec2Model:()=>vx,Wav2Vec2PreTrainedModel:()=>sr,WavLMForAudioFrameClassification:()=>C1,WavLMForCTC:()=>S1,WavLMForSequenceClassification:()=>O1,WavLMForXVector:()=>I1,WavLMModel:()=>M1,WavLMPreTrainedModel:()=>ls,WeSpeakerResNetModel:()=>P1,WeSpeakerResNetPreTrainedModel:()=>wp,WhisperForConditionalGeneration:()=>yp,WhisperModel:()=>L1,WhisperPreTrainedModel:()=>al,XLMForQuestionAnswering:()=>B1,XLMForSequenceClassification:()=>$1,XLMForTokenClassification:()=>D1,XLMModel:()=>z1,XLMPreTrainedModel:()=>cs,XLMRobertaForMaskedLM:()=>F1,XLMRobertaForQuestionAnswering:()=>q1,XLMRobertaForSequenceClassification:()=>G1,XLMRobertaForTokenClassification:()=>j1,XLMRobertaModel:()=>U1,XLMRobertaPreTrainedModel:()=>us,XLMWithLMHeadModel:()=>R1,XVectorOutput:()=>gp,YolosForObjectDetection:()=>V1,YolosModel:()=>W1,YolosObjectDetectionOutput:()=>bp,YolosPreTrainedModel:()=>il,YoutuForCausalLM:()=>X1,YoutuModel:()=>H1,YoutuPreTrainedModel:()=>ll});var Bs=class extends y{},bh=class extends Bs{},vh=class extends Bs{async _call(e){return new q(await super._call(e))}},kh=class extends Bs{async _call(e){return new Te(await super._call(e))}},Eh=class extends Bs{async _call(e){return new ge(await super._call(e))}};var Ko=class extends y{},Ah=class extends Ko{},Th=class extends Ko{};var Yo=class extends y{},Mh=class extends Yo{},Sh=class extends Yo{};var Qo=class extends y{},Oh=class extends Qo{},Ih=class extends Qo{};var Jo=class extends y{},Ch=class extends Jo{},Ph=class extends Jo{};var Ln=class extends y{},Lh=class extends Ln{},Nh=class extends Ln{},zh=class extends Ln{async _call(e){return new q(await super._call(e))}};var Zo=class extends y{},Rh=class extends Zo{},$h=class extends Zo{async _call(e){return new q(await super._call(e))}};var Qr=class extends y{},Dh=class extends Qr{},Bh=class extends Qr{async _call(e){return new ge(await super._call(e))}},Uh=class extends Qr{async _call(e){return new q(await super._call(e))}},Fh=class extends Qr{async _call(e){return new he(await super._call(e))}},Gh=class extends Qr{async _call(e){return new Te(await super._call(e))}};var ea=class extends y{},jh=class extends ea{},qh=class extends ea{};var ta=class extends y{},Wh=class extends ta{},Vh=class extends ta{};var ra=class extends y{},Hh=class extends ra{},Xh=class extends ra{};var Jr=class extends y{},Kh=class extends Jr{},Yh=class extends Jr{async _call(e){return new ge(await super._call(e))}},Qh=class extends Jr{async _call(e){return new q(await super._call(e))}},Jh=class extends Jr{async _call(e){return new he(await super._call(e))}},Zh=class extends Jr{async _call(e){return new Te(await super._call(e))}};var Bz=4299n,NT=6561n,ku=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"]},sa=class extends ku{async encode_speech(e){return fe(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,audio_features:u=null,audio_tokens:f=null,speaker_embeddings:m=null,speaker_features:_=null,...w}){let x;if(!a){let b=this.sessions.embed_tokens.inputNames,A={input_ids:e};if(b.includes("exaggeration")){if(!(n instanceof z)){let S=e.dims[0];if(n==null)n=Xe([S],.5);else if(typeof n=="number")n=Xe([S],n);else if(Array.isArray(n))n=new z("float32",n,[S]);else throw new Error("Unsupported type for `exaggeration` input")}A.exaggeration=n}if(b.includes("position_ids")&&(A.position_ids=o),{inputs_embeds:a}=await fe(this.sessions.embed_tokens,A),u&&f&&m&&_&&(x={audio_features:u,audio_tokens:f,speaker_embeddings:m,speaker_features:_}),x||s)x??=await this.encode_speech(s),a=ve([x.audio_features,a],1),r=Ze([a.dims[0],a.dims[1]]);else{let S=a.dims[1];if(!i||S!==1)throw new Error("Incorrect state encountered during generation.");let M=i.get_seq_length();r=Ze([a.dims[0],M+S])}}return{...await Pt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c},!1),...x}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==NT)-1);r.position_ids=new z("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=NT?0:i++)});r.position_ids=new z("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=Xe([a.dims[0],3],Bz),l=ve([s,a,i],1),{waveform:c}=await fe(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var Eu=class extends y{},eg=class extends Eu{};var Au=class extends y{},tg=class extends Au{};var Nn=class extends y{},rg=class extends Nn{},na=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},oa=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var mr=class extends y{},sg=class extends mr{},ng=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},aa=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},og=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},ag=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var ia=class extends y{},ig=class extends ia{},lg=class extends ia{};var la=class extends y{},cg=class extends la{},ug=class extends la{};var ca=class extends y{},pg=class extends ca{},fg=class extends ca{};var ua=class extends y{},dg=class extends ua{},mg=class extends ua{};var pa=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"]},_g=class extends pa{},hg=class extends pa{};var Zr=class extends y{},gg=class extends Zr{},wg=class extends Zr{async _call(e){return new ge(await super._call(e))}},xg=class extends Zr{async _call(e){return new q(await super._call(e))}},yg=class extends Zr{async _call(e){return new he(await super._call(e))}},bg=class extends Zr{async _call(e){return new Te(await super._call(e))}};var fa=class extends y{},vg=class extends fa{},kg=class extends fa{async _call(e){return new q(await super._call(e))}};var da=class extends y{},Eg=class extends da{},Ag=class extends da{async _call(e){return new q(await super._call(e))}};var ma=class extends y{},Tg=class extends ma{},Mg=class extends ma{async _call(e){return new _r(await super._call(e))}},_r=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var _a=class extends y{},Sg=class extends _a{},Og=class extends _a{async _call(e){return new _r(await super._call(e))}};var Tu=class extends $e{constructor({audio_codes:e}){super(),this.audio_codes=e}},Mu=class extends $e{constructor({audio_values:e}){super(),this.audio_values=e}},zn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Ig=class extends zn{async encode(e){return new Tu(await fe(this.sessions.encoder_model,e))}async decode(e){return new Mu(await fe(this.sessions.decoder_model,e))}},ha=class extends zn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ga=class extends zn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var es=class extends y{},Cg=class extends es{},Pg=class extends es{async _call(e){return new ge(await super._call(e))}},Lg=class extends es{async _call(e){return new q(await super._call(e))}},Ng=class extends es{async _call(e){return new he(await super._call(e))}},zg=class extends es{async _call(e){return new Te(await super._call(e))}};var wa=class extends y{},Rg=class extends wa{},$g=class extends wa{};var ts=class extends y{},Dg=class extends ts{},Bg=class extends ts{async _call(e){return new ge(await super._call(e))}},Ug=class extends ts{async _call(e){return new q(await super._call(e))}},Fg=class extends ts{async _call(e){return new he(await super._call(e))}},Gg=class extends ts{async _call(e){return new Te(await super._call(e))}};var Su=class extends y{},jg=class extends Su{};var xa=class extends y{},qg=class extends xa{},Wg=class extends xa{async _call(e){return new q(await super._call(e))}};var Ou=class extends y{},Vg=class extends Ou{};var Iu=class extends y{},Hg=class extends Iu{};var Rn=class extends y{},Xg=class extends Rn{},Kg=class extends Rn{async _call(e){return new $n(await super._call(e))}},Yg=class extends Rn{async _call(e){return new Cu(await super._call(e))}},$n=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},Cu=class extends $e{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var ya=class extends y{},Qg=class extends ya{},Jg=class extends ya{async _call(e){return new q(await super._call(e))}};var ba=class extends y{},Zg=class extends ba{},ew=class extends ba{async _call(e){return new q(await super._call(e))}};var Pu=class extends y{},tw=class extends Pu{};var Lu=class extends y{},rw=class extends Lu{};var rs=class extends y{},sw=class extends rs{},nw=class extends rs{async _call(e){return new q(await super._call(e))}},ow=class extends rs{async _call(e){return new he(await super._call(e))}},aw=class extends rs{async _call(e){return new Te(await super._call(e))}},iw=class extends rs{async _call(e){return new ge(await super._call(e))}};var Nu=class extends y{},lw=class extends Nu{};var va=class extends y{},cw=class extends va{},uw=class extends va{};var ka=class extends y{},pw=class extends ka{},fw=class extends ka{async _call(e){return new q(await super._call(e))}};var ss=class extends y{},dw=class extends ss{},mw=class extends ss{async _call(e){return new ge(await super._call(e))}},_w=class extends ss{async _call(e){return new q(await super._call(e))}},hw=class extends ss{async _call(e){return new he(await super._call(e))}},gw=class extends ss{async _call(e){return new Te(await super._call(e))}};var Ea=class extends y{},ww=class extends Ea{},xw=class extends Ea{};var Us=class extends y{},yw=class extends Us{},bw=class extends Us{async _call(e){return new ge(await super._call(e))}},vw=class extends Us{async _call(e){return new q(await super._call(e))}},kw=class extends Us{async _call(e){return new he(await super._call(e))}};var Fs=class extends y{},Ew=class extends Fs{},Aw=class extends Fs{async _call(e){return new ge(await super._call(e))}},Tw=class extends Fs{async _call(e){return new q(await super._call(e))}},Mw=class extends Fs{async _call(e){return new he(await super._call(e))}};var Aa=class extends y{},Sw=class extends Aa{},Ow=class extends Aa{};var Ta=class extends y{},Iw=class extends Ta{},Cw=class extends Ta{};var Ma=class extends y{},Pw=class extends Ma{},Lw=class extends Ma{};var Sa=class extends y{},Nw=class extends Sa{},zw=class extends Sa{async _call(e){return new q(await super._call(e))}};var zu=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"},Rw=class extends zu{_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([Ze(r.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:s,attention_mask:n}){if(!e&&!r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,a;return e&&(o=await this.encode_text({input_ids:e})),r&&(a=await this.encode_image({pixel_values:r})),o&&a?{inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:a,input_ids:e,attention_mask:n}):s=o||a,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:r,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:o,encoder_outputs:a,past_key_values:i,inputs_embeds:l,decoder_inputs_embeds:c}){if(l||({inputs_embeds:l,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:l,attention_mask:s})),!a){let{last_hidden_state:f}=await Vt(this,{inputs_embeds:l,attention_mask:s});a=f}if(!c){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:n})}return await Pt(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var Oa=class extends y{},$w=class extends Oa{},Dw=class extends Oa{};var Ia=class extends y{},Bw=class extends Ia{},Uw=class extends Ia{};var Ru=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Et=class extends Ru{_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})}},Fw=class extends Et{},Gw=class extends Et{};var $u=class extends y{},jw=class extends $u{},Du=class extends Et{},qw=class extends Du{};var Bu=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"]},Dn=class extends Bu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:f=null,...m}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await fe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:w}=await fe(this.sessions.vision_encoder,{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 fe(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Pt(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,attention_mask:r,position_ids:a,generation_config:u,logits_processor:f},!0)}_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 vu({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},Ww=class extends Dn{};var Ca=class extends y{},Vw=class extends Ca{},Hw=class extends Ca{};var Pa=class extends y{},Xw=class extends Pa{},Kw=class extends Pa{};var Uu=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Bn=class extends Uu{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,r){if(r){let{data:s,dims:n}=yh(r),o=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),a=Array.from({length:n[0]},(i,l)=>Ce(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return[new z("int64",o,[3,...n]),new z("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 z("int64",o,[3,...e.dims]),Ld([s,1])]}}_reorder_and_write_positions(e,r,s,n){let o=e.reduce((c,u)=>c+u.length,0),a=new Array(o),i=0;for(let c=0;c<3;++c)for(let u of e){let f=u.length/3;for(let m=c*f;m<(c+1)*f;++m)a[i++]=u[m]}let l=0;for(let c=0;c(S==l&&A.push(M),A),[]).map(A=>c[A+1]),m=f.filter(A=>A==a).length,_=f.filter(A=>A==i).length,w=[],x=0,E=m,b=_;for(let A=0;Axe>x&&Z==a),M=c.findIndex((Z,xe)=>xe>x&&Z==i),I=E>0&&S!==-1?S:c.length+1,O=b>0&&M!==-1?M:c.length+1,v,$,G,F;I0?Ce(w.at(-1))[0]+1:0;w.push(Array.from({length:3*B},(Z,xe)=>P+xe%B));let re=B+P,Y=K*W*Q,L=Array.from({length:Y},(Z,xe)=>re+Math.floor(xe/(W*Q))),R=Array.from({length:Y},(Z,xe)=>re+Math.floor(xe/Q)%W),D=Array.from({length:Y},(Z,xe)=>re+xe%Q);w.push([L,R,D].flat()),x=v+Y}if(x0?Ce(w.at(-1))[0]+1:0,S=c.length-x;w.push(Array.from({length:3*S},(M,I)=>A+I%S))}return w}get_rope_index(e,r,s,n){let{vision_config:o}=this.config,a=o.spatial_merge_size??2;if(r||s){let i=e.tolist();n||(n=Cc(e));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),u=r?r.tolist():[],f=s?s.tolist():[],m={image_index:0,video_index:0},_=[];for(let w=0;wl[w][S]==1),E=this._get_multimodal_rope_positions({filtered_ids:x,image_grid_thw_list:u,video_grid_thw_list:f,spatial_merge_size:a,state:m}),b=this._reorder_and_write_positions(E,l[w],c,w);_.push(Ce(b)[0]+1-i[w].length)}return[new z("int64",c.flat(1/0),[3,e.dims[0],e.dims[1]]),new z("int64",_,[_.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:r}){return(await fe(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(e){return 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=Ct([i,i,i],0)}}return r}},La=class extends Bn{};var Gs=class extends Bn{image_grid_thw_name="image_grid_thw"},Na=class extends La{image_grid_thw_name="image_grid_thw"};var Yw=class extends Gs{get_vision_position_ids(e,r,s,n){let o=Math.floor(r[0]/s),a=Math.floor(r[1]/n),i=Math.floor(r[2]/n),l=a*i*o,c=Array.from({length:l},()=>e),u=Array.from({length:l},(m,_)=>e+Math.floor(_/(i*o))),f=Array.from({length:l},(m,_)=>e+_%i);return[...c,...u,...f]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:o}){let{image_token_id:a}=this.config,i=[],l=0,c=e[0]==a?1:0;for(let m=1;m<=e.length;++m){let _=mu+b%x)),u+=x}else{let x=r[o.image_index++].map(Number),E=x[0];f.push(this.get_vision_position_ids(u,x,E,n)),u+=Math.max(x[1],x[2])/n}return f}};var za=class extends y{},Qw=class extends za{},Jw=class extends za{};var Ra=class extends y{},Zw=class extends Ra{},ex=class extends Ra{};var $a=class extends y{},tx=class extends $a{},rx=class extends $a{};var Da=class extends y{},sx=class extends Da{},nx=class extends Da{};var Ba=class extends y{},ox=class extends Ba{},ax=class extends Ba{};var Ua=class extends y{},ix=class extends Ua{},lx=class extends Ua{};var Fa=class extends y{},cx=class extends Fa{},ux=class extends Fa{};var Ga=class extends y{},px=class extends Ga{},fx=class extends Ga{};var ja=class extends y{},dx=class extends ja{},mx=class extends ja{};var Fu=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},js=class extends Fu{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return vu({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}};var _x=class extends js{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var Gu=class extends y{},hx=class extends Gu{};var ju=class extends y{},gx=class extends ju{};var qa=class extends y{},wx=class extends qa{},xx=class extends qa{};var Wa=class extends y{},yx=class extends Wa{},bx=class extends Wa{async _call(e){return new q(await super._call(e))}};var sr=class extends y{},vx=class extends sr{},kx=class extends sr{async _call(e){return new kt(await super._call(e))}},Ex=class extends sr{async _call(e){return new q(await super._call(e))}},Ax=class extends sr{async _call(e){return new he(await super._call(e))}};var Tx=class extends y{},Mx=class extends sr{},Sx=class extends sr{async _call(e){return new kt(await super._call(e))}},Ox=class extends sr{async _call(e){return new q(await super._call(e))}};var Va=class extends y{},Ix=class extends Va{},Cx=class extends Va{};var Px=class extends Et{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var Ha=class extends y{},Lx=class extends Ha{},Nx=class extends Ha{async _call(e){return new q(await super._call(e))}};var Xa=class extends y{},zx=class extends Xa{},Rx=class extends Xa{};var Un=class extends y{},$x=class extends Un{async forward(e){let r=!e.input_ids,s=!e.pixel_values;if(r&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(r&&(e.input_ids=Ze([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=Xe([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}},Ka=class extends Un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Dx=class extends Un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Ya=class extends y{},Bx=class extends Ya{},Ux=class extends Ya{};var Fx=class extends Et{};var Qa=class extends y{},Gx=class extends Qa{},jx=class extends Qa{};var qx=class extends Et{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var Ja=class extends y{},Wx=class extends Ja{},Vx=class extends Ja{};var qu=class extends y{},Hx=class extends qu{};var Za=class extends y{},Xx=class extends Za{},Kx=class extends Za{};var ei=class extends y{},Yx=class extends ei{},Qx=class extends ei{};var ti=class extends y{},Jx=class extends ti{},Zx=class extends ti{};var ri=class extends y{},ey=class extends ri{},ty=class extends ri{};var qs=class extends y{},ry=class extends qs{},sy=class extends qs{},ny=class extends qs{async _call(e){return new q(await super._call(e))}},oy=class extends qs{};var Wu=class extends y{},ay=class extends Wu{};var Vu=class extends y{},iy=class extends Vu{};var Hu=class extends $e{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Xu=class extends y{},ly=class extends Xu{async _call(e){return new Hu(await super._call(e))}};var Ku=class extends $e{constructor({audio_codes:e}){super(),this.audio_codes=e}},Yu=class extends $e{constructor({audio_values:e}){super(),this.audio_values=e}},Fn=class extends y{main_input_name="input_values";forward_params=["input_values"]},cy=class extends Fn{async encode(e){return new Ku(await fe(this.sessions.encoder_model,e))}async decode(e){return new Yu(await fe(this.sessions.decoder_model,e))}},si=class extends Fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ni=class extends Fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var oi=class extends y{},uy=class extends oi{},py=class extends oi{};var ai=class extends y{},fy=class extends ai{},dy=class extends ai{};var Ws=class extends y{},my=class extends Ws{},_y=class extends Ws{async _call(e){return new ge(await super._call(e))}},hy=class extends Ws{async _call(e){return new q(await super._call(e))}},gy=class extends Ws{async _call(e){return new Te(await super._call(e))}};var ii=class extends y{},wy=class extends ii{},xy=class extends ii{};var Gn=class extends y{},yy=class extends Gn{},by=class extends Gn{async _call(e){return new q(await super._call(e))}},vy=class extends Gn{};var jn=class extends y{},ky=class extends jn{},Ey=class extends jn{async _call(e){return new q(await super._call(e))}},Ay=class extends jn{};var qn=class extends y{},Ty=class extends qn{},My=class extends qn{async _call(e){return new q(await super._call(e))}},Sy=class extends qn{};var Wn=class extends y{},Oy=class extends Wn{},Iy=class extends Wn{async _call(e){return new q(await super._call(e))}},Cy=class extends Wn{};var li=class extends y{},Py=class extends li{},Ly=class extends li{async _call(e){return new q(await super._call(e))}};var ci=class extends y{},Ny=class extends ci{},zy=class extends ci{async _call(e){return new q(await super._call(e))}};var Vs=class extends y{},Ry=class extends Vs{},$y=class extends Vs{async _call(e){return new ge(await super._call(e))}},Dy=class extends Vs{async _call(e){return new q(await super._call(e))}},By=class extends Vs{async _call(e){return new he(await super._call(e))}};var ui=class extends y{},Uy=class extends ui{},Fy=class extends ui{};var pi=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Gy=class extends pi{},jy=class extends pi{};var ns=class extends y{},qy=class extends ns{},Wy=class extends ns{async _call(e){return new ge(await super._call(e))}},Vy=class extends ns{async _call(e){return new q(await super._call(e))}},Hy=class extends ns{async _call(e){return new he(await super._call(e))}},Xy=class extends ns{async _call(e){return new Te(await super._call(e))}};var fi=class extends y{},Ky=class extends fi{},Yy=class extends fi{};var di=class extends y{},Qy=class extends di{},Jy=class extends di{};var Qu=class extends y{},Zy=class extends Qu{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=Ye(e,l.inputNames);s=await fe(l,c)}else{let l=this.sessions.gen_img_embeds,c=Ye({image_ids:e.input_ids},l.inputNames);s=await fe(l,c)}let n={...e,...s},o=await Pt(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await fe(a,Ye(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,Io(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=ve([r.attention_mask,Io(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Xe([0,0,3,384,384],1)),n&&(r.images_seq_mask=new z("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new z("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let r=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[r,null]),o=this.sessions.image_decode,{decoded_image:a}=await fe(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let u=Qe.fromTensor(c);l.push(u)}return l}};var mi=class extends y{},e0=class extends mi{},t0=class extends mi{},_i=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[r,s]=e.dims,n=this.config.decoder.num_codebooks,o=s-n,a=0;for(let c=0;c0&&m<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new z(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)),Xo(this,o,r,s)}async generate(e){let r=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await fe(this.sessions.encodec_decode,{audio_codes:s});return n}};var hi=class extends y{},r0=class extends hi{},s0=class extends hi{};var gi=class extends y{},n0=class extends gi{},o0=class extends gi{};var os=class extends y{},a0=class extends os{},i0=class extends os{async _call(e){return new ge(await super._call(e))}},l0=class extends os{async _call(e){return new q(await super._call(e))}},c0=class extends os{async _call(e){return new he(await super._call(e))}},u0=class extends os{async _call(e){return new Te(await super._call(e))}};var Ju=class extends y{},p0=class extends Ju{};var wi=class extends y{},f0=class extends wi{},d0=class extends wi{};var xi=class extends y{},m0=class extends xi{},_0=class extends xi{};var yi=class extends y{},h0=class extends yi{},g0=class extends yi{};var bi=class extends y{},w0=class extends bi{},x0=class extends bi{};var vi=class extends y{},y0=class extends vi{},b0=class extends vi{};var ki=class extends y{},v0=class extends ki{},k0=class extends ki{};var Ei=class extends y{},E0=class extends Ei{},A0=class extends Ei{};var Ai=class extends y{},T0=class extends Ai{},M0=class extends Ai{};var S0=class extends Et{};var Zu=class extends y{},O0=class extends Zu{async _call(e){return new kt(await super._call(e))}};var Ti=class extends y{},I0=class extends Ti{},C0=class extends Ti{};var Mi=class extends y{},P0=class extends Mi{},L0=class extends Mi{};var Si=class extends y{},N0=class extends Si{},z0=class extends Si{};var Oi=class extends y{},R0=class extends Oi{},$0=class extends Oi{};var ep=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Ii=class extends ep{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,...u}){if(!a){let m;if(s&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:m}=await fe(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let _=this.config.normalized_config.hidden_size;m=new z("float32",[],[0,_])}({inputs_embeds:a}=await fe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await Pt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var Ci=class extends y{},D0=class extends Ci{},B0=class extends Ci{async _call(e){return new q(await super._call(e))}};var Pi=class extends y{},U0=class extends Pi{},F0=class extends Pi{async _call(e){return new he(await super._call(e))}};var Li=class extends y{},G0=class extends Li{},j0=class extends Li{};var Ni=class extends y{},q0=class extends Ni{},W0=class extends Ni{};var zi=class extends y{},V0=class extends zi{},H0=class extends zi{};var Ri=class extends y{},X0=class extends Ri{},K0=class extends Ri{};var $i=class extends y{},Y0=class extends $i{},Q0=class extends $i{};var Hs=class extends Gs{},Di=class extends Na{};var J0=class extends Hs{},Z0=class extends Di{};var Vn=class extends Hs{},Bi=class extends Vn{};var eb=class extends Vn{},tb=class extends Bi{};var Ui=class extends y{},rb=class extends Ui{},sb=class extends Ui{async _call(e){return new q(await super._call(e))}};var Fi=class extends y{},nb=class extends Fi{},ob=class extends Fi{async _call(e){return new tp(await super._call(e))}},tp=class extends _r{};var as=class extends y{},ab=class extends as{},ib=class extends as{async _call(e){return new ge(await super._call(e))}},lb=class extends as{async _call(e){return new q(await super._call(e))}},cb=class extends as{async _call(e){return new he(await super._call(e))}},ub=class extends as{async _call(e){return new Te(await super._call(e))}};var is=class extends y{},pb=class extends is{},fb=class extends is{async _call(e){return new ge(await super._call(e))}},db=class extends is{async _call(e){return new q(await super._call(e))}},mb=class extends is{async _call(e){return new he(await super._call(e))}},_b=class extends is{async _call(e){return new Te(await super._call(e))}};var Gi=class extends y{},hb=class extends Gi{},gb=class extends Gi{async _call(e){return new rp(await super._call(e))}},rp=class extends _r{};var sp=class extends $e{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},np=class extends y{},wb=class extends np{async get_image_embeddings({pixel_values:e}){return await Vt(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=Ze(e.input_points.dims.slice(0,-1));let r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await fe(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new sp(await super._call(e))}};var op=class extends $e{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},ap=class extends y{},ji=class extends ap{async get_image_embeddings({pixel_values:e}){return await Vt(this,{pixel_values:e})}async forward(e){let{num_feature_levels:r}=this.config.vision_config;if(Array.from({length:r},(a,i)=>`image_embeddings.${i}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??=Ze(a.slice(0,-1)),e.input_boxes??=Xe([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Xe([a[0],a[1],0],-1n),e.input_points=Xe([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=Ye(e,n.inputNames);return await fe(n,o)}async _call(e){return new op(await super._call(e))}},xb=class extends ji{},yb=class extends ji{};var Hn=class extends y{},bb=class extends Hn{},vb=class extends Hn{},kb=class extends Hn{};var Xn=class extends y{},Eb=class extends Xn{},Ab=class extends Xn{},Tb=class extends Xn{};var qi=class extends y{},Mb=class extends qi{},Wi=class extends qi{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Sb=class extends mr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Vi=class extends y{},Ob=class extends Vi{},Ib=class extends Vi{};var Kn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Cb=class extends Kn{async encode(e){return await fe(this.sessions.encoder_model,e)}async decode(e){return await fe(this.sessions.decoder_model,e)}},Hi=class extends Kn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Xi=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 Ki=class extends y{},Pb=class extends Ki{},Lb=class extends Ki{};var Yn=class extends y{},Nb=class extends Yn{},zb=class extends Yn{},Rb=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 Vt(this,i),u=l.dims[1]/this.config.reduction_factor,f=Math.floor(u*o),m=Math.floor(u*n),_=this.config.num_mel_bins,w=[],x=null,E=null,b=0;for(;;){++b;let M=xh(!!E),I;E?I=E.output_sequence_out:I=new z("float32",new Float32Array(_),[1,1,_]);let O={use_cache_branch:M,output_sequence:I,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(O,x),E=await fe(this.sessions.decoder_model_merged,O),x=this.getPastKeyValues(E,x);let{prob:v,spectrum:$}=E;if(w.push($),b>=m&&(Array.from(v.data).filter(G=>G>=s).length>0||b>=f))break}let A=ve(w),{waveform:S}=await fe(a.sessions.model,{spectrogram:A});return{spectrogram:A,waveform:S}}},$b=class extends y{main_input_name="spectrogram"};var Xs=class extends y{},Db=class extends Xs{},Bb=class extends Xs{async _call(e){return new ge(await super._call(e))}},Ub=class extends Xs{async _call(e){return new q(await super._call(e))}},Fb=class extends Xs{async _call(e){return new Te(await super._call(e))}};var Yi=class extends y{},Gb=class extends Yi{},jb=class extends Yi{};var Qi=class extends y{},qb=class extends Qi{},Wb=class extends Qi{};var ip=class extends y{},Vb=class extends ip{};var lp=class extends y{},Ji=class extends lp{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:c}=this.config,{last_hidden_state:u,durations:f}=await fe(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=f.div(o).mul_(a),_=l*i,w=m.data,x=Int32Array.from(w,F=>Math.ceil(F/_)),E=Math.max(...x),b=e.dims[0],A=new BigInt64Array(b*E);for(let F=0;FE*b,1);l[w]=new z(c,new u(x),f[w])}let m=new z(c,new u(i*zT),[1,i,zT]),_=e[Symbol.asyncIterator]?.()??e[Symbol.iterator]?.();if(!_)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:m,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:_,text_hidden_size:r.hidden_size}}async function Gz(t,e){let r=e.dims[2],s=Math.floor((Uz+r-3)/2)+1,n=new z("int64",BigInt64Array.from({length:s},(u,f)=>BigInt(t.enc_past_seq_len+f)),[1,s]),o=t.enc_past_seq_len+s,a=Ze([1,o]),{audio_embeds:i,present_padding_cache:l,...c}=await fe(t.encoder_session,{input_features:e,attention_mask:a,position_ids:n,past_padding_cache:t.enc_padding_cache,...t.enc_kv_cache});t.enc_padding_cache.location==="gpu-buffer"&&t.enc_padding_cache.dispose(),t.enc_padding_cache=l;for(let u in c)if(u.startsWith("present.")){let f=u.replace("present","past_key_values"),m=t.enc_kv_cache[f];m?.location==="gpu-buffer"&&m.dispose(),t.enc_kv_cache[f]=c[u]}return t.enc_past_seq_len=o,i}async function jz(t,e){for(;t.audio_embed_total_tokens0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let u=0;u=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var k1=class extends Yr{constructor(e){super(),this._s=e}_call(e){let r=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>r)}},hp=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},ol=class extends hp{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=v1.get(this);o&&await jz(o,o.audio_consumed+n);let{inputs_embeds:a}=await fe(this.sessions.embed_tokens,{input_ids:e});o&&qz(o,a,n);let i={inputs_embeds:a,...s};this.addPastKeyValues(i,r);let l=this.sessions.decoder_model_merged,c=Ye(i,l.inputNames);return await fe(l,c)}async generate({input_features:e,stopping_criteria:r,...s}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let n=Fz(this,e);v1.set(this,n);let o=new Sn;o.push(new k1(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),v1.delete(this)}}};var Zn=class extends y{},E1=class extends Zn{},A1=class extends Zn{async _call(e){return new kt(await super._call(e))}},T1=class extends Zn{async _call(e){return new q(await super._call(e))}};var gp=class extends $e{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},ls=class extends y{},M1=class extends ls{},S1=class extends ls{async _call(e){return new kt(await super._call(e))}},O1=class extends ls{async _call(e){return new q(await super._call(e))}},I1=class extends ls{async _call(e){return new gp(await super._call(e))}},C1=class extends ls{async _call(e){return new he(await super._call(e))}};var wp=class extends y{},P1=class extends wp{};var xp=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 al=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"]},L1=class extends al{},yp=class extends al{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,xp)}_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=`<|${oT(s)}|>`;r.push(e.lang_to_id[a]),r.push(e.task_to_id[n??"transcribe"])}else if(s||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(ee.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,...o}){r=this._prepare_generation_config(r,o);let a=o.decoder_input_ids??this._retrieve_init_tokens(r);if(r.return_timestamps&&(s??=new zs,s.push(new cu(r,a))),r.begin_suppress_tokens&&(s??=new zs,s.push(new Tn(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");r.task==="translate"&&ee.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}if(r.return_timestamps&&!o.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:a,kwargs:o});let i=await super.generate({inputs:e,generation_config:r,logits_processor:s,decoder_input_ids:a,...o});return r.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,r.alignment_heads,r.num_frames,.02,a.length)),i}async _generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:n,kwargs:o}){let a=r.no_timestamps_token_id+1,i=Array.isArray(r.eos_token_id)?r.eos_token_id[0]:r.eos_token_id,l=r.return_token_timestamps,c=e,u=c.dims[2],f=2,m=this.config.max_source_positions,_=f*m,w=0,x=[],E=[];for(;wL+Y)}if($.length>0&&$.at(-1)===i&&$.pop(),$.length===0)break;let F=$.map(Y=>Y>=a),K=$.length>=2&&F[$.length-1]&&!F[$.length-2],W=[];for(let Y=0;Y<$.length-1;++Y)F[Y]&&F[Y+1]&&W.push(Y+1);let Q,B=$.length;if(W.length>0)if(K)Q=A-w;else{let Y=W.at(-1);Q=($[Y-1]-a)*f,B=Y}else Q=A-w;let P=Math.floor(w/f),re=a+1500;for(let Y=0;Y=a&&($[Y]=Math.min($[Y]+P,re));x.push(...$.slice(0,B)),G&&E.push(...G.slice(0,B)),w+=Q}x.push(i);let b=[...n,...x];if(l){let A=new z("int64",b.map(BigInt),[1,b.length]),S=[...new Array(n.length).fill(0),...E,0],M=new z("float32",new Float32Array(S),[1,S.length]);return{sequences:A,token_timestamps:M}}return new z("int64",b.map(BigInt),[1,b.length])}_extract_token_timestamps(e,r,s=null,n=.02,o=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");s==null&&ee.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(ee.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let i=e.cross_attentions,l=Array.from({length:this.config.decoder_layers},(b,A)=>ve(i.map(S=>S[A]),2)),c=Ct(r.map(([b,A])=>{if(b>=l.length)throw new Error(`Layer index ${b} is out of bounds for cross attentions (length ${l.length}).`);return s?l[b].slice(null,A,null,[0,s]):l[b].slice(null,A)})).transpose(1,0,2,3),[u,f]=Cd(c,-2,0,!0),m=c.clone();for(let b=0;b0?m.slice(null,null,[o,m.dims[2]],null):m,w=[Ic(_,1)],x=e.sequences.dims,E=new z("float32",new Float32Array(x[0]*x[1]),x);for(let b=0;bS[F+1]-S[F]),O=gt([1],I).map(G=>!!G),v=[];for(let G=0;G0&&$.push(v.at(-1)),E[b].data.set($)}return E}},N1=class extends yp{};var cs=class extends y{},z1=class extends cs{},R1=class extends cs{async _call(e){return new ge(await super._call(e))}},$1=class extends cs{async _call(e){return new q(await super._call(e))}},D1=class extends cs{async _call(e){return new he(await super._call(e))}},B1=class extends cs{async _call(e){return new Te(await super._call(e))}};var us=class extends y{},U1=class extends us{},F1=class extends us{async _call(e){return new ge(await super._call(e))}},G1=class extends us{async _call(e){return new q(await super._call(e))}},j1=class extends us{async _call(e){return new he(await super._call(e))}},q1=class extends us{async _call(e){return new Te(await super._call(e))}};var il=class extends y{},W1=class extends il{},V1=class extends il{async _call(e){return new bp(await super._call(e))}},bp=class extends $e{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var ll=class extends y{},H1=class extends ll{},X1=class extends ll{};var Wz=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"]]),Vz=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"]]),Hz=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),Xz=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"]]),RT=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),$T=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),DT=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),BT=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"]]),UT=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"]]),FT=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),GT=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"],["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"]]),Kz=new Map([["multi_modality","MultiModalityCausalLM"]]),jT=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"]]),qT=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"]]),WT=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),VT=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"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),HT=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),Yz=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),XT=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"]]),KT=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),YT=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),eo=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),QT=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),JT=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),ZT=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),eM=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),tM=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),rM=new Map([["wavlm","WavLMForXVector"]]),sM=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),nM=new Map([["vitmatte","VitMatteForImageMatting"]]),Qz=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),oM=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),aM=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),iM=new Map([["sapiens","SapiensForNormalEstimation"]]),lM=new Map([["vitpose","VitPoseForPoseEstimation"]]),cM=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),K1=[[Wz,H.EncoderOnly],[Vz,H.EncoderDecoder],[Xz,H.DecoderOnlyWithoutHead],[Hz,H.AutoEncoder],[BT,H.EncoderOnly],[UT,H.EncoderOnly],[FT,H.Seq2Seq],[RT,H.Seq2Seq],[GT,H.DecoderOnly],[Kz,H.MultiModality],[jT,H.EncoderOnly],[qT,H.EncoderOnly],[WT,H.Vision2Seq],[VT,H.ImageTextToText],[HT,H.AudioTextToText],[XT,H.EncoderOnly],[eo,H.EncoderOnly],[JT,H.EncoderOnly],[QT,H.EncoderOnly],[nM,H.EncoderOnly],[Qz,H.EncoderOnly],[oM,H.EncoderOnly],[aM,H.EncoderOnly],[iM,H.EncoderOnly],[lM,H.EncoderOnly],[KT,H.EncoderOnly],[YT,H.EncoderOnly],[ZT,H.MaskGeneration],[eM,H.EncoderOnly],[tM,H.EncoderOnly],[$T,H.Seq2Seq],[DT,H.EncoderOnly],[rM,H.EncoderOnly],[sM,H.EncoderOnly],[cM,H.EncoderOnly]];for(let[t,e]of K1)for(let r of t.values()){rr.set(r,e);let s=cl[r];Ds.set(s,r),bu.set(r,s)}var Jz=[["MusicgenForConditionalGeneration",_i,H.Musicgen],["Phi3VForCausalLM",Ii,H.Phi3V],["CLIPTextModelWithProjection",aa,H.EncoderOnly],["SiglipTextModel",Wi,H.EncoderOnly],["JinaCLIPTextModel",Ka,H.EncoderOnly],["ClapTextModelWithProjection",na,H.EncoderOnly],["ClapAudioModelWithProjection",oa,H.EncoderOnly],["DacEncoderModel",ha,H.EncoderOnly],["DacDecoderModel",ga,H.EncoderOnly],["MimiEncoderModel",si,H.EncoderOnly],["MimiDecoderModel",ni,H.EncoderOnly],["SnacEncoderModel",Hi,H.EncoderOnly],["SnacDecoderModel",Xi,H.EncoderOnly],["Gemma3nForConditionalGeneration",Dn,H.ImageAudioTextToText],["SupertonicForConditionalGeneration",Ji,H.Supertonic],["ChatterboxModel",sa,H.Chatterbox],["VoxtralRealtimeForConditionalGeneration",ol,H.VoxtralRealtime]];for(let[t,e,r]of Jz)rr.set(t,r),Ds.set(e,t),bu.set(t,e);var uM=new Map([["modnet",eo],["birefnet",eo],["isnet",eo],["ben",eo]]);for(let[t,e]of uM.entries())e.set(t,"PreTrainedModel"),rr.set(t,H.EncoderOnly),bu.set(t,y);var pM=new Set(uM.keys());rr.set("PreTrainedModel",H.EncoderOnly);Ds.set(y,"PreTrainedModel");var Ne={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:BT,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:UT,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:$T,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:DT,MODEL_FOR_MASKED_LM_MAPPING_NAMES:jT,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:qT,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:XT,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:eo,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:QT,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:JT,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:KT,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:YT,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:ZT,MODEL_FOR_CTC_MAPPING_NAMES:eM,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:tM,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:rM,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:sM,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:Yz,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:nM,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:oM,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:aM,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:iM,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:lM,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:cM,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:VT,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:HT,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:FT,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:RT,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:GT,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:WT};CT(Ne);var Ie=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let r of this.MODEL_CLASS_MAPPINGS)if(r.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:f,session_options:m};if(_.config=await Wt.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:w}=_.config;for(let x of this.MODEL_CLASS_MAPPINGS){let E=x.get(w);if(!E){for(let b of x.values())if(b[0]===w){E=b;break}if(!E)continue}return await cl[E].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return pM.has(w)||ee.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,_);throw Error(`Unsupported model type: ${w}`)}},Ar=class extends Ie{static MODEL_CLASS_MAPPINGS=K1.map(e=>e[0]);static BASE_IF_FAIL=!0},ul=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},vp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},to=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},kp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},Ep=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},Ap=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},Tp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},Mp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},Sp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},Op=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},Ip=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},pl=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},fl=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},dl=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},Cp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Pp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},fM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},Lp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_CTC_MAPPING_NAMES]},Np=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},dM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},mM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},zp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},_M=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},Rp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},$p=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},hM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},gM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},Dp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},wM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},xM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Ne.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function et(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Qe.read(e)))}async function Tr(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?Im(r,e):r instanceof Float64Array?new Float32Array(r):r))}function ml(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 de=class extends Ke{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 _l=class extends de{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 z("float32",Re(c.data),c.dims),l=[];for(let c of n.logits){let u=i(c),f=await tr(u,r),m=f[0].tolist(),w=f[1].tolist().map((x,E)=>({label:a?a[x]:`LABEL_${x}`,score:m[E]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var hl=class extends de{async _call(e,{ignore_labels:r=["O"]}={}){let s=Array.isArray(e),n=this.tokenizer(s?e:[e],{padding:!0,truncation:!0}),a=(await this.model(n)).logits,i=this.model.config.id2label,l=[];for(let c=0;cO==f),E=a[_].tolist(),b=i[_].tolist();for(let O=1;Ov==w[O])!==-1)&&(E[O]=-1/0,b[O]=-1/0);let A=Re(E).map((O,v)=>[O,v]),S=Re(b).map((O,v)=>[O,v]);A[0][0]=0,S[0][0]=0;let M=fE(A,S).filter(O=>O[0][1]<=O[1][1]).map(O=>[O[0][1],O[1][1],O[0][0]*O[1][0]]).sort((O,v)=>v[2]-O[2]),I=[];for(let O=0;OE==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][f],_=await tr(new z("float32",Re(m.data),m.dims),r),w=_[0].tolist(),x=_[1].tolist();i.push(x.map((E,b)=>{let A=u.slice();return A[f]=E,{score:w[b],token:Number(E),token_str:this.tokenizer.decode([E]),sequence:this.tokenizer.decode(A,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Mr=class extends de{_key="generated_text";async _call(e,r={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(l=>s[this.task].prefix+l));let n=this.tokenizer,o={padding:!0,truncation:!0},a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,o,r):a=n(e,o);let i=await this.model.generate({...a,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}};var xl=class extends Mr{_key="summary_text"};var yl=class extends Mr{_key="translation_text"};function yM(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var bl=class extends de{async _call(e,r={}){let s=!1,n=!1,o=r.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=r.tokenizer_encode_kwargs,i;if(typeof e=="string")i=e=[e];else if(Array.isArray(e)&&e.every(w=>typeof w=="string"))s=!0,i=e;else{if(yM(e))e=[e];else if(Array.isArray(e)&&e.every(yM))s=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");n=!0,i=e.map(w=>this.tokenizer.apply_chat_template(w,{tokenize:!1,add_generation_prompt:!0,...a})),o=!1,a=void 0}let l=n?!1:r.return_full_text??!0;this.tokenizer.padding_side="left";let c=this.tokenizer(i,{add_special_tokens:o,padding:!0,truncation:!0,...a}),u=await this.model.generate({...c,...r}),f=this.tokenizer.batch_decode(u,{skip_special_tokens:!0}),m;!l&&c.input_ids.dims.at(-1)>0&&(m=this.tokenizer.batch_decode(c.input_ids,{skip_special_tokens:!0}).map(w=>w.length));let _=Array.from({length:e.length},w=>[]);for(let w=0;w[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(ee.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(ee.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let u=[];for(let _ of a){let w=this.tokenizer(c,{text_pair:_,padding:!0,truncation:!0}),x=await this.model(w);i?u.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):u.push(x.logits.data[this.entailment_id])}let m=(i?u.map(_=>Re(_)[1]):Re(u)).map((_,w)=>[_,w]).sort((_,w)=>w[0]-_[0]);l.push({sequence:c,labels:m.map(_=>r[_[1]]),scores:m.map(_=>_[0])})}return o?l:l[0]}};var kl=class extends de{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await Tr(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),u=(await this.model(l)).logits[0],f=await tr(new z("float32",Re(u.data),u.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,E)=>({label:o?o[x]:`LABEL_${x}`,score:m[E]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var El=class extends de{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(u=>s.replace("{}",u)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await Tr(e,i),c=[];for(let u of l){let f=await this.processor(u),m=await this.model({...a,...f}),_=Re(m.logits_per_audio.data);c.push([..._].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var Al=class extends de{async _call(e,r={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,r);case"moonshine":return this._call_moonshine(e,r);case"cohere_asr":return this._call_cohere_asr(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&ee.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&ee.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Tr(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).logits[0],m=[];for(let w of f)m.push(Ce(w.data)[1]);let _=this.tokenizer.decode(m,{skip_special_tokens:!0}).trim();i.push({text:_})}return s?i[0]:i}async _call_whisper(e,r){let s=r.return_timestamps??!1,n=r.chunk_length_s??0,o=r.force_full_sequences??!1,a=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);let l=!Array.isArray(e),c=l?[e]:e,u=this.processor.feature_extractor.config,f=u.chunk_length/this.model.config.max_source_positions,m=u.hop_length,_=u.sampling_rate,w=await Tr(c,_),x=[];for(let E of w){let b=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let M=_*n,I=_*a,O=M-2*I,v=0;for(;;){let $=v+M,G=E.subarray(v,$),F=await this.processor(G),K=v===0,W=$>=E.length;if(b.push({stride:[G.length,K?0:I,W?0:I],input_features:F.input_features,is_last:W}),W)break;v+=O}}else b=[{stride:[E.length,0,0],input_features:(await this.processor(E)).input_features,is_last:!0}];for(let M of b){i.num_frames=Math.floor(M.stride[0]/m);let I=await this.model.generate({inputs:M.input_features,...i});if(s==="word"){let O=I.sequences.tolist()[0],v=I.token_timestamps.tolist()[0],$=this.tokenizer.timestamp_begin,G=Math.max(O.findIndex(F=>Number(F)>=$),0);M.tokens=O.slice(G),M.token_timestamps=v.slice(G).map(F=>ys(F,2))}else M.tokens=I[0].tolist();M.stride=M.stride.map(O=>O/_)}let[A,S]=this.tokenizer._decode_asr(b,{time_precision:f,return_timestamps:s,force_full_sequences:o});x.push({text:A,...S})}return l?x[0]:x}async _call_moonshine(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Tr(n,o),i=[];for(let l of a){let c=await this.processor(l),u=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:u,...r,...c}),m=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}async _call_cohere_asr(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor,a=o.config.sampling_rate,i=await Tr(n,a),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),u=[];for(let f of i){let m=o.split_audio(f),_=[];for(let x of m){let E=await this.processor(x),b=await this.model.generate({...E,decoder_input_ids:c,...r}),A=this.tokenizer.decode(b[0].tolist(),{skip_special_tokens:!0}).trim();_.push(A)}let w=this.processor.constructor.join_chunks(_,l);u.push({text:w})}return s?u[0]:u}};var Tl=class extends de{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 z("float32",e,[e.length]);else if(!(e instanceof z))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,c=[];for(let u=0;u({generated_text:u.trim()}));a.push(c)}return s?a:a[0]}};var Sl=class extends de{async _call(e,{top_k:r=5}={}){let s=await et(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),{id2label:a}=this.model.config,i=[];for(let l of o.logits){let c=await tr(new z("float32",Re(l.data),l.dims),r),u=c[0].tolist(),m=c[1].tolist().map((_,w)=>({label:a?a[_]:`LABEL_${_}`,score:u[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var bM={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Ys=class extends de{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 et(e),u=c.map(A=>[A.height,A.width]),f=await this.processor(c),{inputNames:m,outputNames:_}=this.model.sessions.model;if(!m.includes("pixel_values")){if(m.length!==1)throw Error(`Expected a single input name, but got ${m.length} inputs: ${m}.`);let A=m[0];if(A in f)throw Error(`Input name ${A} already exists in the inputs.`);f[A]=f.pixel_values}let w=await this.model(f),x=null;if(i!==null)x=bM[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(bM))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=A;break}}let E=this.model.config.id2label,b=[];if(i)if(i==="panoptic"||i==="instance"){let A=x(w,r,s,n,o,a??u)[0],S=A.segmentation;for(let M of A.segments_info){let I=new Uint8ClampedArray(S.data.length);for(let v=0;v$<-1e-5||$>1+1e-5)&&O.sigmoid_();let v=await Qe.fromTensor(O.mul_(255).to("uint8")).resize(I[1],I[0]);b.push({label:null,score:null,mask:v})}}return b}};var Ol=class extends Ys{async _call(e,r={}){let s=await et(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 Il=class extends de{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await et(e),a=r.map(m=>s.replace("{}",m)),i=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(o),c=await this.model({...i,pixel_values:l}),u=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Re(m.data),f=[];for(let m of c.logits_per_image){let w=[...u(m)].map((x,E)=>({score:x,label:r[E]}));w.sort((x,E)=>E.score-x.score),f.push(w)}return n?f:f[0]}};var Cl=class extends de{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 et(e),a=s?null:o.map(_=>[_.height,_.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),c=await this.model({pixel_values:i,pixel_mask:l}),u=this.processor.image_processor.post_process_object_detection(c,r,a),{id2label:f}=this.model.config,m=u.map(_=>_.boxes.map((w,x)=>({score:_.scores[x],label:f[_.classes[x]],box:ml(w,!s)})));return n?m:m[0]}};var Pl=class extends de{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await et(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=await this.processor(i),u=[];for(let f=0;f({score:b.scores[S],label:b.labels[S],box:ml(A,!o)}))}else{let b=this.processor.image_processor.post_process_object_detection(x,s,_,!0)[0];E=b.boxes.map((A,S)=>({score:b.scores[S],label:r[b.classes[S]],box:ml(A,!o)}))}E.sort((b,A)=>A.score-b.score),n!==null&&(E=E.slice(0,n)),u.push(E)}return a?u:u[0]}};var Ll=class extends de{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 et(e))[0],{pixel_values:o}=await this.processor(n),a=`${r}`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...s}),u=this.tokenizer.batch_decode(l)[0].match(/(.*?)<\/s_answer>/),f=null;return u&&u.length>=2&&(f=u[1].trim()),[{answer:f}]}};var Nl=class extends de{async _call(e){let r=await et(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(Qe.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var zl=class extends de{async _call(e){let r=await et(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a`onnx/${m}`);return i.filter(m=>!m.startsWith("onnx/")||f.some(_=>m.startsWith(_)))}}return i}async function rce(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:u=null,model_file_name:f=null,session_options:m={}}={}){t=Bp[t]??t;let _=ro[t.split("_",1)[0]];if(!_)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(ro)}]`);e||(e=_.default.model,ee.info(`No model specified. Using default model: "${e}".`),!l&&_.default.dtype&&(l=_.default.dtype));let w=await Or(t,e,{device:i,dtype:l}),x={};r&&(await Promise.all(w.map(async K=>It(e,K)))).forEach((K,W)=>{K.exists&&(x[w[W]]={loaded:0,total:K.size??0})});let E={progress_callback:r?new hs(r,x):void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:u,model_file_name:f,session_options:m},b=w.includes("tokenizer.json"),A=w.includes("preprocessor_config.json"),S=_.model,M;if(Array.isArray(S)){let F=s??await Wt.from_pretrained(e,E),{model_type:K}=F,W=S.find(Q=>Q.supports(K));if(!W)throw Error(`Unsupported model type "${K}" for task "${t}". None of the candidate model classes support this type.`);M=W.from_pretrained(e,{...E,config:F})}else M=S.from_pretrained(e,E);let[I,O,v]=await Promise.all([b?ne.from_pretrained(e,E):null,A?nu.from_pretrained(e,E):null,M]),$={task:t,model:v};I&&($.tokenizer=I),O&&($.processor=O),lr(r,{status:"ready",task:t,model:e});let G=_.pipeline;return new G($)}var Zz=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,Y1=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},vM=ie.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),Q1=class extends Y1{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??vM,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&&Zz(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===vM&&ie.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}},kM=class extends Q1{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:c=!0,decode_kwargs:u={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,callback_function:s,token_callback_function:n,decode_kwargs:u}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var Dl=class{constructor(e,r){this.image=e,this.timestamp=r}},Fp=class{constructor(e,r){e.length>0&&e[0]instanceof Qe&&(e=e.map((s,n)=>new Dl(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 m=await(await me.fetch(n.src)).blob();n.src=URL.createObjectURL(m),await new Promise(_=>n.onloadedmetadata=_)}let o=n.duration,a,i;e!=null?(a=e,i=e===1?0:o/(e-1)):(i=1/r,a=Math.floor(o/i));let l=[];for(let f=0;f{n.onseeked=x}),u.drawImage(n,0,0,c.width,c.height);let m=u.getImageData(0,0,c.width,c.height),_=new Qe(m.data,c.width,c.height,4),w=new Dl(_,f);s.push(w)}return n.remove(),new Fp(s,o)}async function Gp(t,e,r={}){let s=await Zt(r?.cache_dir);if(!s)return{allCached:!1,files:e.map(a=>({file:a,cached:!1}))};let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=$r(t,o,r,s),l=await Dr(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function EM(t,e,r={}){let s=await Zt(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=$r(t,e,r,s);return!!await Dr(s,n,o)}async function AM(t,e={}){if(!t)throw new Error("modelId is required");if(!await EM(t,"config.json",e))return!1;let r=await Sr(t,e);return(await Gp(t,r,e)).allCached}async function TM(t,e={}){if(!t)throw new Error("modelId is required");let r=await Sr(t,e);return await Gp(t,r,e)}async function MM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await EM(e,"config.json",r))return!1;let s=await Or(t,e,r);return(await Gp(e,s,r)).allCached}async function SM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Or(t,e,r);return await Gp(e,s,r)}async function OM(t,e,r={}){let s=await Zt(r?.cache_dir);if(!s)return{filesDeleted:0,filesCached:0,files:e.map(o=>({file:o,deleted:!1,wasCached:!1}))};if(!s.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=$r(t,o,r,s),c=!!await Dr(s,a,i),u=!1;if(c){let f=await s.delete(i),m=!f&&i!==a?await s.delete(a):!1;u=f||m}return{file:o,deleted:u,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function IM(t,e={}){if(!t)throw new Error("modelId is required");let r=await Sr(t,e);return await OM(t,r,e)}async function CM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Or(t,e,r);return await OM(e,s,r)}var t3=Object.keys(Vr);async function PM(t,{config:e=null,model_file_name:r=null,revision:s="main",cache_dir:n=null,local_files_only:o=!1}={}){e=await Ho(t,{config:e,cache_dir:n,local_files_only:o,revision:s});let a="onnx",i=On(e),{sessions:l}=Vo(i,e,{model_file_name:r}),c=Object.values(l),u={revision:s,cache_dir:n,local_files_only:o};return(await Promise.all(t3.map(async m=>{let _=Vr[m]??"",w=await Promise.all(c.map(async x=>{let E=`${a}/${x}${_}.onnx`;return(await It(t,E,u)).exists}));return{dtype:m,available:w.every(Boolean)}}))).filter(m=>m.available).map(m=>m.dtype)}var J1=class{static async get_files(e,r={}){return Sr(e,r)}static async get_pipeline_files(e,r,s={}){return Or(e,r,s)}static async get_model_files(e,r={}){return In(e,r)}static async get_tokenizer_files(e){return _n(e)}static async get_processor_files(e){return Up(e)}static async get_available_dtypes(e,r={}){return PM(e,r)}static async is_cached(e,r={}){return AM(e,r)}static async is_cached_files(e,r={}){return TM(e,r)}static async is_pipeline_cached(e,r,s={}){return MM(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return SM(e,r,s)}static async get_file_metadata(e,r,s={}){return It(e,r,s)}static async clear_cache(e,r={}){return IM(e,r)}static async clear_pipeline_cache(e,r,s={}){return CM(e,r,s)}};export{Cm as ASTFeatureExtractor,Ph as ASTForAudioClassification,Ch as ASTModel,Jo as ASTPreTrainedModel,Sh as AfmoeForCausalLM,Mh as AfmoeModel,Yo as AfmoePreTrainedModel,Eh as AlbertForMaskedLM,kh as AlbertForQuestionAnswering,vh as AlbertForSequenceClassification,bh as AlbertModel,Bs as AlbertPreTrainedModel,$d as AlbertTokenizer,Th as ApertusForCausalLM,Ah as ApertusModel,Ko as ApertusPreTrainedModel,Ih as ArceeForCausalLM,Oh as ArceeModel,Qo as ArceePreTrainedModel,kl as AudioClassificationPipeline,Wt as AutoConfig,Ge as AutoFeatureExtractor,Ae as AutoImageProcessor,Ar as AutoModel,Np as AutoModelForAudioClassification,mM as AutoModelForAudioFrameClassification,xM as AutoModelForAudioTextToText,Lp as AutoModelForCTC,Tp as AutoModelForCausalLM,$p as AutoModelForDepthEstimation,zp as AutoModelForDocumentQuestionAnswering,Ip as AutoModelForImageClassification,Dp as AutoModelForImageFeatureExtraction,_M as AutoModelForImageMatting,pl as AutoModelForImageSegmentation,wM as AutoModelForImageTextToText,Rp as AutoModelForImageToImage,fM as AutoModelForMaskGeneration,Mp as AutoModelForMaskedLM,hM as AutoModelForNormalEstimation,Cp as AutoModelForObjectDetection,gM as AutoModelForPoseEstimation,Sp as AutoModelForQuestionAnswering,fl as AutoModelForSemanticSegmentation,to as AutoModelForSeq2SeqLM,ul as AutoModelForSequenceClassification,kp as AutoModelForSpeechSeq2Seq,Ep as AutoModelForTextToSpectrogram,Ap as AutoModelForTextToWaveform,vp as AutoModelForTokenClassification,dl as AutoModelForUniversalSegmentation,Op as AutoModelForVision2Seq,dM as AutoModelForXVector,Pp as AutoModelForZeroShotObjectDetection,nu as AutoProcessor,ne as AutoTokenizer,Al as AutomaticSpeechRecognitionPipeline,Ol as BackgroundRemovalPipeline,Nh as BartForConditionalGeneration,zh as BartForSequenceClassification,Lh as BartModel,Ln as BartPretrainedModel,Dd as BartTokenizer,Y1 as BaseStreamer,Xm as BeitFeatureExtractor,$h as BeitForImageClassification,Rh as BeitModel,Zo as BeitPreTrainedModel,Bh as BertForMaskedLM,Gh as BertForQuestionAnswering,Uh as BertForSequenceClassification,Fh as BertForTokenClassification,Dh as BertModel,Qr as BertPreTrainedModel,Bd as BertTokenizer,Km as BitImageProcessor,qh as BlenderbotForConditionalGeneration,jh as BlenderbotModel,ea as BlenderbotPreTrainedModel,Vh as BlenderbotSmallForConditionalGeneration,Wh as BlenderbotSmallModel,ta as BlenderbotSmallPreTrainedModel,Ud as BlenderbotSmallTokenizer,Fd as BlenderbotTokenizer,Xh as BloomForCausalLM,Hh as BloomModel,ra as BloomPreTrainedModel,Gd as BloomTokenizer,tg as CHMv2ForDepthEstimation,Qm as CHMv2ImageProcessor,Au as CHMv2PreTrainedModel,Jm as CLIPFeatureExtractor,Dc as CLIPImageProcessor,sg as CLIPModel,mr as CLIPPreTrainedModel,lg as CLIPSegForImageSegmentation,ig as CLIPSegModel,ia as CLIPSegPreTrainedModel,ng as CLIPTextModel,aa as CLIPTextModelWithProjection,qd as CLIPTokenizer,og as CLIPVisionModel,ag as CLIPVisionModelWithProjection,Yh as CamembertForMaskedLM,Zh as CamembertForQuestionAnswering,Qh as CamembertForSequenceClassification,Jh as CamembertForTokenClassification,Kh as CamembertModel,Jr as CamembertPreTrainedModel,jd as CamembertTokenizer,Pm as ChatterboxFeatureExtractor,sa as ChatterboxModel,ku as ChatterboxPreTrainedModel,Wm as ChatterboxProcessor,Ym as ChineseCLIPFeatureExtractor,eg as ChineseCLIPModel,Eu as ChineseCLIPPreTrainedModel,oa as ClapAudioModelWithProjection,Lm as ClapFeatureExtractor,rg as ClapModel,Nn as ClapPreTrainedModel,na as ClapTextModelWithProjection,_u as ClassifierFreeGuidanceLogitsProcessor,ug as CodeGenForCausalLM,cg as CodeGenModel,la as CodeGenPreTrainedModel,Vd as CodeGenTokenizer,Wd as CodeLlamaTokenizer,mg as Cohere2ForCausalLM,dg as Cohere2Model,ua as Cohere2PreTrainedModel,Nm as CohereAsrFeatureExtractor,hg as CohereAsrForConditionalGeneration,_g as CohereAsrModel,pa as CohereAsrPreTrainedModel,Vm as CohereAsrProcessor,Xd as CohereAsrTokenizer,fg as CohereForCausalLM,pg as CohereModel,ca as CoherePreTrainedModel,Hd as CohereTokenizer,wg as ConvBertForMaskedLM,bg as ConvBertForQuestionAnswering,xg as ConvBertForSequenceClassification,yg as ConvBertForTokenClassification,gg as ConvBertModel,Zr as ConvBertPreTrainedModel,Kd as ConvBertTokenizer,Zm as ConvNextFeatureExtractor,kg as ConvNextForImageClassification,Bc as ConvNextImageProcessor,vg as ConvNextModel,fa as ConvNextPreTrainedModel,Ag as ConvNextV2ForImageClassification,Eg as ConvNextV2Model,da as ConvNextV2PreTrainedModel,Og as DFineForObjectDetection,Sg as DFineModel,_a as DFinePreTrainedModel,tw as DINOv3ConvNextModel,Pu as DINOv3ConvNextPreTrainedModel,r_ as DINOv3ViTImageProcessor,rw as DINOv3ViTModel,Lu as DINOv3ViTPreTrainedModel,n_ as DPTFeatureExtractor,uw as DPTForDepthEstimation,Gc as DPTImageProcessor,cw as DPTModel,va as DPTPreTrainedModel,ga as DacDecoderModel,Mu as DacDecoderOutput,ha as DacEncoderModel,Tu as DacEncoderOutput,$o as DacFeatureExtractor,Ig as DacModel,zn as DacPreTrainedModel,Pg as DebertaForMaskedLM,zg as DebertaForQuestionAnswering,Lg as DebertaForSequenceClassification,Ng as DebertaForTokenClassification,Cg as DebertaModel,es as DebertaPreTrainedModel,Qd as DebertaTokenizer,Bg as DebertaV2ForMaskedLM,Gg as DebertaV2ForQuestionAnswering,Ug as DebertaV2ForSequenceClassification,Fg as DebertaV2ForTokenClassification,Dg as DebertaV2Model,ts as DebertaV2PreTrainedModel,Yd as DebertaV2Tokenizer,jg as DecisionTransformerModel,Su as DecisionTransformerPreTrainedModel,$g as DeepseekV3ForCausalLM,Rg as DeepseekV3Model,wa as DeepseekV3PreTrainedModel,e_ as DeiTFeatureExtractor,Wg as DeiTForImageClassification,Uc as DeiTImageProcessor,qg as DeiTModel,xa as DeiTPreTrainedModel,Vg as DepthAnythingForDepthEstimation,Ou as DepthAnythingPreTrainedModel,zl as DepthEstimationPipeline,Hg as DepthProForDepthEstimation,Iu as DepthProPreTrainedModel,t_ as DetrFeatureExtractor,Kg as DetrForObjectDetection,Yg as DetrForSegmentation,Fc as DetrImageProcessor,Xg as DetrModel,$n as DetrObjectDetectionOutput,Rn as DetrPreTrainedModel,Cu as DetrSegmentationOutput,Jg as Dinov2ForImageClassification,Qg as Dinov2Model,ya as Dinov2PreTrainedModel,ew as Dinov2WithRegistersForImageClassification,Zg as Dinov2WithRegistersModel,ba as Dinov2WithRegistersPreTrainedModel,iw as DistilBertForMaskedLM,aw as DistilBertForQuestionAnswering,nw as DistilBertForSequenceClassification,ow as DistilBertForTokenClassification,sw as DistilBertModel,rs as DistilBertPreTrainedModel,Jd as DistilBertTokenizer,Ll as DocumentQuestionAnsweringPipeline,s_ as DonutFeatureExtractor,wn as DonutImageProcessor,lw as DonutSwinModel,Nu as DonutSwinPreTrainedModel,Wo as DynamicCache,xb as EdgeTamModel,fw as EfficientNetForImageClassification,o_ as EfficientNetImageProcessor,pw as EfficientNetModel,ka as EfficientNetPreTrainedModel,mw as ElectraForMaskedLM,gw as ElectraForQuestionAnswering,_w as ElectraForSequenceClassification,hw as ElectraForTokenClassification,dw as ElectraModel,ss as ElectraPreTrainedModel,Zd as ElectraTokenizer,zo as EncodecFeatureExtractor,wu as EosTokenCriteria,xw as Ernie4_5ForCausalLM,ww as Ernie4_5Model,Ea as Ernie4_5PretrainedModel,bw as EsmForMaskedLM,vw as EsmForSequenceClassification,kw as EsmForTokenClassification,yw as EsmModel,Us as EsmPreTrainedModel,em as EsmTokenizer,Aw as EuroBertForMaskedLM,Tw as EuroBertForSequenceClassification,Mw as EuroBertForTokenClassification,Ew as EuroBertModel,Fs as EuroBertPreTrainedModel,Ow as ExaoneForCausalLM,Sw as ExaoneModel,Aa as ExaonePreTrainedModel,Cw as FalconForCausalLM,Lw as FalconH1ForCausalLM,Pw as FalconH1Model,Ma as FalconH1PreTrainedModel,Iw as FalconModel,Ta as FalconPreTrainedModel,tm as FalconTokenizer,zw as FastViTForImageClassification,Nw as FastViTModel,Sa as FastViTPreTrainedModel,Rl as FeatureExtractionPipeline,Ee as FeatureExtractor,wl as FillMaskPipeline,Rw as Florence2ForConditionalGeneration,zu as Florence2PreTrainedModel,D_ as Florence2Processor,au as ForcedBOSTokenLogitsProcessor,iu as ForcedEOSTokenLogitsProcessor,l_ as GLPNFeatureExtractor,Jw as GLPNForDepthEstimation,Qw as GLPNModel,za as GLPNPreTrainedModel,lx as GPT2LMHeadModel,ix as GPT2Model,Ua as GPT2PreTrainedModel,nm as GPT2Tokenizer,ex as GPTBigCodeForCausalLM,Zw as GPTBigCodeModel,Ra as GPTBigCodePreTrainedModel,ux as GPTJForCausalLM,cx as GPTJModel,Fa as GPTJPreTrainedModel,rx as GPTNeoForCausalLM,tx as GPTNeoModel,$a as GPTNeoPreTrainedModel,nx as GPTNeoXForCausalLM,sx as GPTNeoXModel,Da as GPTNeoXPreTrainedModel,sm as GPTNeoXTokenizer,Uw as Gemma2ForCausalLM,Bw as Gemma2Model,Ia as Gemma2PreTrainedModel,qw as Gemma3ForCausalLM,Du as Gemma3ForConditionalGeneration,a_ as Gemma3ImageProcessor,jw as Gemma3Model,$u as Gemma3PreTrainedModel,B_ as Gemma3Processor,zm as Gemma3nAudioFeatureExtractor,Ww as Gemma3nForCausalLM,Dn as Gemma3nForConditionalGeneration,Bu as Gemma3nPreTrainedModel,U_ as Gemma3nProcessor,Dw as GemmaForCausalLM,$w as GemmaModel,Oa as GemmaPreTrainedModel,rm as GemmaTokenizer,i_ as Glm46VImageProcessor,F_ as Glm46VProcessor,Hw as GlmForCausalLM,Vw as GlmModel,Kw as GlmMoeDsaForCausalLM,Xw as GlmMoeDsaModel,Pa as GlmMoeDsaPreTrainedModel,Yw as GlmOcrForConditionalGeneration,Ca as GlmPreTrainedModel,ax as GptOssForCausalLM,ox as GptOssModel,Ba as GptOssPreTrainedModel,fx as GraniteForCausalLM,px as GraniteModel,mx as GraniteMoeHybridForCausalLM,dx as GraniteMoeHybridModel,ja as GraniteMoeHybridPreTrainedModel,Ga as GranitePreTrainedModel,Rm as GraniteSpeechFeatureExtractor,_x as GraniteSpeechForConditionalGeneration,G_ as GraniteSpeechProcessor,hx as GroundingDinoForObjectDetection,c_ as GroundingDinoImageProcessor,Gu as GroundingDinoPreTrainedModel,j_ as GroundingDinoProcessor,gx as GroupViTModel,ju as GroupViTPreTrainedModel,xx as HeliumForCausalLM,wx as HeliumModel,qa as HeliumPreTrainedModel,om as HerbertTokenizer,bx as HieraForImageClassification,yx as HieraModel,Wa as HieraPreTrainedModel,Sx as HubertForCTC,Ox as HubertForSequenceClassification,Mx as HubertModel,Tx as HubertPreTrainedModel,Cx as HunYuanDenseV1ForCausalLM,Ix as HunYuanDenseV1Model,Va as HunYuanDenseV1PreTrainedModel,Nx as IJepaForImageClassification,Lx as IJepaModel,Ha as IJepaPreTrainedModel,Px as Idefics3ForConditionalGeneration,jc as Idefics3ImageProcessor,Zc as Idefics3Processor,Sl as ImageClassificationPipeline,$l as ImageFeatureExtractionPipeline,X as ImageFeatureExtractor,X as ImageProcessor,Ys as ImageSegmentationPipeline,Nl as ImageToImagePipeline,Ml as ImageToTextPipeline,ST as InterruptableStoppingCriteria,Rx as JAISLMHeadModel,zx as JAISModel,Xa as JAISPreTrainedModel,p_ as JinaCLIPImageProcessor,$x as JinaCLIPModel,Un as JinaCLIPPreTrainedModel,W_ as JinaCLIPProcessor,Ka as JinaCLIPTextModel,Dx as JinaCLIPVisionModel,Ux as Lfm2ForCausalLM,Bx as Lfm2Model,jx as Lfm2MoeForCausalLM,Gx as Lfm2MoeModel,Qa as Lfm2MoePreTrainedModel,Ya as Lfm2PreTrainedModel,qx as Lfm2VlForConditionalGeneration,f_ as Lfm2VlImageProcessor,V_ as Lfm2VlProcessor,Fx as LightOnOcrForConditionalGeneration,N1 as LiteWhisperForConditionalGeneration,Hx as Llama4ForCausalLM,qu as Llama4PreTrainedModel,Vx as LlamaForCausalLM,Wx as LlamaModel,Ja as LlamaPreTrainedModel,am as LlamaTokenizer,Et as LlavaForConditionalGeneration,Et as LlavaOnevisionForConditionalGeneration,d_ as LlavaOnevisionImageProcessor,Ru as LlavaPreTrainedModel,H_ as LlavaProcessor,Gw as LlavaQwen2ForCausalLM,Ot as LogLevel,Dt as LogitsProcessor,zs as LogitsProcessorList,qo as LogitsWarper,Kx as LongT5ForConditionalGeneration,Xx as LongT5Model,Za as LongT5PreTrainedModel,Qx as M2M100ForConditionalGeneration,Yx as M2M100Model,ei as M2M100PreTrainedModel,im as M2M100Tokenizer,cm as MBart50Tokenizer,oy as MBartForCausalLM,sy as MBartForConditionalGeneration,ny as MBartForSequenceClassification,ry as MBartModel,qs as MBartPreTrainedModel,Co as MBartTokenizer,Wy as MPNetForMaskedLM,Xy as MPNetForQuestionAnswering,Vy as MPNetForSequenceClassification,Hy as MPNetForTokenClassification,qy as MPNetModel,ns as MPNetPreTrainedModel,fm as MPNetTokenizer,Jy as MT5ForConditionalGeneration,Qy as MT5Model,di as MT5PreTrainedModel,Zx as MarianMTModel,Jx as MarianModel,ti as MarianPreTrainedModel,lm as MarianTokenizer,__ as Mask2FormerImageProcessor,m_ as MaskFormerFeatureExtractor,ty as MaskFormerForInstanceSegmentation,xn as MaskFormerImageProcessor,ey as MaskFormerModel,ri as MaskFormerPreTrainedModel,gu as MaxLengthCriteria,ay as Metric3DForDepthEstimation,Wu as Metric3DPreTrainedModel,iy as Metric3Dv2ForDepthEstimation,Vu as Metric3Dv2PreTrainedModel,ly as MgpstrForSceneTextRecognition,Hu as MgpstrModelOutput,Xu as MgpstrPreTrainedModel,X_ as MgpstrProcessor,um as MgpstrTokenizer,ni as MimiDecoderModel,Yu as MimiDecoderOutput,si as MimiEncoderModel,Ku as MimiEncoderOutput,cy as MimiModel,Fn as MimiPreTrainedModel,fu as MinLengthLogitsProcessor,du as MinNewTokensLengthLogitsProcessor,dy as Mistral4ForCausalLM,fy as Mistral4Model,ai as Mistral4PreTrainedModel,py as MistralForCausalLM,uy as MistralModel,oi as MistralPreTrainedModel,_y as MobileBertForMaskedLM,gy as MobileBertForQuestionAnswering,hy as MobileBertForSequenceClassification,my as MobileBertModel,Ws as MobileBertPreTrainedModel,pm as MobileBertTokenizer,xy as MobileLLMForCausalLM,wy as MobileLLMModel,ii as MobileLLMPreTrainedModel,h_ as MobileNetV1FeatureExtractor,by as MobileNetV1ForImageClassification,vy as MobileNetV1ForSemanticSegmentation,qc as MobileNetV1ImageProcessor,yy as MobileNetV1Model,Gn as MobileNetV1PreTrainedModel,g_ as MobileNetV2FeatureExtractor,Ey as MobileNetV2ForImageClassification,Ay as MobileNetV2ForSemanticSegmentation,Wc as MobileNetV2ImageProcessor,ky as MobileNetV2Model,jn as MobileNetV2PreTrainedModel,w_ as MobileNetV3FeatureExtractor,My as MobileNetV3ForImageClassification,Sy as MobileNetV3ForSemanticSegmentation,Vc as MobileNetV3ImageProcessor,Ty as MobileNetV3Model,qn as MobileNetV3PreTrainedModel,x_ as MobileNetV4FeatureExtractor,Iy as MobileNetV4ForImageClassification,Cy as MobileNetV4ForSemanticSegmentation,Hc as MobileNetV4ImageProcessor,Oy as MobileNetV4Model,Wn as MobileNetV4PreTrainedModel,y_ as MobileViTFeatureExtractor,Ly as MobileViTForImageClassification,Xc as MobileViTImageProcessor,Py as MobileViTModel,li as MobileViTPreTrainedModel,zy as MobileViTV2ForImageClassification,Ny as MobileViTV2Model,ci as MobileViTV2PreTrainedModel,J1 as ModelRegistry,Fy as ModernBertDecoderForCausalLM,Uy as ModernBertDecoderModel,ui as ModernBertDecoderPreTrainedModel,$y as ModernBertForMaskedLM,Dy as ModernBertForSequenceClassification,By as ModernBertForTokenClassification,Ry as ModernBertModel,Vs as ModernBertPreTrainedModel,Fw as Moondream1ForConditionalGeneration,$m as MoonshineFeatureExtractor,jy as MoonshineForConditionalGeneration,Gy as MoonshineModel,pi as MoonshinePreTrainedModel,K_ as MoonshineProcessor,Yy as MptForCausalLM,Ky as MptModel,fi as MptPreTrainedModel,Zy as MultiModalityCausalLM,Qu as MultiModalityPreTrainedModel,t0 as MusicgenForCausalLM,_i as MusicgenForConditionalGeneration,e0 as MusicgenModel,mi as MusicgenPreTrainedModel,s0 as NanoChatForCausalLM,r0 as NanoChatModel,hi as NanoChatPreTrainedModel,o0 as NemotronHForCausalLM,n0 as NemotronHModel,gi as NemotronHPreTrainedModel,i0 as NeoBertForMaskedLM,u0 as NeoBertForQuestionAnswering,l0 as NeoBertForSequenceClassification,c0 as NeoBertForTokenClassification,a0 as NeoBertModel,os as NeoBertPreTrainedModel,dm as NllbTokenizer,mu as NoBadWordsLogitsProcessor,uu as NoRepeatNGramLogitsProcessor,p0 as NomicBertModel,Ju as NomicBertPreTrainedModel,b_ as NougatImageProcessor,mm as NougatTokenizer,k0 as OPTForCausalLM,v0 as OPTModel,ki as OPTPreTrainedModel,Cl as ObjectDetectionPipeline,_0 as Olmo2ForCausalLM,m0 as Olmo2Model,xi as Olmo2PreTrainedModel,g0 as Olmo3ForCausalLM,h0 as Olmo3Model,yi as Olmo3PreTrainedModel,d0 as OlmoForCausalLM,x0 as OlmoHybridForCausalLM,w0 as OlmoHybridModel,bi as OlmoHybridPreTrainedModel,f0 as OlmoModel,wi as OlmoPreTrainedModel,b0 as OpenELMForCausalLM,y0 as OpenELMModel,vi as OpenELMPreTrainedModel,v_ as OwlViTFeatureExtractor,M0 as OwlViTForObjectDetection,yn as OwlViTImageProcessor,T0 as OwlViTModel,Ai as OwlViTPreTrainedModel,Y_ as OwlViTProcessor,A0 as Owlv2ForObjectDetection,k_ as Owlv2ImageProcessor,E0 as Owlv2Model,Ei as Owlv2PreTrainedModel,S0 as PaliGemmaForConditionalGeneration,Q_ as PaliGemmaProcessor,Ro as ParakeetFeatureExtractor,O0 as ParakeetForCTC,Zu as ParakeetPreTrainedModel,C0 as PatchTSMixerForPrediction,I0 as PatchTSMixerModel,Ti as PatchTSMixerPreTrainedModel,L0 as PatchTSTForPrediction,P0 as PatchTSTModel,Mi as PatchTSTPreTrainedModel,$0 as Phi3ForCausalLM,R0 as Phi3Model,Oi as Phi3PreTrainedModel,Ii as Phi3VForCausalLM,T_ as Phi3VImageProcessor,ep as Phi3VPreTrainedModel,J_ as Phi3VProcessor,z0 as PhiForCausalLM,N0 as PhiModel,Si as PhiPreTrainedModel,M_ as PixtralImageProcessor,Z_ as PixtralProcessor,y as PreTrainedModel,V as PreTrainedTokenizer,An as PretrainedConfig,se as Processor,B0 as PvtForImageClassification,S_ as PvtImageProcessor,D0 as PvtModel,Ci as PvtPreTrainedModel,Do as PyAnnoteFeatureExtractor,F0 as PyAnnoteForAudioFrameClassification,U0 as PyAnnoteModel,Pi as PyAnnotePreTrainedModel,eh as PyAnnoteProcessor,gl as QuestionAnsweringPipeline,j0 as Qwen2ForCausalLM,G0 as Qwen2Model,W0 as Qwen2MoeForCausalLM,q0 as Qwen2MoeModel,Ni as Qwen2MoePreTrainedModel,Li as Qwen2PreTrainedModel,_m as Qwen2Tokenizer,La as Qwen2VLForCausalLM,Bn as Qwen2VLForConditionalGeneration,Uo as Qwen2VLImageProcessor,Uu as Qwen2VLPreTrainedModel,Ls as Qwen2VLProcessor,Na as Qwen2_5_VLForCausalLM,Gs as Qwen2_5_VLForConditionalGeneration,Go as Qwen2_5_VLProcessor,H0 as Qwen3ForCausalLM,V0 as Qwen3Model,K0 as Qwen3MoeForCausalLM,X0 as Qwen3MoeModel,Ri as Qwen3MoePreTrainedModel,Q0 as Qwen3NextForCausalLM,Y0 as Qwen3NextModel,$i as Qwen3NextPreTrainedModel,zi as Qwen3PreTrainedModel,Di as Qwen3VLForCausalLM,Hs as Qwen3VLForConditionalGeneration,Z0 as Qwen3VLMoeForCausalLM,J0 as Qwen3VLMoeForConditionalGeneration,th as Qwen3VLProcessor,Bi as Qwen3_5ForCausalLM,Vn as Qwen3_5ForConditionalGeneration,tb as Qwen3_5MoeForCausalLM,eb as Qwen3_5MoeForConditionalGeneration,ob as RFDetrForObjectDetection,nb as RFDetrModel,tp as RFDetrObjectDetectionOutput,Fi as RFDetrPreTrainedModel,Mg as RTDetrForObjectDetection,O_ as RTDetrImageProcessor,Tg as RTDetrModel,_r as RTDetrObjectDetectionOutput,ma as RTDetrPreTrainedModel,gb as RTDetrV2ForObjectDetection,hb as RTDetrV2Model,rp as RTDetrV2ObjectDetectionOutput,Gi as RTDetrV2PreTrainedModel,No as RawAudio,Qe as RawImage,Fp as RawVideo,Dl as RawVideoFrame,pu as RepetitionPenaltyLogitsProcessor,sb as ResNetForImageClassification,rb as ResNetModel,Ui as ResNetPreTrainedModel,fb as RoFormerForMaskedLM,_b as RoFormerForQuestionAnswering,db as RoFormerForSequenceClassification,mb as RoFormerForTokenClassification,pb as RoFormerModel,is as RoFormerPreTrainedModel,gm as RoFormerTokenizer,ib as RobertaForMaskedLM,ub as RobertaForQuestionAnswering,lb as RobertaForSequenceClassification,cb as RobertaForTokenClassification,ab as RobertaModel,as as RobertaPreTrainedModel,hm as RobertaTokenizer,Fo as Sam2ImageProcessor,op as Sam2ImageSegmentationOutput,ji as Sam2Model,ap as Sam2PreTrainedModel,eu as Sam2Processor,rh as Sam2VideoProcessor,Fo as Sam3ImageProcessor,yb as Sam3TrackerModel,Fo as SamImageProcessor,sp as SamImageSegmentationOutput,wb as SamModel,np as SamPreTrainedModel,jo as SamProcessor,I_ as SapiensFeatureExtractor,vb as SapiensForDepthEstimation,kb as SapiensForNormalEstimation,bb as SapiensForSemanticSegmentation,Kc as SapiensImageProcessor,Hn as SapiensPreTrainedModel,Dm as SeamlessM4TFeatureExtractor,C_ as SegformerFeatureExtractor,Ab as SegformerForImageClassification,Tb as SegformerForSemanticSegmentation,Yc as SegformerImageProcessor,Eb as SegformerModel,Xn as SegformerPreTrainedModel,P_ as SiglipImageProcessor,Mb as SiglipModel,qi as SiglipPreTrainedModel,Wi as SiglipTextModel,wm as SiglipTokenizer,Sb as SiglipVisionModel,Ib as SmolLM3ForCausalLM,Ob as SmolLM3Model,Vi as SmolLM3PreTrainedModel,jc as SmolVLMImageProcessor,Zc as SmolVLMProcessor,Xi as SnacDecoderModel,Hi as SnacEncoderModel,Bm as SnacFeatureExtractor,Cb as SnacModel,Kn as SnacPreTrainedModel,Lb as SolarOpenForCausalLM,Pb as SolarOpenModel,Ki as SolarOpenPreTrainedModel,Um as SpeechT5FeatureExtractor,zb as SpeechT5ForSpeechToText,Rb as SpeechT5ForTextToSpeech,$b as SpeechT5HifiGan,Nb as SpeechT5Model,Yn as SpeechT5PreTrainedModel,sh as SpeechT5Processor,xm as SpeechT5Tokenizer,Bb as SqueezeBertForMaskedLM,Fb as SqueezeBertForQuestionAnswering,Ub as SqueezeBertForSequenceClassification,Db as SqueezeBertModel,Xs as SqueezeBertPreTrainedModel,ym as SqueezeBertTokenizer,jb as StableLmForCausalLM,Gb as StableLmModel,Yi as StableLmPreTrainedModel,Wb as Starcoder2ForCausalLM,qb as Starcoder2Model,Qi as Starcoder2PreTrainedModel,Yr as StoppingCriteria,Sn as StoppingCriteriaList,Vb as StyleTextToSpeech2Model,ip as StyleTextToSpeech2PreTrainedModel,xl as SummarizationPipeline,Ji as SupertonicForConditionalGeneration,lp as SupertonicPreTrainedModel,Tn as SuppressTokensAtBeginLogitsProcessor,lu as SuppressTokensLogitsProcessor,Qb as Swin2SRForImageSuperResolution,L_ as Swin2SRImageProcessor,Yb as Swin2SRModel,Zi as Swin2SRPreTrainedModel,Xb as SwinForImageClassification,Kb as SwinForSemanticSegmentation,Hb as SwinModel,Qn as SwinPreTrainedModel,Zb as T5ForConditionalGeneration,Jb as T5Model,el as T5PreTrainedModel,bm as T5Tokenizer,t1 as TableTransformerForObjectDetection,e1 as TableTransformerModel,cp as TableTransformerObjectDetectionOutput,tl as TableTransformerPreTrainedModel,hu as TemperatureLogitsWarper,z as Tensor,Mr as Text2TextGenerationPipeline,_l as TextClassificationPipeline,bl as TextGenerationPipeline,Q1 as TextStreamer,Tl as TextToAudioPipeline,hl as TokenClassificationPipeline,V as TokenizersBackend,MT as TopKLogitsWarper,TT as TopPLogitsWarper,r1 as TrOCRForCausalLM,up as TrOCRPreTrainedModel,yl as TranslationPipeline,js as UltravoxModel,Fu as UltravoxPreTrainedModel,nh as UltravoxProcessor,n1 as UniSpeechForCTC,o1 as UniSpeechForSequenceClassification,s1 as UniSpeechModel,Jn as UniSpeechPreTrainedModel,c1 as UniSpeechSatForAudioFrameClassification,i1 as UniSpeechSatForCTC,l1 as UniSpeechSatForSequenceClassification,a1 as UniSpeechSatModel,Ks as UniSpeechSatPreTrainedModel,q_ as VLChatProcessor,u_ as VLMImageProcessor,p1 as VaultGemmaForCausalLM,u1 as VaultGemmaModel,rl as VaultGemmaPreTrainedModel,N_ as ViTFeatureExtractor,m1 as ViTForImageClassification,Qc as ViTImageProcessor,_1 as ViTMAEModel,pp as ViTMAEPreTrainedModel,g1 as ViTMSNForImageClassification,h1 as ViTMSNModel,nl as ViTMSNPreTrainedModel,d1 as ViTModel,sl as ViTPreTrainedModel,f1 as VisionEncoderDecoderModel,w1 as VitMatteForImageMatting,z_ as VitMatteImageProcessor,fp as VitMattePreTrainedModel,x1 as VitPoseForPoseEstimation,R_ as VitPoseImageProcessor,dp as VitPosePreTrainedModel,y1 as VitsModel,mp as VitsModelOutput,_p as VitsPreTrainedModel,km as VitsTokenizer,b1 as VoxtralForConditionalGeneration,oh as VoxtralProcessor,jm as VoxtralRealtimeFeatureExtractor,ol as VoxtralRealtimeForConditionalGeneration,hp as VoxtralRealtimePreTrainedModel,ih as VoxtralRealtimeProcessor,A1 as Wav2Vec2BertForCTC,T1 as Wav2Vec2BertForSequenceClassification,E1 as Wav2Vec2BertModel,Zn as Wav2Vec2BertPreTrainedModel,Em as Wav2Vec2CTCTokenizer,Fm as Wav2Vec2FeatureExtractor,Ax as Wav2Vec2ForAudioFrameClassification,kx as Wav2Vec2ForCTC,Ex as Wav2Vec2ForSequenceClassification,vx as Wav2Vec2Model,sr as Wav2Vec2PreTrainedModel,lh as Wav2Vec2Processor,ch as Wav2Vec2ProcessorWithLM,C1 as WavLMForAudioFrameClassification,S1 as WavLMForCTC,O1 as WavLMForSequenceClassification,I1 as WavLMForXVector,M1 as WavLMModel,ls as WavLMPreTrainedModel,Gm as WeSpeakerFeatureExtractor,P1 as WeSpeakerResNetModel,wp as WeSpeakerResNetPreTrainedModel,qm as WhisperFeatureExtractor,yp as WhisperForConditionalGeneration,L1 as WhisperModel,al as WhisperPreTrainedModel,uh as WhisperProcessor,kM as WhisperTextStreamer,cu as WhisperTimeStampLogitsProcessor,Am as WhisperTokenizer,B1 as XLMForQuestionAnswering,$1 as XLMForSequenceClassification,D1 as XLMForTokenClassification,z1 as XLMModel,cs as XLMPreTrainedModel,F1 as XLMRobertaForMaskedLM,q1 as XLMRobertaForQuestionAnswering,G1 as XLMRobertaForSequenceClassification,j1 as XLMRobertaForTokenClassification,U1 as XLMRobertaModel,us as XLMRobertaPreTrainedModel,Tm as XLMRobertaTokenizer,Mm as XLMTokenizer,R1 as XLMWithLMHeadModel,gp as XVectorOutput,$_ as YolosFeatureExtractor,V1 as YolosForObjectDetection,Jc as YolosImageProcessor,W1 as YolosModel,bp as YolosObjectDetectionOutput,il as YolosPreTrainedModel,X1 as YoutuForCausalLM,H1 as YoutuModel,ll as YoutuPreTrainedModel,El as ZeroShotAudioClassificationPipeline,vl as ZeroShotClassificationPipeline,Il as ZeroShotImageClassificationPipeline,Pl as ZeroShotObjectDetectionPipeline,ve as cat,oN as cos_sim,tA as dot,me as env,Xe as full,Io as full_like,Id as interpolate,vt as interpolate_4d,SD as layer_norm,uz as load_image,e3 as load_video,Lf as log_softmax,eT as matmul,Ic as mean,tT as mean_pooling,Ze as ones,Cc as ones_like,FN as permute,rce as pipeline,sT as quantize_embeddings,OD as rand,rT as randn,xs as random,Im as read_audio,MD as rfft,Oc as slice,Re as softmax,Ct as stack,Cd as std_mean,tr as topk,Ld as zeros,Nd as zeros_like};