@huggingface/transformers 4.0.0-next.8 → 4.0.0-next.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/ort-wasm-simd-threaded.jsep.mjs +26 -26
- package/dist/transformers.js +338 -230
- package/dist/transformers.min.js +22 -18
- package/dist/transformers.node.cjs +339 -228
- package/dist/transformers.node.min.cjs +23 -19
- package/dist/transformers.node.min.mjs +23 -19
- package/dist/transformers.node.mjs +336 -228
- package/dist/transformers.web.js +220 -112
- package/dist/transformers.web.min.js +18 -14
- package/package.json +2 -2
- package/src/env.js +1 -1
- package/src/models/gemma3/image_processing_gemma3.js +3 -0
- package/src/models/gemma3/modeling_gemma3.js +4 -1
- package/src/models/gemma3/processing_gemma3.js +45 -0
- package/src/models/image_processors.js +1 -0
- package/src/models/modeling_utils.js +46 -25
- package/src/models/processors.js +1 -0
- package/src/models/qwen2_vl/modeling_qwen2_vl.js +39 -32
- package/src/models/registry.js +2 -8
- package/src/utils/model_registry/ModelRegistry.js +36 -0
- package/src/utils/model_registry/get_available_dtypes.js +68 -0
- package/src/utils/model_registry/get_model_files.js +7 -60
- package/src/utils/model_registry/resolve_model_type.js +66 -0
- package/types/models/gemma3/image_processing_gemma3.d.ts +4 -0
- package/types/models/gemma3/image_processing_gemma3.d.ts.map +1 -0
- package/types/models/gemma3/modeling_gemma3.d.ts +4 -1
- package/types/models/gemma3/modeling_gemma3.d.ts.map +1 -1
- package/types/models/gemma3/processing_gemma3.d.ts +20 -0
- package/types/models/gemma3/processing_gemma3.d.ts.map +1 -0
- package/types/models/image_processors.d.ts +1 -0
- package/types/models/modeling_utils.d.ts +2 -3
- package/types/models/modeling_utils.d.ts.map +1 -1
- package/types/models/processors.d.ts +1 -0
- package/types/models/qwen2_vl/modeling_qwen2_vl.d.ts.map +1 -1
- package/types/models/registry.d.ts.map +1 -1
- package/types/utils/model_registry/ModelRegistry.d.ts +27 -0
- package/types/utils/model_registry/ModelRegistry.d.ts.map +1 -1
- package/types/utils/model_registry/get_available_dtypes.d.ts +26 -0
- package/types/utils/model_registry/get_available_dtypes.d.ts.map +1 -0
- package/types/utils/model_registry/get_model_files.d.ts +25 -0
- package/types/utils/model_registry/get_model_files.d.ts.map +1 -1
- package/types/utils/model_registry/resolve_model_type.d.ts +24 -0
- package/types/utils/model_registry/resolve_model_type.d.ts.map +1 -0
package/dist/transformers.min.js
CHANGED
|
@@ -1,27 +1,31 @@
|
|
|
1
|
-
var
|
|
2
|
-
`:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(t)}}clean_text(t){let e=[];for(let r of t){let s=r.charCodeAt(0);s===0||s===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},HI=VI,XI=class extends br{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(r=>r.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},KI=XI,YI=class extends br{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>iE(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},QI=YI,JI=class extends br{normalize(t){let e=Jl(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},ZI=JI,eC=class extends br{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Zl=eC,tC=class extends Zl{constructor(){super(...arguments),this.form="NFC"}},rC=tC,sC=class extends Zl{constructor(){super(...arguments),this.form="NFD"}},nC=sC,oC=class extends Zl{constructor(){super(...arguments),this.form="NFKC"}},aC=oC,iC=class extends Zl{constructor(){super(...arguments),this.form="NFKD"}},lC=iC,cC=class extends br{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}},uC=cC,pC=class extends br{normalize(t){return aE(t)}},dC=pC,fC=class extends br{normalize(t){return t.toLowerCase()}},mC=fC,_C=class extends br{normalize(t){return t=this.config.prepend+t,t}},hC=_C;function gC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new HI(t);case"Precompiled":return new KI(t);case"Sequence":return new QI(t);case"Replace":return new ZI(t);case"NFC":return new rC(t);case"NFD":return new nC(t);case"NFKC":return new aC(t);case"NFKD":return new lC(t);case"Strip":return new uC(t);case"StripAccents":return new dC(t);case"Lowercase":return new mC(t);case"Prepend":return new hC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var iE=gC,wC=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)}},Kt=wC,xC=class extends Kt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=oE,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(""))}},yC=xC,bC=class extends Kt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},vC=bC,kC=class extends Kt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},EC=kC,AC=class extends Kt{constructor(t){super(),this.config=t,this.pattern=Jl(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):GI(t,this.pattern)}},TC=AC,MC=class extends Kt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Ql}]+|[${Ql}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},SC=MC,OC=class extends Kt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},IC=OC,CC=class extends Kt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Ql}]+|[${Ql}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},PC=CC,LC=class extends Kt{constructor(t){super(),this.config=t,this.pattern=Jl(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},zC=LC,NC=class extends Kt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>lE(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},RC=NC,$C=class extends Kt{pre_tokenize_text(t){return jI(t)}},DC=$C,BC=class extends Kt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;r<t.length;r+=this._length)e.push(t.slice(r,r+this._length));return e}},UC=BC;function FC(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new PC;case"Sequence":return new RC(t);case"Whitespace":return new vC;case"WhitespaceSplit":return new DC;case"Metaspace":return new EC(t);case"ByteLevel":return new yC(t);case"Split":return new TC(t);case"Punctuation":return new SC(t);case"Digits":return new IC(t);case"Replace":return new zC(t);case"FixedLength":return new UC(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var lE=FC,GC=class extends co{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=$I(e,this.tokens_to_ids,this.unk_token_id)),e}},ec=GC,jC=class extends ec{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=wd(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let s=[...r];if(s.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o<s.length;){let i=s.length,l=null;for(;o<i;){let c=s.slice(o,i).join("");if(o>0&&(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}},tE=jC,rE=class cE{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new cE(!1,new Map)}},qC=class{constructor(){this.root=rE.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=rE.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)}}},WC=qC,hd=class uE{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 uE(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},VC=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 hd(this.bos_token_id??0,0,0,0,0),n=new hd(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 hd(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+a.score;(l===null||p>i)&&(l=c.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},HC=VC;function XC(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}var KC=class extends ec{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=t.vocab[s];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=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=XC(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new WC,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;s<e.length;){let n=!1,o=[],a=e.slice(s).join(""),i=this.trie.common_prefix_search(a);for(let l of i){o.push(l);let c=this.tokens_to_ids.get(l),p=this.scores[c],d=UI(l);t.insert(s,d,p,c),!n&&d===r&&(n=!0)}n||t.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(t){let e=new HC(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let s=this.tokenize(r);e.push(...s)}return e}},sE=KC,YC=class{constructor(t=(r,s)=>r>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.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&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.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},QC=YC,JC=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},ZC=JC,eP=class extends ec{constructor(t){super(t),this.tokens_to_ids=wd(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 ZC(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 QC((i,l)=>i.score<l.score),o={token:r[0],bias:0,prev:null,next:null},a=o;for(let i=1;i<r.length;++i){let l={bias:i/r.length,token:r[i],prev:a,next:null};a.next=l,this.add_node(n,a),a=l}for(;!n.is_empty();){let i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){let c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:o=c}let l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):o=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=o;i!==null;i=i.next)s.push(i.token)}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,s),s}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let s=this.bpe(r);for(let n of s)if(this.tokens_to_ids.has(n))e.push(n);else if(this.byte_fallback){let o=Array.from(this.text_encoder.encode(n)).map(a=>`<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}},nE=eP,tP=class extends ec{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=wd(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}},rP=tP;function sP(t,e){switch(t.type){case"WordPiece":return new tE(t);case"Unigram":return new sE(t,e.eos_token);case"BPE":return new nE(t);default:if(t.vocab)return Array.isArray(t.vocab)?new sE(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new nE(t):new tE(t):new rP(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 nP=sP,oP=class extends co{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},uo=oP,aP=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=Xt(n,t),o=Xt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Xt(n,e),o=Xt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},iP=aP,lP=class extends uo{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},cP=lP,uP=class extends uo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Xt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Xt(t,n,e,o),s=Xt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},pP=uP,dP=class extends uo{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Xt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Xt(t,n,e,o),s=Xt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},fP=dP,mP=class extends uo{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>pE(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},_P=mP;function hP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new iP(t);case"ByteLevel":return new cP(t);case"BertProcessing":return new pP(t);case"RobertaProcessing":return new fP(t);case"Sequence":return new _P(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var pE=hP,gP=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("")}},Bt=gP,wP=class extends Bt{constructor(t){super(t),this.byte_decoder=zI,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}},xP=wP,yP=class extends Bt{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=gd(e)),e})}},bP=yP,vP=class extends Bt{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),e.push(s)}return e}},kP=vP,EP=class extends Bt{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},AP=EP,TP=class extends Bt{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;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let s=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=gd(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},MP=TP,SP=class extends Bt{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>dE(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},OP=SP,IP=class extends Bt{decode_chain(t){let e=Jl(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},CP=IP,PP=class extends Bt{decode_chain(t){return[t.join("")]}},LP=PP,zP=class extends Bt{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<this.start&&e[n]===this.content;++n){r=n+1;continue}let s=e.length;for(let n=0;n<this.stop;++n){let o=e.length-n-1;if(e[o]===this.content){s=o;continue}else break}return e.slice(r,s)})}},NP=zP,RP=class extends Bt{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let s of t){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){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}},$P=RP;function DP(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new xP(t);case"WordPiece":return new bP(t);case"Metaspace":return new kP(t);case"BPEDecoder":return new AP(t);case"CTC":return new MP(t);case"Sequence":return new OP(t);case"Replace":return new CP(t);case"Fuse":return new LP(t);case"Strip":return new NP(t);case"ByteFallback":return new $P(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var dE=DP,BP=class{constructor(t,e){let r=eE(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=eE(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=iE(this.tokenizer.normalizer),this.pre_tokenizer=lE(this.tokenizer.pre_tokenizer),this.model=nP(this.tokenizer.model,this.config),this.post_processor=pE(this.tokenizer.post_processor),this.decoder=dE(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 PI(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 Jk(n),this.splitter_normalized=new Jk(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||!BI(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=gd(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<e.length-1&&(e[s+1]=e[s+1].trimStart()))}),e.flatMap((r,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=FI(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<n.length-1&&(n[a+1]=n[a+1].trimStart()))}),n.flatMap(o=>{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Xt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r<this.model.vocab.length;++r){let s=this.model.vocab[r];(t||!this.added_tokens_map.has(s))&&e.set(s,r)}return e}},fE=BP;var D=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Ut=class{constructor(t,e){this.value=t,this.type=e}};function mE(t){return/\w/.test(t)}function po(t){return/[0-9]/.test(t)}function _E(t){return/\s/.test(t)}var UP=[["{%",D.OpenStatement],["%}",D.CloseStatement],["{{",D.OpenExpression],["}}",D.CloseExpression],["(",D.OpenParen],[")",D.CloseParen],["{",D.OpenCurlyBracket],["}",D.CloseCurlyBracket],["[",D.OpenSquareBracket],["]",D.CloseSquareBracket],[",",D.Comma],[".",D.Dot],[":",D.Colon],["|",D.Pipe],["<=",D.ComparisonBinaryOperator],[">=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["*",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],FP=new Map([["n",`
|
|
3
|
-
`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function
|
|
4
|
-
`)&&(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 jP(t,e={}){let r=[],s=GP(t,e),n=0,o=0,a=c=>{let p="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let d=s[n++],m=FP.get(d);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${d}`);p+=m;continue}if(p+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return p},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n<s.length&&_E(s[n]);)++n};e:for(;n<s.length;){let c=r.at(-1)?.type;if(c===void 0||c===D.CloseStatement||c===D.CloseExpression||c===D.Comment){let d="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)d+=s[n++];if(d.length>0){r.push(new Ut(d,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let d=s[n]==="-";d&&++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)),d&&i(),r.push(new Ut(m,D.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Ut("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Ut("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(_E),s.slice(n,n+3)==="-%}"){r.push(new Ut("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Ut("}}",D.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let d=r.at(-1)?.type;if(d===D.Text||d===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(d){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let m=a(po);r.push(new Ut(`${p}${m}`,m.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[d,m]of UP){if(d==="}}"&&o>0)continue;if(s.slice(n,n+d.length)===d){r.push(new Ut(d,m)),m===D.OpenExpression?o=0:m===D.OpenCurlyBracket?++o:m===D.CloseCurlyBracket&&--o,n+=d.length;continue e}}if(p==="'"||p==='"'){++n;let d=a(m=>m!==p);r.push(new Ut(d,D.StringLiteral)),++n;continue}if(po(p)){let d=a(po);if(s[n]==="."&&po(s[n+1])){++n;let m=a(po);d=`${d}.${m}`}r.push(new Ut(d,D.NumericLiteral));continue}if(mE(p)){let d=a(mE);r.push(new Ut(d,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Qt=class{type="Statement"},qP=class extends Qt{constructor(t){super(),this.body=t}type="Program"},WP=class extends Qt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},VP=class extends Qt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},HP=class extends Qt{type="Break"},XP=class extends Qt{type="Continue"},KP=class extends Qt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},YP=class extends Qt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},QP=class extends Qt{constructor(t){super(),this.value=t}type="Comment"},Pt=class extends Qt{type="Expression"},JP=class extends Pt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},hE=class extends Pt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},an=class extends Pt{constructor(t){super(),this.value=t}type="Identifier"},ln=class extends Pt{constructor(t){super(),this.value=t}type="Literal"},ZP=class extends ln{type="IntegerLiteral"},eL=class extends ln{type="FloatLiteral"},gE=class extends ln{type="StringLiteral"},tL=class extends ln{type="ArrayLiteral"},wE=class extends ln{type="TupleLiteral"},rL=class extends ln{type="ObjectLiteral"},fo=class extends Pt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},sL=class extends Pt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},nL=class extends Qt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},oL=class extends Pt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},aL=class extends Pt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},iL=class extends Pt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},lL=class extends Pt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},cL=class extends Pt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},uL=class extends Pt{constructor(t){super(),this.argument=t}type="SpreadExpression"},pL=class extends Qt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},dL=class extends Pt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function fL(t){let e=new qP([]),r=0;function s(L,N){let B=t[r++];if(!B||B.type!==L)throw new Error(`Parser Error: ${N}. ${B.type} !== ${L}.`);return B}function n(L){if(!l(L))throw new SyntaxError(`Expected ${L}`);++r}function o(){switch(t[r].type){case D.Comment:return new QP(t[r++].value);case D.Text:return c();case D.OpenStatement:return p();case D.OpenExpression:return d();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...L){return r+L.length<=t.length&&L.every((N,B)=>N===t[r+B].type)}function i(...L){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&L.includes(t[r+1]?.value)}function l(...L){return r+L.length<=t.length&&L.every((N,B)=>t[r+B].type==="Identifier"&&N===t[r+B].value)}function c(){return new gE(s(D.Text,"Expected text token").value)}function p(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let L=t[r].value,N;switch(L){case"set":++r,N=m();break;case"if":++r,N=_(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,N=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,N=k(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let B=null;a(D.OpenParen)&&(B=U());let J=ae();if(J.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let xe=U();s(D.CloseStatement,"Expected closing statement token");let ue=[];for(;!i("endcall");)ue.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let qe=new hE(J,xe);N=new pL(qe,B,ue);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),N=new HP;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),N=new XP;break;case"filter":{++r;let B=ae();B instanceof an&&a(D.OpenParen)&&(B=X(B)),s(D.CloseStatement,"Expected closing statement token");let J=[];for(;!i("endfilter");)J.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),N=new nL(B,J);break}default:throw new SyntaxError(`Unknown statement type: ${L}`)}return N}function d(){s(D.OpenExpression,"Expected opening expression token");let L=b();return s(D.CloseExpression,"Expected closing expression token"),L}function m(){let L=x(),N=null,B=[];if(a(D.Equals))++r,N=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)B.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new KP(L,N,B)}function _(){let L=b();s(D.CloseStatement,"Expected closing statement token");let N=[],B=[];for(;!i("elif","else","endif");)N.push(o());if(i("elif")){++r,++r;let J=_();B.push(J)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)B.push(o());return new WP(L,N,B)}function w(){let L=ae();if(L.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let N=U();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endmacro");)B.push(o());return new YP(L,N,B)}function x(L=!1){let N=L?ae:b,B=[N()],J=a(D.Comma);for(;J&&(++r,B.push(N()),!!a(D.Comma)););return J?new wE(B):B[0]}function k(){let L=x(!0);if(!(L instanceof an||L instanceof wE))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 N=b();s(D.CloseStatement,"Expected closing statement token");let B=[];for(;!i("endfor","else");)B.push(o());let J=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)J.push(o());return new VP(L,N,B,J)}function b(){return A()}function A(){let L=S();if(l("if")){++r;let N=S();if(l("else")){++r;let B=A();return new dL(N,L,B)}else return new oL(L,N)}return L}function S(){let L=M();for(;l("or");){let N=t[r];++r;let B=M();L=new fo(N,L,B)}return L}function M(){let L=P();for(;l("and");){let N=t[r];++r;let B=P();L=new fo(N,L,B)}return L}function P(){let L;for(;l("not");){let N=t[r];++r;let B=P();L=new iL(N,B)}return L??O()}function O(){let L=E();for(;;){let N;if(l("not","in"))N=new Ut("not in",D.Identifier),r+=2;else if(l("in"))N=t[r++];else if(a(D.ComparisonBinaryOperator))N=t[r++];else break;let B=E();L=new fo(N,L,B)}return L}function E(){let L=$();for(;a(D.AdditiveBinaryOperator);){let N=t[r];++r;let B=$();L=new fo(N,L,B)}return L}function W(){let L=Y(ae());return a(D.OpenParen)?X(L):L}function X(L){let N=new hE(L,U());return N=Y(N),a(D.OpenParen)&&(N=X(N)),N}function U(){s(D.OpenParen,"Expected opening parenthesis for arguments list");let L=H();return s(D.CloseParen,"Expected closing parenthesis for arguments list"),L}function H(){let L=[];for(;!a(D.CloseParen);){let N;if(t[r].type===D.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let B=b();N=new uL(B)}else if(N=b(),a(D.Equals)){if(++r,!(N instanceof an))throw new SyntaxError("Expected identifier for keyword argument");let B=b();N=new cL(N,B)}L.push(N),a(D.Comma)&&++r}return L}function j(){let L=[],N=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(L.push(void 0),++r,N=!0):(L.push(b()),a(D.Colon)&&(++r,N=!0));if(L.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(L.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new lL(...L)}return L[0]}function Y(L){for(;a(D.Dot)||a(D.OpenSquareBracket);){let N=t[r];++r;let B,J=N.type===D.OpenSquareBracket;if(J)B=j(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(B=ae(),B.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");L=new JP(L,B,J)}return L}function $(){let L=C();for(;a(D.MultiplicativeBinaryOperator);){let N=t[r++],B=C();L=new fo(N,L,B)}return L}function C(){let L=te();for(;l("is");){++r;let N=l("not");N&&++r;let B=ae();if(!(B instanceof an))throw new SyntaxError("Expected identifier for the test");L=new aL(L,N,B)}return L}function te(){let L=W();for(;a(D.Pipe);){++r;let N=ae();if(!(N instanceof an))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&(N=X(N)),L=new sL(L,N)}return L}function ae(){let L=t[r++];switch(L.type){case D.NumericLiteral:{let N=L.value;return N.includes(".")?new eL(Number(N)):new ZP(Number(N))}case D.StringLiteral:{let N=L.value;for(;a(D.StringLiteral);)N+=t[r++].value;return new gE(N)}case D.Identifier:return new an(L.value);case D.OpenParen:{let N=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),N}case D.OpenSquareBracket:{let N=[];for(;!a(D.CloseSquareBracket);)N.push(b()),a(D.Comma)&&++r;return++r,new tL(N)}case D.OpenCurlyBracket:{let N=new Map;for(;!a(D.CloseCurlyBracket);){let B=b();s(D.Colon,"Expected colon between key and value in object literal");let J=b();N.set(B,J),a(D.Comma)&&++r}return++r,new rL(N)}default:throw new SyntaxError(`Unexpected token: ${L.type}`)}}for(;r<t.length;)e.body.push(o());return e}function mL(t,e,r=1){if(e===void 0&&(e=t,t=0),r===0)throw new Error("range() step must not be zero");let s=[];if(r>0)for(let n=t;n<e;n+=r)s.push(n);else for(let n=t;n>e;n+=r)s.push(n);return s}function xE(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*a<n*r;a+=s)o.push(t[a]);return o}function _L(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function hL(t){return gL(new Date,t)}function gL(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 wL(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xL(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(wL(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var yE=class extends Error{},bE=class extends Error{},ir=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 ir{type="IntegerValue"},Qe=class extends ir{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},ee=class extends ir{type="StringValue";builtins=new Map([["upper",new je(()=>new ee(this.value.toUpperCase()))],["lower",new je(()=>new ee(this.value.toLowerCase()))],["strip",new je(()=>new ee(this.value.trim()))],["title",new je(()=>new ee(_L(this.value)))],["capitalize",new je(()=>new ee(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new _e(this.value.length)],["rstrip",new je(()=>new ee(this.value.trimEnd()))],["lstrip",new je(()=>new ee(this.value.trimStart()))],["startswith",new je(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof ee)return new pe(this.value.startsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof ee))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 je(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof ee)return new pe(this.value.endsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof ee))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 je(t=>{let e=t[0]??new We;if(!(e instanceof ee||e instanceof We))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 We){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 ee(n)))})],["replace",new je(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof ee&&r instanceof ee))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 We:s=t[2]:s=new We,!(s instanceof _e||s instanceof We))throw new Error("replace() count argument must be a number or null");return new ee(xL(this.value,e.value,r.value,s.value))})]])},pe=class extends ir{type="BooleanValue"},yL=/[\x7f-\uffff]/g;function vE(t){return t.replace(yL,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function ms(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=vE(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",d=`
|
|
5
|
-
`+p.repeat(r),m=
|
|
1
|
+
var vI=Object.defineProperty;var fs=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var ds=(t,e)=>{for(var r in e)vI(t,r,{get:e[r],enumerable:!0})};var ht={};var Bt={};var Xk={};var kI="4.0.0-next.9",pf=typeof self<"u",tn=!eE(ht),Qk=!eE(Bt),Gl=pf&&"caches"in self,EI=typeof globalThis.Deno<"u",YN=typeof globalThis.Bun<"u",ql=EI&&Gl&&!tn,Jk=typeof process<"u",Zk=Jk&&process?.release?.name==="node"&&!ql,ff=typeof window<"u"&&typeof window.document<"u",df=pf&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),AI=ff||df||ql,TI=Zk||typeof navigator<"u"&&"gpu"in navigator,MI=typeof navigator<"u"&&"ml"in navigator,SI=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",OI=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",II=typeof ServiceWorkerGlobalScope<"u"&&pf&&self instanceof ServiceWorkerGlobalScope,CI=()=>{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},PI=CI(),ie=Object.freeze({IS_BROWSER_ENV:ff,IS_WEBWORKER_ENV:df,IS_WEB_ENV:AI,IS_SERVICE_WORKER_ENV:II,IS_DENO_WEB_RUNTIME:ql,IS_WEB_CACHE_AVAILABLE:Gl,IS_WEBGPU_AVAILABLE:TI,IS_WEBNN_AVAILABLE:MI,IS_SAFARI:PI,IS_PROCESS_AVAILABLE:Jk,IS_NODE_ENV:Zk,IS_FS_AVAILABLE:tn,IS_PATH_AVAILABLE:Qk,IS_CRYPTO_AVAILABLE:SI,IS_CHROME_AVAILABLE:OI}),mf=tn&&Qk,jl="./";if(mf){let t=Object(import.meta).url;t?jl=Bt.dirname(Bt.dirname(Xk.fileURLToPath(t))):typeof __dirname<"u"&&(jl=Bt.dirname(__dirname))}var LI=mf?Bt.join(jl,"/.cache/"):null,Kk="/models/",zI=mf?Bt.join(jl,Kk):Kk,NI=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,Ot=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),Yk=Ot.WARNING,me={version:kI,backends:{onnx:{}},get logLevel(){return Yk},set logLevel(t){Yk=t,me.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(ff||df||ql),localModelPath:zI,useFS:tn,useBrowserCache:Gl,useFSCache:tn,cacheDir:LI,useCustomCache:!1,customCache:null,useWasmCache:Gl||tn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:NI};function eE(t){return Object.keys(t).length===0}function yr(t,e){t&&t(e)}function tE(t){return Number.isInteger(t)||typeof t=="bigint"}function _f(t){return t==null||t===-1}function hf(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 rE(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function rn(t,e){return Math.abs((t+e)%(2*e)-e)}function Ke(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function sE(t,e){let r=0;for(let s of t)s===e&&++r;return r}var Z={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 RI=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;n<r.length;++n){let o=r[n];s=s[o]??=Object.create(null)}s.end=r}return e}split(t){let e=[],r=t.length,s=0,n=0;for(;n<r;){let o=this.trie,a=null,i=n;for(;i<r&&(o=o[t[i]]);)o.end&&(a=o.end),++i;a?(n>s&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s<r&&e.push(t.slice(s)),e}},nE=RI,$I=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??!this.special}},BI=$I,pE=(()=>{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]]))})(),DI=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),UI=DI(pE),oE=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",FI=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|[${oE}])]+`,` ?[^\\s${oE}]+`]]),Wl="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",wf=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"),Vl=(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 FI)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=GI(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},GI=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),jI=(t,e,r)=>{let s=[],n=0;for(;n<t.length;){if(s.push(t[n]),(e.get(t[n])??r)!==r){++n;continue}for(;++n<t.length&&(e.get(t[n])??r)===r;)e.get(s.at(-1))!==r&&(s[s.length-1]+=t[n])}return s},qI=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,WI=t=>Number.isInteger(t)||typeof t=="bigint",VI=t=>{let e=0;for(let r of t)++e;return e},HI=t=>fE(t.toLowerCase()),Kt=(...t)=>Array.prototype.concat.apply([],t),xf=t=>new Map(Object.entries(t)),XI=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s<n.index&&r.push(t.slice(s,n.index)),o.length>0&&r.push(o),s=n.index+o.length}return s<t.length&&r.push(t.slice(s)),r},fE=t=>t.replace(/\p{M}/gu,""),aE=(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},KI=t=>t.match(/\S+/g)||[],YI=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},oo=YI,QI=class extends oo{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},br=QI,JI=class extends br{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r],n=s.charCodeAt(0);qI(n)?(e.push(" "),e.push(s),e.push(" ")):e.push(s)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(t){switch(t){case" ":case`
|
|
2
|
+
`:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(t)}}clean_text(t){let e=[];for(let r of t){let s=r.charCodeAt(0);s===0||s===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},ZI=JI,eC=class extends br{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(r=>r.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},tC=eC,rC=class extends br{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>dE(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},sC=rC,nC=class extends br{normalize(t){let e=Vl(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},oC=nC,aC=class extends br{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Hl=aC,iC=class extends Hl{constructor(){super(...arguments),this.form="NFC"}},lC=iC,cC=class extends Hl{constructor(){super(...arguments),this.form="NFD"}},uC=cC,pC=class extends Hl{constructor(){super(...arguments),this.form="NFKC"}},fC=pC,dC=class extends Hl{constructor(){super(...arguments),this.form="NFKD"}},mC=dC,_C=class extends br{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}},hC=_C,gC=class extends br{normalize(t){return fE(t)}},wC=gC,xC=class extends br{normalize(t){return t.toLowerCase()}},yC=xC,bC=class extends br{normalize(t){return t=this.config.prepend+t,t}},vC=bC;function kC(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new ZI(t);case"Precompiled":return new tC(t);case"Sequence":return new sC(t);case"Replace":return new oC(t);case"NFC":return new lC(t);case"NFD":return new uC(t);case"NFKC":return new fC(t);case"NFKD":return new mC(t);case"Strip":return new hC(t);case"StripAccents":return new wC(t);case"Lowercase":return new yC(t);case"Prepend":return new vC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var dE=kC,EC=class extends oo{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=EC,AC=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=pE,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(""))}},TC=AC,MC=class extends Yt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},SC=MC,OC=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]}},IC=OC,CC=class extends Yt{constructor(t){super(),this.config=t,this.pattern=Vl(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):XI(t,this.pattern)}},PC=CC,LC=class extends Yt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Wl}]+|[${Wl}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},zC=LC,NC=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)||[]}},RC=NC,$C=class extends Yt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Wl}]+|[${Wl}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},BC=$C,DC=class extends Yt{constructor(t){super(),this.config=t,this.pattern=Vl(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},UC=DC,FC=class extends Yt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>mE(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},GC=FC,jC=class extends Yt{pre_tokenize_text(t){return KI(t)}},qC=jC,WC=class extends Yt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;r<t.length;r+=this._length)e.push(t.slice(r,r+this._length));return e}},VC=WC;function HC(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new BC;case"Sequence":return new GC(t);case"Whitespace":return new SC;case"WhitespaceSplit":return new qC;case"Metaspace":return new IC(t);case"ByteLevel":return new TC(t);case"Split":return new PC(t);case"Punctuation":return new zC(t);case"Digits":return new RC(t);case"Replace":return new UC(t);case"FixedLength":return new VC(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var mE=HC,XC=class extends oo{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=jI(e,this.tokens_to_ids,this.unk_token_id)),e}},Xl=XC,KC=class extends Xl{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=xf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let s=[...r];if(s.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o<s.length;){let i=s.length,l=null;for(;o<i;){let c=s.slice(o,i).join("");if(o>0&&(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}},iE=KC,lE=class _E{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new _E(!1,new Map)}},YC=class{constructor(){this.root=lE.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=lE.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)}}},QC=YC,gf=class hE{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 hE(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},JC=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 gf(this.bos_token_id??0,0,0,0,0),n=new gf(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 gf(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let p=c.backtrace_score+a.score;(l===null||p>i)&&(l=c.clone(),i=p)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},ZC=JC;function eP(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}var tP=class extends Xl{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=t.vocab[s];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=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=eP(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new QC,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;s<e.length;){let n=!1,o=[],a=e.slice(s).join(""),i=this.trie.common_prefix_search(a);for(let l of i){o.push(l);let c=this.tokens_to_ids.get(l),p=this.scores[c],f=VI(l);t.insert(s,f,p,c),!n&&f===r&&(n=!0)}n||t.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(t){let e=new ZC(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let s=this.tokenize(r);e.push(...s)}return e}},cE=tP,rP=class{constructor(t=(r,s)=>r>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.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&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.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},sP=rP,nP=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},oP=nP,aP=class extends Xl{constructor(t){super(t),this.tokens_to_ids=xf(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 oP(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 sP((i,l)=>i.score<l.score),o={token:r[0],bias:0,prev:null,next:null},a=o;for(let i=1;i<r.length;++i){let l={bias:i/r.length,token:r[i],prev:a,next:null};a.next=l,this.add_node(n,a),a=l}for(;!n.is_empty();){let i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){let c={...i.prev};i.prev.deleted=!0,i.prev=c,c.prev?c.prev.next=c:o=c}let l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):o=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=o;i!==null;i=i.next)s.push(i.token)}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,s),s}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let s=this.bpe(r);for(let n of s)if(this.tokens_to_ids.has(n))e.push(n);else if(this.byte_fallback){let o=Array.from(this.text_encoder.encode(n)).map(a=>`<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}},uE=aP,iP=class extends Xl{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=xf(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}},lP=iP;function cP(t,e){switch(t.type){case"WordPiece":return new iE(t);case"Unigram":return new cE(t,e.eos_token);case"BPE":return new uE(t);default:if(t.vocab)return Array.isArray(t.vocab)?new cE(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new uE(t):new iE(t):new lP(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 uP=cP,pP=class extends oo{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},ao=pP,fP=class extends ao{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}}},dP=fP,mP=class extends ao{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},_P=mP,hP=class extends ao{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}}},gP=hP,wP=class extends ao{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}}},xP=wP,yP=class extends ao{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>gE(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}},bP=yP;function vP(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new dP(t);case"ByteLevel":return new _P(t);case"BertProcessing":return new gP(t);case"RobertaProcessing":return new xP(t);case"Sequence":return new bP(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var gE=vP,kP=class extends oo{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Dt=kP,EP=class extends Dt{constructor(t){super(t),this.byte_decoder=UI,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}},AP=EP,TP=class extends Dt{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=wf(e)),e})}},MP=TP,SP=class extends Dt{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),e.push(s)}return e}},OP=SP,IP=class extends Dt{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},CP=IP,PP=class extends Dt{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let s=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=wf(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},LP=PP,zP=class extends Dt{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>wE(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},NP=zP,RP=class extends Dt{decode_chain(t){let e=Vl(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},$P=RP,BP=class extends Dt{decode_chain(t){return[t.join("")]}},DP=BP,UP=class extends Dt{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n<this.start&&e[n]===this.content;++n){r=n+1;continue}let s=e.length;for(let n=0;n<this.stop;++n){let o=e.length-n-1;if(e[o]===this.content){s=o;continue}else break}return e.slice(r,s)})}},FP=UP,GP=class extends Dt{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let s of t){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){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}},jP=GP;function qP(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new AP(t);case"WordPiece":return new MP(t);case"Metaspace":return new OP(t);case"BPEDecoder":return new CP(t);case"CTC":return new LP(t);case"Sequence":return new NP(t);case"Replace":return new $P(t);case"Fuse":return new DP(t);case"Strip":return new FP(t);case"ByteFallback":return new jP(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var wE=qP,WP=class{constructor(t,e){let r=aE(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=aE(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=dE(this.tokenizer.normalizer),this.pre_tokenizer=mE(this.tokenizer.pre_tokenizer),this.model=uP(this.tokenizer.model,this.config),this.post_processor=gE(this.tokenizer.post_processor),this.decoder=wE(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 BI(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 nE(n),this.splitter_normalized=new nE(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||!WI(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=wf(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<e.length-1&&(e[s+1]=e[s+1].trimStart()))}),e.flatMap((r,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=HI(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<n.length-1&&(n[a+1]=n[a+1].trimStart()))}),n.flatMap(o=>{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<this.model.vocab.length;++r){let s=this.model.vocab[r];(t||!this.added_tokens_map.has(s))&&e.set(s,r)}return e}},xE=WP;var B=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Ut=class{constructor(t,e){this.value=t,this.type=e}};function yE(t){return/\w/.test(t)}function io(t){return/[0-9]/.test(t)}function bE(t){return/\s/.test(t)}var VP=[["{%",B.OpenStatement],["%}",B.CloseStatement],["{{",B.OpenExpression],["}}",B.CloseExpression],["(",B.OpenParen],[")",B.CloseParen],["{",B.OpenCurlyBracket],["}",B.CloseCurlyBracket],["[",B.OpenSquareBracket],["]",B.CloseSquareBracket],[",",B.Comma],[".",B.Dot],[":",B.Colon],["|",B.Pipe],["<=",B.ComparisonBinaryOperator],[">=",B.ComparisonBinaryOperator],["==",B.ComparisonBinaryOperator],["!=",B.ComparisonBinaryOperator],["<",B.ComparisonBinaryOperator],[">",B.ComparisonBinaryOperator],["+",B.AdditiveBinaryOperator],["-",B.AdditiveBinaryOperator],["~",B.AdditiveBinaryOperator],["*",B.MultiplicativeBinaryOperator],["/",B.MultiplicativeBinaryOperator],["%",B.MultiplicativeBinaryOperator],["=",B.Equals]],HP=new Map([["n",`
|
|
3
|
+
`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function XP(t,e={}){return t.endsWith(`
|
|
4
|
+
`)&&(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 KP(t,e={}){let r=[],s=XP(t,e),n=0,o=0,a=c=>{let p="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=HP.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);p+=m;continue}if(p+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return p},i=()=>{let c=r.at(-1);c&&c.type===B.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n<s.length&&bE(s[n]);)++n};e:for(;n<s.length;){let c=r.at(-1)?.type;if(c===void 0||c===B.CloseStatement||c===B.CloseExpression||c===B.Comment){let f="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)f+=s[n++];if(f.length>0){r.push(new Ut(f,B.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 Ut(m,B.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Ut("{%",B.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Ut("{{",B.OpenExpression)),o=0,n+=3;continue}if(a(bE),s.slice(n,n+3)==="-%}"){r.push(new Ut("%}",B.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Ut("}}",B.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===B.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case B.Identifier:case B.NumericLiteral:case B.StringLiteral:case B.CloseParen:case B.CloseSquareBracket:break;default:{++n;let m=a(io);r.push(new Ut(`${p}${m}`,m.length>0?B.NumericLiteral:B.UnaryOperator));continue}}}for(let[f,m]of VP){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Ut(f,m)),m===B.OpenExpression?o=0:m===B.OpenCurlyBracket?++o:m===B.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(m=>m!==p);r.push(new Ut(f,B.StringLiteral)),++n;continue}if(io(p)){let f=a(io);if(s[n]==="."&&io(s[n+1])){++n;let m=a(io);f=`${f}.${m}`}r.push(new Ut(f,B.NumericLiteral));continue}if(yE(p)){let f=a(yE);r.push(new Ut(f,B.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Jt=class{type="Statement"},YP=class extends Jt{constructor(t){super(),this.body=t}type="Program"},QP=class extends Jt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},JP=class extends Jt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},ZP=class extends Jt{type="Break"},eL=class extends Jt{type="Continue"},tL=class extends Jt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},rL=class extends Jt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},sL=class extends Jt{constructor(t){super(),this.value=t}type="Comment"},Pt=class extends Jt{type="Expression"},nL=class extends Pt{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},vE=class extends Pt{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},sn=class extends Pt{constructor(t){super(),this.value=t}type="Identifier"},nn=class extends Pt{constructor(t){super(),this.value=t}type="Literal"},oL=class extends nn{type="IntegerLiteral"},aL=class extends nn{type="FloatLiteral"},kE=class extends nn{type="StringLiteral"},iL=class extends nn{type="ArrayLiteral"},EE=class extends nn{type="TupleLiteral"},lL=class extends nn{type="ObjectLiteral"},lo=class extends Pt{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},cL=class extends Pt{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},uL=class extends Jt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},pL=class extends Pt{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},fL=class extends Pt{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},dL=class extends Pt{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},mL=class extends Pt{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},_L=class extends Pt{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},hL=class extends Pt{constructor(t){super(),this.argument=t}type="SpreadExpression"},gL=class extends Jt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},wL=class extends Pt{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function xL(t){let e=new YP([]),r=0;function s(L,N){let D=t[r++];if(!D||D.type!==L)throw new Error(`Parser Error: ${N}. ${D.type} !== ${L}.`);return D}function n(L){if(!l(L))throw new SyntaxError(`Expected ${L}`);++r}function o(){switch(t[r].type){case B.Comment:return new sL(t[r++].value);case B.Text:return c();case B.OpenStatement:return p();case B.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...L){return r+L.length<=t.length&&L.every((N,D)=>N===t[r+D].type)}function i(...L){return t[r]?.type===B.OpenStatement&&t[r+1]?.type===B.Identifier&&L.includes(t[r+1]?.value)}function l(...L){return r+L.length<=t.length&&L.every((N,D)=>t[r+D].type==="Identifier"&&N===t[r+D].value)}function c(){return new kE(s(B.Text,"Expected text token").value)}function p(){if(s(B.OpenStatement,"Expected opening statement token"),t[r].type!==B.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let L=t[r].value,N;switch(L){case"set":++r,N=m();break;case"if":++r,N=_(),s(B.OpenStatement,"Expected {% token"),n("endif"),s(B.CloseStatement,"Expected %} token");break;case"macro":++r,N=w(),s(B.OpenStatement,"Expected {% token"),n("endmacro"),s(B.CloseStatement,"Expected %} token");break;case"for":++r,N=b(),s(B.OpenStatement,"Expected {% token"),n("endfor"),s(B.CloseStatement,"Expected %} token");break;case"call":{++r;let D=null;a(B.OpenParen)&&(D=U());let J=ae();if(J.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let xe=U();s(B.CloseStatement,"Expected closing statement token");let ue=[];for(;!i("endcall");)ue.push(o());s(B.OpenStatement,"Expected '{%'"),n("endcall"),s(B.CloseStatement,"Expected closing statement token");let qe=new vE(J,xe);N=new gL(qe,D,ue);break}case"break":++r,s(B.CloseStatement,"Expected closing statement token"),N=new ZP;break;case"continue":++r,s(B.CloseStatement,"Expected closing statement token"),N=new eL;break;case"filter":{++r;let D=ae();D instanceof sn&&a(B.OpenParen)&&(D=X(D)),s(B.CloseStatement,"Expected closing statement token");let J=[];for(;!i("endfilter");)J.push(o());s(B.OpenStatement,"Expected '{%'"),n("endfilter"),s(B.CloseStatement,"Expected '%}'"),N=new uL(D,J);break}default:throw new SyntaxError(`Unknown statement type: ${L}`)}return N}function f(){s(B.OpenExpression,"Expected opening expression token");let L=E();return s(B.CloseExpression,"Expected closing expression token"),L}function m(){let L=x(),N=null,D=[];if(a(B.Equals))++r,N=x();else{for(s(B.CloseStatement,"Expected %} token");!i("endset");)D.push(o());s(B.OpenStatement,"Expected {% token"),n("endset")}return s(B.CloseStatement,"Expected closing statement token"),new tL(L,N,D)}function _(){let L=E();s(B.CloseStatement,"Expected closing statement token");let N=[],D=[];for(;!i("elif","else","endif");)N.push(o());if(i("elif")){++r,++r;let J=_();D.push(J)}else if(i("else"))for(++r,++r,s(B.CloseStatement,"Expected closing statement token");!i("endif");)D.push(o());return new QP(L,N,D)}function w(){let L=ae();if(L.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let N=U();s(B.CloseStatement,"Expected closing statement token");let D=[];for(;!i("endmacro");)D.push(o());return new rL(L,N,D)}function x(L=!1){let N=L?ae:E,D=[N()],J=a(B.Comma);for(;J&&(++r,D.push(N()),!!a(B.Comma)););return J?new EE(D):D[0]}function b(){let L=x(!0);if(!(L instanceof sn||L instanceof EE))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 N=E();s(B.CloseStatement,"Expected closing statement token");let D=[];for(;!i("endfor","else");)D.push(o());let J=[];if(i("else"))for(++r,++r,s(B.CloseStatement,"Expected closing statement token");!i("endfor");)J.push(o());return new JP(L,N,D,J)}function E(){return A()}function A(){let L=S();if(l("if")){++r;let N=S();if(l("else")){++r;let D=A();return new wL(N,L,D)}else return new pL(L,N)}return L}function S(){let L=M();for(;l("or");){let N=t[r];++r;let D=M();L=new lo(N,L,D)}return L}function M(){let L=P();for(;l("and");){let N=t[r];++r;let D=P();L=new lo(N,L,D)}return L}function P(){let L;for(;l("not");){let N=t[r];++r;let D=P();L=new dL(N,D)}return L??O()}function O(){let L=k();for(;;){let N;if(l("not","in"))N=new Ut("not in",B.Identifier),r+=2;else if(l("in"))N=t[r++];else if(a(B.ComparisonBinaryOperator))N=t[r++];else break;let D=k();L=new lo(N,L,D)}return L}function k(){let L=$();for(;a(B.AdditiveBinaryOperator);){let N=t[r];++r;let D=$();L=new lo(N,L,D)}return L}function W(){let L=K(ae());return a(B.OpenParen)?X(L):L}function X(L){let N=new vE(L,U());return N=K(N),a(B.OpenParen)&&(N=X(N)),N}function U(){s(B.OpenParen,"Expected opening parenthesis for arguments list");let L=H();return s(B.CloseParen,"Expected closing parenthesis for arguments list"),L}function H(){let L=[];for(;!a(B.CloseParen);){let N;if(t[r].type===B.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let D=E();N=new hL(D)}else if(N=E(),a(B.Equals)){if(++r,!(N instanceof sn))throw new SyntaxError("Expected identifier for keyword argument");let D=E();N=new _L(N,D)}L.push(N),a(B.Comma)&&++r}return L}function j(){let L=[],N=!1;for(;!a(B.CloseSquareBracket);)a(B.Colon)?(L.push(void 0),++r,N=!0):(L.push(E()),a(B.Colon)&&(++r,N=!0));if(L.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(L.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new mL(...L)}return L[0]}function K(L){for(;a(B.Dot)||a(B.OpenSquareBracket);){let N=t[r];++r;let D,J=N.type===B.OpenSquareBracket;if(J)D=j(),s(B.CloseSquareBracket,"Expected closing square bracket");else if(D=ae(),D.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");L=new nL(L,D,J)}return L}function $(){let L=C();for(;a(B.MultiplicativeBinaryOperator);){let N=t[r++],D=C();L=new lo(N,L,D)}return L}function C(){let L=te();for(;l("is");){++r;let N=l("not");N&&++r;let D=ae();if(!(D instanceof sn))throw new SyntaxError("Expected identifier for the test");L=new fL(L,N,D)}return L}function te(){let L=W();for(;a(B.Pipe);){++r;let N=ae();if(!(N instanceof sn))throw new SyntaxError("Expected identifier for the filter");a(B.OpenParen)&&(N=X(N)),L=new cL(L,N)}return L}function ae(){let L=t[r++];switch(L.type){case B.NumericLiteral:{let N=L.value;return N.includes(".")?new aL(Number(N)):new oL(Number(N))}case B.StringLiteral:{let N=L.value;for(;a(B.StringLiteral);)N+=t[r++].value;return new kE(N)}case B.Identifier:return new sn(L.value);case B.OpenParen:{let N=x();return s(B.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),N}case B.OpenSquareBracket:{let N=[];for(;!a(B.CloseSquareBracket);)N.push(E()),a(B.Comma)&&++r;return++r,new iL(N)}case B.OpenCurlyBracket:{let N=new Map;for(;!a(B.CloseCurlyBracket);){let D=E();s(B.Colon,"Expected colon between key and value in object literal");let J=E();N.set(D,J),a(B.Comma)&&++r}return++r,new lL(N)}default:throw new SyntaxError(`Unexpected token: ${L.type}`)}}for(;r<t.length;)e.body.push(o());return e}function yL(t,e,r=1){if(e===void 0&&(e=t,t=0),r===0)throw new Error("range() step must not be zero");let s=[];if(r>0)for(let n=t;n<e;n+=r)s.push(n);else for(let n=t;n>e;n+=r)s.push(n);return s}function AE(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*a<n*r;a+=s)o.push(t[a]);return o}function bL(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function vL(t){return kL(new Date,t)}function kL(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 EL(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function AL(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(EL(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var TE=class extends Error{},ME=class extends Error{},lr=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 lr{type="IntegerValue"},Qe=class extends lr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},ee=class extends lr{type="StringValue";builtins=new Map([["upper",new je(()=>new ee(this.value.toUpperCase()))],["lower",new je(()=>new ee(this.value.toLowerCase()))],["strip",new je(()=>new ee(this.value.trim()))],["title",new je(()=>new ee(bL(this.value)))],["capitalize",new je(()=>new ee(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new _e(this.value.length)],["rstrip",new je(()=>new ee(this.value.trimEnd()))],["lstrip",new je(()=>new ee(this.value.trimStart()))],["startswith",new je(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof ee)return new pe(this.value.startsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof ee))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 je(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof ee)return new pe(this.value.endsWith(e.value));if(e instanceof ye){for(let r of e.value){if(!(r instanceof ee))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 je(t=>{let e=t[0]??new We;if(!(e instanceof ee||e instanceof We))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 We){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 ee(n)))})],["replace",new je(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof ee&&r instanceof ee))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 We:s=t[2]:s=new We,!(s instanceof _e||s instanceof We))throw new Error("replace() count argument must be a number or null");return new ee(AL(this.value,e.value,r.value,s.value))})]])},pe=class extends lr{type="BooleanValue"},TL=/[\x7f-\uffff]/g;function SE(t){return t.replace(TL,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function _s(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let p=JSON.stringify(t.value);return o&&(p=SE(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",f=`
|
|
5
|
+
`+p.repeat(r),m=f+p;if(t.type==="ArrayValue"){let _=t.value.map(w=>_s(w,e,r+1,s));return n?`[${m}${_.join(`${l}${m}`)}${f}]`:`[${_.join(l)}]`}else{let _=Array.from(t.value.entries());i&&(_=_.sort(([x],[b])=>x.localeCompare(b)));let w=_.map(([x,b])=>{let E=JSON.stringify(x);o&&(E=SE(E));let A=`${E}${c}${_s(b,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 lr{type="ObjectValue";__bool__(){return new pe(this.value.size>0)}builtins=new Map([["get",new je(([t,e])=>{if(!(t instanceof ee))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new We})],["items",new je(()=>this.items())],["keys",new je(()=>this.keys())],["values",new je(()=>this.values())],["dictsort",new je(t=>{let e=new Map,r=t.filter(i=>i instanceof co?(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 ee("key");if(!(n instanceof ee))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 ee(i),l])).sort((i,l)=>{let c=n.value==="key"?0:1,p=i.value[c],f=l.value[c],m=yf(p,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 ee(t),e])))}keys(){return new ye(Array.from(this.value.keys()).map(t=>new ee(t)))}values(){return new ye(Array.from(this.value.values()))}toString(){return _s(this,{},0,!1)}},co=class extends ct{type="KeywordArgumentsValue"},ye=class extends lr{type="ArrayValue";builtins=new Map([["length",new _e(this.value.length)]]);__bool__(){return new pe(this.value.length>0)}toString(){return _s(this,{},0,!1)}},OE=class extends ye{type="TupleValue"},je=class extends lr{type="FunctionValue"},We=class extends lr{type="NullValue"},Ge=class extends lr{type="UndefinedValue"},ms=class{constructor(t){this.parent=t}variables=new Map([["namespace",new je(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 je],["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 Qe],["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 ee],["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,Kl(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 Ge}catch{return new Ge}}};function ML(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",yL),t.set("strftime_now",vL),t.set("True",!0),t.set("False",!1),t.set("None",null)}function IE(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof ct)s=s.value.get(n)??new Ge;else if(s instanceof ye){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&o<s.value.length)s=s.value[o];else return new Ge}else return new Ge;return s}function yf(t,e,r=!1){if(t instanceof We&&e instanceof We)return 0;if(t instanceof We||e instanceof We)throw new Error(`Cannot compare ${t.type} with ${e.type}`);if(t instanceof Ge&&e instanceof Ge)return 0;if(t instanceof Ge||e instanceof Ge)throw new Error(`Cannot compare ${t.type} with ${e.type}`);let s=o=>o instanceof _e||o instanceof Qe||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 o<a?-1:o>a?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()),o<a?-1:o>a?1:0}else throw new Error(`Cannot compare type: ${t.type}`)}var SL=class{global;constructor(t){this.global=t??new ms}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 Ge||s instanceof Ge){if(s instanceof Ge&&["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 We||s instanceof We)throw new Error("Cannot perform operation on null values");if(t.operator.value==="~")return new ee(r.value.toString()+s.value.toString());if((r instanceof _e||r instanceof Qe)&&(s instanceof _e||s instanceof Qe)){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 Qe||s instanceof Qe?new Qe(a):new _e(a)}case"/":return new Qe(n/o);case"%":{let a=n%o;return r instanceof Qe||s instanceof Qe?new Qe(a):new _e(a)}case"<":return new pe(n<o);case">":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 ee||s instanceof ee)&&t.operator.value==="+")return new ee(r.value.toString()+s.value.toString());if(r instanceof ee&&s instanceof ee)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 ee&&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 ee(_s(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)=>yf(n,o,!1)));case"join":return new ee(t.value.map(n=>n.value).join(""));case"string":return new ee(_s(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 ee)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=t.builtins.get(s.value);if(n instanceof je)return n.value([],r);if(n instanceof _e)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new ee(t.value.trim());case"indent":return new ee(t.value.split(`
|
|
6
6
|
`).map((n,o)=>o===0||n.length===0?n:" "+n).join(`
|
|
7
|
-
`));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 Qe(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof _e||t instanceof Qe)switch(s.value){case"abs":return t instanceof _e?new _e(Math.abs(t.value)):new Qe(Math.abs(t.value));case"int":return new _e(Math.floor(t.value));case"float":return new Qe(t.value);case"string":return new ee(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 ee(n),o])));case"length":return new _e(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof je?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 Qe(t.value?1:0);case"string":return new ee(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 We;if(!(a instanceof _e||a instanceof We))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 We,p=null;if(c instanceof ye||c instanceof
|
|
8
|
-
`),
|
|
9
|
-
`))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof je))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new
|
|
10
|
-
`,kL="{%- ",EL=" -%}";function AL(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 TL(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Yt(t.body,0,r).replace(/\n$/,"")}function wt(...t){return kL+t.join(" ")+EL}function Yt(t,e,r){return t.map(s=>ML(s,e,r)).join(rt)}function ML(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Yt(t.body,e,r);case"If":return SL(t,e,r);case"For":return OL(t,e,r);case"Set":return IL(t,e,r);case"Macro":return CL(t,e,r);case"Break":return s+wt("break");case"Continue":return s+wt("continue");case"CallStatement":return PL(t,e,r);case"FilterStatement":return LL(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ve(t)+" -}}"}}function SL(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",ve(n[0].test))+rt+Yt(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=rt+s+wt("elif",ve(n[i].test))+rt+Yt(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=rt+s+wt("else")+rt+Yt(o.alternate,e+1,r)),a+=rt+s+wt("endif"),a}function OL(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ve(a.lhs)} if ${ve(a.test)}`}else n=ve(t.iterable);let o=s+wt("for",ve(t.loopvar),"in",n)+rt+Yt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=rt+s+wt("else")+rt+Yt(t.defaultBlock,e+1,r)),o+=rt+s+wt("endfor"),o}function IL(t,e,r){let s=r.repeat(e),n=ve(t.assignee),o=t.value?ve(t.value):"",a=s+wt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+rt+Yt(t.body,e+1,r)+rt+s+wt("endset")}function CL(t,e,r){let s=r.repeat(e),n=t.args.map(ve).join(", ");return s+wt("macro",`${t.name.value}(${n})`)+rt+Yt(t.body,e+1,r)+rt+s+wt("endmacro")}function PL(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ve).join(", ")})`:"",o=ve(t.call),a=s+wt(`call${n}`,o)+rt;return a+=Yt(t.body,e+1,r)+rt,a+=s+wt("endcall"),a}function LL(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ve(t.filter),o=s+wt("filter",n)+rt;return o+=Yt(t.body,e+1,r)+rt,o+=s+wt("endfilter"),o}function ve(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ve(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=AL(r),n=ve(r.left,s),o=ve(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s<e?`(${a})`:a}case"UnaryExpression":{let r=t;return r.operator.value+(r.operator.value==="not"?" ":"")+ve(r.argument,1/0)}case"CallExpression":{let r=t,s=r.args.map(ve).join(", ");return`${ve(r.callee)}(${s})`}case"MemberExpression":{let r=t,s=ve(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ve(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{let r=t,s=ve(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ve(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{let r=t;return`${ve(r.lhs)} if ${ve(r.test)}`}case"TestExpression":{let r=t;return`${ve(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=t.value.map(ve),s=t.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([s,n])=>`${ve(s)}: ${ve(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ve(r.start):"",n=r.stop?ve(r.stop):"",o=r.step?`:${ve(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ve(r.value)}`}case"Ternary":{let r=t,s=`${ve(r.trueExpr)} if ${ve(r.condition,0)} else ${ve(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var AE=class{parsed;constructor(t){let e=jP(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=fL(e)}render(t){let e=new fs;if(bL(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new vL(e).run(this.parsed).value}format(t){return TL(this.parsed,t?.indent||" ")}};var et=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")}};var zL={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"},Cr=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",zL[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 cn=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[TE(this._random_fn,r)]}};function TE(t,e){let r=0;for(let n=0;n<e.length;++n)r+=e[n];let s=t()*r;for(let n=0;n<e.length;++n)if(s-=e[n],s<0)return n;return e.length-1}var lr=new cn,_s=Object.freeze({Random:cn,seed:lr.seed.bind(lr),random:lr.random.bind(lr),gauss:lr.gauss.bind(lr),shuffle:lr.shuffle.bind(lr),choices:lr.choices.bind(lr)}),ME=t=>TE(_s.random,t);var NL=new cn,un=class{constructor(e){this.path=e}async match(e){let r=Dt.join(this.path,e),s=new Cr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Dt.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=NL._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await ht.promises.mkdir(Dt.dirname(n),{recursive:!0});let d=ht.createWriteStream(i),m=r.body.getReader();for(;;){let{done:_,value:w}=await m.read();if(_)break;await new Promise((k,b)=>{d.write(w,A=>{if(A){b(A);return}k()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,total:c})}await new Promise((_,w)=>{d.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=Dt.join(this.path,e);try{return await ht.promises.unlink(r),!0}catch{return!1}}};var SE={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"},rc=100,OE=/^(\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 Pr(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 IE(t){return!(!OE.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function CE(t,e,r){if(!r)return null;let s=SE[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function PE(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&Z.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:p}=await i.read();if(c)return;let d=a+p.length;if(d>n){n=d;let _=new Uint8Array(n);_.set(o),o=_}o.set(p,a),a=d;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}function yd(t){return Pr(t,["blob:"])}function bd(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 zE="SHA-256",RL="experimental_transformers-hash-cache",LE=t=>({algorithm:zE,value:t}),ho=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(RL),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([LE(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([LE(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(zE,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Jt(t=null){let e=null;if(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){Z.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 un(t??me.cacheDir)}return e}async function NE(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var sc=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 $L=100,vd=new sc($L);function nc(t,e){let r=vd.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(vd.delete(t),Promise.reject(n)));return vd.put(t,s),s}async function DL(t){if(!Pr(t,["http:","https:"]))return null;let e=kd(t);return e.set("Range","bytes=0-0"),me.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function cr(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return nc(s,()=>BL(t,e,r))}async function BL(t,e,r){let s=await Jt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=zr(t,e,r,s),l=await Nr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(me.allowLocalModels&&!Pr(n,["http:","https:"]))try{let p=await Lr(n);if(typeof p!="string"&&p.status!==404){let d=p.headers.get("content-length"),m=p.headers.get("content-type");return{exists:!0,size:d?parseInt(d,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(me.allowRemoteModels&&!r.local_files_only&&i)try{let c=await DL(o);if(c&&c.status>=200&&c.status<300){let p,d=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+)/);_&&(p=parseInt(_[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let m=c.headers.get("content-length");p=m?parseInt(m,10):void 0}return{exists:!0,size:p,contentType:d||void 0,fromCache:!1}}}catch(c){Z.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Lr(t){return me.useFS&&!Pr(t,["http:","https:","blob:"])?new Cr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):me.fetch(t,{headers:kd(t)})}function kd(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};`),Pr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function zr(t,e,r={},s=null){let n=r.revision??"main",o=_o(t,e),a=IE(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 un?n==="main"?o:_o(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Nr(t,e,r){if(t)return await NE(t,e,r)}async function UL(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=>{Z.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>yr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function FL(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=zr(t,e,s,o),d,m=!1,_;_=await Nr(o,i,c);let w=_!==void 0;if(!w){if(me.allowLocalModels)if(Pr(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 Lr(i),d=i}catch(A){Z.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(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Lr(l),_.status!==200)return CE(_.status,l,r);d=c}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}yr(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()),yr(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 cr(t,e,s);M.size&&(A=M.size)}catch{}b=await PE(_,M=>{yr(s.progress_callback,{status:"progress",name:t,file:e,...M})},A)}x=b}if(m&&d&&typeof _!="string"&&await UL(t,e,o,d,_,x,s),yr(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 Cr)return _.filePath;let k=await o?.match(d);if(k instanceof Cr)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}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`.")}yr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await Jt(s?.cache_dir);return await FL(t,e,r,s,n,o)}async function Ed(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 Ed(t,e,r,s);return n===null?{}:JSON.parse(n)}function $E(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),d=r*s,m=n*o;for(let _=0;_<n;++_)for(let w=0;w<o;++w){let x=_*o+w,k=(w+.5)/l-.5,b=(_+.5)/c-.5,A=Math.floor(k),S=Math.floor(b),M=Math.min(A+1,s-1),P=Math.min(S+1,r-1);A=Math.max(A,0),S=Math.max(S,0);let O=k-A,E=b-S,W=(1-O)*(1-E),X=O*(1-E),U=(1-O)*E,H=O*E,j=S*s,Y=P*s,$=j+A,C=j+M,te=Y+A,ae=Y+M;for(let L=0;L<e;++L){let N=L*d;p[L*m+x]=W*t[N+$]+X*t[N+C]+U*t[N+te]+H*t[N+ae]}}return p}function DE(t,e,r){let s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=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<t.length;++i){let l=0;for(let c=e.length-1,p=i;c>=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function Ne(t){let e=Oe(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 Td(t){let e=Oe(t)[0],r=0;for(let o=0;o<t.length;++o)r+=Math.exp(t[o]-e);let s=Math.log(r);return t.map(o=>o-e-s)}function BE(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function GL(t,e){let r=BE(t,e),s=RE(t),n=RE(e);return r/(s*n)}function RE(t){return Math.sqrt(t.reduce((e,r)=>e+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;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}function Oe(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]>e&&(e=t[s],r=s);return[e,r]}function UE(t){return t>0&&(t&t-1)===0}var oc=class{constructor(e){if(this.size=e|0,this.size<=1||!UE(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;s<this.table.length;s+=2){let n=Math.PI*s/this.size;this.table[s]=Math.cos(n),this.table[s+1]=-Math.sin(n)}let r=0;for(let s=1;this.size>s;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<<this._width);for(let s=0;s<this._bitrev.length;++s){this._bitrev[s]=0;for(let n=0;n<this._width;n+=2){let o=this._width-n-2;this._bitrev[s]|=(s>>>n&3)<<o}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,r){let s=r||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)s[n>>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n<s.length;n+=2)s[n]=e[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<e.length;++s)e[s]/=this.size}_transform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,c,p=this._bitrev;if(i===4)for(l=0,c=0;l<n;l+=i,++c){let m=p[c];this._singleTransform2(r,e,l,m,a)}else for(l=0,c=0;l<n;l+=i,++c){let m=p[c];this._singleTransform4(r,e,l,m,a,s)}let d=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l<n;l+=i){let _=l+m-1;for(let w=l,x=0;w<_;w+=2,x+=a){let k=w,b=k+m,A=b+m,S=A+m,M=e[k],P=e[k+1],O=e[b],E=e[b+1],W=e[A],X=e[A+1],U=e[S],H=e[S+1],j=d[x],Y=s*d[x+1],$=O*j-E*Y,C=O*Y+E*j,te=d[2*x],ae=s*d[2*x+1],L=W*te-X*ae,N=W*ae+X*te,B=d[3*x],J=s*d[3*x+1],xe=U*B-H*J,ue=U*J+H*B,qe=M+L,ot=P+N,mt=M-L,at=P-N,Et=$+xe,Be=C+ue,Te=s*($-xe),Ze=s*(C-ue);e[k]=qe+Et,e[k+1]=ot+Be,e[b]=mt+Ze,e[b+1]=at-Te,e[A]=qe-Et,e[A+1]=ot-Be,e[S]=mt-Ze,e[S+1]=at+Te}}}}_singleTransform2(e,r,s,n,o){let a=e[n],i=e[n+1],l=e[n+o],c=e[n+o+1];r[s]=a+l,r[s+1]=i+c,r[s+2]=a-l,r[s+3]=i-c}_singleTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+1],d=e[n+o],m=e[n+o+1],_=e[n+i],w=e[n+i+1],x=e[n+l],k=e[n+l+1],b=c+_,A=p+w,S=c-_,M=p-w,P=d+x,O=m+k,E=a*(d-x),W=a*(m-k);r[s]=b+P,r[s+1]=A+O,r[s+2]=S+W,r[s+3]=M-E,r[s+4]=b-P,r[s+5]=A-O,r[s+6]=S-W,r[s+7]=M+E}_realTransform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,c,p=this._bitrev;if(i===4)for(l=0,c=0;l<n;l+=i,++c){let _=p[c];this._singleRealTransform2(r,e,l,_>>>1,a>>>1)}else for(l=0,c=0;l<n;l+=i,++c){let _=p[c];this._singleRealTransform4(r,e,l,_>>>1,a>>>1,s)}let d=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<n;l+=i)for(let k=0,b=0;k<=x;k+=2,b+=a){let A=l+k,S=A+w,M=S+w,P=M+w,O=e[A],E=e[A+1],W=e[S],X=e[S+1],U=e[M],H=e[M+1],j=e[P],Y=e[P+1],$=O,C=E,te=d[b],ae=s*d[b+1],L=W*te-X*ae,N=W*ae+X*te,B=d[2*b],J=s*d[2*b+1],xe=U*B-H*J,ue=U*J+H*B,qe=d[3*b],ot=s*d[3*b+1],mt=j*qe-Y*ot,at=j*ot+Y*qe,Et=$+xe,Be=C+ue,Te=$-xe,Ze=C-ue,sr=L+mt,Le=N+at,Ue=s*(L-mt),Qs=s*(N-at);if(e[A]=Et+sr,e[A+1]=Be+Le,e[S]=Te+Qs,e[S+1]=Ze-Ue,k===0){e[M]=Et-sr,e[M+1]=Be-Le;continue}if(k===x)continue;let so=l+w-k,Js=l+_-k;e[so]=Te-s*Qs,e[so+1]=-Ze-s*Ue,e[Js]=Et-s*sr,e[Js+1]=-Be+s*Le}}let m=n>>>1;for(let _=2;_<m;_+=2)e[n-_]=e[_],e[n-_+1]=-e[_+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+o],d=e[n+i],m=e[n+l],_=c+d,w=c-d,x=p+m,k=a*(p-m);r[s]=_+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=_-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},Ad=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p<s>>1;++p){let d=(p+1-e)**2/2,m=Math.sqrt(l**2+c**2)**d,_=d*Math.atan2(c,l),w=2*p;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 oc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let d=0;d<c.length;d+=2){let m=d+1,_=d>>1,w=r[_];n[d]=w*c[d],n[m]=w*c[m]}else for(let d=0;d<c.length;d+=2){let m=d+1;n[d]=r[d]*c[d]-r[m]*c[m],n[m]=r[d]*c[m]+r[m]*c[d]}this._f.transform(a,n);for(let d=0;d<l.length;d+=2){let m=d+1;o[d]=a[d]*l[d]-a[m]*l[m],o[m]=a[d]*l[m]+a[m]*l[d]}this._f.inverseTransform(i,o);for(let d=0;d<i.length;d+=2){let m=i[d+p],_=i[d+p+1],w=c[d],x=c[d+1];e[d]=m*w-_*x,e[d+1]=m*x+_*w}}transform(e,r){this._transform(e,r,!1)}realTransform(e,r){this._transform(e,r,!0)}},ac=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=UE(e),this.isPowerOfTwo?(this.fft=new oc(e),this.outputBufferSize=2*e):(this.fft=new Ad(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function FE(t,e){if(e%2===0||e<=0)throw new Error("Window size must be a positive odd number");let r=new t.constructor(t.length),s=new t.constructor(e),n=Math.floor(e/2);for(let o=0;o<t.length;++o){let a=0;for(let i=-n;i<=n;++i){let l=o+i;l<0?l=Math.abs(l):l>=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function hs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function GE(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function jE(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let p=1;p<s[1];++p)for(let d=1;d<s[0];++d){let m=n[d-1][p-1],_=n[d-1][p],w=n[d][p-1],x,k;m<_&&m<w?(x=m,k=0):_<m&&_<w?(x=_,k=1):(x=w,k=2),n[d][p]=t[d-1][p-1]+x,o[d][p]=k}for(let p=0;p<s[1];++p)o[0][p]=2;for(let p=0;p<s[0];++p)o[p][0]=1;let a=e,i=r,l=[],c=[];for(;a>0||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 qE=(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<t.length;++l){let c=0,p=(l&32768)<<16,d=(l&31744)>>10,m=l&1023;if(d===31)c=p|2139095040|m<<13;else if(d===0)if(m===0)c=p;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,c=p|_<<23|m<<13}else c=p|d+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;o<r;++o)n[o]=s[e[o]];return n}})();var Md={};ds(Md,{default:()=>jL});var jL={};var wf={};ds(wf,{InferenceSession:()=>rf,TRACE:()=>_c,TRACE_EVENT_BEGIN:()=>Ur,TRACE_EVENT_END:()=>Fr,TRACE_FUNC_BEGIN:()=>vs,TRACE_FUNC_END:()=>ks,Tensor:()=>Zt,default:()=>wz,env:()=>Ve,registerBackend:()=>bs});var ef=Object.defineProperty,qL=Object.getOwnPropertyDescriptor,WL=Object.getOwnPropertyNames,VL=Object.prototype.hasOwnProperty,HL=(t=>typeof ps<"u"?ps:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof ps<"u"?ps:e)[r]}):t)(function(t){if(typeof ps<"u")return ps.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)ef(t,r,{get:e[r],enumerable:!0})},XL=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of WL(e))!VL.call(t,n)&&n!==r&&ef(t,n,{get:()=>e[n],enumerable:!(s=qL(e,n))||s.enumerable});return t},mc=t=>XL(ef({},"__esModule",{value:!0}),t),xo,Rr,bs,WE,wA,xA=be(()=>{"use strict";xo=new Map,Rr=[],bs=(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=Rr.indexOf(t);n!==-1&&Rr.splice(n,1);for(let o=0;o<Rr.length;o++)if(xo.get(Rr[o]).priority<=r){Rr.splice(o,0,t);return}Rr.push(t)}return}throw new TypeError("not a valid backend")},WE=async t=>{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}}},wA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Rr:r,n,o=[],a=new Set;for(let l of s){let c=await WE(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)})]}}),KL=be(()=>{"use strict";xA()}),yA,YL=be(()=>{"use strict";yA="1.24.0-dev.20251116-b39e144322"}),Sd,pt,bA=be(()=>{"use strict";YL(),Sd="warning",pt={wasm:{},webgl:{},webgpu:{},versions:{common:yA},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}`);Sd=t}},get logLevel(){return Sd}},Object.defineProperty(pt,"logLevel",{enumerable:!0})}),Ve,QL=be(()=>{"use strict";bA(),Ve=pt}),vA,kA,JL=be(()=>{"use strict";vA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,d=0,m=p,_=p*2,w=-1;a==="RGBA"?(d=0,m=p,_=p*2,w=p*3):a==="RGB"?(d=0,m=p,_=p*2):a==="RBG"&&(d=0,_=p,m=p*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let b=(t.data[d++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[_++]-c[2])*l[2],M=w===-1?255:(t.data[w++]-c[3])*l[3];s.fillStyle="rgba("+b+","+A+","+S+","+M+")",s.fillRect(k,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},kA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=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,k=3,b=0,A=d,S=d*2,M=-1;i==="RGBA"?(b=0,A=d,S=d*2,M=d*3):i==="RGB"?(b=0,A=d,S=d*2):i==="RBG"&&(b=0,S=d,A=d*2),s=r.createImageData(n,o);for(let P=0;P<o*n;_+=m,w+=m,x+=m,k+=m,P++)s.data[_]=(t.data[b++]-p[0])*c[0],s.data[w]=(t.data[A++]-p[1])*c[1],s.data[x]=(t.data[S++]-p[2])*c[2],s.data[k]=M===-1?255:(t.data[M++]-p[3])*c[3]}else throw new Error("Can not access image data");return s}}),ic,EA,AA,TA,MA,SA,ZL=be(()=>{"use strict";tf(),ic=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,m=0,_=1,w=2,x=3,k=0,b=c,A=c*2,S=-1;i==="RGB"&&(d=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,A=c,b=c*2):l==="BGR"&&(A=0,b=c,k=c*2);for(let M=0;M<c;M++,m+=d,w+=d,_+=d,x+=d)p[k++]=(t[m]+a[0])/o[0],p[b++]=(t[_]+a[1])/o[1],p[A++]=(t[w]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new Nt("float32",p,[1,4,r,s]):new Nt("float32",p,[1,3,r,s])},EA=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let d=c(p);if(d!=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=_;d.drawImage(t,0,0),a=d.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,d=e.resizedWidth):(p=t.height,d=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=d,e!==void 0){let m=l();m.width=d,m.height=p;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let d=c(p);if(d!=null){let m=t.height,_=t.width;return d.drawImage(t,0,0,_,m),a=d.getImageData(0,0,_,m).data,i.height=m,i.width=_,ic(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{let m=l(),_=c(m);if(!t||!_)return d();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,p(ic(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return ic(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},AA=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Nt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},TA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},MA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},SA=(t,e,r)=>new Nt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),xs,Eo,Od,OA,ez=be(()=>{"use strict";xs=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"]]),Od=!1,OA=()=>{if(!Od){Od=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(xs.set("int64",BigInt64Array),Eo.set(BigInt64Array,"int64")),e&&(xs.set("uint64",BigUint64Array),Eo.set(BigUint64Array,"uint64")),s?(xs.set("float16",r),Eo.set(r,"float16")):xs.set("float16",Uint16Array)}}}),IA,CA,tz=be(()=>{"use strict";tf(),IA=t=>{let e=1;for(let r=0;r<t.length;r++){let s=t[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);e*=s}return e},CA=(t,e)=>{switch(t.location){case"cpu":return new Nt(t.type,t.data,e);case"cpu-pinned":return new Nt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Nt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Nt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Nt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Nt,tf=be(()=>{"use strict";JL(),ZL(),ez(),tz(),Nt=class{constructor(t,e,r){OA();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=xs.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=xs.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=IA(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 EA(t,e)}static fromTexture(t,e){return AA(t,e)}static fromGpuBuffer(t,e){return TA(t,e)}static fromMLTensor(t,e){return MA(t,e)}static fromPinnedBuffer(t,e,r){return SA(t,e,r)}toDataURL(t){return vA(this,t)}toImageData(t){return kA(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 CA(this,t)}}}),Zt,PA=be(()=>{"use strict";tf(),Zt=Nt}),_c,Id,vs,ks,Ur,Fr,LA=be(()=>{"use strict";bA(),_c=(t,e)=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Id=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n<r.length;n++){if(s&&!r[n].includes("TRACE_FUNC")){let o=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(o+=`::${e}`),_c("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},vs=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||Id("BEGIN",t)},ks=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||Id("END",t)},Ur=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.time(`ORT::${t}`)},Fr=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeEnd(`ORT::${t}`)}}),zA,rz=be(()=>{"use strict";xA(),PA(),LA(),zA=class NA{constructor(e){this.handler=e}async run(e,r,s){vs(),Ur("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Zt||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 Zt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let m=r[d];(m===null||m instanceof Zt)&&(c=!0,a=!1,n[d]=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 p=i[c];p instanceof Zt?l[c]=p:l[c]=new Zt(p.type,p.data,p.dims)}return Fr("InferenceSession.run"),ks(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){vs(),Ur("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,d=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(d=r,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(m=e.byteLength-d,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||d+m>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,d,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await wA(a),c=await i.createInferenceSessionHandler(o,l);return Fr("InferenceSession.create"),ks(),new NA(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}}}),rf,sz=be(()=>{"use strict";rz(),rf=zA}),nz=be(()=>{"use strict"}),oz=be(()=>{"use strict"}),az=be(()=>{"use strict"}),iz=be(()=>{"use strict"}),RA={};To(RA,{InferenceSession:()=>rf,TRACE:()=>_c,TRACE_EVENT_BEGIN:()=>Ur,TRACE_EVENT_END:()=>Fr,TRACE_FUNC_BEGIN:()=>vs,TRACE_FUNC_END:()=>ks,Tensor:()=>Zt,env:()=>Ve,registerBackend:()=>bs});var Es=be(()=>{"use strict";KL(),QL(),sz(),PA(),nz(),oz(),LA(),az(),iz()}),sf=be(()=>{"use strict"}),$A={};To($A,{default:()=>DA});var Cd,Pd,DA,lz=be(()=>{"use strict";ZA(),As(),nf(),Cd="ort-wasm-proxy-worker",Pd=globalThis.self?.name===Cd,Pd&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":of(r.wasm).then(()=>{pf(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;df(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=wc(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;ff(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":mf(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;_f(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},gf([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":hf(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),DA=Pd?null:t=>new Worker(t??Lt,{type:"module",name:Cd})}),BA={};To(BA,{default:()=>UA});async function VE(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,f)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,f)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let o=()=>{let u=f=>(...h)=>{let g=or;return h=f(...h),or!=g?new Promise((v,T)=>{Vp={resolve:v,reject:T}}):h};(()=>{for(let f of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[f]=u(e[f])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,f)=>{throw f},c=import.meta.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var f=new XMLHttpRequest;return f.open("GET",u,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),a=async u=>{if(O(u))return new Promise((h,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):g(v.status)},v.onerror=g,v.send(null)});var f=await fetch(u,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)}}var d,m,_,w,x,k,b=console.log.bind(console),A=console.error.bind(console),S=b,M=A,P=!1,O=u=>u.startsWith("file://");function E(){Or.buffer!=U.buffer&&xe()}if(n){let u=function(f){try{var h=f.data,g=h.Oc;if(g==="load"){let v=[];self.onmessage=T=>v.push(T),k=()=>{postMessage({Oc:"loaded"});for(let T of v)u(T);self.onmessage=u};for(let T of h.de)e[T]&&!e[T].proxy||(e[T]=(...I)=>{postMessage({Oc:"callHandler",ce:T,args:I})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));Or=h.je,xe(),m=h.ke,mt(),Hl()}else if(g==="run"){(function(v){var T=(E(),C)[v+52>>>2>>>0];v=(E(),C)[v+56>>>2>>>0],Jv(T,T-v),le(T)})(h.Nc),nd(h.Nc,0,0,1,0,0),B1(),jp(h.Nc),X||(zv(),X=!0);try{hM(h.he,h.Wc)}catch(v){if(v!="unwind")throw v}}else h.target!=="setimmediate"&&(g==="checkMailbox"?X&&Bl():g&&(M(`worker: received unknown command ${g}`),M(h)))}catch(v){throw Hv(),v}};var W=u,X=!1;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=u}var U,H,j,Y,$,C,te,ae,L,N,B,J=!1;function xe(){var u=Or.buffer;e.HEAP8=U=new Int8Array(u),j=new Int16Array(u),e.HEAPU8=H=new Uint8Array(u),Y=new Uint16Array(u),e.HEAP32=$=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),te=new Float32Array(u),ae=new Float64Array(u),L=new BigInt64Array(u),N=new BigUint64Array(u)}function ue(){J=!0,n?k():xr._b()}function qe(u){throw M(u="Aborted("+u+")"),P=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function ot(){return{a:{f:gM,J:wM,k:xM,p:yM,l:bM,ta:vM,b:kM,ca:EM,Ka:W1,s:AM,da:K1,_a:Y1,Ga:Q1,Ia:J1,$a:Z1,Ya:ev,Ra:tv,Xa:rv,pa:sv,Ha:nv,Yb:ov,Za:av,Fa:iv,eb:TM,Da:SM,Tb:OM,Rb:CM,Ca:LM,M:zM,I:NM,Sb:RM,ka:jM,Ub:qM,Ua:WM,Wb:HM,La:XM,Pb:KM,la:YM,Ta:jp,bb:QM,U:tS,n:aS,c:Fp,sb:iS,w:lS,L:cS,z:uS,j:pS,o:_v,tb:dS,G:fS,T:mS,h:_S,u:hS,m:gS,i:wS,Oa:xS,Pa:yS,Qa:bS,Ma:xv,Na:yv,Qb:bv,fb:kS,db:TS,Y:MS,rb:SS,ma:OS,cb:ES,gb:IS,ab:CS,Xb:PS,N:vS,hb:LS,X:zS,Vb:NS,ob:qS,C:WS,sa:VS,ra:HS,qb:XS,W:KS,v:YS,nb:QS,mb:JS,lb:ZS,pb:eO,kb:tO,jb:rO,ib:sO,Va:Mv,Wa:Sv,Ja:Js,ea:Ov,oa:Iv,Sa:Cv,na:Pv,Db:fI,xa:oI,Eb:dI,ya:nI,F:XO,e:NO,r:LO,x:PO,D:WO,Ib:tI,ba:ZO,B:$O,za:rI,$:aI,ha:eI,Fb:uI,Gb:cI,Ba:KO,Aa:JO,Jb:YO,wa:pI,aa:sI,d:RO,A:DO,q:zO,Cb:mI,t:UO,y:VO,H:BO,E:FO,K:HO,S:iI,ja:qO,_:lI,Kb:jO,Lb:GO,P:QO,g:oO,a:Or,Ob:Qs,Hb:aO,ia:iO,O:lO,qa:cO,Mb:uO,Q:pO,zb:dO,Ab:fO,ua:mO,fa:_O,R:hO,Ea:gO,va:wO,Z:xO,xb:yO,Zb:bO,V:vO,Bb:kO,ub:EO,vb:TO,wb:MO,ga:SO,yb:OO,Nb:IO}}}async function mt(){function u(g,v){var T=xr=g.exports;g={};for(let[I,z]of Object.entries(T))typeof z=="function"?(T=JM(z),g[I]=T):g[I]=z;return xr=g,xr=(function(){var I=xr,z=Q=>Me=>Q(Me)>>>0,F=Q=>()=>Q()>>>0;return(I=Object.assign({},I)).$b=z(I.$b),I.Cc=F(I.Cc),I.Ec=z(I.Ec),I.rd=(Q=>(Me,ze)=>Q(Me,ze)>>>0)(I.rd),I.wd=z(I.wd),I.xd=F(I.xd),I.Bd=z(I.Bd),I})(),$1.push(xr.id),Lv=(g=xr).$b,zv=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,Jp=e._OrtGetWebGpuDevice=g.Bc,Wl=g.Cc,Ht=e._free=g.Dc,sn=e._malloc=g.Ec,Nv=e._wgpuBufferRelease=g.Fc,Rv=e._wgpuCreateInstance=g.Gc,$v=g.Hc,Dv=g.Ic,Bv=g.Jc,Uv=g.Kc,Fv=g.Lc,Gv=g.Pc,jv=g.Zc,qv=g._c,Wv=g.$c,Zp=g.bd,ed=g.cd,td=g.dd,rd=g.ed,io=g.fd,sd=g.gd,Vv=g.hd,nd=g.kd,Hv=g.ld,Xv=g.md,Kv=g.nd,od=g.od,Yv=g.pd,Qv=g.qd,ad=g.rd,we=g.sd,lo=g.td,Jv=g.ud,le=g.vd,Vl=g.wd,ce=g.xd,Zv=g.yd,id=g.zd,ek=g.Ad,tk=g.Bd,rk=g.Cd,ld=g.Dd,sk=g.Ed,nk=g.Fd,ok=g.Gd,ak=g.Hd,ik=g.Id,lk=g.Jd,ck=g.Kd,uk=g.Ld,pk=g.Md,dk=g.Nd,fk=g.Od,mk=g.Pd,_k=g.Qd,hk=g.Rd,gk=g.Td,wk=g.Ud,xk=g.Vd,yk=g.Wd,bk=g.Yd,vk=g.Zd,kk=g._d,Ek=g.$d,Ak=g.ae,Tk=g.be,Mk=g.pe,Sk=g.qe,Ok=g.re,Ik=g.se,Ck=g.te,Pk=g.ue,Lk=g.ve,zk=g.we,Nk=g.xe,Rk=g.ye,$k=g.ze,Dk=g.Xe,Bk=g.Ye,Uk=g.Ze,Fk=g._e,m=v,xr}var f,h=ot();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(v,T)=>{g(u(v,T))})}):n?u(new WebAssembly.Instance(m,ot()),m):(B??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,f=await(async function(g){var v=B;if(!d&&!O(v))try{var T=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(I){M(`wasm streaming compile failed: ${I}`),M("falling back to ArrayBuffer instantiation")}return(async function(I,z){try{var F=await(async function(Q){if(!d)try{var Me=await a(Q);return new Uint8Array(Me)}catch{}if(Q==B&&d)Q=new Uint8Array(d);else{if(!i)throw"both async and sync fetching of the wasm failed";Q=i(Q)}return Q})(I);return await WebAssembly.instantiate(F,z)}catch(Q){M(`failed to asynchronously prepare wasm: ${Q}`),qe(Q)}})(v,g)})(h),u(f.instance,f.module))}class at{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var Et=u=>{u.terminate(),u.onmessage=()=>{}},Be=[],Te=0,Ze=null,sr=u=>{Sr.length==0&&(F1(),U1(Sr[0]));var f=Sr.pop();if(!f)return 6;no.push(f),ls[u.Nc]=f,f.Nc=u.Nc;var h={Oc:"run",he:u.ge,Wc:u.Wc,Nc:u.Nc};return f.postMessage(h,u.Yc),0},Le=0,Ue=(u,f,...h)=>{var g,v=16*h.length,T=ce(),I=Vl(v),z=I>>>3;for(g of h)typeof g=="bigint"?((E(),L)[z++>>>0]=1n,(E(),L)[z++>>>0]=g):((E(),L)[z++>>>0]=0n,(E(),ae)[z++>>>0]=g);return u=Xv(u,0,v,I,f),le(T),u};function Qs(u){if(n)return Ue(0,1,u);if(_=u,!(0<Le)){for(var f of no)Et(f);for(f of Sr)Et(f);Sr=[],no=[],ls={},P=!0}l(0,new at(u))}function so(u){if(n)return Ue(1,0,u);Js(u)}var Js=u=>{if(_=u,n)throw so(u),"unwind";Qs(u)},Sr=[],no=[],$1=[],ls={},D1=u=>{var f=u.Nc;delete ls[f],Sr.push(u),no.splice(no.indexOf(u),1),u.Nc=0,Kv(f)};function B1(){$1.forEach(u=>u())}var U1=u=>new Promise(f=>{u.onmessage=v=>{var T=v.data;if(v=T.Oc,T.Vc&&T.Vc!=Wl()){var I=ls[T.Vc];I?I.postMessage(T,T.Yc):M(`Internal error! Worker sent a message "${v}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?Bl():v==="spawnThread"?sr(T):v==="cleanupThread"?Tt(()=>{D1(ls[T.ie])}):v==="loaded"?(u.loaded=!0,f(u)):T.target==="setimmediate"?u.postMessage(T):v==="uncaughtException"?u.onerror(T.error):v==="callHandler"?e[T.ce](...T.args):v&&M(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw M(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);u.postMessage({Oc:"load",de:g,je:Or,ke:m})});function F1(){var u=new Worker((()=>{let f=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new f("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Sr.push(u)}var Or,hM=(u,f)=>{Le=0,u=ld(u,f),0<Le?_=u:od(u)},$l=[],Dl=0,At=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function gM(u){var f=new $p(u>>>=0);return(E(),U)[f.Qc+12>>>0]==0&&(G1(f,!0),Dl--),j1(f,!1),$l.push(f),tk(u)}var Zs=0,wM=()=>{we(0,0);var u=$l.pop();Zv(u.Xc),Zs=0};function G1(u,f){f=f?1:0,(E(),U)[u.Qc+12>>>0]=f}function j1(u,f){f=f?1:0,(E(),U)[u.Qc+13>>>0]=f}class $p{constructor(f){this.Xc=f,this.Qc=f-24}}var Dp=u=>{var f=Zs;if(!f)return lo(0),0;var h=new $p(f);(E(),C)[h.Qc+16>>>2>>>0]=f;var g=(E(),C)[h.Qc+4>>>2>>>0];if(!g)return lo(0),f;for(var v of u){if(v===0||v===g)break;if(ek(v,g,h.Qc+16))return lo(v),f}return lo(g),f};function xM(){return Dp([])}function yM(u){return Dp([u>>>0])}function bM(u,f,h,g){return Dp([u>>>0,f>>>0,h>>>0,g>>>0])}var vM=()=>{var u=$l.pop();u||qe("no exception to throw");var f=u.Xc;throw(E(),U)[u.Qc+13>>>0]==0&&($l.push(u),j1(u,!0),G1(u,!1),Dl++),id(f),Zs=f};function kM(u,f,h){var g=new $p(u>>>=0);throw f>>>=0,h>>>=0,(E(),C)[g.Qc+16>>>2>>>0]=0,(E(),C)[g.Qc+4>>>2>>>0]=f,(E(),C)[g.Qc+8>>>2>>>0]=h,id(u),Dl++,Zs=u}var EM=()=>Dl;function q1(u,f,h,g){return n?Ue(2,1,u,f,h,g):W1(u,f,h,g)}function W1(u,f,h,g){if(u>>>=0,f>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?q1(u,f,h,g):(u={ge:h,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):sr(u))}function AM(u){throw Zs||=u>>>0,Zs}var V1=globalThis.TextDecoder&&new TextDecoder,H1=(u,f,h,g)=>{if(h=f+h,g)return h;for(;u[f]&&!(f>=h);)++f;return f},X1=(u,f=0,h,g)=>{if(16<(h=H1(u,f>>>=0,h,g))-f&&u.buffer&&V1)return V1.decode(u.buffer instanceof ArrayBuffer?u.subarray(f,h):u.slice(f,h));for(g="";f<h;){var v=u[f++];if(128&v){var T=63&u[f++];if((224&v)==192)g+=String.fromCharCode((31&v)<<6|T);else{var I=63&u[f++];65536>(v=(240&v)==224?(15&v)<<12|T<<6|I:(7&v)<<18|T<<12|I<<6|63&u[f++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},en=(u,f,h)=>(u>>>=0)?X1((E(),H),u,f,h):"";function K1(u,f,h){return n?Ue(3,1,u,f,h):0}function Y1(u,f){if(n)return Ue(4,1,u,f)}function Q1(u,f){if(n)return Ue(5,1,u,f)}function J1(u,f,h){if(n)return Ue(6,1,u,f,h)}function Z1(u,f,h){return n?Ue(7,1,u,f,h):0}function ev(u,f){if(n)return Ue(8,1,u,f)}function tv(u,f,h){if(n)return Ue(9,1,u,f,h)}function rv(u,f,h,g){if(n)return Ue(10,1,u,f,h,g)}function sv(u,f,h,g){if(n)return Ue(11,1,u,f,h,g)}function nv(u,f,h,g){if(n)return Ue(12,1,u,f,h,g)}function ov(u){if(n)return Ue(13,1,u)}function av(u,f){if(n)return Ue(14,1,u,f)}function iv(u,f,h){if(n)return Ue(15,1,u,f,h)}var TM=()=>qe(""),nr=u=>{u>>>=0;for(var f="";;){var h=(E(),H)[u++>>>0];if(!h)return f;f+=String.fromCharCode(h)}},Bp={},Up={},MM={},tn=class extends Error{constructor(u){super(u),this.name="BindingError"}};function mr(u,f,h={}){return(function(g,v,T={}){var I=v.name;if(!g)throw new tn(`type "${I}" must have a positive integer typeid pointer`);if(Up.hasOwnProperty(g)){if(T.ee)return;throw new tn(`Cannot register type '${I}' twice`)}Up[g]=v,delete MM[g],Bp.hasOwnProperty(g)&&(v=Bp[g],delete Bp[g],v.forEach(z=>z()))})(u,f,h)}var lv=(u,f,h)=>{switch(f){case 1:return h?g=>(E(),U)[g>>>0]:g=>(E(),H)[g>>>0];case 2:return h?g=>(E(),j)[g>>>1>>>0]:g=>(E(),Y)[g>>>1>>>0];case 4:return h?g=>(E(),$)[g>>>2>>>0]:g=>(E(),C)[g>>>2>>>0];case 8:return h?g=>(E(),L)[g>>>3>>>0]:g=>(E(),N)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${f}): ${u}`)}};function SM(u,f,h,g,v){u>>>=0,h>>>=0,f=nr(f>>>0);let T=I=>I;if(g=g===0n){let I=8*h;T=z=>BigInt.asUintN(I,z),v=T(v)}mr(u,{name:f,Mc:T,Sc:(I,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Rc:lv(f,h,!g),Tc:null})}function OM(u,f,h,g){mr(u>>>=0,{name:f=nr(f>>>0),Mc:function(v){return!!v},Sc:function(v,T){return T?h:g},Rc:function(v){return this.Mc((E(),H)[v>>>0])},Tc:null})}var cv=[],cs=[0,1,,1,null,1,!0,1,!1,1];function Fp(u){9<(u>>>=0)&&--cs[u+1]==0&&(cs[u]=void 0,cv.push(u))}var $t=u=>{if(!u)throw new tn(`Cannot use deleted val. handle = ${u}`);return cs[u]},Vt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=cv.pop()||cs.length;return cs[f]=u,cs[f+1]=1,f}};function Gp(u){return this.Mc((E(),C)[u>>>2>>>0])}var IM={name:"emscripten::val",Mc:u=>{var f=$t(u);return Fp(u),f},Sc:(u,f)=>Vt(f),Rc:Gp,Tc:null};function CM(u){return mr(u>>>0,IM)}var PM=(u,f)=>{switch(f){case 4:return function(h){return this.Mc((E(),te)[h>>>2>>>0])};case 8:return function(h){return this.Mc((E(),ae)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${u}`)}};function LM(u,f,h){h>>>=0,mr(u>>>=0,{name:f=nr(f>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:PM(f,h),Tc:null})}function zM(u,f,h,g,v){u>>>=0,h>>>=0,f=nr(f>>>0);let T=z=>z;if(g===0){var I=32-8*h;T=z=>z<<I>>>I,v=T(v)}mr(u,{name:f,Mc:T,Sc:(z,F)=>F,Rc:lv(f,h,g!==0),Tc:null})}function NM(u,f,h){function g(T){var I=(E(),C)[T>>>2>>>0];return T=(E(),C)[T+4>>>2>>>0],new v((E(),U).buffer,T,I)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];mr(u>>>=0,{name:h=nr(h>>>0),Mc:g,Rc:g},{ee:!0})}var _r=(u,f,h)=>{var g=(E(),H);if(f>>>=0,0<h){var v=f;h=f+h-1;for(var T=0;T<u.length;++T){var I=u.codePointAt(T);if(127>=I){if(f>=h)break;g[f++>>>0]=I}else if(2047>=I){if(f+1>=h)break;g[f++>>>0]=192|I>>6,g[f++>>>0]=128|63&I}else if(65535>=I){if(f+2>=h)break;g[f++>>>0]=224|I>>12,g[f++>>>0]=128|I>>6&63,g[f++>>>0]=128|63&I}else{if(f+3>=h)break;g[f++>>>0]=240|I>>18,g[f++>>>0]=128|I>>12&63,g[f++>>>0]=128|I>>6&63,g[f++>>>0]=128|63&I,T++}}g[f>>>0]=0,u=f-v}else u=0;return u},hr=u=>{for(var f=0,h=0;h<u.length;++h){var g=u.charCodeAt(h);127>=g?f++:2047>=g?f+=2:55296<=g&&57343>=g?(f+=4,++h):f+=3}return f};function RM(u,f){mr(u>>>=0,{name:f=nr(f>>>0),Mc(h){var g=(E(),C)[h>>>2>>>0];return g=en(h+4,g,!0),Ht(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new tn("Cannot pass non-string to std::string");var T=v?hr(g):g.length,I=sn(4+T+1),z=I+4;return(E(),C)[I>>>2>>>0]=T,v?_r(g,z,T+1):(E(),H).set(g,z>>>0),h!==null&&h.push(Ht,I),I},Rc:Gp,Tc(h){Ht(h)}})}var uv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,$M=(u,f,h)=>{if(u>>>=1,16<(f=H1((E(),Y),u,f/2,h))-u&&uv)return uv.decode((E(),Y).slice(u,f));for(h="";u<f;++u){var g=(E(),Y)[u>>>0];h+=String.fromCharCode(g)}return h},DM=(u,f,h)=>{if(h??=2147483647,2>h)return 0;var g=f;h=(h-=2)<2*u.length?h/2:u.length;for(var v=0;v<h;++v){var T=u.charCodeAt(v);(E(),j)[f>>>1>>>0]=T,f+=2}return(E(),j)[f>>>1>>>0]=0,f-g},BM=u=>2*u.length,UM=(u,f,h)=>{var g="";u>>>=2;for(var v=0;!(v>=f/4);v++){var T=(E(),C)[u+v>>>0];if(!T&&!h)break;g+=String.fromCodePoint(T)}return g},FM=(u,f,h)=>{if(f>>>=0,h??=2147483647,4>h)return 0;var g=f;h=g+h-4;for(var v=0;v<u.length;++v){var T=u.codePointAt(v);if(65535<T&&v++,(E(),$)[f>>>2>>>0]=T,(f+=4)+4>h)break}return(E(),$)[f>>>2>>>0]=0,f-g},GM=u=>{for(var f=0,h=0;h<u.length;++h)65535<u.codePointAt(h)&&h++,f+=4;return f};function jM(u,f,h){if(u>>>=0,f>>>=0,h=nr(h>>>=0),f===2)var g=$M,v=DM,T=BM;else g=UM,v=FM,T=GM;mr(u,{name:h,Mc:I=>{var z=(E(),C)[I>>>2>>>0];return z=g(I+4,z*f,!0),Ht(I),z},Sc:(I,z)=>{if(typeof z!="string")throw new tn(`Cannot pass non-string to C++ string type ${h}`);var F=T(z),Q=sn(4+F+f);return(E(),C)[Q>>>2>>>0]=F/f,v(z,Q+4,F+f),I!==null&&I.push(Ht,Q),Q},Rc:Gp,Tc(I){Ht(I)}})}function qM(u,f){mr(u>>>=0,{fe:!0,name:f=nr(f>>>0),Mc:()=>{},Sc:()=>{}})}function WM(u){nd(u>>>0,!s,1,!r,131072,!1),B1()}var Tt=u=>{if(!P)try{if(u(),!(0<Le))try{n?Wl()&&od(_):Js(_)}catch(f){f instanceof at||f=="unwind"||l(0,f)}}catch(f){f instanceof at||f=="unwind"||l(0,f)}},VM=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function jp(u){u>>>=0,VM||(Atomics.waitAsync((E(),$),u>>>2,u).value.then(Bl),u+=128,Atomics.store((E(),$),u>>>2,1))}var Bl=()=>Tt(()=>{var u=Wl();u&&(jp(u),Qv())});function HM(u,f){(u>>>=0)==f>>>0?setTimeout(Bl):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=ls[u])&&u.postMessage({Oc:"checkMailbox"})}var qp=[];function XM(u,f,h,g,v){for(f>>>=0,v>>>=0,qp.length=0,h=v>>>3,g=v+g>>>3;h<g;){var T;T=(E(),L)[h++>>>0]?(E(),L)[h++>>>0]:(E(),ae)[h++>>>0],qp.push(T)}return(f?cd[f]:CO[u])(...qp)}var KM=()=>{Le=0};function YM(u){u>>>=0,n?postMessage({Oc:"cleanupThread",ie:u}):D1(ls[u])}function QM(u){}var Ul=u=>{try{u()}catch(f){qe(f)}};function JM(u){var f=(...h)=>{Fl.push(u);try{return u(...h)}finally{P||(Fl.pop(),or&&Ir===1&&Fl.length===0&&(Ir=0,Le+=1,Ul(Bk),typeof Fibers<"u"&&Fibers.De()))}};return fv.set(u,f),f}var Ir=0,or=null,pv=0,Fl=[],Wp=new Map,dv=new Map,fv=new Map,ZM=0,Vp=null,eS=[],mv=u=>(function(f){if(!P){if(Ir===0){var h=!1,g=!1;f((v=0)=>{if(!P&&(pv=v,h=!0,g)){Ir=2,Ul(()=>Uk(or)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var T=(function(){var F=(E(),$)[or+8>>>2>>>0];return F=dv.get(F),F=fv.get(F),--Le,F()})()}catch(F){T=F,v=!0}var I=!1;if(!or){var z=Vp;z&&(Vp=null,(v?z.reject:z.resolve)(T),I=!0)}if(v&&!I)throw T}}),g=!0,h||(Ir=1,or=(function(){var v=sn(65548),T=v+12;if((E(),C)[v>>>2>>>0]=T,(E(),C)[v+4>>>2>>>0]=T+65536,T=Fl[0],!Wp.has(T)){var I=ZM++;Wp.set(T,I),dv.set(I,T)}return T=Wp.get(T),(E(),$)[v+8>>>2>>>0]=T,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),Ul(()=>Dk(or)))}else Ir===2?(Ir=0,Ul(Fk),Ht(or),or=null,eS.forEach(Tt)):qe(`invalid state: ${Ir}`);return pv}})(f=>{u().then(f)});function tS(u){return u>>>=0,mv(async()=>{var f=await $t(u);return Vt(f)})}var Hp=[],rS=u=>{var f=Hp.length;return Hp.push(u),f},sS=(u,f)=>{for(var h=Array(u),g=0;g<u;++g){var v=g,T=(E(),C)[f+4*g>>>2>>>0],I=Up[T];if(I===void 0)throw u=`parameter ${g}`,T=Lv(T),f=nr(T),Ht(T),new tn(`${u} has unknown type ${f}`);h[v]=I}return h},nS=(u,f,h)=>{var g=[];return u=u(g,h),g.length&&((E(),C)[f>>>2>>>0]=Vt(g)),u},oS={},Gl=u=>{var f=oS[u];return f===void 0?nr(u):f};function aS(u,f,h){var[g,...v]=sS(u,f>>>0);f=g.Sc.bind(g);var T=v.map(F=>F.Rc.bind(F));u--;var I={toValue:$t};switch(u=T.map((F,Q)=>{var Me=`argFromPtr${Q}`;return I[Me]=F,`${Me}(args${Q?"+"+8*Q:""})`}),h){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:I.getStringOrSymbol=Gl,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${u})`,g.fe||(I.toReturnWire=f,I.emval_returnValue=nS,z=`return emval_returnValue(toReturnWire, destructorsRef, ${z})`),z=`return function (handle, methodName, destructorsRef, args) {
|
|
7
|
+
`));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 Qe(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof _e||t instanceof Qe)switch(s.value){case"abs":return t instanceof _e?new _e(Math.abs(t.value)):new Qe(Math.abs(t.value));case"int":return new _e(Math.floor(t.value));case"float":return new Qe(t.value);case"string":return new ee(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 ee(n),o])));case"length":return new _e(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof je?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 Qe(t.value?1:0);case"string":return new ee(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 We;if(!(a instanceof _e||a instanceof We))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 We,p=null;if(c instanceof ye||c instanceof OE){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.value;if(!(f instanceof ee)||!(m instanceof ee))throw new Error("separators must be a tuple of two strings");p=[f.value,m.value]}else if(!(c instanceof We))throw new Error("If set, separators must be a tuple of two strings");return new ee(_s(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:p}))}else if(n==="join"){let o;if(t instanceof ee)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 ee("");if(!(l instanceof ee))throw new Error("separator must be a string");return new ee(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 Qe(0));if(t instanceof ee){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new _e(l):new Qe(l)}else{if(t instanceof _e||t instanceof Qe)return t;if(t instanceof pe)return n==="int"?new _e(t.value?1:0):new Qe(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 ee(""),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 Ge||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 We;if(!(c instanceof ee||c instanceof _e||c instanceof We))throw new Error("attribute must be a string, integer, or null");let p=f=>{if(c instanceof We)return f;let m=c instanceof _e?String(c.value):c.value;return IE(f,m)};return new ye(t.value.slice().sort((f,m)=>{let _=p(f),w=p(m),x=yf(_,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 p=t.value.filter(f=>{let m=f.value.get(a.value),_=m?c(m,l):!1;return o?_:!_});return new ye(p)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof ee))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 p=IE(c,a.value);return p instanceof Ge?i??new Ge:p});return new ye(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof ee){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),p=t.value.split(`
|
|
8
|
+
`),f=" ".repeat(i.value),m=p.map((_,w)=>!l.value&&w===0||!c.value&&_.length===0?_:f+_);return new ee(m.join(`
|
|
9
|
+
`))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof je))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new co(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ct){let o=t.builtins.get(n);if(o&&o instanceof je){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new co(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 Ge}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 ee(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 co(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 ee))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 Ge))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof _e||n instanceof Ge))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof _e||o instanceof Ge))throw new Error("Slice step must be numeric or undefined");return t instanceof ye?new ye(AE(t.value,s.value,n.value,o.value)):new ee(AE(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 ee(t.property.value);let n;if(r instanceof ct){if(!(s instanceof ee))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 ee)if(s instanceof _e)n=r.value.at(s.value),r instanceof ee&&(n=new ee(r.value.at(s.value)));else if(s instanceof ee)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 ee))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof lr?n:new Ge}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<s.value.length;++o){let a=s.value[o];if(a.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${a.type}`);e.setVariable(a.value,n[o])}}else if(t.assignee.type==="MemberExpression"){let s=t.assignee,n=this.evaluate(s.object,e);if(!(n instanceof ct))throw new Error("Cannot assign to member of non-object");if(s.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(s.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new We}evaluateIf(t,e){let r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){let r=new ms(e),s,n;if(t.iterable.type==="SelectExpression"){let c=t.iterable;n=this.evaluate(c.lhs,r),s=c.test}else n=this.evaluate(t.iterable,r);if(!(n instanceof ye||n instanceof ct))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof ct&&(n=n.keys());let o=[],a=[];for(let c=0;c<n.value.length;++c){let p=new ms(r),f=n.value[c],m;if(t.loopvar.type==="Identifier")m=_=>_.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 b=0;b<_.value.length;++b){if(_.value[b].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_.value[b].type}`);x.setVariable(_.value[b].value,w.value[b])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(p),!this.evaluate(s,p).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let c=0;c<o.length;++c){let p=new Map([["index",new _e(c+1)],["index0",new _e(c)],["revindex",new _e(o.length-c)],["revindex0",new _e(o.length-c-1)],["first",new pe(c===0)],["last",new pe(c===o.length-1)],["length",new _e(o.length)],["previtem",c>0?o[c-1]:new Ge],["nextitem",c<o.length-1?o[c+1]:new Ge]]);r.setVariable("loop",new ct(p)),a[c](r);try{let f=this.evaluateBlock(t.body,r);i+=f.value}catch(f){if(f instanceof ME)continue;if(f instanceof TE)break;throw f}l=!1}if(l){let c=this.evaluateBlock(t.defaultBlock,r);i+=c.value}return new ee(i)}evaluateMacro(t,e){return e.setVariable(t.name.value,new je((r,s)=>{let n=new ms(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a<t.args.length;++a){let i=t.args[a],l=r[a];if(i.type==="Identifier"){let c=i;if(!l)throw new Error(`Missing positional argument: ${c.value}`);n.setVariable(c.value,l)}else if(i.type==="KeywordArgumentExpression"){let c=i,p=l??o?.value.get(c.key.value)??this.evaluate(c.value,n);n.setVariable(c.key.value,p)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(t.body,n)})),new We}evaluateCallStatement(t,e){let r=new je((i,l)=>{let c=new ms(l);if(t.callerArgs)for(let p=0;p<t.callerArgs.length;++p){let f=t.callerArgs[p];if(f.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${f.type}`);c.setVariable(f.value,i[p]??new Ge)}return this.evaluateBlock(t.body,c)}),[s,n]=this.evaluateArguments(t.call.args,e);s.push(new co(n));let o=this.evaluate(t.call.callee,e);if(o.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${o.type}`);let a=new ms(e);return a.setVariable("caller",r),o.value(s,a)}evaluateFilterStatement(t,e){let r=this.evaluateBlock(t.body,e);return this.applyFilter(r,t.filter,e)}evaluate(t,e){if(!t)return new Ge;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"CallStatement":return this.evaluateCallStatement(t,e);case"Break":throw new TE;case"Continue":throw new ME;case"IntegerLiteral":return new _e(t.value);case"FloatLiteral":return new Qe(t.value);case"StringLiteral":return new ee(t.value);case"ArrayLiteral":return new ye(t.value.map(r=>this.evaluate(r,e)));case"TupleLiteral":return new OE(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 ee))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 We;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Kl(t){switch(typeof t){case"number":return Number.isInteger(t)?new _e(t):new Qe(t);case"string":return new ee(t);case"boolean":return new pe(t);case"undefined":return new Ge;case"object":return t===null?new We:Array.isArray(t)?new ye(t.map(Kl)):new ct(new Map(Object.entries(t).map(([e,r])=>[e,Kl(r)])));case"function":return new je((e,r)=>{let s=t(...e.map(n=>n.value))??null;return Kl(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var rt=`
|
|
10
|
+
`,OL="{%- ",IL=" -%}";function CL(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 PL(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Qt(t.body,0,r).replace(/\n$/,"")}function wt(...t){return OL+t.join(" ")+IL}function Qt(t,e,r){return t.map(s=>LL(s,e,r)).join(rt)}function LL(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Qt(t.body,e,r);case"If":return zL(t,e,r);case"For":return NL(t,e,r);case"Set":return RL(t,e,r);case"Macro":return $L(t,e,r);case"Break":return s+wt("break");case"Continue":return s+wt("continue");case"CallStatement":return BL(t,e,r);case"FilterStatement":return DL(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ve(t)+" -}}"}}function zL(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",ve(n[0].test))+rt+Qt(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=rt+s+wt("elif",ve(n[i].test))+rt+Qt(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=rt+s+wt("else")+rt+Qt(o.alternate,e+1,r)),a+=rt+s+wt("endif"),a}function NL(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ve(a.lhs)} if ${ve(a.test)}`}else n=ve(t.iterable);let o=s+wt("for",ve(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 RL(t,e,r){let s=r.repeat(e),n=ve(t.assignee),o=t.value?ve(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 $L(t,e,r){let s=r.repeat(e),n=t.args.map(ve).join(", ");return s+wt("macro",`${t.name.value}(${n})`)+rt+Qt(t.body,e+1,r)+rt+s+wt("endmacro")}function BL(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ve).join(", ")})`:"",o=ve(t.call),a=s+wt(`call${n}`,o)+rt;return a+=Qt(t.body,e+1,r)+rt,a+=s+wt("endcall"),a}function DL(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ve(t.filter),o=s+wt("filter",n)+rt;return o+=Qt(t.body,e+1,r)+rt,o+=s+wt("endfilter"),o}function ve(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ve(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=CL(r),n=ve(r.left,s),o=ve(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s<e?`(${a})`:a}case"UnaryExpression":{let r=t;return r.operator.value+(r.operator.value==="not"?" ":"")+ve(r.argument,1/0)}case"CallExpression":{let r=t,s=r.args.map(ve).join(", ");return`${ve(r.callee)}(${s})`}case"MemberExpression":{let r=t,s=ve(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ve(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{let r=t,s=ve(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ve(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{let r=t;return`${ve(r.lhs)} if ${ve(r.test)}`}case"TestExpression":{let r=t;return`${ve(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=t.value.map(ve),s=t.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([s,n])=>`${ve(s)}: ${ve(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ve(r.start):"",n=r.stop?ve(r.stop):"",o=r.step?`:${ve(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ve(r.value)}`}case"Ternary":{let r=t,s=`${ve(r.trueExpr)} if ${ve(r.condition,0)} else ${ve(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var CE=class{parsed;constructor(t){let e=KP(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=xL(e)}render(t){let e=new ms;if(ML(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new SL(e).run(this.parsed).value}format(t){return PL(this.parsed,t?.indent||" ")}};var et=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")}};var UL={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"},Cr=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",UL[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 on=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[PE(this._random_fn,r)]}};function PE(t,e){let r=0;for(let n=0;n<e.length;++n)r+=e[n];let s=t()*r;for(let n=0;n<e.length;++n)if(s-=e[n],s<0)return n;return e.length-1}var cr=new on,hs=Object.freeze({Random:on,seed:cr.seed.bind(cr),random:cr.random.bind(cr),gauss:cr.gauss.bind(cr),shuffle:cr.shuffle.bind(cr),choices:cr.choices.bind(cr)}),LE=t=>PE(hs.random,t);var FL=new on,an=class{constructor(e){this.path=e}async match(e){let r=Bt.join(this.path,e),s=new Cr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Bt.join(this.path,e),o=ie.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=FL._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),p=0;await ht.promises.mkdir(Bt.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((b,E)=>{f.write(w,A=>{if(A){E(A);return}b()})}),p+=w.length;let x=c?p/c*100:0;s?.({progress:x,loaded:p,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=Bt.join(this.path,e);try{return await ht.promises.unlink(r),!0}catch{return!1}}};var zE={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"},Yl=100,NE=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function uo(...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 Pr(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 RE(t){return!(!NE.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function $E(t,e,r){if(!r)return null;let s=zE[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function BE(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&Z.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:p}=await i.read();if(c)return;let f=a+p.length;if(f>n){n=f;let _=new Uint8Array(n);_.set(o),o=_}o.set(p,a),a=f;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}function bf(t){return Pr(t,["blob:"])}function vf(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 UE="SHA-256",GL="experimental_transformers-hash-cache",DE=t=>({algorithm:UE,value:t}),po=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(GL),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([DE(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([DE(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(UE,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&&po.isAvailable()&&(e=new po),!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){Z.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 an(t??me.cacheDir)}return e}async function FE(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var Ql=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 jL=100,kf=new Ql(jL);function Jl(t,e){let r=kf.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(kf.delete(t),Promise.reject(n)));return kf.put(t,s),s}async function qL(t){if(!Pr(t,["http:","https:"]))return null;let e=Ef(t);return e.set("Range","bytes=0-0"),me.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Ft(t,e,r={}){let s=JSON.stringify([t,e,r?.revision,r?.cache_dir,r?.local_files_only]);return Jl(s,()=>WL(t,e,r))}async function WL(t,e,r){let s=await Zt(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=zr(t,e,r,s),l=await Nr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),p=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:p||void 0,fromCache:!0}}if(me.allowLocalModels&&!Pr(n,["http:","https:"]))try{let p=await Lr(n);if(typeof p!="string"&&p.status!==404){let f=p.headers.get("content-length"),m=p.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 qL(o);if(c&&c.status>=200&&c.status<300){let p,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+)/);_&&(p=parseInt(_[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(p===void 0){let m=c.headers.get("content-length");p=m?parseInt(m,10):void 0}return{exists:!0,size:p,contentType:f||void 0,fromCache:!1}}}catch(c){Z.warn(`Unable to fetch file metadata for "${o}": ${c}`)}return{exists:!1,fromCache:!1}}async function Lr(t){return me.useFS&&!Pr(t,["http:","https:","blob:"])?new Cr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):me.fetch(t,{headers:Ef(t)})}function Ef(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};`),Pr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function zr(t,e,r={},s=null){let n=r.revision??"main",o=uo(t,e),a=RE(t),i=a?uo(me.localModelPath,o):o,l=uo(me.remoteHost,me.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof an?n==="main"?o:uo(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Nr(t,e,r){if(t)return await FE(t,e,r)}async function VL(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=>{Z.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>yr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function HL(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=zr(t,e,s,o),f,m=!1,_;_=await Nr(o,i,c);let w=_!==void 0;if(!w){if(me.allowLocalModels)if(Pr(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 Lr(i),f=i}catch(A){Z.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(!p)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Lr(l),_.status!==200)return $E(_.status,l,r);f=c}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}yr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(ie.IS_NODE_ENV&&n)){let E;if(typeof _!="string")if(!s.progress_callback)E=new Uint8Array(await _.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))E=new Uint8Array(await _.arrayBuffer()),yr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:E.length,total:E.length});else{let A,S=_.headers.get("content-length");if(S)A=parseInt(S,10);else try{let M=await Ft(t,e,s);M.size&&(A=M.size)}catch{}E=await BE(_,M=>{yr(s.progress_callback,{status:"progress",name:t,file:e,...M})},A)}x=E}if(m&&f&&typeof _!="string"&&await VL(t,e,o,f,_,x,s),yr(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 Cr)return _.filePath;let b=await o?.match(f);if(b instanceof Cr)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}async function fo(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`.")}yr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await Zt(s?.cache_dir);return await HL(t,e,r,s,n,o)}async function Af(t,e,r=!0,s={}){let n=await fo(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 Af(t,e,r,s);return n===null?{}:JSON.parse(n)}function jE(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,p=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_<n;++_)for(let w=0;w<o;++w){let x=_*o+w,b=(w+.5)/l-.5,E=(_+.5)/c-.5,A=Math.floor(b),S=Math.floor(E),M=Math.min(A+1,s-1),P=Math.min(S+1,r-1);A=Math.max(A,0),S=Math.max(S,0);let O=b-A,k=E-S,W=(1-O)*(1-k),X=O*(1-k),U=(1-O)*k,H=O*k,j=S*s,K=P*s,$=j+A,C=j+M,te=K+A,ae=K+M;for(let L=0;L<e;++L){let N=L*f;p[L*m+x]=W*t[N+$]+X*t[N+C]+U*t[N+te]+H*t[N+ae]}}return p}function qE(t,e,r){let s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=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<t.length;++i){let l=0;for(let c=e.length-1,p=i;c>=0;--c)l+=p%e[c]*o[c],p=Math.floor(p/e[c]);a[l]=t[i]}return[a,s]}function Ne(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 Mf(t){let e=Ce(t)[0],r=0;for(let o=0;o<t.length;++o)r+=Math.exp(t[o]-e);let s=Math.log(r);return t.map(o=>o-e-s)}function WE(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function XL(t,e){let r=WE(t,e),s=GE(t),n=GE(e);return r/(s*n)}function GE(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function mo(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}function Ce(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]>e&&(e=t[s],r=s);return[e,r]}function VE(t){return t>0&&(t&t-1)===0}var Zl=class{constructor(e){if(this.size=e|0,this.size<=1||!VE(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;s<this.table.length;s+=2){let n=Math.PI*s/this.size;this.table[s]=Math.cos(n),this.table[s+1]=-Math.sin(n)}let r=0;for(let s=1;this.size>s;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<<this._width);for(let s=0;s<this._bitrev.length;++s){this._bitrev[s]=0;for(let n=0;n<this._width;n+=2){let o=this._width-n-2;this._bitrev[s]|=(s>>>n&3)<<o}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,r){let s=r||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)s[n>>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n<s.length;n+=2)s[n]=e[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<e.length;++s)e[s]/=this.size}_transform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,c,p=this._bitrev;if(i===4)for(l=0,c=0;l<n;l+=i,++c){let m=p[c];this._singleTransform2(r,e,l,m,a)}else for(l=0,c=0;l<n;l+=i,++c){let m=p[c];this._singleTransform4(r,e,l,m,a,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l<n;l+=i){let _=l+m-1;for(let w=l,x=0;w<_;w+=2,x+=a){let b=w,E=b+m,A=E+m,S=A+m,M=e[b],P=e[b+1],O=e[E],k=e[E+1],W=e[A],X=e[A+1],U=e[S],H=e[S+1],j=f[x],K=s*f[x+1],$=O*j-k*K,C=O*K+k*j,te=f[2*x],ae=s*f[2*x+1],L=W*te-X*ae,N=W*ae+X*te,D=f[3*x],J=s*f[3*x+1],xe=U*D-H*J,ue=U*J+H*D,qe=M+L,ot=P+N,mt=M-L,at=P-N,At=$+xe,De=C+ue,Me=s*($-xe),Ze=s*(C-ue);e[b]=qe+At,e[b+1]=ot+De,e[E]=mt+Ze,e[E+1]=at-Me,e[A]=qe-At,e[A+1]=ot-De,e[S]=mt-Ze,e[S+1]=at+Me}}}}_singleTransform2(e,r,s,n,o){let a=e[n],i=e[n+1],l=e[n+o],c=e[n+o+1];r[s]=a+l,r[s+1]=i+c,r[s+2]=a-l,r[s+3]=i-c}_singleTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+1],f=e[n+o],m=e[n+o+1],_=e[n+i],w=e[n+i+1],x=e[n+l],b=e[n+l+1],E=c+_,A=p+w,S=c-_,M=p-w,P=f+x,O=m+b,k=a*(f-x),W=a*(m-b);r[s]=E+P,r[s+1]=A+O,r[s+2]=S+W,r[s+3]=M-k,r[s+4]=E-P,r[s+5]=A-O,r[s+6]=S-W,r[s+7]=M+k}_realTransform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,c,p=this._bitrev;if(i===4)for(l=0,c=0;l<n;l+=i,++c){let _=p[c];this._singleRealTransform2(r,e,l,_>>>1,a>>>1)}else for(l=0,c=0;l<n;l+=i,++c){let _=p[c];this._singleRealTransform4(r,e,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<n;l+=i)for(let b=0,E=0;b<=x;b+=2,E+=a){let A=l+b,S=A+w,M=S+w,P=M+w,O=e[A],k=e[A+1],W=e[S],X=e[S+1],U=e[M],H=e[M+1],j=e[P],K=e[P+1],$=O,C=k,te=f[E],ae=s*f[E+1],L=W*te-X*ae,N=W*ae+X*te,D=f[2*E],J=s*f[2*E+1],xe=U*D-H*J,ue=U*J+H*D,qe=f[3*E],ot=s*f[3*E+1],mt=j*qe-K*ot,at=j*ot+K*qe,At=$+xe,De=C+ue,Me=$-xe,Ze=C-ue,nr=L+mt,Se=N+at,Ue=s*(L-mt),Xs=s*(N-at);if(e[A]=At+nr,e[A+1]=De+Se,e[S]=Me+Xs,e[S+1]=Ze-Ue,b===0){e[M]=At-nr,e[M+1]=De-Se;continue}if(b===x)continue;let Zn=l+w-b,Ks=l+_-b;e[Zn]=Me-s*Xs,e[Zn+1]=-Ze-s*Ue,e[Ks]=At-s*nr,e[Ks+1]=-De+s*Se}}let m=n>>>1;for(let _=2;_<m;_+=2)e[n-_]=e[_],e[n-_+1]=-e[_+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,c=e[n],p=e[n+o],f=e[n+i],m=e[n+l],_=c+f,w=c-f,x=p+m,b=a*(p-m);r[s]=_+x,r[s+1]=0,r[s+2]=w,r[s+3]=-b,r[s+4]=_-x,r[s+5]=0,r[s+6]=w,r[s+7]=b}},Tf=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),c=Math.sin(i);for(let p=0;p<s>>1;++p){let f=(p+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,_=f*Math.atan2(c,l),w=2*p;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 Zl(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,p=this._a;if(s)for(let f=0;f<c.length;f+=2){let m=f+1,_=f>>1,w=r[_];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f<c.length;f+=2){let m=f+1;n[f]=r[f]*c[f]-r[m]*c[m],n[m]=r[f]*c[m]+r[m]*c[f]}this._f.transform(a,n);for(let f=0;f<l.length;f+=2){let m=f+1;o[f]=a[f]*l[f]-a[m]*l[m],o[m]=a[f]*l[m]+a[m]*l[f]}this._f.inverseTransform(i,o);for(let f=0;f<i.length;f+=2){let m=i[f+p],_=i[f+p+1],w=c[f],x=c[f+1];e[f]=m*w-_*x,e[f+1]=m*x+_*w}}transform(e,r){this._transform(e,r,!1)}realTransform(e,r){this._transform(e,r,!0)}},ec=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=VE(e),this.isPowerOfTwo?(this.fft=new Zl(e),this.outputBufferSize=2*e):(this.fft=new Tf(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function HE(t,e){if(e%2===0||e<=0)throw new Error("Window size must be a positive odd number");let r=new t.constructor(t.length),s=new t.constructor(e),n=Math.floor(e/2);for(let o=0;o<t.length;++o){let a=0;for(let i=-n;i<=n;++i){let l=o+i;l<0?l=Math.abs(l):l>=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function gs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function XE(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function KE(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let p=1;p<s[1];++p)for(let f=1;f<s[0];++f){let m=n[f-1][p-1],_=n[f-1][p],w=n[f][p-1],x,b;m<_&&m<w?(x=m,b=0):_<m&&_<w?(x=_,b=1):(x=w,b=2),n[f][p]=t[f-1][p-1]+x,o[f][p]=b}for(let p=0;p<s[1];++p)o[0][p]=2;for(let p=0;p<s[0];++p)o[p][0]=1;let a=e,i=r,l=[],c=[];for(;a>0||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 YE=(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<t.length;++l){let c=0,p=(l&32768)<<16,f=(l&31744)>>10,m=l&1023;if(f===31)c=p|2139095040|m<<13;else if(f===0)if(m===0)c=p;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,c=p|_<<23|m<<13}else c=p|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;o<r;++o)n[o]=s[e[o]];return n}})();var Sf={};ds(Sf,{default:()=>KL});var KL={};var wd={};ds(wd,{InferenceSession:()=>sd,TRACE:()=>cc,TRACE_EVENT_BEGIN:()=>Ur,TRACE_EVENT_END:()=>Fr,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>er,default:()=>Ez,env:()=>Ve,registerBackend:()=>vs});var td=Object.defineProperty,YL=Object.getOwnPropertyDescriptor,QL=Object.getOwnPropertyNames,JL=Object.prototype.hasOwnProperty,ZL=(t=>typeof fs<"u"?fs:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof fs<"u"?fs:e)[r]}):t)(function(t){if(typeof fs<"u")return fs.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),be=(t,e)=>()=>(t&&(e=t(t=0)),e),vo=(t,e)=>{for(var r in e)td(t,r,{get:e[r],enumerable:!0})},ez=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of QL(e))!JL.call(t,n)&&n!==r&&td(t,n,{get:()=>e[n],enumerable:!(s=YL(e,n))||s.enumerable});return t},lc=t=>ez(td({},"__esModule",{value:!0}),t),_o,Rr,vs,QE,EA,AA=be(()=>{"use strict";_o=new Map,Rr=[],vs=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=_o.get(t);if(s===void 0)_o.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=Rr.indexOf(t);n!==-1&&Rr.splice(n,1);for(let o=0;o<Rr.length;o++)if(_o.get(Rr[o]).priority<=r){Rr.splice(o,0,t);return}Rr.push(t)}return}throw new TypeError("not a valid backend")},QE=async t=>{let e=_o.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}}},EA=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Rr:r,n,o=[],a=new Set;for(let l of s){let c=await QE(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)})]}}),tz=be(()=>{"use strict";AA()}),TA,rz=be(()=>{"use strict";TA="1.24.0-dev.20251116-b39e144322"}),Of,pt,MA=be(()=>{"use strict";rz(),Of="warning",pt={wasm:{},webgl:{},webgpu:{},versions:{common:TA},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}`);Of=t}},get logLevel(){return Of}},Object.defineProperty(pt,"logLevel",{enumerable:!0})}),Ve,sz=be(()=>{"use strict";MA(),Ve=pt}),SA,OA,nz=be(()=>{"use strict";SA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,m=p,_=p*2,w=-1;a==="RGBA"?(f=0,m=p,_=p*2,w=p*3):a==="RGB"?(f=0,m=p,_=p*2):a==="RBG"&&(f=0,_=p,m=p*2);for(let x=0;x<o;x++)for(let b=0;b<n;b++){let E=(t.data[f++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[_++]-c[2])*l[2],M=w===-1?255:(t.data[w++]-c[3])*l[3];s.fillStyle="rgba("+E+","+A+","+S+","+M+")",s.fillRect(b,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},OA=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,E=0,A=f,S=f*2,M=-1;i==="RGBA"?(E=0,A=f,S=f*2,M=f*3):i==="RGB"?(E=0,A=f,S=f*2):i==="RBG"&&(E=0,S=f,A=f*2),s=r.createImageData(n,o);for(let P=0;P<o*n;_+=m,w+=m,x+=m,b+=m,P++)s.data[_]=(t.data[E++]-p[0])*c[0],s.data[w]=(t.data[A++]-p[1])*c[1],s.data[x]=(t.data[S++]-p[2])*c[2],s.data[b]=M===-1?255:(t.data[M++]-p[3])*c[3]}else throw new Error("Can not access image data");return s}}),tc,IA,CA,PA,LA,zA,oz=be(()=>{"use strict";rd(),tc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,E=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(b=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,b=c*2);for(let M=0;M<c;M++,m+=f,w+=f,_+=f,x+=f)p[b++]=(t[m]+a[0])/o[0],p[E++]=(t[_]+a[1])/o[1],p[A++]=(t[w]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new Nt("float32",p,[1,4,r,s]):new Nt("float32",p,[1,3,r,s])},IA=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let 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 p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let m=l();m.width=f,m.height=p;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,tc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,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,p(tc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return tc(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},CA=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Nt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},PA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},LA=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Nt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},zA=(t,e,r)=>new Nt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ys,yo,If,NA,az=be(()=>{"use strict";ys=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),yo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),If=!1,NA=()=>{if(!If){If=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(ys.set("int64",BigInt64Array),yo.set(BigInt64Array,"int64")),e&&(ys.set("uint64",BigUint64Array),yo.set(BigUint64Array,"uint64")),s?(ys.set("float16",r),yo.set(r,"float16")):ys.set("float16",Uint16Array)}}}),RA,$A,iz=be(()=>{"use strict";rd(),RA=t=>{let e=1;for(let r=0;r<t.length;r++){let s=t[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);e*=s}return e},$A=(t,e)=>{switch(t.location){case"cpu":return new Nt(t.type,t.data,e);case"cpu-pinned":return new Nt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Nt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Nt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Nt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Nt,rd=be(()=>{"use strict";nz(),oz(),az(),iz(),Nt=class{constructor(t,e,r){NA();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=ys.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=ys.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=yo.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=RA(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 IA(t,e)}static fromTexture(t,e){return CA(t,e)}static fromGpuBuffer(t,e){return PA(t,e)}static fromMLTensor(t,e){return LA(t,e)}static fromPinnedBuffer(t,e,r){return zA(t,e,r)}toDataURL(t){return SA(this,t)}toImageData(t){return OA(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 $A(this,t)}}}),er,BA=be(()=>{"use strict";rd(),er=Nt}),cc,Cf,ks,Es,Ur,Fr,DA=be(()=>{"use strict";MA(),cc=(t,e)=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Cf=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n<r.length;n++){if(s&&!r[n].includes("TRACE_FUNC")){let o=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(o+=`::${e}`),cc("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},ks=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||Cf("BEGIN",t)},Es=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||Cf("END",t)},Ur=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.time(`ORT::${t}`)},Fr=t=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeEnd(`ORT::${t}`)}}),UA,lz=be(()=>{"use strict";AA(),BA(),DA(),UA=class FA{constructor(e){this.handler=e}async run(e,r,s){ks(),Ur("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof er||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof er)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(p.indexOf(f)!==-1){let 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 p=i[c];p instanceof er?l[c]=p:l[c]=new er(p.type,p.data,p.dims)}return Fr("InferenceSession.run"),Es(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ks(),Ur("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let p=e,f=0,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>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.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>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await EA(a),c=await i.createInferenceSessionHandler(o,l);return Fr("InferenceSession.create"),Es(),new FA(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}}}),sd,cz=be(()=>{"use strict";lz(),sd=UA}),uz=be(()=>{"use strict"}),pz=be(()=>{"use strict"}),fz=be(()=>{"use strict"}),dz=be(()=>{"use strict"}),GA={};vo(GA,{InferenceSession:()=>sd,TRACE:()=>cc,TRACE_EVENT_BEGIN:()=>Ur,TRACE_EVENT_END:()=>Fr,TRACE_FUNC_BEGIN:()=>ks,TRACE_FUNC_END:()=>Es,Tensor:()=>er,env:()=>Ve,registerBackend:()=>vs});var As=be(()=>{"use strict";tz(),sz(),cz(),BA(),uz(),pz(),DA(),fz(),dz()}),nd=be(()=>{"use strict"}),jA={};vo(jA,{default:()=>qA});var Pf,Lf,qA,mz=be(()=>{"use strict";o2(),Ts(),od(),Pf="ort-wasm-proxy-worker",Lf=globalThis.self?.name===Pf,Lf&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":ad(r.wasm).then(()=>{pd(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;fd(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=fc(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;dd(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":md(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;_d(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},gd([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":hd(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),qA=Lf?null:t=>new Worker(t??Lt,{type:"module",name:Pf})}),WA={};vo(WA,{default:()=>VA});async function JE(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(u,d)=>{u.startsWith("./")&&(u=u.substring(2)),(e.Uc||(e.Uc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let o=()=>{let u=d=>(...h)=>{let g=ar;return h=d(...h),ar!=g?new Promise((v,T)=>{Vp={resolve:v,reject:T}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=u(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(u,d)=>{throw d},c=import.meta.url,p="";if(r||s){try{p=new URL(".",c).href}catch{}s&&(i=u=>{var d=new XMLHttpRequest;return d.open("GET",u,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async u=>{if(O(u))return new Promise((h,g)=>{var v=new XMLHttpRequest;v.open("GET",u,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):g(v.status)},v.onerror=g,v.send(null)});var d=await fetch(u,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,_,w,x,b,E=console.log.bind(console),A=console.error.bind(console),S=E,M=A,P=!1,O=u=>u.startsWith("file://");function k(){Or.buffer!=U.buffer&&xe()}if(n){let u=function(d){try{var h=d.data,g=h.Oc;if(g==="load"){let v=[];self.onmessage=T=>v.push(T),b=()=>{postMessage({Oc:"loaded"});for(let T of v)u(T);self.onmessage=u};for(let T of h.de)e[T]&&!e[T].proxy||(e[T]=(...I)=>{postMessage({Oc:"callHandler",ce:T,args:I})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));Or=h.je,xe(),m=h.ke,mt(),Fl()}else if(g==="run"){(function(v){var T=(k(),C)[v+52>>>2>>>0];v=(k(),C)[v+56>>>2>>>0],nk(T,T-v),le(T)})(h.Nc),nf(h.Nc,0,0,1,0,0),W1(),jp(h.Nc),X||(Uv(),X=!0);try{vM(h.he,h.Wc)}catch(v){if(v!="unwind")throw v}}else h.target!=="setimmediate"&&(g==="checkMailbox"?X&&Ll():g&&(M(`worker: received unknown command ${g}`),M(h)))}catch(v){throw Zv(),v}};var W=u,X=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var U,H,j,K,$,C,te,ae,L,N,D,J=!1;function xe(){var u=Or.buffer;e.HEAP8=U=new Int8Array(u),j=new Int16Array(u),e.HEAPU8=H=new Uint8Array(u),K=new Uint16Array(u),e.HEAP32=$=new Int32Array(u),e.HEAPU32=C=new Uint32Array(u),te=new Float32Array(u),ae=new Float64Array(u),L=new BigInt64Array(u),N=new BigUint64Array(u)}function ue(){J=!0,n?b():xr._b()}function qe(u){throw M(u="Aborted("+u+")"),P=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function ot(){return{a:{f:kM,J:EM,k:AM,p:TM,l:MM,ta:SM,b:OM,ca:IM,Ka:Q1,q:CM,da:tv,_a:rv,Ga:sv,Ia:nv,$a:ov,Ya:av,Ra:iv,Xa:lv,pa:cv,Ha:uv,Yb:pv,Za:fv,Fa:dv,eb:PM,Da:zM,Tb:NM,Rb:$M,Ca:DM,M:UM,I:FM,Sb:GM,ka:KM,Ub:YM,Ua:QM,Wb:ZM,La:eS,Pb:tS,la:rS,Ta:jp,bb:sS,U:iS,n:fS,c:Fp,sb:dS,w:mS,L:_S,z:hS,j:gS,o:bv,tb:wS,G:xS,T:yS,h:bS,u:vS,m:kS,i:ES,Oa:AS,Pa:TS,Qa:MS,Ma:Av,Na:Tv,Qb:Mv,fb:OS,db:PS,Y:LS,rb:zS,ma:NS,cb:IS,gb:RS,ab:$S,Xb:BS,N:SS,hb:DS,X:US,Vb:FS,ob:YS,C:QS,sa:JS,ra:ZS,qb:eO,W:tO,v:rO,nb:sO,mb:nO,lb:oO,pb:aO,kb:iO,jb:lO,ib:cO,Va:Lv,Wa:zv,Ja:Ks,ea:Nv,oa:Rv,Sa:$v,na:Bv,Db:xI,xa:pI,Eb:wI,ya:uI,F:eI,e:FO,s:DO,x:BO,D:QO,Ib:iI,ba:oI,B:qO,za:lI,$:fI,ha:aI,Fb:hI,Gb:_I,Ba:tI,Aa:nI,Jb:rI,wa:gI,aa:cI,d:UO,A:jO,r:GO,Cb:yI,t:VO,y:JO,H:WO,E:HO,K:ZO,S:dI,ja:YO,_:mI,Kb:KO,Lb:XO,P:sI,g:pO,a:Or,Ob:Xs,Hb:fO,ia:dO,O:mO,qa:_O,Mb:hO,Q:gO,zb:wO,Ab:xO,ua:yO,fa:bO,R:vO,Ea:kO,va:EO,Z:AO,xb:TO,Zb:MO,V:SO,Bb:OO,ub:IO,vb:PO,wb:LO,ga:zO,yb:NO,Nb:RO}}}async function mt(){function u(g,v){var T=xr=g.exports;g={};for(let[I,z]of Object.entries(T))typeof z=="function"?(T=nS(z),g[I]=T):g[I]=z;return xr=g,xr=(function(){var I=xr,z=Y=>Oe=>Y(Oe)>>>0,F=Y=>()=>Y()>>>0;return(I=Object.assign({},I)).$b=z(I.$b),I.Cc=F(I.Cc),I.Ec=z(I.Ec),I.rd=(Y=>(Oe,ze)=>Y(Oe,ze)>>>0)(I.rd),I.wd=z(I.wd),I.xd=F(I.xd),I.Bd=z(I.Bd),I})(),j1.push(xr.id),Dv=(g=xr).$b,Uv=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,Jp=e._OrtGetWebGpuDevice=g.Bc,Dl=g.Cc,Xt=e._free=g.Dc,en=e._malloc=g.Ec,Fv=e._wgpuBufferRelease=g.Fc,Gv=e._wgpuCreateInstance=g.Gc,jv=g.Hc,qv=g.Ic,Wv=g.Jc,Vv=g.Kc,Hv=g.Lc,Xv=g.Pc,Kv=g.Zc,Yv=g._c,Qv=g.$c,Zp=g.bd,ef=g.cd,tf=g.dd,rf=g.ed,so=g.fd,sf=g.gd,Jv=g.hd,nf=g.kd,Zv=g.ld,ek=g.md,tk=g.nd,of=g.od,rk=g.pd,sk=g.qd,af=g.rd,we=g.sd,no=g.td,nk=g.ud,le=g.vd,Ul=g.wd,ce=g.xd,ok=g.yd,lf=g.zd,ak=g.Ad,ik=g.Bd,lk=g.Cd,cf=g.Dd,ck=g.Ed,uk=g.Fd,pk=g.Gd,fk=g.Hd,dk=g.Id,mk=g.Jd,_k=g.Kd,hk=g.Ld,gk=g.Md,wk=g.Nd,xk=g.Od,yk=g.Pd,bk=g.Qd,vk=g.Rd,kk=g.Td,Ek=g.Ud,Ak=g.Vd,Tk=g.Wd,Mk=g.Yd,Sk=g.Zd,Ok=g._d,Ik=g.$d,Ck=g.ae,Pk=g.be,Lk=g.pe,zk=g.qe,Nk=g.re,Rk=g.se,$k=g.te,Bk=g.ue,Dk=g.ve,Uk=g.we,Fk=g.xe,Gk=g.ye,jk=g.ze,qk=g.Xe,Wk=g.Ye,Vk=g.Ze,Hk=g._e,m=v,xr}var d,h=ot();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(v,T)=>{g(u(v,T))})}):n?u(new WebAssembly.Instance(m,ot()),m):(D??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",p):p+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var v=D;if(!f&&!O(v))try{var T=fetch(v,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(I){M(`wasm streaming compile failed: ${I}`),M("falling back to ArrayBuffer instantiation")}return(async function(I,z){try{var F=await(async function(Y){if(!f)try{var Oe=await a(Y);return new Uint8Array(Oe)}catch{}if(Y==D&&f)Y=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";Y=i(Y)}return Y})(I);return await WebAssembly.instantiate(F,z)}catch(Y){M(`failed to asynchronously prepare wasm: ${Y}`),qe(Y)}})(v,g)})(h),u(d.instance,d.module))}class at{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var At=u=>{u.terminate(),u.onmessage=()=>{}},De=[],Me=0,Ze=null,nr=u=>{Sr.length==0&&(H1(),V1(Sr[0]));var d=Sr.pop();if(!d)return 6;eo.push(d),cs[u.Nc]=d,d.Nc=u.Nc;var h={Oc:"run",he:u.ge,Wc:u.Wc,Nc:u.Nc};return d.postMessage(h,u.Yc),0},Se=0,Ue=(u,d,...h)=>{var g,v=16*h.length,T=ce(),I=Ul(v),z=I>>>3;for(g of h)typeof g=="bigint"?((k(),L)[z++>>>0]=1n,(k(),L)[z++>>>0]=g):((k(),L)[z++>>>0]=0n,(k(),ae)[z++>>>0]=g);return u=ek(u,0,v,I,d),le(T),u};function Xs(u){if(n)return Ue(0,1,u);if(_=u,!(0<Se)){for(var d of eo)At(d);for(d of Sr)At(d);Sr=[],eo=[],cs={},P=!0}l(0,new at(u))}function Zn(u){if(n)return Ue(1,0,u);Ks(u)}var Ks=u=>{if(_=u,n)throw Zn(u),"unwind";Xs(u)},Sr=[],eo=[],j1=[],cs={},q1=u=>{var d=u.Nc;delete cs[d],Sr.push(u),eo.splice(eo.indexOf(u),1),u.Nc=0,tk(d)};function W1(){j1.forEach(u=>u())}var V1=u=>new Promise(d=>{u.onmessage=v=>{var T=v.data;if(v=T.Oc,T.Vc&&T.Vc!=Dl()){var I=cs[T.Vc];I?I.postMessage(T,T.Yc):M(`Internal error! Worker sent a message "${v}" to target pthread ${T.Vc}, but that thread no longer exists!`)}else v==="checkMailbox"?Ll():v==="spawnThread"?nr(T):v==="cleanupThread"?Mt(()=>{q1(cs[T.ie])}):v==="loaded"?(u.loaded=!0,d(u)):T.target==="setimmediate"?u.postMessage(T):v==="uncaughtException"?u.onerror(T.error):v==="callHandler"?e[T.ce](...T.args):v&&M(`worker sent an unknown command ${v}`)},u.onerror=v=>{throw M(`worker sent an error! ${v.filename}:${v.lineno}: ${v.message}`),v};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);u.postMessage({Oc:"load",de:g,je:Or,ke:m})});function H1(){var u=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Sr.push(u)}var Or,vM=(u,d)=>{Se=0,u=cf(u,d),0<Se?_=u:of(u)},Cl=[],Pl=0,Tt=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function kM(u){var d=new $p(u>>>=0);return(k(),U)[d.Qc+12>>>0]==0&&(X1(d,!0),Pl--),K1(d,!1),Cl.push(d),ik(u)}var Ys=0,EM=()=>{we(0,0);var u=Cl.pop();ok(u.Xc),Ys=0};function X1(u,d){d=d?1:0,(k(),U)[u.Qc+12>>>0]=d}function K1(u,d){d=d?1:0,(k(),U)[u.Qc+13>>>0]=d}class $p{constructor(d){this.Xc=d,this.Qc=d-24}}var Bp=u=>{var d=Ys;if(!d)return no(0),0;var h=new $p(d);(k(),C)[h.Qc+16>>>2>>>0]=d;var g=(k(),C)[h.Qc+4>>>2>>>0];if(!g)return no(0),d;for(var v of u){if(v===0||v===g)break;if(ak(v,g,h.Qc+16))return no(v),d}return no(g),d};function AM(){return Bp([])}function TM(u){return Bp([u>>>0])}function MM(u,d,h,g){return Bp([u>>>0,d>>>0,h>>>0,g>>>0])}var SM=()=>{var u=Cl.pop();u||qe("no exception to throw");var d=u.Xc;throw(k(),U)[u.Qc+13>>>0]==0&&(Cl.push(u),K1(u,!0),X1(u,!1),Pl++),lf(d),Ys=d};function OM(u,d,h){var g=new $p(u>>>=0);throw d>>>=0,h>>>=0,(k(),C)[g.Qc+16>>>2>>>0]=0,(k(),C)[g.Qc+4>>>2>>>0]=d,(k(),C)[g.Qc+8>>>2>>>0]=h,lf(u),Pl++,Ys=u}var IM=()=>Pl;function Y1(u,d,h,g){return n?Ue(2,1,u,d,h,g):Q1(u,d,h,g)}function Q1(u,d,h,g){if(u>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var v=[];return n&&v.length===0?Y1(u,d,h,g):(u={ge:h,Nc:u,Wc:g,Yc:v},n?(u.Oc="spawnThread",postMessage(u,v),0):nr(u))}function CM(u){throw Ys||=u>>>0,Ys}var J1=globalThis.TextDecoder&&new TextDecoder,Z1=(u,d,h,g)=>{if(h=d+h,g)return h;for(;u[d]&&!(d>=h);)++d;return d},ev=(u,d=0,h,g)=>{if(16<(h=Z1(u,d>>>=0,h,g))-d&&u.buffer&&J1)return J1.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,h):u.slice(d,h));for(g="";d<h;){var v=u[d++];if(128&v){var T=63&u[d++];if((224&v)==192)g+=String.fromCharCode((31&v)<<6|T);else{var I=63&u[d++];65536>(v=(240&v)==224?(15&v)<<12|T<<6|I:(7&v)<<18|T<<12|I<<6|63&u[d++])?g+=String.fromCharCode(v):(v-=65536,g+=String.fromCharCode(55296|v>>10,56320|1023&v))}}else g+=String.fromCharCode(v)}return g},Qs=(u,d,h)=>(u>>>=0)?ev((k(),H),u,d,h):"";function tv(u,d,h){return n?Ue(3,1,u,d,h):0}function rv(u,d){if(n)return Ue(4,1,u,d)}function sv(u,d){if(n)return Ue(5,1,u,d)}function nv(u,d,h){if(n)return Ue(6,1,u,d,h)}function ov(u,d,h){return n?Ue(7,1,u,d,h):0}function av(u,d){if(n)return Ue(8,1,u,d)}function iv(u,d,h){if(n)return Ue(9,1,u,d,h)}function lv(u,d,h,g){if(n)return Ue(10,1,u,d,h,g)}function cv(u,d,h,g){if(n)return Ue(11,1,u,d,h,g)}function uv(u,d,h,g){if(n)return Ue(12,1,u,d,h,g)}function pv(u){if(n)return Ue(13,1,u)}function fv(u,d){if(n)return Ue(14,1,u,d)}function dv(u,d,h){if(n)return Ue(15,1,u,d,h)}var PM=()=>qe(""),or=u=>{u>>>=0;for(var d="";;){var h=(k(),H)[u++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},Dp={},Up={},LM={},Js=class extends Error{constructor(u){super(u),this.name="BindingError"}};function mr(u,d,h={}){return(function(g,v,T={}){var I=v.name;if(!g)throw new Js(`type "${I}" must have a positive integer typeid pointer`);if(Up.hasOwnProperty(g)){if(T.ee)return;throw new Js(`Cannot register type '${I}' twice`)}Up[g]=v,delete LM[g],Dp.hasOwnProperty(g)&&(v=Dp[g],delete Dp[g],v.forEach(z=>z()))})(u,d,h)}var mv=(u,d,h)=>{switch(d){case 1:return h?g=>(k(),U)[g>>>0]:g=>(k(),H)[g>>>0];case 2:return h?g=>(k(),j)[g>>>1>>>0]:g=>(k(),K)[g>>>1>>>0];case 4:return h?g=>(k(),$)[g>>>2>>>0]:g=>(k(),C)[g>>>2>>>0];case 8:return h?g=>(k(),L)[g>>>3>>>0]:g=>(k(),N)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function zM(u,d,h,g,v){u>>>=0,h>>>=0,d=or(d>>>0);let T=I=>I;if(g=g===0n){let I=8*h;T=z=>BigInt.asUintN(I,z),v=T(v)}mr(u,{name:d,Mc:T,Sc:(I,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Rc:mv(d,h,!g),Tc:null})}function NM(u,d,h,g){mr(u>>>=0,{name:d=or(d>>>0),Mc:function(v){return!!v},Sc:function(v,T){return T?h:g},Rc:function(v){return this.Mc((k(),H)[v>>>0])},Tc:null})}var _v=[],us=[0,1,,1,null,1,!0,1,!1,1];function Fp(u){9<(u>>>=0)&&--us[u+1]==0&&(us[u]=void 0,_v.push(u))}var $t=u=>{if(!u)throw new Js(`Cannot use deleted val. handle = ${u}`);return us[u]},Ht=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=_v.pop()||us.length;return us[d]=u,us[d+1]=1,d}};function Gp(u){return this.Mc((k(),C)[u>>>2>>>0])}var RM={name:"emscripten::val",Mc:u=>{var d=$t(u);return Fp(u),d},Sc:(u,d)=>Ht(d),Rc:Gp,Tc:null};function $M(u){return mr(u>>>0,RM)}var BM=(u,d)=>{switch(d){case 4:return function(h){return this.Mc((k(),te)[h>>>2>>>0])};case 8:return function(h){return this.Mc((k(),ae)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function DM(u,d,h){h>>>=0,mr(u>>>=0,{name:d=or(d>>>0),Mc:g=>g,Sc:(g,v)=>v,Rc:BM(d,h),Tc:null})}function UM(u,d,h,g,v){u>>>=0,h>>>=0,d=or(d>>>0);let T=z=>z;if(g===0){var I=32-8*h;T=z=>z<<I>>>I,v=T(v)}mr(u,{name:d,Mc:T,Sc:(z,F)=>F,Rc:mv(d,h,g!==0),Tc:null})}function FM(u,d,h){function g(T){var I=(k(),C)[T>>>2>>>0];return T=(k(),C)[T+4>>>2>>>0],new v((k(),U).buffer,T,I)}var v=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];mr(u>>>=0,{name:h=or(h>>>0),Mc:g,Rc:g},{ee:!0})}var _r=(u,d,h)=>{var g=(k(),H);if(d>>>=0,0<h){var v=d;h=d+h-1;for(var T=0;T<u.length;++T){var I=u.codePointAt(T);if(127>=I){if(d>=h)break;g[d++>>>0]=I}else if(2047>=I){if(d+1>=h)break;g[d++>>>0]=192|I>>6,g[d++>>>0]=128|63&I}else if(65535>=I){if(d+2>=h)break;g[d++>>>0]=224|I>>12,g[d++>>>0]=128|I>>6&63,g[d++>>>0]=128|63&I}else{if(d+3>=h)break;g[d++>>>0]=240|I>>18,g[d++>>>0]=128|I>>12&63,g[d++>>>0]=128|I>>6&63,g[d++>>>0]=128|63&I,T++}}g[d>>>0]=0,u=d-v}else u=0;return u},hr=u=>{for(var d=0,h=0;h<u.length;++h){var g=u.charCodeAt(h);127>=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function GM(u,d){mr(u>>>=0,{name:d=or(d>>>0),Mc(h){var g=(k(),C)[h>>>2>>>0];return g=Qs(h+4,g,!0),Xt(h),g},Sc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var v=typeof g=="string";if(!(v||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Js("Cannot pass non-string to std::string");var T=v?hr(g):g.length,I=en(4+T+1),z=I+4;return(k(),C)[I>>>2>>>0]=T,v?_r(g,z,T+1):(k(),H).set(g,z>>>0),h!==null&&h.push(Xt,I),I},Rc:Gp,Tc(h){Xt(h)}})}var hv=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,jM=(u,d,h)=>{if(u>>>=1,16<(d=Z1((k(),K),u,d/2,h))-u&&hv)return hv.decode((k(),K).slice(u,d));for(h="";u<d;++u){var g=(k(),K)[u>>>0];h+=String.fromCharCode(g)}return h},qM=(u,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*u.length?h/2:u.length;for(var v=0;v<h;++v){var T=u.charCodeAt(v);(k(),j)[d>>>1>>>0]=T,d+=2}return(k(),j)[d>>>1>>>0]=0,d-g},WM=u=>2*u.length,VM=(u,d,h)=>{var g="";u>>>=2;for(var v=0;!(v>=d/4);v++){var T=(k(),C)[u+v>>>0];if(!T&&!h)break;g+=String.fromCodePoint(T)}return g},HM=(u,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var v=0;v<u.length;++v){var T=u.codePointAt(v);if(65535<T&&v++,(k(),$)[d>>>2>>>0]=T,(d+=4)+4>h)break}return(k(),$)[d>>>2>>>0]=0,d-g},XM=u=>{for(var d=0,h=0;h<u.length;++h)65535<u.codePointAt(h)&&h++,d+=4;return d};function KM(u,d,h){if(u>>>=0,d>>>=0,h=or(h>>>=0),d===2)var g=jM,v=qM,T=WM;else g=VM,v=HM,T=XM;mr(u,{name:h,Mc:I=>{var z=(k(),C)[I>>>2>>>0];return z=g(I+4,z*d,!0),Xt(I),z},Sc:(I,z)=>{if(typeof z!="string")throw new Js(`Cannot pass non-string to C++ string type ${h}`);var F=T(z),Y=en(4+F+d);return(k(),C)[Y>>>2>>>0]=F/d,v(z,Y+4,F+d),I!==null&&I.push(Xt,Y),Y},Rc:Gp,Tc(I){Xt(I)}})}function YM(u,d){mr(u>>>=0,{fe:!0,name:d=or(d>>>0),Mc:()=>{},Sc:()=>{}})}function QM(u){nf(u>>>0,!s,1,!r,131072,!1),W1()}var Mt=u=>{if(!P)try{if(u(),!(0<Se))try{n?Dl()&&of(_):Ks(_)}catch(d){d instanceof at||d=="unwind"||l(0,d)}}catch(d){d instanceof at||d=="unwind"||l(0,d)}},JM=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function jp(u){u>>>=0,JM||(Atomics.waitAsync((k(),$),u>>>2,u).value.then(Ll),u+=128,Atomics.store((k(),$),u>>>2,1))}var Ll=()=>Mt(()=>{var u=Dl();u&&(jp(u),sk())});function ZM(u,d){(u>>>=0)==d>>>0?setTimeout(Ll):n?postMessage({Vc:u,Oc:"checkMailbox"}):(u=cs[u])&&u.postMessage({Oc:"checkMailbox"})}var qp=[];function eS(u,d,h,g,v){for(d>>>=0,v>>>=0,qp.length=0,h=v>>>3,g=v+g>>>3;h<g;){var T;T=(k(),L)[h++>>>0]?(k(),L)[h++>>>0]:(k(),ae)[h++>>>0],qp.push(T)}return(d?uf[d]:$O[u])(...qp)}var tS=()=>{Se=0};function rS(u){u>>>=0,n?postMessage({Oc:"cleanupThread",ie:u}):q1(cs[u])}function sS(u){}var zl=u=>{try{u()}catch(d){qe(d)}};function nS(u){var d=(...h)=>{Nl.push(u);try{return u(...h)}finally{P||(Nl.pop(),ar&&Ir===1&&Nl.length===0&&(Ir=0,Se+=1,zl(Wk),typeof Fibers<"u"&&Fibers.De()))}};return xv.set(u,d),d}var Ir=0,ar=null,gv=0,Nl=[],Wp=new Map,wv=new Map,xv=new Map,oS=0,Vp=null,aS=[],yv=u=>(function(d){if(!P){if(Ir===0){var h=!1,g=!1;d((v=0)=>{if(!P&&(gv=v,h=!0,g)){Ir=2,zl(()=>Vk(ar)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),v=!1;try{var T=(function(){var F=(k(),$)[ar+8>>>2>>>0];return F=wv.get(F),F=xv.get(F),--Se,F()})()}catch(F){T=F,v=!0}var I=!1;if(!ar){var z=Vp;z&&(Vp=null,(v?z.reject:z.resolve)(T),I=!0)}if(v&&!I)throw T}}),g=!0,h||(Ir=1,ar=(function(){var v=en(65548),T=v+12;if((k(),C)[v>>>2>>>0]=T,(k(),C)[v+4>>>2>>>0]=T+65536,T=Nl[0],!Wp.has(T)){var I=oS++;Wp.set(T,I),wv.set(I,T)}return T=Wp.get(T),(k(),$)[v+8>>>2>>>0]=T,v})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),zl(()=>qk(ar)))}else Ir===2?(Ir=0,zl(Hk),Xt(ar),ar=null,aS.forEach(Mt)):qe(`invalid state: ${Ir}`);return gv}})(d=>{u().then(d)});function iS(u){return u>>>=0,yv(async()=>{var d=await $t(u);return Ht(d)})}var Hp=[],lS=u=>{var d=Hp.length;return Hp.push(u),d},cS=(u,d)=>{for(var h=Array(u),g=0;g<u;++g){var v=g,T=(k(),C)[d+4*g>>>2>>>0],I=Up[T];if(I===void 0)throw u=`parameter ${g}`,T=Dv(T),d=or(T),Xt(T),new Js(`${u} has unknown type ${d}`);h[v]=I}return h},uS=(u,d,h)=>{var g=[];return u=u(g,h),g.length&&((k(),C)[d>>>2>>>0]=Ht(g)),u},pS={},Rl=u=>{var d=pS[u];return d===void 0?or(u):d};function fS(u,d,h){var[g,...v]=cS(u,d>>>0);d=g.Sc.bind(g);var T=v.map(F=>F.Rc.bind(F));u--;var I={toValue:$t};switch(u=T.map((F,Y)=>{var Oe=`argFromPtr${Y}`;return I[Oe]=F,`${Oe}(args${Y?"+"+8*Y:""})`}),h){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:I.getStringOrSymbol=Rl,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${u})`,g.fe||(I.toReturnWire=d,I.emval_returnValue=uS,z=`return emval_returnValue(toReturnWire, destructorsRef, ${z})`),z=`return function (handle, methodName, destructorsRef, args) {
|
|
11
11
|
${z}
|
|
12
|
-
}`,h=new Function(Object.keys(I),z)(...Object.values(I)),z=`methodCaller<(${v.map(F=>F.name)}) => ${g.name}>`,rS(Object.defineProperty(h,"name",{value:z}))}function iS(u,f){return f>>>=0,(u=$t(u>>>0))==$t(f)}function lS(u){return(u>>>=0)?(u=Gl(u),Vt(globalThis[u])):Vt(globalThis)}function cS(u){return u=Gl(u>>>0),Vt(e[u])}function uS(u,f){return f>>>=0,u=$t(u>>>0),f=$t(f),Vt(u[f])}function pS(u){9<(u>>>=0)&&(cs[u+1]+=1)}function _v(u,f,h,g,v){return Hp[u>>>0](f>>>0,h>>>0,g>>>0,v>>>0)}function dS(u,f,h,g,v){return _v(u>>>0,f>>>0,h>>>0,g>>>0,v>>>0)}function fS(){return Vt([])}function mS(u){u=$t(u>>>0);for(var f=Array(u.length),h=0;h<u.length;h++)f[h]=u[h];return Vt(f)}function _S(u){return Vt(Gl(u>>>0))}function hS(){return Vt({})}function gS(u){for(var f=$t(u>>>=0);f.length;){var h=f.pop();f.pop()(h)}Fp(u)}function wS(u,f,h){f>>>=0,h>>>=0,u=$t(u>>>0),f=$t(f),h=$t(h),u[f]=h}function xS(u,f){u=At(u),f>>>=0,u=new Date(1e3*u),(E(),$)[f>>>2>>>0]=u.getUTCSeconds(),(E(),$)[f+4>>>2>>>0]=u.getUTCMinutes(),(E(),$)[f+8>>>2>>>0]=u.getUTCHours(),(E(),$)[f+12>>>2>>>0]=u.getUTCDate(),(E(),$)[f+16>>>2>>>0]=u.getUTCMonth(),(E(),$)[f+20>>>2>>>0]=u.getUTCFullYear()-1900,(E(),$)[f+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(E(),$)[f+28>>>2>>>0]=u}var hv=u=>u%4==0&&(u%100!=0||u%400==0),gv=[0,31,60,91,121,152,182,213,244,274,305,335],wv=[0,31,59,90,120,151,181,212,243,273,304,334];function yS(u,f){u=At(u),f>>>=0,u=new Date(1e3*u),(E(),$)[f>>>2>>>0]=u.getSeconds(),(E(),$)[f+4>>>2>>>0]=u.getMinutes(),(E(),$)[f+8>>>2>>>0]=u.getHours(),(E(),$)[f+12>>>2>>>0]=u.getDate(),(E(),$)[f+16>>>2>>>0]=u.getMonth(),(E(),$)[f+20>>>2>>>0]=u.getFullYear()-1900,(E(),$)[f+24>>>2>>>0]=u.getDay();var h=(hv(u.getFullYear())?gv:wv)[u.getMonth()]+u.getDate()-1|0;(E(),$)[f+28>>>2>>>0]=h,(E(),$)[f+36>>>2>>>0]=-60*u.getTimezoneOffset(),h=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(h!=g&&u.getTimezoneOffset()==Math.min(g,h)),(E(),$)[f+32>>>2>>>0]=u}function bS(u){u>>>=0;var f=new Date((E(),$)[u+20>>>2>>>0]+1900,(E(),$)[u+16>>>2>>>0],(E(),$)[u+12>>>2>>>0],(E(),$)[u+8>>>2>>>0],(E(),$)[u+4>>>2>>>0],(E(),$)[u>>>2>>>0],0),h=(E(),$)[u+32>>>2>>>0],g=f.getTimezoneOffset(),v=new Date(f.getFullYear(),6,1).getTimezoneOffset(),T=new Date(f.getFullYear(),0,1).getTimezoneOffset(),I=Math.min(T,v);return 0>h?(E(),$)[u+32>>>2>>>0]=+(v!=T&&I==g):0<h!=(I==g)&&(v=Math.max(T,v),f.setTime(f.getTime()+6e4*((0<h?I:v)-g))),(E(),$)[u+24>>>2>>>0]=f.getDay(),h=(hv(f.getFullYear())?gv:wv)[f.getMonth()]+f.getDate()-1|0,(E(),$)[u+28>>>2>>>0]=h,(E(),$)[u>>>2>>>0]=f.getSeconds(),(E(),$)[u+4>>>2>>>0]=f.getMinutes(),(E(),$)[u+8>>>2>>>0]=f.getHours(),(E(),$)[u+12>>>2>>>0]=f.getDate(),(E(),$)[u+16>>>2>>>0]=f.getMonth(),(E(),$)[u+20>>>2>>>0]=f.getYear(),u=f.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function xv(u,f,h,g,v,T,I){return n?Ue(16,1,u,f,h,g,v,T,I):-52}function yv(u,f,h,g,v,T){if(n)return Ue(17,1,u,f,h,g,v,T)}var oo={},vS=()=>performance.timeOrigin+performance.now();function bv(u,f){if(n)return Ue(18,1,u,f);if(oo[u]&&(clearTimeout(oo[u].id),delete oo[u]),!f)return 0;var h=setTimeout(()=>{delete oo[u],Tt(()=>Yv(u,performance.timeOrigin+performance.now()))},f);return oo[u]={id:h,Ce:f},0}function kS(u,f,h,g){u>>>=0,f>>>=0,h>>>=0,g>>>=0;var v=new Date().getFullYear(),T=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var I=Math.max(T,v);(E(),C)[u>>>2>>>0]=60*I,(E(),$)[f>>>2>>>0]=+(T!=v),u=(f=z=>{var F=Math.abs(z);return`UTC${0<=z?"-":"+"}${String(Math.floor(F/60)).padStart(2,"0")}${String(F%60).padStart(2,"0")}`})(T),f=f(v),v<T?(_r(u,h,17),_r(f,g,17)):(_r(u,g,17),_r(f,h,17))}var ES=()=>Date.now(),AS=1;function TS(u,f,h){if(h>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!AS)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(E(),L)[h>>>3>>>0]=BigInt(u),0}var Xp=[],vv=(u,f)=>{Xp.length=0;for(var h;h=(E(),H)[u++>>>0];){var g=h!=105;f+=(g&=h!=112)&&f%8?4:0,Xp.push(h==112?(E(),C)[f>>>2>>>0]:h==106?(E(),L)[f>>>3>>>0]:h==105?(E(),$)[f>>>2>>>0]:(E(),ae)[f>>>3>>>0]),f+=g?8:4}return Xp};function MS(u,f,h){return u>>>=0,f=vv(f>>>0,h>>>0),cd[u](...f)}function SS(u,f,h){return u>>>=0,f=vv(f>>>0,h>>>0),cd[u](...f)}var OS=()=>{};function IS(u,f){return M(en(u>>>0,f>>>0))}var CS=()=>{throw Le+=1,"unwind"};function PS(){return 4294901760}var LS=()=>1,zS=()=>navigator.hardwareConcurrency;function NS(u){u>>>=0;var f=(E(),H).length;if(u<=f||4294901760<u)return!1;for(var h=1;4>=h;h*=2){var g=f*(1+.2/h);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Or.buffer.byteLength+65535)/65536|0;try{Or.grow(g),xe();var v=1;break e}catch{}v=void 0}if(v)return!0}return!1}var ar=u=>{var f=hr(u)+1,h=Vl(f);return _r(u,h,f),h},Kp=(u,f)=>{(E(),C)[u>>>2>>>0]=f;var h=(E(),C)[u>>>2>>>0];(E(),C)[u+4>>>2>>>0]=(f-h)/4294967296},ao=u=>(E(),C)[u>>>2>>>0]+4294967296*(E(),$)[u+4>>>2>>>0],_t=[],RS=(u,f)=>{_t[u>>>0]=f},gr=[],jl=[],rn=(u,f)=>{jl[u]=new Promise(h=>f.finally(()=>h(u)))},se=u=>{if(u)return _t[u>>>0]},$S=(u,f)=>{for(u=(E(),C)[u>>>2>>>0];u;u=(E(),C)[u>>>2>>>0])f[(E(),$)[u+4>>>2>>>0]](u)},ql=(u,f,h)=>{(E(),C)[u>>>2>>>0]=f,(E(),C)[u+4>>>2>>>0]=h},kv=u=>{var f=(E(),C)[u>>>2>>>0];return u=(E(),C)[u+4>>>2>>>0],en(f,u)},wr=u=>{var f=(E(),C)[u>>>2>>>0];return u=(E(),C)[u+4>>>2>>>0],f?en(f,u):u===0?"":void 0},DS=u=>{var f=wr(u+4),h=(h=(E(),C)[u+12>>>2>>>0])?se(h):"auto";if(u+=16){var g=se((E(),C)[u+4>>>2>>>0]),v=(E(),C)[u+16>>>2>>>0],T=(E(),C)[u+20>>>2>>>0];if(v){for(var I={},z=0;z<v;++z){var F=T+24*z;I[kv(F+4)]=(E(),ae)[F+16>>>3>>>0]}v=I}else v=void 0;u={module:g,constants:v,entryPoint:wr(u+8)}}else u=void 0;return{label:f,layout:h,compute:u}},Ev=(u,f)=>{function h(g,v){g=u[g],(E(),C)[f+v>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),Kp(f+64,u.maxUniformBufferBindingSize),Kp(f+72,u.maxStorageBufferBindingSize),h("maxVertexBuffers",88),Kp(f+96,u.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),u.Ae!==void 0&&h("maxImmediateSize",148)},BS=[,"validation","out-of-memory","internal"],US=[,"compatibility","core"],Av={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"},FS=[,"low-power","high-performance"],GS=[,"occlusion","timestamp"],jS={undefined:1,unknown:1,destroyed:2};function qS(u,f,h,g,v,T){f=At(f),h=At(h),g>>>=0,v>>>=0,T>>>=0;var I=se(u>>>0);if(u={},T){var z=(E(),C)[T+12>>>2>>>0];if(z){var F=(E(),C)[T+16>>>2>>>0];u.requiredFeatures=Array.from((E(),C).subarray(F>>>2>>>0,F+4*z>>>2>>>0),ne=>Av[ne])}var Q=(E(),C)[T+20>>>2>>>0];if(Q){let ne=function(Mt,lt,us=!1){lt=Q+lt,(lt=(E(),C)[lt>>>2>>>0])==4294967295||us&<==0||(Fe[Mt]=lt)},it=function(Mt,lt){lt=Q+lt;var us=(E(),C)[lt>>>2>>>0],_I=(E(),C)[lt+4>>>2>>>0];us==4294967295&&_I==4294967295||(Fe[Mt]=ao(lt))};var Me=ne,ze=it,Fe={};ne("maxTextureDimension1D",4),ne("maxTextureDimension2D",8),ne("maxTextureDimension3D",12),ne("maxTextureArrayLayers",16),ne("maxBindGroups",20),ne("maxBindGroupsPlusVertexBuffers",24),ne("maxDynamicUniformBuffersPerPipelineLayout",32),ne("maxDynamicStorageBuffersPerPipelineLayout",36),ne("maxSampledTexturesPerShaderStage",40),ne("maxSamplersPerShaderStage",44),ne("maxStorageBuffersPerShaderStage",48),ne("maxStorageTexturesPerShaderStage",52),ne("maxUniformBuffersPerShaderStage",56),ne("minUniformBufferOffsetAlignment",80),ne("minStorageBufferOffsetAlignment",84),it("maxUniformBufferBindingSize",64),it("maxStorageBufferBindingSize",72),ne("maxVertexBuffers",88),it("maxBufferSize",96),ne("maxVertexAttributes",104),ne("maxVertexBufferArrayStride",108),ne("maxInterStageShaderVariables",112),ne("maxColorAttachments",116),ne("maxColorAttachmentBytesPerSample",120),ne("maxComputeWorkgroupStorageSize",124),ne("maxComputeInvocationsPerWorkgroup",128),ne("maxComputeWorkgroupSizeX",132),ne("maxComputeWorkgroupSizeY",136),ne("maxComputeWorkgroupSizeZ",140),ne("maxComputeWorkgroupsPerDimension",144),ne("maxImmediateSize",148,!0),u.requiredLimits=Fe}(z=(E(),C)[T+24>>>2>>>0])&&(z={label:wr(z+4)},u.defaultQueue=z),u.label=wr(T+4)}Le+=1,rn(f,I.requestDevice(u).then(ne=>{--Le,Tt(()=>{_t[v>>>0]=ne.queue,_t[g>>>0]=ne,rn(h,ne.lost.then(it=>{Tt(()=>{ne.onuncapturederror=()=>{};var Mt=ce(),lt=ar(it.message);ed(h,jS[it.reason],lt),le(Mt)})})),ne.onuncapturederror=it=>{var Mt=5;it.error instanceof GPUValidationError?Mt=2:it.error instanceof GPUOutOfMemoryError?Mt=3:it.error instanceof GPUInternalError&&(Mt=4);var lt=ce();it=ar(it.error.message),Vv(g,Mt,it),le(lt)},"adapterInfo"in ne||(ne.adapterInfo=I.info),sd(f,1,g,0)})},ne=>{--Le,Tt(()=>{var it=ce(),Mt=ar(ne.message);sd(f,3,g,Mt),h&&ed(h,4,Mt),le(it)})}))}function WS(u){var f=se(u>>>=0),h=gr[u];if(h){for(var g=0;g<h.length;++g)h[g]();delete gr[u]}f.destroy()}function VS(u,f,h){h>>>=0;var g=se(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(f>>>0,h)}catch{return 0}var T=ad(16,v.byteLength);return(E(),H).set(new Uint8Array(v),T>>>0),gr[u].push(()=>Ht(T)),T}function HS(u,f,h){h>>>=0;var g=se(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(f>>>0,h)}catch{return 0}var T=ad(16,v.byteLength);return(E(),H).fill(0,T,v.byteLength),gr[u].push(()=>{new Uint8Array(v).set((E(),H).subarray(T>>>0,T+v.byteLength>>>0)),Ht(T)}),T}function XS(u,f,h,g,v){u>>>=0,f=At(f),h=At(h),v>>>=0;var T=se(u);gr[u]=[],v==4294967295&&(v=void 0),Le+=1,rn(f,T.mapAsync(h,g>>>0,v).then(()=>{--Le,Tt(()=>{td(f,1,0)})},I=>{--Le,Tt(()=>{ce();var z=ar(I.message);td(f,I.name==="AbortError"?4:I.name==="OperationError"?3:0,z),delete gr[u]})}))}function KS(u){var f=se(u>>>=0),h=gr[u];if(h){for(var g=0;g<h.length;++g)h[g]();delete gr[u],f.unmap()}}function YS(u){delete _t[u>>>0]}function QS(u,f,h){u>>>=0,f>>>=0,h>>>=0;var g=!!(E(),C)[f+32>>>2>>>0];f={label:wr(f+4),usage:(E(),C)[f+16>>>2>>>0],size:ao(f+24),mappedAtCreation:g},u=se(u);try{var v=u.createBuffer(f)}catch{return!1}return _t[h>>>0]=v,g&&(gr[h]=[]),!0}function JS(u,f,h,g){u>>>=0,f=At(f),g>>>=0,h=DS(h>>>0),u=se(u),Le+=1,rn(f,u.createComputePipelineAsync(h).then(v=>{--Le,Tt(()=>{_t[g>>>0]=v,Zp(f,1,g,0)})},v=>{--Le,Tt(()=>{var T=ce(),I=ar(v.message);Zp(f,v.reason==="validation"?3:v.reason==="internal"?4:0,g,I),le(T)})}))}function ZS(u,f,h){u>>>=0,f>>>=0,h>>>=0;var g=(E(),C)[f>>>2>>>0],v=(E(),$)[g+4>>>2>>>0];f={label:wr(f+4),code:""},v===2&&(f.code=kv(g+8)),u=se(u).createShaderModule(f),_t[h>>>0]=u}var eO=u=>{(u=se(u)).onuncapturederror=null,u.destroy()};function tO(u,f){f=At(f),u=se(u>>>0),Le+=1,rn(f,u.popErrorScope().then(h=>{--Le,Tt(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var v=ce(),T=h?ar(h.message):0;rd(f,1,g,T),le(v)})},h=>{--Le,Tt(()=>{var g=ce(),v=ar(h.message);rd(f,1,5,v),le(g)})}))}function rO(u,f,h,g){if(f=At(f),g>>>=0,h>>>=0){var v={featureLevel:US[(E(),$)[h+4>>>2>>>0]],powerPreference:FS[(E(),$)[h+8>>>2>>>0]],forceFallbackAdapter:!!(E(),C)[h+12>>>2>>>0]};(u=(E(),C)[h>>>2>>>0])!==0&&(E(),v.Fe=!!(E(),C)[u+8>>>2>>>0])}"gpu"in navigator?(Le+=1,rn(f,navigator.gpu.requestAdapter(v).then(T=>{--Le,Tt(()=>{if(T)_t[g>>>0]=T,io(f,1,g,0);else{var I=ce(),z=ar("WebGPU not available on this browser (requestAdapter returned null)");io(f,3,g,z),le(I)}})},T=>{--Le,Tt(()=>{var I=ce(),z=ar(T.message);io(f,4,g,z),le(I)})}))):(v=ce(),u=ar("WebGPU not available on this browser (navigator.gpu is not available)"),io(f,3,g,u),le(v))}function sO(u,f,h){return u>>>=0,f>>>=0,h>>>=0,mv(async()=>{var g=[];if(h){var v=(E(),$)[h>>>2>>>0];g.length=f+1,g[f]=new Promise(z=>setTimeout(z,v,0))}else g.length=f;for(var T=0;T<f;++T){var I=ao(u+8*T);if(!(I in jl))return I;g[T]=jl[I]}return g=await Promise.race(g),delete jl[g],g})}var Yp,Qp={},Tv=()=>{if(!Yp){var u,f={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in Qp)Qp[u]===void 0?delete f[u]:f[u]=Qp[u];var h=[];for(u in f)h.push(`${u}=${f[u]}`);Yp=h}return Yp};function Mv(u,f){if(n)return Ue(19,1,u,f);u>>>=0,f>>>=0;var h,g=0,v=0;for(h of Tv()){var T=f+g;(E(),C)[u+v>>>2>>>0]=T,g+=_r(h,T,1/0)+1,v+=4}return 0}function Sv(u,f){if(n)return Ue(20,1,u,f);u>>>=0,f>>>=0;var h=Tv();for(var g of((E(),C)[u>>>2>>>0]=h.length,u=0,h))u+=hr(g)+1;return(E(),C)[f>>>2>>>0]=u,0}function Ov(u){return n?Ue(21,1,u):52}function Iv(u,f,h,g){return n?Ue(22,1,u,f,h,g):52}function Cv(u,f,h,g){return n?Ue(23,1,u,f,h,g):70}var nO=[null,[],[]];function Pv(u,f,h,g){if(n)return Ue(24,1,u,f,h,g);f>>>=0,h>>>=0,g>>>=0;for(var v=0,T=0;T<h;T++){var I=(E(),C)[f>>>2>>>0],z=(E(),C)[f+4>>>2>>>0];f+=8;for(var F=0;F<z;F++){var Q=u,Me=(E(),H)[I+F>>>0],ze=nO[Q];Me===0||Me===10?((Q===1?S:M)(X1(ze)),ze.length=0):ze.push(Me)}v+=z}return(E(),C)[g>>>2>>>0]=v,0}function oO(u){return u>>>0}function aO(u,f){return Ev(se(u>>>0).limits,f>>>0),1}function iO(u,f){return se(u>>>0).features.has(Av[f])}function lO(u){return BigInt(se(u>>>0).size)}function cO(u){return BigInt(se(u>>>0).usage)}function uO(u,f){if(u>>>=0,f>>>=0){var h=wr(f+4);h={label:h,timestampWrites:f=(f=(E(),C)[f+12>>>2>>>0])!==0?{querySet:se((E(),C)[f+4>>>2>>>0]),beginningOfPassWriteIndex:(E(),C)[f+8>>>2>>>0],endOfPassWriteIndex:(E(),C)[f+12>>>2>>>0]}:void 0}}return f=se(u),u=Fv(0),h=f.beginComputePass(h),_t[u>>>0]=h,u}function pO(u,f,h,g,v,T){h=At(h),v=At(v),T=At(T),se(u>>>0).copyBufferToBuffer(se(f>>>0),h,se(g>>>0),v,T)}function dO(u){var f=se(u>>>0);return u=Bv(0),f=f.finish(),_t[u>>>0]=f,u}function fO(u,f,h,g,v,T){T=At(T),se(u>>>0).resolveQuerySet(se(f>>>0),h,g,se(v>>>0),T)}function mO(u,f,h,g){se(u>>>0).dispatchWorkgroups(f,h,g)}function _O(u,f,h){h=At(h),se(u>>>0).dispatchWorkgroupsIndirect(se(f>>>0),h)}function hO(u){se(u>>>0).end()}function gO(u,f,h,g,v){g>>>=0,v>>>=0,u=se(u>>>0),h=se(h>>>0),g==0?u.setBindGroup(f,h):u.setBindGroup(f,h,(E(),C),v>>>2,g)}function wO(u,f){se(u>>>0).setPipeline(se(f>>>0))}function xO(u,f,h){se(u>>>0).Ee(se(f>>>0),h)}function yO(u,f){var h=se(u>>>0);return u=Dv(0),f=h.getBindGroupLayout(f),_t[u>>>0]=f,u}function bO(u,f){function h(v){var T=(E(),C)[v+8>>>2>>>0],I=(E(),C)[v+32>>>2>>>0],z=(E(),C)[v+36>>>2>>>0],F=0;return $S(v,{327681:Q=>{F=(E(),C)[Q+8>>>2>>>0]}}),T?((I=ao(v+24))==-1&&(I=void 0),T={buffer:se(T),offset:ao(v+16),size:I}):T=se(I||z||F),{binding:(E(),C)[v+4>>>2>>>0],resource:T}}u>>>=0,f={label:wr(4+(f>>>=0)),layout:se((E(),C)[f+12>>>2>>>0]),entries:(function(v,T){for(var I=[],z=0;z<v;++z)I.push(h(T+40*z));return I})((E(),C)[f+16>>>2>>>0],(E(),C)[f+20>>>2>>>0])},u=se(u);var g=$v(0);return RS(g,u.createBindGroup(f)),g}function vO(u,f){var h;return u>>>=0,(f>>>=0)&&(h={label:wr(f+4)}),f=se(u),u=Uv(0),h=f.createCommandEncoder(h),_t[u>>>0]=h,u}function kO(u,f){u>>>=0,f>>>=0,f={type:GS[(E(),$)[f+12>>>2>>>0]],count:(E(),C)[f+16>>>2>>>0]};var h=se(u);return u=Gv(0),f=h.createQuerySet(f),_t[u>>>0]=f,u}function EO(u,f){u=se(u>>>0).adapterInfo,f>>>=0,(E(),C)[f+52>>>2>>>0]=u.subgroupMinSize,(E(),C)[f+56>>>2>>>0]=u.subgroupMaxSize;var h=u.vendor+u.architecture+u.device+u.description,g=hr(h)+1,v=sn(g);return v&&_r(h,v,g),h=v,g=hr(u.vendor),ql(f+4,h,g),h+=g,g=hr(u.architecture),ql(f+12,h,g),h+=g,g=hr(u.device),ql(f+20,h,g),ql(f+28,h+g,hr(u.description)),(E(),$)[f+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(E(),$)[f+40>>>2>>>0]=u,(E(),C)[f+44>>>2>>>0]=0,(E(),C)[f+48>>>2>>>0]=0,1}var AO={"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 TO(u,f){f>>>=0;var h=se(u>>>0);u=sn(4*h.features.size);var g=0,v=0;for(let T of h.features)0<=(h=AO[T])&&((E(),$)[u+g>>>2>>>0]=h,g+=4,v++);(E(),C)[f+4>>>2>>>0]=u,(E(),C)[f>>>2>>>0]=v}function MO(u,f){return Ev(se(u>>>0).limits,f>>>0),1}function SO(u,f){se(u>>>0).pushErrorScope(BS[f])}function OO(u,f,h){f>>>=0,h>>>=0,u=se(u>>>0),f=Array.from((E(),$).subarray(h>>>2>>>0,h+4*f>>>2>>>0),g=>se(g)),u.submit(f)}function IO(u,f,h,g,v){h=At(h),g>>>=0,v>>>=0,u=se(u>>>0),f=se(f>>>0),g=(E(),H).subarray(g>>>0,g+v>>>0),u.writeBuffer(f,h,g,0,v)}n||(function(){for(var u=e.numThreads-1;u--;)F1();Be.push(async()=>{var f=(async function(){if(!n)return Promise.all(Sr.map(U1))})();Te++,await f,--Te==0&&Ze&&(f=Ze,Ze=null,f())})})(),n||(Or=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),xe()),e.wasmBinary&&(d=e.wasmBinary),e.stackSave=()=>ce(),e.stackRestore=u=>le(u),e.stackAlloc=u=>Vl(u),e.setValue=function(u,f,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(E(),U)[u>>>0]=f;break;case"i16":(E(),j)[u>>>1>>>0]=f;break;case"i32":(E(),$)[u>>>2>>>0]=f;break;case"i64":(E(),L)[u>>>3>>>0]=BigInt(f);break;case"float":(E(),te)[u>>>2>>>0]=f;break;case"double":(E(),ae)[u>>>3>>>0]=f;break;case"*":(E(),C)[u>>>2>>>0]=f;break;default:qe(`invalid type for setValue: ${h}`)}},e.getValue=function(u,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return(E(),U)[u>>>0];case"i16":return(E(),j)[u>>>1>>>0];case"i32":return(E(),$)[u>>>2>>>0];case"i64":return(E(),L)[u>>>3>>>0];case"float":return(E(),te)[u>>>2>>>0];case"double":return(E(),ae)[u>>>3>>>0];case"*":return(E(),C)[u>>>2>>>0];default:qe(`invalid type for getValue: ${f}`)}},e.UTF8ToString=en,e.stringToUTF8=_r,e.lengthBytesUTF8=hr;var Lv,zv,Jp,Wl,Ht,sn,Nv,Rv,$v,Dv,Bv,Uv,Fv,Gv,jv,qv,Wv,Zp,ed,td,rd,io,sd,Vv,nd,Hv,Xv,Kv,od,Yv,Qv,ad,we,lo,Jv,le,Vl,ce,Zv,id,ek,tk,rk,ld,sk,nk,ok,ak,ik,lk,ck,uk,pk,dk,fk,mk,_k,hk,gk,wk,xk,yk,bk,vk,kk,Ek,Ak,Tk,Mk,Sk,Ok,Ik,Ck,Pk,Lk,zk,Nk,Rk,$k,Dk,Bk,Uk,Fk,xr,CO=[Qs,so,q1,K1,Y1,Q1,J1,Z1,ev,tv,rv,sv,nv,ov,av,iv,xv,yv,bv,Mv,Sv,Ov,Iv,Cv,Pv],cd={925676:(u,f,h,g,v)=>{if(e===void 0||!e.Uc)return 1;if((u=en(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(f=Number(f>>>0),h=Number(h>>>0),g=Number(g>>>0),f+h>u.byteLength)return 3;try{let T=u.subarray(f,f+h);switch(v){case 0:(E(),H).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}},926500:(u,f,h)=>{e.Sd(u,(E(),H).subarray(f>>>0,f+h>>>0))},926564:()=>e.me(),926606:u=>{e.jd(u)},926643:()=>typeof wasmOffsetConverter<"u"};function PO(u,f,h,g){var v=ce();try{return uk(u,f,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function LO(u,f,h){var g=ce();try{return ik(u,f,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function zO(u,f,h){var g=ce();try{rk(u,f,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function NO(u,f){var h=ce();try{return ld(u,f)}catch(g){if(le(h),g!==g+0)throw g;we(1,0)}}function RO(u){var f=ce();try{sk(u)}catch(h){if(le(f),h!==h+0)throw h;we(1,0)}}function $O(u,f,h,g,v,T,I){var z=ce();try{return ak(u,f,h,g,v,T,I)}catch(F){if(le(z),F!==F+0)throw F;we(1,0)}}function DO(u,f){var h=ce();try{pk(u,f)}catch(g){if(le(h),g!==g+0)throw g;we(1,0)}}function BO(u,f,h,g,v,T){var I=ce();try{nk(u,f,h,g,v,T)}catch(z){if(le(I),z!==z+0)throw z;we(1,0)}}function UO(u,f,h,g){var v=ce();try{ck(u,f,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function FO(u,f,h,g,v,T,I){var z=ce();try{fk(u,f,h,g,v,T,I)}catch(F){if(le(z),F!==F+0)throw F;we(1,0)}}function GO(u,f,h,g,v,T,I){var z=ce();try{mk(u,f,h,g,v,T,I)}catch(F){if(le(z),F!==F+0)throw F;we(1,0)}}function jO(u,f,h,g,v,T,I,z){var F=ce();try{kk(u,f,h,g,v,T,I,z)}catch(Q){if(le(F),Q!==Q+0)throw Q;we(1,0)}}function qO(u,f,h,g,v,T,I,z,F,Q,Me,ze){var Fe=ce();try{_k(u,f,h,g,v,T,I,z,F,Q,Me,ze)}catch(ne){if(le(Fe),ne!==ne+0)throw ne;we(1,0)}}function WO(u,f,h,g,v){var T=ce();try{return dk(u,f,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;we(1,0)}}function VO(u,f,h,g,v){var T=ce();try{ok(u,f,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;we(1,0)}}function HO(u,f,h,g,v,T,I,z){var F=ce();try{lk(u,f,h,g,v,T,I,z)}catch(Q){if(le(F),Q!==Q+0)throw Q;we(1,0)}}function XO(u){var f=ce();try{return Ek(u)}catch(h){if(le(f),h!==h+0)throw h;we(1,0)}}function KO(u,f,h){var g=ce();try{return Ak(u,f,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function YO(u,f){var h=ce();try{return $k(u,f)}catch(g){if(le(h),g!==g+0)throw g;return we(1,0),0n}}function QO(u,f,h,g,v){var T=ce();try{Tk(u,f,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;we(1,0)}}function JO(u){var f=ce();try{return hk(u)}catch(h){if(le(f),h!==h+0)throw h;return we(1,0),0n}}function ZO(u,f,h,g,v,T){var I=ce();try{return bk(u,f,h,g,v,T)}catch(z){if(le(I),z!==z+0)throw z;we(1,0)}}function eI(u,f,h,g,v,T){var I=ce();try{return Mk(u,f,h,g,v,T)}catch(z){if(le(I),z!==z+0)throw z;we(1,0)}}function tI(u,f,h,g,v,T){var I=ce();try{return Sk(u,f,h,g,v,T)}catch(z){if(le(I),z!==z+0)throw z;we(1,0)}}function rI(u,f,h,g,v,T,I,z){var F=ce();try{return vk(u,f,h,g,v,T,I,z)}catch(Q){if(le(F),Q!==Q+0)throw Q;we(1,0)}}function sI(u,f,h,g,v){var T=ce();try{return Ok(u,f,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;return we(1,0),0n}}function nI(u,f,h,g){var v=ce();try{return Ik(u,f,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function oI(u,f,h,g){var v=ce();try{return Ck(u,f,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function aI(u,f,h,g,v,T,I,z,F,Q,Me,ze){var Fe=ce();try{return Pk(u,f,h,g,v,T,I,z,F,Q,Me,ze)}catch(ne){if(le(Fe),ne!==ne+0)throw ne;we(1,0)}}function iI(u,f,h,g,v,T,I,z,F,Q,Me){var ze=ce();try{Lk(u,f,h,g,v,T,I,z,F,Q,Me)}catch(Fe){if(le(ze),Fe!==Fe+0)throw Fe;we(1,0)}}function lI(u,f,h,g,v,T,I,z,F,Q,Me,ze,Fe,ne,it,Mt){var lt=ce();try{zk(u,f,h,g,v,T,I,z,F,Q,Me,ze,Fe,ne,it,Mt)}catch(us){if(le(lt),us!==us+0)throw us;we(1,0)}}function cI(u,f,h,g){var v=ce();try{return Nk(u,f,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function uI(u,f,h,g,v){var T=ce();try{return Rk(u,f,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;we(1,0)}}function pI(u,f,h){var g=ce();try{return wk(u,f,h)}catch(v){if(le(g),v!==v+0)throw v;return we(1,0),0n}}function dI(u,f,h){var g=ce();try{return gk(u,f,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function fI(u,f,h){var g=ce();try{return xk(u,f,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function mI(u,f,h,g){var v=ce();try{yk(u,f,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function Hl(){if(0<Te)Ze=Hl;else if(n)w?.(e),ue();else{for(var u=Be;0<u.length;)u.shift()(e);0<Te?Ze=Hl:(e.calledRun=!0,P||(ue(),w?.(e)))}}return n||(xr=await mt(),Hl()),e.PTR_SIZE=4,e.webgpuInit=u=>{let f=new WeakMap,h,g,v=1;e.webgpuRegisterDevice=z=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var F=f.get(z);if(!F){let Q=((Me,ze=0)=>{var Fe=Wv(ze);return ze=qv(ze,Fe),_t[Fe>>>0]=Me.queue,_t[ze>>>0]=Me,ze})(z,F=Rv(0));F=[v++,F,Q],f.set(z,F)}return h=z,g=F[0],F}h=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(g!==void 0){var F=g;if(g=void 0,z){let Q=Jp(F);T.set(z,Q),F===0&&u(h??se(Q))}h=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let I=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,F,Q)=>{if(Q)return z[I]=[Q,NaN],Q;if(Q=z[I])return Q[1]++,Q[0];if((F=T.get(F))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return F=((Me,ze=0)=>(Me.mapState==="unmapped"||qe(),ze=jv(ze),_t[ze>>>0]=Me,ze))(z,F),z[I]=[F,1],F},e.webgpuUnregisterBuffer=z=>{let F=z[I];if(!F)throw Error("Buffer is not registered");F[1]--,F[1]===0&&(Nv(F[0]),delete z[I])},e.webgpuGetBuffer=z=>se(z),e.webgpuCreateDownloader=(z,F,Q)=>{if((Q=T.get(Q))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Me=se(Q),ze=16*Math.ceil(Number(F)/16);return async()=>{let Fe=Me.createBuffer({size:ze,usage:9});try{let ne=Me.createCommandEncoder();return ne.copyBufferToBuffer(z,0,Fe,0,ze),Me.queue.submit([ne.finish()]),await Fe.mapAsync(GPUMapMode.READ),Fe.getMappedRange().slice(0,F)}finally{Fe.destroy()}}},e.ad=(z,F)=>{var Q=F.buffer;let Me=F.byteOffset,ze=F.byteLength;if(F=16*Math.ceil(Number(ze)/16),z=se(z),!h){var Fe=Jp(g);h=se(Fe)}let ne=(Fe=h.createBuffer({mappedAtCreation:!0,size:F,usage:6})).getMappedRange();new Uint8Array(ne).set(new Uint8Array(Q,Me,ze)),Fe.unmap(),(Q=h.createCommandEncoder()).copyBufferToBuffer(Fe,0,z,0,F),h.queue.submit([Q.finish()]),Fe.destroy()}},e.webnnInit=u=>{let f=u[0];[e.me,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.le,e.webnnEnableTraceEvent]=u.slice(1),e.webnnReleaseTensorId=e.jd,e.webnnUploadTensor=e.Sd,e.webnnRegisterMLContext=e.le,e.webnnOnRunStart=h=>f.onRunStart(h),e.webnnOnRunEnd=f.onRunEnd.bind(f),e.webnnOnReleaseSession=h=>{f.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>f.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,v,T)=>f.registerMLTensor(h,g,v,T),e.webnnCreateMLContext=h=>f.createMLContext(h),e.webnnRegisterMLConstant=(h,g,v,T,I,z)=>f.registerMLConstant(h,g,v,T,I,e.Uc,z),e.webnnRegisterGraphInput=f.registerGraphInput.bind(f),e.webnnIsGraphInput=f.isGraphInput.bind(f),e.webnnRegisterGraphOutput=f.registerGraphOutput.bind(f),e.webnnIsGraphOutput=f.isGraphOutput.bind(f),e.webnnCreateTemporaryTensor=f.createTemporaryTensor.bind(f),e.webnnIsGraphInputOutputTypeSupported=f.isGraphInputOutputTypeSupported.bind(f)},J?e:new Promise((u,f)=>{w=u,x=f})}var UA,HE,cz=be(()=>{"use strict";UA=VE,HE=globalThis.self?.name?.startsWith("em-pthread"),HE&&VE()}),Ld,Kd,XE,Lt,FA,lc,KE,YE,zd,QE,Nd,GA,Rd,jA,nf=be(()=>{"use strict";sf(),Ld=typeof location>"u"?void 0:location.origin,Kd=import.meta.url>"file:"&&import.meta.url<"file;",XE=()=>{if(Kd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Ld).href}return import.meta.url},Lt=XE(),FA=()=>{if(Lt&&!Lt.startsWith("blob:"))return Lt.substring(0,Lt.lastIndexOf("/")+1)},lc=(t,e)=>{try{let r=e??Lt;return(r?new URL(t,r):new URL(t)).origin===Ld}catch{return!1}},KE=(t,e)=>{let r=e??Lt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},YE=(t,e)=>`${e??"./"}${t}`,zd=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},QE=async t=>(await import(t)).default,Nd=(lz(),mc($A)).default,GA=async()=>{if(!Lt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(lc(Lt))return[void 0,Nd()];let t=await zd(Lt);return[t,Nd(t)]},Rd=(cz(),mc(BA)).default,jA=async(t,e,r,s)=>{let n=Rd&&!(t||e);if(n)if(Lt)n=lc(Lt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Rd];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??KE(o,e),i=r&&a&&!lc(a,e),l=i?await zd(a):a??YE(o,e);return[i?l:void 0,await QE(l)]}}}),$d,cc,yo,Dd,JE,ZE,eA,of,De,As=be(()=>{"use strict";nf(),cc=!1,yo=!1,Dd=!1,JE=()=>{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}},ZE=()=>{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}},eA=()=>{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}},of=async t=>{if(cc)return Promise.resolve();if(yo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Dd)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(!eA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ZE())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=JE();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=t.wasmBinary,[d,m]=await jA(i,o,r>1,!!p||!!c),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,k)=>{let b={numThreads:r};if(p)b.wasmBinary=p,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(d){let A=FA();A&&(b.locateFile=S=>A+S)}m(b).then(A=>{yo=!1,cc=!0,$d=A,x(),d&&URL.revokeObjectURL(d)},A=>{yo=!1,Dd=!0,k(A)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},De=()=>{if(cc&&$d)return $d;throw new Error("WebAssembly is not initialized yet.")}}),zt,hc,Ie,af=be(()=>{"use strict";As(),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},hc=(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")hc(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}`)})},Ie=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)}}}),qA,uz=be(()=>{"use strict";As(),af(),qA=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&&Ie("Can't create run options."),t?.extra!==void 0&&hc(t.extra,"",new WeakSet,(a,i)=>{let l=zt(a,s),c=zt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Ie(`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}}}),tA,rA,sA,uc,$r,nA,WA,pz=be(()=>{"use strict";As(),af(),tA=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}`)}},rA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},sA=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)},uc=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);De()._OrtAddSessionConfigEntry(t,n,o)!==0&&Ie(`Can't set a session config entry: ${e} - ${r}.`)},$r=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);t.push([n,o])},nA=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 d=n?.deviceType;d&&uc(t,"deviceType",d,r)}break;case"webgpu":{o="WebGPU";let d;if(typeof n!="string"){let _=n;if(_.device)if(typeof GPUDevice<"u"&&_.device instanceof GPUDevice)d=_.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&$r(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&$r(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];$r(a,"forceCpuNodeNames",x.join(`
|
|
13
|
-
`),r)}_.validationMode&&$r(a,"validationMode",_.validationMode,r)}let m=De().webgpuRegisterDevice(d);if(m){let[_,w,x]=m;$r(a,"deviceId",_.toString(),r),$r(a,"webgpuInstance",w.toString(),r),$r(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=zt(o,r),l=a.length,c=0,p=0;if(l>0){c=De()._malloc(l*De().PTR_SIZE),r.push(c),p=De()._malloc(l*De().PTR_SIZE),r.push(p);for(let d=0;d<l;d++)De().setValue(c+d*De().PTR_SIZE,a[d][0],"*"),De().setValue(p+d*De().PTR_SIZE,a[d][1],"*")}await De()._OrtAppendExecutionProvider(t,i,c,p,l)!==0&&Ie(`Can't append execution provider: ${o}.`)}},WA=async t=>{let e=De(),r=0,s=[],n=t||{};sA(n);try{let o=tA(n.graphOptimizationLevel??"all"),a=rA(n.executionMode??"sequential"),i=typeof n.logId=="string"?zt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?zt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&Ie("Can't create session options."),n.executionProviders&&await nA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);uc(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[d,m]of Object.entries(n.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);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(d,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&Ie(`Can't set a free dimension override: ${d} - ${m}.`)}return n.extra!==void 0&&hc(n.extra,"",new WeakSet,(d,m)=>{uc(r,d,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Ie("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),ys,fc,dn,Ao,gc,lf,cf,Yd,fn=be(()=>{"use strict";ys=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}`)}},fc=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}`)}},dn=(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}`)}},gc=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}`)}},lf=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",cf=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Yd=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}`)}}}),uf,VA=be(()=>{"use strict";sf(),uf=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)}}),HA,dz=be(()=>{"use strict";fn(),HA=(t,e)=>new(Ao(e))(t)}),oA,aA,iA,lA,XA,cA,bt,KA=be(()=>{"use strict";fn(),oA=["V","I","W","E","F"],aA=(t,e)=>{console.log(`[${oA[t]},${new Date().toISOString()}]${e}`)},XA=(t,e)=>{iA=t,lA=e},cA=(t,e)=>{let r=gc(t),s=gc(iA);r>=s&&aA(r,typeof e=="function"?e():e)},bt=(...t)=>{lA&&cA(...t)}}),Bd,Qd,Ud,uA,Fd,pA,Gd,jd,qd,dA,YA,fz=be(()=>{"use strict";fn(),KA(),Bd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Qd=(t,e)=>{if(e==="int32")return t;let r=Bd.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;i<n;i++){let l=o[i];if(l>2147483647n||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'`)}},Ud=(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}`)}},uA=1,Fd=()=>uA++,pA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Gd=(t,e)=>{let r=Bd.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},jd=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 Gd(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=Ud(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}},qd=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=pA.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!==Gd(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=Qd(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?Ud(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()}},dA=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=Fd();return this.tensorTrackersById.set(t,new qd(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=Fd(),a=new jd({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new qd(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){bt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let d=this.freeTensors.splice(c,1)[0];return d.sessionId=t,d}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 jd({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)}},YA=(...t)=>new dA(...t)}),QA={};To(QA,{WebNNBackend:()=>JA});var bo,fA,JA,mz=be(()=>{"use strict";fn(),As(),dz(),fz(),KA(),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"]]),fA=(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])},JA=class{constructor(t){this.tensorManager=YA(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,XA(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=>fA(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 HA(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,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let d=Qd(new Uint8Array(c),"int64");p=new Int32Array(d.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return 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,p)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=bo.get(ys(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),mA,pf,df,Dr,_A,Wd,wc,ff,mf,Vd,_f,hf,gf,ZA=be(()=>{"use strict";Es(),uz(),pz(),fn(),As(),af(),VA(),mA=(t,e)=>{De()._OrtInit(t,e)!==0&&Ie("Can't initialize onnxruntime.")},pf=async t=>{mA(t.wasm.numThreads,gc(t.logLevel))},df=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(mz(),mc(QA)).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])}},Dr=new Map,_A=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&&Ie("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)}},Wd=(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&&Ie("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],p=[];for(let d=0;d<c;d++){let m=Number(r.getValue(n+8+d*o,"*"));p.push(m!==0?r.UTF8ToString(m):Number(r.getValue(n+8+(d+c)*o,"*")))}return[i,l,p]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},wc=t=>{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]},ff=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]=wc(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await WA(e),e?.externalData&&n.mountExternalData){let M=[];for(let P of e.externalData){let O=typeof P=="string"?P:P.path;M.push(uf(typeof P=="string"?P:P.data).then(E=>{n.mountExternalData(O,E)}))}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 P=M,O=P?.context,E=P?.gpuDevice,W=P?.deviceType,X=P?.powerPreference;O?n.currentContext=O:E?n.currentContext=await n.webnnCreateMLContext(E):n.currentContext=await n.webnnCreateMLContext({deviceType:W,powerPreference:X})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Ie("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[d,m]=_A(o),_=!!e?.enableGraphCapture,w=[],x=[],k=[],b=[],A=[];for(let M=0;M<d;M++){let[P,O,E]=Wd(o,M);P===0&&Ie("Can't get an input name."),c.push(P);let W=n.UTF8ToString(P);w.push(W),k.push(O===0?{name:W,isTensor:!1}:{name:W,isTensor:!0,type:fc(O),shape:E})}for(let M=0;M<m;M++){let[P,O,E]=Wd(o,M+d);P===0&&Ie("Can't get an output name."),p.push(P);let W=n.UTF8ToString(P);x.push(W),b.push(O===0?{name:W,isTensor:!1}:{name:W,isTensor:!0,type:fc(O),shape:E});{if(_&&e?.preferredOutputLocation===void 0){A.push("gpu-buffer");continue}let X=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[W]??"cpu",U=n.webnnIsGraphOutput;if(X==="cpu"&&U&&U(o,W)){A.push("ml-tensor-cpu-output");continue}if(X!=="cpu"&&X!=="cpu-pinned"&&X!=="gpu-buffer"&&X!=="ml-tensor")throw new Error(`Not supported preferred output location: ${X}.`);if(_&&X!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${X}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);A.push(X)}}let S=null;return A.some(M=>M==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Ie("Can't create IO binding."),S={handle:i,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>Yd(M))}),Dr.set(o,[o,c,p,S,_,!1]),[o,w,x,k,b]}catch(d){throw c.forEach(m=>n._OrtFree(m)),p.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Ie("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Ie("Can't release session."),d}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Ie("Can't release session options."),l.forEach(d=>n._free(d)),n.unmountExternalData?.()}},mf=t=>{let e=De(),r=Dr.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&&Ie("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Ie("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&&Ie("Can't release session."),Dr.delete(t)},Vd=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=De(),l=i.PTR_SIZE,c=t[0],p=t[1],d=t[3],m=d,_,w;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let b=t[2].gpuBuffer;w=dn(ys(c),p);{let A=i.webgpuRegisterBuffer;if(!A)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=A(b,s)}}else if(d==="ml-tensor"){let b=t[2].mlTensor;w=dn(ys(c),p);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=A(s,b,ys(c),p)}else{let b=t[2];if(Array.isArray(b)){w=l*b.length,_=i._malloc(w),r.push(_);for(let A=0;A<b.length;A++){if(typeof b[A]!="string")throw new TypeError(`tensor data at index ${A} is not a string`);i.setValue(_+A*l,zt(b[A],r),"*")}}else{let A=i.webnnIsGraphInput,S=i.webnnIsGraphOutput;if(c!=="string"&&A&&S){let M=i.UTF8ToString(n);if(A(s,M)||S(s,M)){let P=ys(c);w=dn(P,p),m="ml-tensor";let O=i.webnnCreateTemporaryTensor,E=i.webnnUploadTensor;if(!O||!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let W=await O(s,P,p);E(W,new Uint8Array(b.buffer,b.byteOffset,b.byteLength)),_=W}else w=b.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(b.buffer,b.byteOffset,w),_)}else w=b.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(b.buffer,b.byteOffset,w),_)}}let x=i.stackSave(),k=i.stackAlloc(4*p.length);try{p.forEach((A,S)=>i.setValue(k+S*l,A,l===4?"i32":"i64"));let b=i._OrtCreateTensor(ys(c),_,w,k,p.length,Yd(m));b===0&&Ie(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(b)}finally{i.stackRestore(x)}},_f=async(t,e,r,s,n,o)=>{let a=De(),i=a.PTR_SIZE,l=Dr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],d=l[2],m=l[3],_=l[4],w=l[5],x=e.length,k=s.length,b=0,A=[],S=[],M=[],P=[],O=[],E=a.stackSave(),W=a.stackAlloc(x*i),X=a.stackAlloc(x*i),U=a.stackAlloc(k*i),H=a.stackAlloc(k*i);try{[b,A]=qA(o),Ur("wasm prepareInputOutputTensor");for(let C=0;C<x;C++)await Vd(r[C],S,P,t,p[e[C]],e[C],_);for(let C=0;C<k;C++)await Vd(n[C],M,P,t,d[s[C]],x+s[C],_);Fr("wasm prepareInputOutputTensor");for(let C=0;C<x;C++)a.setValue(W+C*i,S[C],"*"),a.setValue(X+C*i,p[e[C]],"*");for(let C=0;C<k;C++)a.setValue(U+C*i,M[C],"*"),a.setValue(H+C*i,d[s[C]],"*");if(m&&!w){let{handle:C,outputPreferredLocations:te,outputPreferredLocationsEncoded:ae}=m;if(p.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${p.length}).`);Ur("wasm bindInputsOutputs");for(let L=0;L<x;L++){let N=e[L];await a._OrtBindInput(C,p[N],S[L])!==0&&Ie(`Can't bind input[${L}] for session=${t}.`)}for(let L=0;L<k;L++){let N=s[L];n[L]?.[3]?(O.push(M[L]),a._OrtBindOutput(C,d[N],M[L],0)!==0&&Ie(`Can't bind pre-allocated output[${L}] for session=${t}.`)):a._OrtBindOutput(C,d[N],0,ae[N])!==0&&Ie(`Can't bind output[${L}] to ${te[L]} for session=${t}.`)}Fr("wasm bindInputsOutputs"),Dr.set(t,[c,p,d,m,_,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let j;m?j=await a._OrtRunWithBinding(c,m.handle,k,U,b):j=await a._OrtRun(c,X,W,x,H,k,U,b),j!==0&&Ie("failed to call OrtRun().");let Y=[],$=[];Ur("wasm ProcessOutputTensor");for(let C=0;C<k;C++){let te=Number(a.getValue(U+C*i,"*"));if(te===M[C]||O.includes(M[C])){Y.push(n[C]),te!==M[C]&&a._OrtReleaseTensor(te)!==0&&Ie("Can't release tensor.");continue}let ae=a.stackSave(),L=a.stackAlloc(4*i),N=!1,B,J=0;try{a._OrtGetTensorData(te,L,L+i,L+2*i,L+3*i)!==0&&Ie(`Can't access output tensor data on index ${C}.`);let xe=i===4?"i32":"i64",ue=Number(a.getValue(L,xe));J=a.getValue(L+i,"*");let qe=a.getValue(L+i*2,"*"),ot=Number(a.getValue(L+i*3,xe)),mt=[];for(let Be=0;Be<ot;Be++)mt.push(Number(a.getValue(qe+Be*i,xe)));a._OrtFree(qe)!==0&&Ie("Can't free memory for tensor dims.");let at=mt.reduce((Be,Te)=>Be*Te,1);B=fc(ue);let Et=m?.outputPreferredLocations[s[C]];if(B==="string"){if(Et==="gpu-buffer"||Et==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Be=[];for(let Te=0;Te<at;Te++){let Ze=a.getValue(J+Te*i,"*"),sr=a.getValue(J+(Te+1)*i,"*"),Le=Te===at-1?void 0:sr-Ze;Be.push(a.UTF8ToString(Ze,Le))}Y.push([B,mt,Be,"cpu"])}else if(Et==="gpu-buffer"&&at>0){let Be=a.webgpuGetBuffer;if(!Be)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Te=Be(J),Ze=dn(ue,at);if(Ze===void 0||!lf(B))throw new Error(`Unsupported data type: ${B}`);N=!0;{a.webgpuRegisterBuffer(Te,t,J);let sr=a.webgpuCreateDownloader(Te,Ze,t);Y.push([B,mt,{gpuBuffer:Te,download:async()=>{let Le=await sr();return new(Ao(B))(Le)},dispose:()=>{a._OrtReleaseTensor(te)!==0&&Ie("Can't release tensor.")}},"gpu-buffer"])}}else if(Et==="ml-tensor"&&at>0){let Be=a.webnnEnsureTensor,Te=a.webnnIsGraphInputOutputTypeSupported;if(!Be||!Te)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(dn(ue,at)===void 0||!cf(B))throw new Error(`Unsupported data type: ${B}`);if(!Te(t,B,!1))throw new Error(`preferredLocation "ml-tensor" for ${B} output is not supported by current WebNN Context.`);let Ze=await Be(t,J,ue,mt,!1);N=!0,Y.push([B,mt,{mlTensor:Ze,download:a.webnnCreateMLTensorDownloader(J,B),dispose:()=>{a.webnnReleaseTensorId(J),a._OrtReleaseTensor(te)}},"ml-tensor"])}else if(Et==="ml-tensor-cpu-output"&&at>0){let Be=a.webnnCreateMLTensorDownloader(J,B)(),Te=Y.length;N=!0,$.push((async()=>{let Ze=[Te,await Be];return a.webnnReleaseTensorId(J),a._OrtReleaseTensor(te),Ze})()),Y.push([B,mt,[],"cpu"])}else{let Be=Ao(B),Te=new Be(at);new Uint8Array(Te.buffer,Te.byteOffset,Te.byteLength).set(a.HEAPU8.subarray(J,J+Te.byteLength)),Y.push([B,mt,Te,"cpu"])}}finally{a.stackRestore(ae),B==="string"&&J&&a._free(J),N||a._OrtReleaseTensor(te)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Ie("Can't clear bound outputs."),Dr.set(t,[c,p,d,m,_,!1]));for(let[C,te]of await Promise.all($))Y[C][2]=te;return Fr("wasm ProcessOutputTensor"),Y}finally{a.webnnOnRunEnd?.(c),a.stackRestore(E),r.forEach(j=>{j&&j[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(j[2].gpuBuffer)}),n.forEach(j=>{j&&j[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(j[2].gpuBuffer)}),S.forEach(j=>a._OrtReleaseTensor(j)),M.forEach(j=>a._OrtReleaseTensor(j)),P.forEach(j=>a._free(j)),b!==0&&a._OrtReleaseRunOptions(b),A.forEach(j=>a._free(j))}},hf=t=>{let e=De(),r=Dr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Ie("Can't get an profile file name."),e._OrtFree(n)},gf=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Br,Ft,pn,vo,ko,pc,Hd,dc,gs,ws,hA,e2,t2,r2,s2,n2,o2,a2,i2=be(()=>{"use strict";Es(),ZA(),As(),nf(),Br=()=>!!Ve.wasm.proxy&&typeof document<"u",pn=!1,vo=!1,ko=!1,dc=new Map,gs=(t,e)=>{let r=dc.get(t);r?r.push(e):dc.set(t,[e])},ws=()=>{if(pn||!vo||ko||!Ft)throw new Error("worker not ready")},hA=t=>{switch(t.data.type){case"init-wasm":pn=!1,t.data.err?(ko=!0,Hd[1](t.data.err)):(vo=!0,Hd[0]()),pc&&(URL.revokeObjectURL(pc),pc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=dc.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},e2=async()=>{if(!vo){if(pn)throw new Error("multiple calls to 'initWasm()' detected.");if(ko)throw new Error("previous call to 'initWasm()' failed.");if(pn=!0,Br())return new Promise((t,e)=>{Ft?.terminate(),GA().then(([r,s])=>{try{Ft=s,Ft.onerror=o=>e(o),Ft.onmessage=hA,Hd=[t,e];let n={type:"init-wasm",in:Ve};!n.in.wasm.wasmPaths&&(r||Kd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Ft.postMessage(n),pc=r}catch(n){e(n)}},e)});try{await of(Ve.wasm),await pf(Ve),vo=!0}catch(t){throw ko=!0,t}finally{pn=!1}}},t2=async t=>{if(Br())return ws(),new Promise((e,r)=>{gs("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ve}};Ft.postMessage(s)});await df(Ve,t)},r2=async t=>Br()?(ws(),new Promise((e,r)=>{gs("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Ft.postMessage(s,[t.buffer])})):wc(t),s2=async(t,e)=>{if(Br()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ws(),new Promise((r,s)=>{gs("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Ft.postMessage(n,o)})}else return ff(t,e)},n2=async t=>{if(Br())return ws(),new Promise((e,r)=>{gs("release",[e,r]);let s={type:"release",in:t};Ft.postMessage(s)});mf(t)},o2=async(t,e,r,s,n,o)=>{if(Br()){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 ws(),new Promise((a,i)=>{gs("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Ft.postMessage(c,gf(l))})}else return _f(t,e,r,s,n,o)},a2=async t=>{if(Br())return ws(),new Promise((e,r)=>{gs("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Ft.postMessage(s)});hf(t)}}),Xd,gA,l2,_z=be(()=>{"use strict";Es(),i2(),fn(),sf(),VA(),Xd=(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()}`)}},gA=t=>{switch(t[3]){case"cpu":return new Zt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!lf(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Zt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!cf(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Zt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},l2=class{async fetchModelAndCopyToWasmMemory(t){return r2(await uf(t))}async loadModel(t,e){vs();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await s2(r,e),ks()}async dispose(){return n2(this.sessionId)}async run(t,e,r){vs();let s=[],n=[];Object.entries(t).forEach(d=>{let m=d[0],_=d[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(d=>{let m=d[0],_=d[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(_),a.push(w)});let i=s.map((d,m)=>Xd(d,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((d,m)=>d?Xd(d,()=>`output "${this.outputNames[a[m]]}"`):null),c=await o2(this.sessionId,n,i,a,l,r),p={};for(let d=0;d<c.length;d++)p[this.outputNames[a[d]]]=o[d]??gA(c[d]);return ks(),p}startProfiling(){}endProfiling(){a2(this.sessionId)}}}),c2={};To(c2,{OnnxruntimeWebAssemblyBackend:()=>Zd,initializeFlags:()=>Jd,wasmBackend:()=>u2});var Jd,Zd,u2,hz=be(()=>{"use strict";Es(),i2(),_z(),Jd=()=>{(typeof Ve.wasm.initTimeout!="number"||Ve.wasm.initTimeout<0)&&(Ve.wasm.initTimeout=0);let t=Ve.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.`),Ve.wasm.simd=!1),typeof Ve.wasm.proxy!="boolean"&&(Ve.wasm.proxy=!1),typeof Ve.wasm.trace!="boolean"&&(Ve.wasm.trace=!1),typeof Ve.wasm.numThreads!="number"||!Number.isInteger(Ve.wasm.numThreads)||Ve.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ve.wasm.numThreads=1;else{let e=typeof navigator>"u"?HL("node:os").cpus().length:navigator.hardwareConcurrency;Ve.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Zd=class{async init(t){Jd(),await e2(),await t2(t)}async createInferenceSessionHandler(t,e){let r=new l2;return await r.loadModel(t,e),r}},u2=new Zd});Es();Es();Es();var gz="1.25.0-dev.20260307-d626b568e0",wz=RA;{let t=(hz(),mc(c2)).wasmBackend;bs("webgpu",t,5),bs("webnn",t,5),bs("cpu",t,10),bs("wasm",t,10)}Object.defineProperty(Ve.versions,"web",{value:gz,enumerable:!0});async function p2(t){let e=t.split("/").pop(),r;try{if(r=await Jt(),r){let n=await r.match(t);if(n)return n}}catch(n){Z.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){Z.warn(`Failed to cache ${e}:`,n)}return s}async function d2(t){let e=await p2(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return Z.warn("Failed to read WASM binary:",r),null}}async function f2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await p2(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 Z.warn("Failed to read WASM factory:",r),null}}var m2="1.24.3";var _2="warning",xf={wasm:{},webgl:{},webgpu:{},versions:{common:m2},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}`);_2=t}},get logLevel(){return _2}};Object.defineProperty(xf,"logLevel",{enumerable:!0});var h2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,d=0,m=p,_=p*2,w=-1;a==="RGBA"?(d=0,m=p,_=p*2,w=p*3):a==="RGB"?(d=0,m=p,_=p*2):a==="RBG"&&(d=0,_=p,m=p*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let b=(t.data[d++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[_++]-c[2])*l[2],M=w===-1?255:(t.data[w++]-c[3])*l[3];s.fillStyle="rgba("+b+","+A+","+S+","+M+")",s.fillRect(k,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},g2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=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,k=3,b=0,A=d,S=d*2,M=-1;i==="RGBA"?(b=0,A=d,S=d*2,M=d*3):i==="RGB"?(b=0,A=d,S=d*2):i==="RBG"&&(b=0,S=d,A=d*2),s=r.createImageData(n,o);for(let P=0;P<o*n;_+=m,w+=m,x+=m,k+=m,P++)s.data[_]=(t.data[b++]-p[0])*c[0],s.data[w]=(t.data[A++]-p[1])*c[1],s.data[x]=(t.data[S++]-p[2])*c[2],s.data[k]=M===-1?255:(t.data[M++]-p[3])*c[3]}else throw new Error("Can not access image data");return s};var yf=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,m=0,_=1,w=2,x=3,k=0,b=c,A=c*2,S=-1;i==="RGB"&&(d=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,A=c,b=c*2):l==="BGR"&&(A=0,b=c,k=c*2);for(let P=0;P<c;P++,m+=d,w+=d,_+=d,x+=d)p[k++]=(t[m]+a[0])/o[0],p[b++]=(t[_]+a[1])/o[1],p[A++]=(t[w]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new xt("float32",p,[1,4,r,s]):new xt("float32",p,[1,3,r,s])},w2=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let d=c(p);if(d!=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=_;d.drawImage(t,0,0),a=d.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,d=e.resizedWidth):(p=t.height,d=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=d,e!==void 0){let m=l();m.width=d,m.height=p;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let d=c(p);if(d!=null){let m=t.height,_=t.width;return d.drawImage(t,0,0,_,m),a=d.getImageData(0,0,_,m).data,i.height=m,i.width=_,yf(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{let m=l(),_=c(m);if(!t||!_)return d();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,p(yf(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return yf(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},x2=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new xt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},y2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new xt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},b2=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new xt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},v2=(t,e,r)=>new xt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Ts=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"]]),k2=!1,E2=()=>{if(!k2){k2=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Ts.set("int64",BigInt64Array),Mo.set(BigInt64Array,"int64")),e&&(Ts.set("uint64",BigUint64Array),Mo.set(BigUint64Array,"uint64")),s?(Ts.set("float16",r),Mo.set(r,"float16")):Ts.set("float16",Uint16Array)}};var A2=t=>{let e=1;for(let r=0;r<t.length;r++){let s=t[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);e*=s}return e},T2=(t,e)=>{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){E2();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=Ts.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=Ts.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=A2(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 w2(e,r)}static fromTexture(e,r){return x2(e,r)}static fromGpuBuffer(e,r){return y2(e,r)}static fromMLTensor(e,r){return b2(e,r)}static fromPinnedBuffer(e,r,s){return v2(e,r,s)}toDataURL(e){return h2(this,e)}toImageData(e){return g2(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 T2(this,e)}};var xc=xt;var xz=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 I2(t){return t<=St.DEBUG?0:t<=St.INFO?2:t<=St.WARNING||t<=St.ERROR?3:4}var yz={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Gt=[],bf,_n,M2=Symbol.for("onnxruntime");if(M2 in globalThis)_n=globalThis[M2];else if(ie.IS_NODE_ENV){switch(_n=Md,process.platform){case"win32":Gt.push("dml");break;case"linux":process.arch==="x64"&&Gt.push("cuda");break;case"darwin":Gt.push("coreml");break}Gt.push("webgpu"),Gt.push("cpu"),bf=["cpu"]}else _n=wf,ie.IS_WEBNN_AVAILABLE&&Gt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&Gt.push("webgpu"),Gt.push("wasm"),bf=["wasm"];var bz=_n.InferenceSession;function C2(t=null){if(!t)return bf;switch(t){case"auto":return Gt;case"gpu":return Gt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Gt.includes(t))return[xz[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Gt.join(", ")}.`)}var S2=Promise.resolve(),mn=null;async function vz(){if(mn)return mn;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 mn=Promise.resolve(),mn}return mn=(async()=>{let e=st.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!yd(e.wasm)?(async()=>{try{let s=await d2(bd(e.wasm));s&&(st.wasm.wasmBinary=s,r=!0)}catch(s){Z.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!yd(e.mjs)?(async()=>{try{let s=await f2(bd(e.mjs));s&&(st.wasm.wasmPaths.mjs=s)}catch(s){Z.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(st.wasm.wasmPaths.mjs=e.mjs)})(),mn}async function yc(t,e,r){await vz();let s=I2(me.logLevel??St.WARNING),n=()=>bz.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?S2=S2.then(n):n());return o.config=r,o}var O2=Promise.resolve();async function bc(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?O2=O2.then(r):r()}function vc(t){return t instanceof _n.Tensor}var st=_n?.env;function So(){return st?.wasm?.proxy}if(st){let t=function(e){let r=I2(e);st.logLevel=yz[r]};if(st.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&st.versions?.web&&!st.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${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??St.WARNING),me.backends.onnx={...st,setLogLevel:t}}var Gr=async(t,e,r)=>{let s=await yc(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 bc(s,a);return Array.isArray(r)?r.map(l=>new R(i[l])):new R(i[r])})},ur=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Gr([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=Gr([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=Gr([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=Gr([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=Gr([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=Gr([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=Gr([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=Gr([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 P2=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"}),vf=ie.IS_NODE_ENV?"cpu":"wasm";function kc(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 (${vf}).`),vf):vf}var N2=(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"}),L2=yt.fp32,z2=Object.freeze({[P2.wasm]:yt.q8}),Oo=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 Ec(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=z2[r]??L2}else o&&yt.hasOwnProperty(o)?i=o:i=z2[r]??L2;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var vr=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 R=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 vc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new xc(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;n<e;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(e){let[r,...s]=this.dims;if(e=pr(e,r),s.length>0){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<r.length;++s)if(r[s]==e)return s;return-1}_subarray(e,r,s){let n=e*r,o=(e+1)*r,a="subarray"in this.data?this.data.subarray(n,o):this.data.slice(n,o);return new t(this.type,a,s)}item(){let e=this.data;if(e.length!==1)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return kz(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=1/(1+Math.exp(-e[r]));return this}map(e){return this.clone().map_(e)}map_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]=e(r[s],s,r);return this}mul(e){return this.clone().mul_(e)}mul_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]-=e;return this}clone(){return new t(this.type,this.data.slice(),this.dims.slice())}slice(...e){let r=[],s=[];for(let p=0;p<this.dims.length;++p){let d=e[p];if(d==null)s.push([0,this.dims[p]]),r.push(this.dims[p]);else if(typeof d=="number")d=pr(d,this.dims[p],p),s.push([d,d+1]);else if(Array.isArray(d)&&d.length===2){let[m,_]=d;if(m=m===null?0:pr(m,this.dims[p],p,!1),_=_===null?this.dims[p]:pr(_,this.dims[p],p,!1),m>_)throw new Error(`Invalid slice: ${d}`);let w=[Math.max(m,0),Math.min(_,this.dims[p])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${d}`)}let n=s.map(([p,d])=>d-p),o=n.reduce((p,d)=>p*d),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let p=1;p<n.length;++p)if(s[p][0]!==0||s[p][1]!==this.dims[p]){c=!1;break}if(c){let p=s[0][0]*l[0],d=s[0][1]*l[0];if(ArrayBuffer.isView(a))i.set(a.subarray(p,d));else if(Array.isArray(a)){let m=a.slice(p,d);for(let _=0;_<m.length;++_)i[_]=m[_]}else throw new Error("Unsupported data type for slicing")}else for(let p=0;p<o;++p){let d=0;for(let m=n.length-1,_=p;m>=0;--m){let w=n[m];d+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[p]=a[d]}return new t(this.type,i,r)}permute(...e){return Ez(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=(d,m)=>d+m,i=0n):(a=(d,m)=>d+m**e,i=0),r===null){let d=n.reduce(a,i);return e!==1&&(d=d**(1/e)),new t(this.type,[d],[])}let[l,c,p]=Io(a,this,r,s);if(e!==1)for(let d=0;d<c.length;++d)c[d]=c[d]**(1/e);return new t(l,c,p)}normalize_(e=2,r=1){r=pr(r,this.dims.length);let s=this.norm(e,r,!0),n=this.data,o=s.data;for(let a=0;a<n.length;++a){let i=0;for(let l=this.dims.length-1,c=a,p=1;l>=0;--l){let d=this.dims[l];if(l!==r){let m=c%d;i+=m*p,p*=this.dims[l]}c=Math.floor(c/d)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return kf(this.dims)}squeeze(e=null){return new t(this.type,this.data,R2(this.dims,e))}squeeze_(e=null){return this.dims=R2(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,$2(this.dims,e))}unsqueeze_(e){return this.dims=$2(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;n<e.length;++n)if(e[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}let s=this.data;if(r!==-1){let n=e.reduce((o,a,i)=>i!==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;r<e.length;++r)e[r]=-e[r];return this}neg(){return this.clone().neg_()}gt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>e?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;n<s.length;++n)r[n]=s[n]<e?1:0;return new t("bool",r,this.dims)}clamp_(e,r){let s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],e),r);return this}clamp(e,r){return this.clone().clamp_(e,r)}round_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=Math.round(e[r]);return this}round(){return this.clone().round_()}mean(e=null,r=!1){return Mc(this,e,r)}min(e=null,r=!1){if(e===null){let a=wo(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Io((a,i)=>Math.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Oe(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Io((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=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=Oe(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${e.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(e.every(p=>p===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,d=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),d)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((p,d)=>p*e[d]),o=n.reduce((p,d)=>p*d,1),a=this.data,i=new a.constructor(o),l=kf(s),c=kf(n);for(let p=0;p<o;++p){let d=p,m=0;for(let _=0;_<n.length;++_){let w=Math.floor(d/c[_]);d=d%c[_];let x=w%s[_];m+=x*l[_]}i[p]=a[m]}return new t(this.type,i,n)}tile(...e){if(e.length<this.dims.length){let r=this.dims.length-e.length;e=Array(r).fill(1).concat(e)}return this.repeat(...e)}to(e){if(this.type===e)return this;if(!vr.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);let r,s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(e);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=o=>BigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,qE(this.data),this.dims);return new t(e,vr[e].from(this.data,r),this.dims)}};function kz(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.length<e[o]?l.push(i):a.push([i]),a},[[]]);return n[0]}function Ez(t,e){let[r,s]=DE(t.data,t.dims,e);return new R(t.type,r,s)}function Ef(t,[e,r],s="bilinear",n=!1){let o=t.dims.at(-3)??1,a=t.dims.at(-2),i=t.dims.at(-1),l=$E(t.data,[o,a,i],[e,r],s,n);return new R(t.type,l,[o,e,r])}async function vt(t,{size:e=null,mode:r="bilinear"}={}){if(t.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!e)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(e.length===2)s=[...t.dims.slice(0,2),...e];else if(e.length===3)s=[t.dims[0],...e];else if(e.length===4)s=e;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await ur.nearest_interpolate_4d;else if(r==="bilinear")n=await ur.bilinear_interpolate_4d;else if(r==="bicubic")n=await ur.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new R("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function D2(t,e){return await(await ur.matmul)({a:t,b:e})}async function aD(t,e){return await(await ur.rfft)({x:t,a:e})}async function er(t,e){let r=await ur.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new R("int64",[BigInt(e)],[1])})}var Ac=t=>new R("int64",t,[t.length]);async function Tc(t,e,r,s,n){return await(await ur.slice)({x:t,s:Ac(e),e:Ac(r),a:Ac(s),t:Ac(n??new Array(s.length).fill(1))})}function B2(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;p<a;++p){let d=p*l*i;for(let m=0;m<l;++m){let _=0,w=0,x=p*i,k=d+m;for(let A=0;A<i;++A){let S=Number(s[x+A]);w+=S,_+=r[k+A*l]*S}let b=_/w;o[c++]=b}}return new R(t.type,o,n)}function iD(t,e,{eps:r=1e-5}={}){if(t.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[s,n]=t.dims;if(e.length!==1&&e[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[o,a]=Af(t,1,0,!0),i=o.data,l=a.data,c=t.data,p=new c.constructor(c.length);for(let d=0;d<s;++d){let m=d*n;for(let _=0;_<n;++_){let w=m+_;p[w]=(c[w]-l[d])/(i[d]+r)}}return new R(t.type,p,t.dims)}function R2(t,e){return t=t.slice(),e===null?t=t.filter(r=>r!==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 $2(t,e){return e=pr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function pr(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 ke(t,e=0){e=pr(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<t.length;++i){let{data:l,dims:c}=t[i];for(let p=0;p<l.length;++p){let d=0;for(let m=c.length-1,_=p,w=1;m>=0;--m){let x=c[m],k=_%x;m===e&&(k+=a),d+=k*w,w*=r[m],_=Math.floor(_/x)}n[d]=l[p]}a+=c[e]}}return new R(o,n,r)}function Ot(t,e=0){return ke(t.map(r=>r.unsqueeze(e)),e)}function Io(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=pr(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<o.length;++c){let p=0;for(let d=a.length-1,m=c,_=1;d>=0;--d){let w=a[d];if(d!==r){let x=m%w;p+=x*_,_*=i[d]}m=Math.floor(m/w)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function Af(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 R(t.type,[_],[]);return[new R(t.type,[w],[]),x]}e=pr(e,o.length);let a=Mc(t,e,s),i=a.data,[l,c,p]=Io((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;m<c.length;++m)c[m]=Math.sqrt(c[m]/(o[e]-r));return[new R(l,c,p),a]}function Mc(t,e=null,r=!1){let s=t.dims,n=t.data;if(e===null){let l=n.reduce((c,p)=>c+p,0);return new R(t.type,[l/n.length],[])}e=pr(e,s.length);let[o,a,i]=Io((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l<a.length;++l)a[l]/=s[e];return new R(o,a,i)}function kf(t){let e=new Array(t.length);for(let r=t.length-1,s=1;r>=0;--r)e[r]=s,s*=t[r];return e}function Tf(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new R(r,new s(n).fill(e),t)}function He(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 Tf(t,e,r,s)}function Co(t,e){return He(t.dims,e)}function tt(t){return Tf(t,1n,"int64",BigInt64Array)}function Sc(t){return tt(t.dims)}function Mf(t){return Tf(t,0n,"int64",BigInt64Array)}function Sf(t){return Mf(t.dims)}function lD(t){let e=t.reduce((r,s)=>r*s,1);return new R("float32",Float32Array.from({length:e},()=>_s.random()),t)}function U2(t){let e=t.reduce((r,s)=>r*s,1);return new R("float32",Float32Array.from({length:e},()=>_s.gauss()),t)}function F2(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;i<o.length;++i){let l=o[i]>0?1:0,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new R(s,a,[t.dims[0],t.dims[1]/8])}async function hn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await cr(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Of(t,e){let r=await hn(t);return await Promise.all(r.map(s=>ut(t,s,!0,e)))}function If(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 Az=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Tz(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 Mz(t,e){for(let r of Object.keys(t))t[r].length=e}function Ms(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 Sz(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var q=class extends et{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new fE(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ms(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ms(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ms(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ms(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ms(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ms(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=Sz(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 Of(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),p;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");p=e.map((m,_)=>this._encode_plus(m,{text_pair:r[_],add_special_tokens:s,return_token_type_ids:l}))}else p=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).");p=[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?(Z.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&&(Z.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(Oe(p.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;m<p.length;++m)p[m].input_ids.length!==a&&(p[m].input_ids.length>a?o&&Mz(p[m],a):n&&Tz(p[m],a,_=>_==="input_ids"?this.pad_token_id:0,this.padding_side));let d={};if(i){if(!(n&&o)&&p.some(_=>{for(let w of Object.keys(_))if(_[w].length!==p[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=[p.length,p[0].input_ids.length];for(let _ of Object.keys(p[0]))d[_]=new R("int64",BigInt64Array.from(p.flatMap(w=>w[_]).map(BigInt)),m)}else{for(let m of Object.keys(p[0]))d[m]=p.map(_=>_[m]);if(!c)for(let m of Object.keys(d))d[m]=d[m][0]}return d}_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 R&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof R&&(e=If(e)),!Array.isArray(e)||e.length===0||!Kk(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:p=!0,return_dict:d=!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 AE(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let b of Az){let A=Ms(this.config,b);A&&(x[b]=A)}let k=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,..._});if(a){let b=this._call(k,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:p,...m});return d?b:b.input_ids}return k}};function gn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var bm={};ds(bm,{AlbertTokenizer:()=>Cf,AutoTokenizer:()=>oe,BartTokenizer:()=>Pf,BertTokenizer:()=>Lf,BlenderbotSmallTokenizer:()=>zf,BlenderbotTokenizer:()=>Nf,BloomTokenizer:()=>Rf,CLIPTokenizer:()=>Df,CamembertTokenizer:()=>$f,CodeGenTokenizer:()=>Uf,CodeLlamaTokenizer:()=>Bf,CohereTokenizer:()=>Ff,ConvBertTokenizer:()=>Gf,DebertaTokenizer:()=>qf,DebertaV2Tokenizer:()=>jf,DistilBertTokenizer:()=>Wf,ElectraTokenizer:()=>Vf,EsmTokenizer:()=>Hf,FalconTokenizer:()=>Xf,GPT2Tokenizer:()=>Qf,GPTNeoXTokenizer:()=>Yf,GemmaTokenizer:()=>Kf,HerbertTokenizer:()=>Jf,LlamaTokenizer:()=>Zf,M2M100Tokenizer:()=>em,MBart50Tokenizer:()=>rm,MBartTokenizer:()=>Po,MPNetTokenizer:()=>om,MarianTokenizer:()=>tm,MgpstrTokenizer:()=>sm,MobileBertTokenizer:()=>nm,NllbTokenizer:()=>am,NougatTokenizer:()=>im,PreTrainedTokenizer:()=>q,Qwen2Tokenizer:()=>lm,RoFormerTokenizer:()=>um,RobertaTokenizer:()=>cm,SiglipTokenizer:()=>pm,SpeechT5Tokenizer:()=>dm,SqueezeBertTokenizer:()=>fm,T5Tokenizer:()=>mm,TokenizersBackend:()=>q,VitsTokenizer:()=>hm,Wav2Vec2CTCTokenizer:()=>gm,WhisperTokenizer:()=>wm,XLMRobertaTokenizer:()=>xm,XLMTokenizer:()=>ym});var Cf=class extends q{return_token_type_ids=!0};var Pf=class extends q{};var Lf=class extends q{return_token_type_ids=!0};var zf=class extends q{};var Nf=class extends q{};var Rf=class extends q{};var $f=class extends q{};var Df=class extends q{};var Bf=class extends q{};var Uf=class extends q{};var Ff=class extends q{};var Gf=class extends q{return_token_type_ids=!0};var jf=class extends q{return_token_type_ids=!0};var qf=class extends q{return_token_type_ids=!0};var Wf=class extends q{};var Vf=class extends q{return_token_type_ids=!0};var Hf=class extends q{};var Xf=class extends q{};var Kf=class extends q{};var Yf=class extends q{};var Qf=class extends q{};var Jf=class extends q{return_token_type_ids=!0};var Zf=class extends q{padding_side="left"};var em=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var tm=class extends q{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)),Z.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)||Z.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 Po=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var rm=class extends Po{};var sm=class extends q{};var nm=class extends q{return_token_type_ids=!0};var om=class extends q{};var am=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return gn(this,e,r,s)}};var im=class extends q{};var lm=class extends q{};var cm=class extends q{};var um=class extends q{return_token_type_ids=!0};var pm=class extends q{};var dm=class extends q{};var fm=class extends q{return_token_type_ids=!0};var mm=class extends q{};var _m=class extends Bt{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},hm=class extends q{constructor(e,r){super(e,r),this._tokenizer.decoder=new _m({type:"VitsDecoder"})}};var gm=class extends q{};var G2=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],Lo=new Map(G2),Oz=new Map([...G2.map(([t,e])=>[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 j2(t){t=t.toLowerCase();let e=Oz.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Lo.has(t))e=t;else{let n=t.length===2?Lo.keys():Lo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var Iz="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",q2=new RegExp(`^[${Iz}]+$`,"gu"),wm=class extends q{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],p=l(),d=0,m=this.timestamp_begin,w=m+1500,x=[],k=[],b=!1,A=null,S=new Set(this.all_special_ids);for(let O of e){let E=O.tokens,W=i?O.token_timestamps:null,X=null,U=m;if("stride"in O){let[Y,$,C]=O.stride;if(d-=$,A=Y-C,$&&(U=$/n+m),C)for(let te=E.length-1;te>=0;--te){let ae=Number(E[te]);if(ae>=m){if(X!==null&&(ae-m)*n<A)break;X=ae}}}let H=[],j=[];for(let Y=0;Y<E.length;++Y){let $=Number(E[Y]);if(S.has($)){let C=this.decode([$]),te=Lo.get(C.slice(2,-2));if(te!==void 0){if(a!==null&&te!==a&&!r){x.push(H);let ae=this.findLongestCommonSequence(x)[0],L=this.decode(ae);p.text=L,c.push(p),x=[],H=[],p=l()}a=p.language=te}}else if($>=m&&$<=w){let C=($-m)*n+d,te=hs(C,2);if(X!==null&&$>=X)b=!0;else if(b||x.length>0&&$<U)b=!1;else if(p.timestamp[0]===null)p.timestamp[0]=te;else if(te!==p.timestamp[0]){p.timestamp[1]=te,x.push(H),i&&k.push(j);let[ae,L]=this.findLongestCommonSequence(x,k),N=this.decode(ae);p.text=N,i&&(p.words=this.collateWordTimestamps(ae,L,a)),c.push(p),x=[],H=[],k=[],j=[],p=l()}}else if(H.push($),i){let C=hs(W[Y]+d,2),te;if(Y+1<W.length){te=hs(W[Y+1]+d,2);let ae=this.decode([$]);q2.test(ae)&&(te=hs(Math.min(C+n,te),2))}else te=null;j.push([C,te])}}if("stride"in O){let[Y,$,C]=O.stride;d+=Y-C}H.length>0?(x.push(H),i&&k.push(j)):x.every(Y=>Y.length===0)&&(p=l(),x=[],H=[],k=[],j=[])}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,E]=this.findLongestCommonSequence(x,k),W=this.decode(O);p.text=W,i&&(p.words=this.collateWordTimestamps(O,E,a)),c.push(p)}let M=Object.create(null),P=c.map(O=>O.text).join("");if(r||s){for(let O=0;O<c.length;++O){let E=c[O];r||delete E.timestamp,s||delete E.language}if(i){let O=[];for(let E of c)for(let W of E.words)O.push(W);M={chunks:O}}else M={chunks:c}}return[P,M]}findLongestCommonSequence(e,r=null){let s=e[0],n=s.length,o=[],a=Array.isArray(r)&&r.length>0,i=a?[]:null,l=a?r[0]:null;for(let c=1;c<e.length;++c){let p=e[c],d=0,m=[n,n,0,0],_=p.length;for(let M=1;M<n+_;++M){let P=Math.max(0,n-M),O=Math.min(n,n+_-M),E=s.slice(P,O),W=Math.max(0,M-n),X=Math.min(_,M),U=p.slice(W,X);if(E.length!==U.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let H;a?H=E.filter(($,C)=>$===U[C]&&l[P+C]<=r[c][W+C]).length:H=E.filter(($,C)=>$===U[C]).length;let j=M/1e4,Y=H/M+j;H>1&&Y>d&&(d=Y,m=[P,O,W,X])}let[w,x,k,b]=m,A=Math.floor((x+w)/2),S=Math.floor((b+k)/2);o.push(...s.slice(0,A)),s=p.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.length;++l){let c=a[l];i.push({text:n[l],timestamp:[r[c.at(0)][0],r[c.at(-1)][1]]})}return i}combineTokensIntoWords(e,r,s=`"'\u201C\xA1\xBF([{-`,n=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){r=r??"english";let o,a,i;return["chinese","japanese","thai","lao","myanmar"].includes(r)?[o,a,i]=this.splitTokensOnUnicode(e):[o,a,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(o,a,i,s,n)}decode(e,r){let s;return r?.decode_with_timestamps?(e instanceof R&&(e=If(e)),s=this.decodeWithTimestamps(e,r)):s=super.decode(e,r),s}decodeWithTimestamps(e,r){let s=r?.time_precision??.02,n=this.all_special_ids.at(-1)+1,o=[[]];for(let a of e)if(a=Number(a),a>=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let p=0;p<e.length;++p){let d=e[p];i.push(d),l.push(p);let m=this.decode(i,{decode_with_timestamps:!0});(!m.includes(s)||r[c+m.indexOf(s)]===s)&&(n.push(m),o.push(i),a.push(l),i=[],l=[],c+=m.length)}return[n,o,a]}splitTokensOnSpaces(e){let[r,s,n]=this.splitTokensOnUnicode(e),o=[],a=[],i=[];for(let l=0;l<r.length;++l){let c=r[l],p=s[l],d=n[l],m=p[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=c.startsWith(" "),w=c.trim(),x=q2.test(w);if(m||_||x||o.length===0)o.push(c),a.push(p),i.push(d);else{let k=o.length-1;o[k]+=c,a[k].push(...p),i[k].push(...d)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=gt(i[c],i[p]),l[p]=gt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;p<a.length;)!a[c].endsWith(" ")&&o.includes(a[p])?(a[c]+=a[p],i[c]=gt(i[c],i[p]),l[c]=gt(l[c],l[p]),a[p]="",i[p]=[],l[p]=[]):c=p,++p;return[a.filter(d=>d),i.filter(d=>d.length>0),l.filter(d=>d.length>0)]}};var xm=class extends q{};var ym=class extends q{return_token_type_ids=!0;constructor(e,r){super(e,r),Z.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var oe=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 Of(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=bm[c];return p||(Z.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=q),new p(i,l)}};var jr="https://github.com/huggingface/transformers.js/issues/new/choose";var zo="preprocessor_config.json",kr=zo,W2="processor_config.json",V2="chat_template.jinja";var re=class extends et{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,W2,!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?Ed(e,V2,!0,r):null]);return new this(s,n,o)}};var eu={};ds(eu,{ChatterboxProcessor:()=>Dm,Florence2Processor:()=>O_,Gemma3nProcessor:()=>I_,Glm46VProcessor:()=>C_,GraniteSpeechProcessor:()=>P_,GroundingDinoProcessor:()=>L_,Idefics3Processor:()=>Yc,JinaCLIPProcessor:()=>N_,Lfm2VlProcessor:()=>R_,LlavaProcessor:()=>$_,MgpstrProcessor:()=>D_,MoonshineProcessor:()=>B_,OwlViTProcessor:()=>U_,PaliGemmaProcessor:()=>F_,Phi3VProcessor:()=>G_,PixtralProcessor:()=>j_,Processor:()=>re,PyAnnoteProcessor:()=>q_,Qwen2VLProcessor:()=>Os,Qwen2_5_VLProcessor:()=>Go,Qwen3VLProcessor:()=>W_,Sam2Processor:()=>Qc,Sam2VideoProcessor:()=>V_,SamProcessor:()=>jo,SmolVLMProcessor:()=>Yc,SpeechT5Processor:()=>H_,UltravoxProcessor:()=>X_,VLChatProcessor:()=>z_,VoxtralProcessor:()=>K_,VoxtralRealtimeProcessor:()=>Q_,Wav2Vec2Processor:()=>J_,Wav2Vec2ProcessorWithLM:()=>Z_,WhisperProcessor:()=>eh});var Ee=class extends et{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await ut(e,zo,!0,r);return new this(s)}};function $e(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={};ds(Bo,{ASTFeatureExtractor:()=>Em,ChatterboxFeatureExtractor:()=>Am,ClapFeatureExtractor:()=>Tm,DacFeatureExtractor:()=>$o,EncodecFeatureExtractor:()=>Ro,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Mm,GraniteSpeechFeatureExtractor:()=>Sm,MoonshineFeatureExtractor:()=>Om,ParakeetFeatureExtractor:()=>Im,PyAnnoteFeatureExtractor:()=>Do,SeamlessM4TFeatureExtractor:()=>Cm,SnacFeatureExtractor:()=>Pm,SpeechT5FeatureExtractor:()=>Lm,VoxtralRealtimeFeatureExtractor:()=>Rm,Wav2Vec2FeatureExtractor:()=>zm,WeSpeakerFeatureExtractor:()=>Nm,WhisperFeatureExtractor:()=>$m});var Cz=()=>{};var H2={fromWeb:Cz};var Pz=()=>{};var X2=Pz;async function Oc(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=H2.fromWeb(r),n=ht.createWriteStream(t);await X2(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function km(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 Lr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&Z.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;c<n.length;++c)o[c]=a*(i[c]+l[c])/2}else o=n.getChannelData(0);return o}function Q2(t,e){if(t<1)return new Float64Array;if(t===1)return new Float64Array([1]);let r=1-e,s=2*Math.PI/(t-1),n=new Float64Array(t);for(let o=0;o<t;++o)n[o]=e-r*Math.cos(o*s);return n}function K2(t){return Q2(t,.5)}function Lz(t){return Q2(t,.54)}var zz={htk:t=>2595*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 vm(t,e="htk"){let r=zz[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 Nz={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 Rz(t,e="htk"){let r=Nz[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 $z(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;a<t.length;++a){let i=s[a];for(let l=0;l<e.length;++l)i[l]=e[l]-t[a]}let n=e.length-2,o=Array.from({length:n},()=>new Array(t.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<n;++l){let c=-i[l]/r[l],p=i[l+2]/r[l+1];o[l][a]=Math.max(0,Math.min(c,p))}}return o}function Y2(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+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=vm(r,a),c=vm(s,a),p=Y2(l,c,e+2),d=Rz(p,a),m;if(i){let w=n/((t-1)*2);m=vm(Float64Array.from({length:t},(x,k)=>k*w),a),d=p}else m=Y2(0,Math.floor(n/2),t);let _=$z(m,d);if(o!==null&&o==="slaney")for(let w=0;w<e;++w){let x=_[w],k=2/(d[w+2]-d[w]);for(let b=0;b<t;++b)x[b]*=k}return _}function Dz(t,e,r){let s=new t.constructor(t.length+e+r),n=t.length-1;for(let o=0;o<t.length;++o)s[e+o]=t[o];for(let o=1;o<=e;++o)s[e-o]=t[on(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[on(n-o,n)];return s}function J2(t,e,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);let o=Math.log10(r);for(let a=0;a<t.length;++a)t[a]=e*Math.log10(Math.max(s,t[a])-o);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");let a=Oe(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function Bz(t,e=1,r=1e-5,s=null){return J2(t,20,e,r,s)}function Uz(t,e=1,r=1e-10,s=null){return J2(t,10,e,r,s)}async function dt(t,e,r,s,{fft_length:n=null,power:o=1,center:a=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:p=!0,mel_filters:d=null,mel_floor:m=1e-10,log_mel:_=null,max_log_mel:w=null,reference:x=1,min_value:k=1e-10,db_range:b=null,remove_dc_offset:A=null,min_num_frames:S=null,max_num_frames:M=null,do_pad:P=!0,transpose:O=!1,mel_offset:E=0}={}){let W=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(W!==r)throw new Error(`Length of the window (${W}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&d!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a)switch(i){case"reflect":{let B=Math.floor((n-1)/2)+1;t=Dz(t,B,B);break}case"constant":{let B=Math.floor(n/2),J=new t.constructor(t.length+2*B);J.set(t,B),t=J;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let X=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&X<S&&(X=S);let U=l?Math.floor(n/2)+1:n,H=X,j=X;M!==null&&(M>X?P&&(j=M):j=H=M);let Y=new ac(n),$=new Float64Array(n),C=new Float64Array(Y.outputBufferSize),te=new Float32Array(U*j);for(let B=0;B<H;++B){let J=B*s,xe=Math.min(t.length-J,r);xe!==r&&$.fill(0,0,r);for(let ue=0;ue<xe;++ue)$[ue]=t[J+ue];if(A){let ue=0;for(let ot=0;ot<xe;++ot)ue+=$[ot];let qe=ue/xe;for(let ot=0;ot<xe;++ot)$[ot]-=qe}if(c!==null){for(let ue=xe-1;ue>=1;--ue)$[ue]-=c*$[ue-1];$[0]*=1-c}for(let ue=0;ue<e.length;++ue)$[ue]*=e[ue];Y.realTransform(C,$);for(let ue=0;ue<U;++ue){let qe=ue<<1;te[ue*j+B]=C[qe]**2+C[qe+1]**2}}if(o!==null&&o!==2){let B=o/2;for(let J=0;J<te.length;++J)te[J]**=B}let ae=d.length,L=await D2(new R("float32",d.flat(),[ae,U]),new R("float32",te,[U,j]));O&&(L=L.transpose(1,0));let N=L.data;for(let B=0;B<N.length;++B)N[B]=E+Math.max(m,N[B]);if(o!==null&&_!==null){let B=Math.min(N.length,H*ae);switch(_){case"log":for(let J=0;J<B;++J)N[J]=Math.log(N[J]);break;case"log10":for(let J=0;J<B;++J)N[J]=Math.log10(N[J]);break;case"log10_max_norm":{for(let ue=0;ue<B;++ue)N[ue]=Math.log10(N[ue]);let xe=(w??Oe(N)[0])-8;for(let ue=0;ue<B;++ue)N[ue]=(Math.max(N[ue],xe)+4)/4;break}case"dB":if(o===1)Bz(N,x,k,b);else if(o===2)Uz(N,x,k,b);else throw new Error(`Cannot use log_mel option '${_}' with power ${o}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${_}'`)}}return L}function ft(t,e,{periodic:r=!0,frame_length:s=null,center:n=!0}={}){let o=r?t+1:t,a;switch(e){case"boxcar":a=new Float64Array(o).fill(1);break;case"hann":case"hann_window":a=K2(o);break;case"hamming":a=Lz(o);break;case"povey":a=K2(o).map(i=>Math.pow(i,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);return a}function Fz(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return Ic(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),Ic(n,8,"WAVE"),Ic(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),Ic(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function Ic(t,e,r){for(let s=0;s<r.length;++s)t.setUint8(e+s,r.charCodeAt(s))}var No=class{constructor(e,r){this.audio=e,this.sampling_rate=r}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((n,o)=>n+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]),Fz(e,this.sampling_rate)}async save(e){return Oc(e,this.toBlob())}};var Em=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=ft(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return dt(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){$e(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;o<n.length;++o)n[o]=(n[o]-this.mean)/s}return{input_values:r.unsqueeze_(0)}}};var Ro=class extends Ee{async _call(e){$e(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=this.config.feature_size;if(e.length%r!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${r}).`);let s=[1,r,e.length/r];return{input_values:new R("float32",e,s)}}};var Am=class extends Ee{async _call(e){$e(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new R("float32",e,r)}}};var Tm=class extends Ee{constructor(e){super(e),this.mel_filters=nt(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=nt(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=ft(this.config.fft_window_size,"hann")}async _get_input_mel(e,r,s,n){let o,a=!1,i=e.length-r;if(i>0)if(s==="rand_trunc"){a=!0;let l=Math.floor(_s.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<r;c+=e.length)l.set(e.subarray(0,Math.min(e.length,r-c)),c);else if(n==="repeatpad")for(let c=e.length;c<-i;c+=e.length)l.set(e,c);e=l}if(s==="fusion")throw new Error(`Truncation strategy "${s}" not implemented`);o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return o.unsqueeze_(0)}async _extract_fbank_features(e,r,s=null){return dt(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:r,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:r=null}={}){return $e(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,r??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}};var $o=class extends Ro{};var Mm=class extends Ee{constructor(e){super(e);let{fft_length:r,feature_size:s,min_frequency:n,max_frequency:o,sampling_rate:a,frame_length:i}=this.config,l=nt(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=ft(i,"hann")}async _extract_fbank_features(e,r){return dt(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:r=48e4,truncation:s=!0,padding:n=!0,pad_to_multiple_of:o=128}={}){if($e(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>r&&(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=He([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Sm=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=ft(s,"hann");this.window=new Float64Array(r);let i=Math.floor((r-s)/2);this.window.set(a,i)}async _call(e){$e(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 dt(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 Om=class extends Ee{async _call(e){$e(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new R("float32",e,r)}}};var Gz=1e-5,Im=class extends Ee{constructor(e){super(e),this.config.mel_filters??=nt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let r=ft(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let s=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(r,s)}async _extract_fbank_features(e){let r=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=r*e[n-1];return await dt(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){$e(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 d=0;d<s;++d){let m=d*a;for(let _=0;_<a;++_){let w=n[m+_];i[_]+=w,l[_]+=w*w}}let c=s>1?s-1:1;for(let d=0;d<a;++d){let m=i[d]/s,_=(l[d]-s*m*m)/c,x=1/(Math.sqrt(_)+Gz);for(let k=0;k<s;++k){let b=k*a+d;n[b]=(n[b]-m)*x}}let p=new BigInt64Array(o);return p.fill(1n,0,s),{input_features:r.unsqueeze_(0),attention_mask:new R("int64",p,[1,o])}}};var Do=class extends Ee{async _call(e){$e(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new R("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<o.length;++l){let c=Ne(o[l]),[p,d]=Oe(c),[m,_]=[l,l+1];d!==i?(i=d,a.push({id:d,start:m,end:_,score:p})):(a.at(-1).end=_,a.at(-1).score+=p)}n.push(a.map(({id:l,start:c,end:p,score:d})=>({id:l,start:c*s,end:p*s,confidence:d/(p-c)})))}return n}};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=ft(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),dt(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}={}){$e(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let b=0;b<x;++b){let A=0;for(let O=0;O<w;++O)A+=k[O*x+b];let S=A/w,M=0;for(let O=0;O<w;++O)M+=(k[O*x+b]-S)**2;M/=w-1;let P=Math.sqrt(M+1e-7);for(let O=0;O<w;++O){let E=O*x+b;k[E]=(k[E]-S)/P}}}let i;if(r){let[w,x]=a.dims,k=a.data,b=w%s;if(b>0){let A=new Float32Array(x*(w+b));A.set(k),A.fill(this.config.padding_value,k.length);let S=w+b;a=new R(a.type,A,[S,x]),o&&(i=new R("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let m=a.view(1,Math.floor(l/p),c*p),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let b=1,A=0;b<l;b+=p,++A)x[A]=k[b]}else x.fill(1n);_.attention_mask=new R("int64",x,[1,w])}return _}};var Pm=class extends $o{};var Lm=class extends Ee{};var zm=class extends Ee{_zero_mean_unit_var_norm(e){let s=e.reduce((o,a)=>o+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){$e(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 R("float32",r,s),attention_mask:new R("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Nm=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=ft(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),dt(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){$e(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;l<o;++l){let c=l*a*i,p=l*i;for(let d=0;d<a;++d){let m=c+d*i;for(let _=0;_<i;++_)n[m+_]-=s[p+_]}}}return{input_features:r}}};var Rm=class extends Ee{constructor(e){super(e),this.config.mel_filters??=nt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=ft(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:r=!0}={}){let{n_fft:s,hop_length:n,mel_filters:o,global_log_mel_max:a}=this.config,i=Math.floor(r?e.length/n:(e.length-s)/n);return await dt(e,this.window,s,n,{power:2,mel_filters:o,log_mel:"log10_max_norm",max_log_mel:a,center:r,max_num_frames:i,do_pad:!1})}async _call(e,{center:r=!0}={}){return $e(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:r})).unsqueeze_(0)}}};var $m=class extends Ee{constructor(e){super(e),this.config.mel_filters??=nt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=ft(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await dt(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:r=null}={}){$e(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&Z.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 Xe=class{static async from_pretrained(e,r={}){let s=await ut(e,zo,!0,r),n=s.feature_extractor_type,o=Bo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${jr}.`);return new o(s)}};var Dm=class extends re{static tokenizer_class=oe;static feature_extractor_class=Xe;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var Cc={};var Ss,Z2,qr;if(ie.IS_WEB_ENV)Ss=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},qr=self.createImageBitmap,Z2=self.ImageData;else if(Cc)qr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Ye(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 jz={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},qz=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Ye=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 Lr(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 qr(e),s=Ss(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=Cc(await e.arrayBuffer());return await qr(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<this.data.length;r+=this.channels){let n=this.data[r],o=this.data[r+1],a=this.data[r+2];e[s++]=Math.round(.2989*n+.587*o+.114*a)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2],e[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${e.channels}`);let r=this.data,s=e.data,n=this.width*this.height;if(this.channels===3){let o=new Uint8ClampedArray(n*4);for(let a=0,i=0,l=0;a<n;++a)o[l++]=r[i++],o[l++]=r[i++],o[l++]=r[i++],o[l++]=s[a];return this._update(o,this.width,this.height,4)}else if(this.channels===4){for(let o=0;o<n;++o)r[4*o+3]=s[o];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(e,r,{resample:s=2}={}){if(this.width===e&&this.height===r)return this;let n=jz[s]??s,o=md(e),a=md(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),ie.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=Ss(e,r).getContext("2d");return c.drawImage(l,0,0,e,r),new t(c.getImageData(0,0,e,r).data,e,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(Z.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([e/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:e,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await qr(i)}}async pad([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),e===0&&r===0&&s===0&&n===0)return this;if(ie.IS_WEB_ENV){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,c=Ss(i,l).getContext("2d");return c.drawImage(a,0,0,this.width,this.height,e,s,this.width,this.height),new t(c.getImageData(0,0,i,l).data,i,l,4).convert(o)}else{let o=this.toSharp().extend({left:e,right:r,top:s,bottom:n});return await qr(o)}}async crop([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),e===0&&r===0&&s===this.width-1&&n===this.height-1)return this;let o=s-e+1,a=n-r+1;if(ie.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=Ss(o,a).getContext("2d");return c.drawImage(l,e,r,o,a,0,0,o,a),new t(c.getImageData(0,0,o,a).data,o,a,4).convert(i)}else{let i=this.toSharp().extract({left:e,top:r,width:o,height:a});return await qr(i)}}async center_crop(e,r){if(this.width===e&&this.height===r)return this;let s=(this.width-e)/2,n=(this.height-r)/2;if(ie.IS_WEB_ENV){let o=this.channels,a=this.toCanvas(),i=Ss(e,r).getContext("2d"),l=0,c=0,p=0,d=0;return s>=0?l=s:p=-s,n>=0?c=n:d=-n,i.drawImage(a,l,c,e,r,p,d,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 qr(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 R("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!ie.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=Ss(e.width,e.height),s=new Z2(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;l<a;++l){let c=n*l;for(let p=0;p<n;++p)i[p][l]=e[c+p]}return i.map(l=>new 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=qz.get(r)??"image/png",n=await this.toBlob(s);return Oc(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 Cc(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},Wz=Ye.read.bind(Ye);function eT(t,e,r=0,s=null){let n=t/e,o=GE(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function tT([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function Bm([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Wr(t,e=.5,r=null,s=!1){let n=t.logits,o=t.pred_boxes,[a,i,l]=n.dims;if(r!==null&&r.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let p=0;p<a;++p){let d=r!==null?r[p]:null,m={boxes:[],classes:[],scores:[]},_=n[p],w=o[p];for(let x=0;x<i;++x){let k=_[x],b=[],A;if(s){A=k.sigmoid().data;for(let S=0;S<A.length;++S)A[S]>e&&b.push(S)}else{let S=Oe(k.data)[1];if(S===l-1||(A=Ne(k.data),A[S]<e))continue;b.push(S)}for(let S of b){let M=w[x].data;M=Bm(M),d!==null&&(M=M.map((P,O)=>P*d[(O+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(A[S])}}c.push(m)}return c}function Pc(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;o<s;++o){let a=e!==null?e[o]:null,i=r[o];a!==null&&(i=Ef(i,a,"bilinear",!1));let[l,c]=a??i.dims.slice(-2),p=new R("int32",new Int32Array(l*c),[l,c]),d=i[0].data,m=p.data;for(let x=1;x<i.dims[0];++x){let k=i[x].data;for(let b=0;b<k.length;++b)k[b]>d[b]&&(d[b]=k[b],m[b]=x)}let _=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let k=m[x];_[k]=k}let w=_.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function Vz(t,e,r,s){let n=[],o=[],a=[];for(let i=0;i<t.dims[0];++i){let l=t[i],c=e[i],p=Oe(l.data)[1];if(p===s)continue;let m=Ne(l.data)[p];m>r&&(n.push(c),o.push(m),a.push(p))}return[n,o,a]}function Hz(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let p=0;p<t.length;++p)t[p]===r&&(o.push(p),++a),l[p]>=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function Xz(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new R("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=Ef(t[x],a,"bilinear",!1);let d=new Int32Array(t[0].data.length),m=new Float32Array(t[0].data.length);for(let x=0;x<t.length;++x){let k=e[x],b=t[x].data;for(let A=0;A<b.length;++A)b[A]*=k,b[A]>m[A]&&(d[A]=x,m[A]=b[A])}let _=0,w=c.data;for(let x=0;x<r.length;++x){let k=r[x],[b,A]=Hz(d,t,x,s,n);if(b){++_;for(let S of A)w[S]=_;p.push({id:_,label_id:k,score:e[x]})}}return[c,p]}function wn(t,e,r=28,s=3136,n=784*1280,o=1){if(t<r||e<r){let l=Math.max(r/t,r/e);t=Math.round(t*l),e=Math.round(e*l)}if(Math.max(t,e)/Math.min(t,e)>200)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*i<s){let l=Math.sqrt(s/(o*t*e));a=Math.ceil(t*l/r)*r,i=Math.ceil(e*l/r)*r}return[i,a]}function Lc(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(Z.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);let a=t.class_queries_logits??t.logits,l=(t.masks_queries_logits??t.pred_masks).sigmoid(),[c,p,d]=a.dims;if(d-=1,o!==null&&o.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let m=[];for(let _=0;_<c;++_){let w=o!==null?o[_]:null,x=a[_],k=l[_],[b,A,S]=Vz(x,k,e,d);if(S.length===0){let[O,E]=w??k.dims.slice(-2),W=new R("int32",new Int32Array(O*E).fill(-1),[O,E]);m.push({segmentation:W,segments_info:[]});continue}let[M,P]=Xz(b,A,S,r,s,n,w);m.push({segmentation:M,segments_info:P})}return m}function zc(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var V=class extends et{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,r,s=2){let n=e.height,o=e.width,a=r.height,i=r.width,l=Math.min(n,a),c=Math.min(o,i);return l===n&&c===o?e:(n>o?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=Oe(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,p=0,d=0,m=s.data;for(let _=0;_<s.height;++_){let w=_*s.width;for(let x=0;x<s.width;++x)(m[w+x]-n)/a<i&&(l=Math.min(l,x),c=Math.min(c,_),p=Math.max(p,x),d=Math.max(d,_))}return e=await e.crop([l,c,p,d]),e}pad_image(e,r,s,{mode:n="constant",center:o=!1,constant_values:a=0}={}){let[i,l,c]=r,p,d;if(typeof s=="number"?(p=s,d=s):s==="square"?p=d=Math.max(i,l):(p=s.width,d=s.height),p!==l||d!==i){let m=new Float32Array(p*d*c);if(Array.isArray(a))for(let x=0;x<m.length;++x)m[x]=a[x%c];else a!==0&&m.fill(a);let[_,w]=o?[Math.floor((p-l)/2),Math.floor((d-i)/2)]:[0,0];for(let x=0;x<i;++x){let k=(x+w)*p,b=x*l;for(let A=0;A<l;++A){let S=(k+A+_)*c,M=(b+A)*c;for(let P=0;P<c;++P)m[S+P]=e[M+P]}}if(n==="symmetric"){if(o)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let x=i-1,k=l-1;for(let b=0;b<d;++b){let A=b*p,S=on(b,x)*l;for(let M=0;M<p;++M){if(b<i&&M<l)continue;let P=(A+M)*c,O=(S+on(M,k))*c;for(let E=0;E<c;++E)m[P+E]=e[O+E]}}}e=m,r=[d,p,c]}return[e,r]}rescale(e){for(let r=0;r<e.length;++r)e[r]=this.rescale_factor*e[r]}get_resize_output_image_size(e,r){let[s,n]=e.size,o,a;if(this.do_thumbnail){let{height:i,width:l}=r;o=Math.min(i,l)}else Number.isInteger(r)?(o=r,a=this.config.max_size??o):r!==void 0&&(o=r.shortest_edge,a=r.longest_edge);if(o!==void 0||a!==void 0){let i=o===void 0?1:Math.max(o/s,o/n),l=s*i,c=n*i,p=a===void 0?1:Math.min(a/l,a/c),d=Math.floor(Number((l*p).toFixed(2))),m=Math.floor(Number((c*p).toFixed(2)));return this.size_divisibility!==void 0&&([d,m]=tT([d,m],this.size_divisibility)),[d,m]}else if(r!==void 0&&r.width!==void 0&&r.height!==void 0){let i=r.width,l=r.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let c=l/n,p=i/s;Math.abs(1-p)<Math.abs(1-c)?c=p:p=c,l=eT(c*n,this.config.ensure_multiple_of),i=eT(p*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return tT([s,n],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(r)}`)}}async resize(e){let[r,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(r,s,{resample:this.resample})}async preprocess(e,{do_normalize:r=null,do_pad:s=null,do_convert_rgb:n=null,do_convert_grayscale:o=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[i,l]=e.size;if(n??this.do_convert_rgb?e=e.rgb():o&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,w;Number.isInteger(this.crop_size)?(_=this.crop_size,w=this.crop_size):(_=this.crop_size.width,w=this.crop_size.height),e=await e.center_crop(_,w)}let c=[e.height,e.width],p=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(p),r??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let w=this.image_std;if(Array.isArray(this.image_std)||(w=new Array(e.channels).fill(w)),_.length!==e.channels||w.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${w.length}) must match the number of channels in the image (${e.channels}).`);for(let x=0;x<p.length;x+=e.channels)for(let k=0;k<e.channels;++k)p[x+k]=(p[x+k]-_[k])/w[k]}if(s??this.do_pad){if(this.pad_size)[p,d]=this.pad_image(p,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let _=Math.ceil(d[1]/this.size_divisibility)*this.size_divisibility,w=Math.ceil(d[0]/this.size_divisibility)*this.size_divisibility;[p,d]=this.pad_image(p,d,{width:_,height:w})}}if(a??this.do_flip_channel_order){if(d[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<p.length;_+=3){let w=p[_];p[_]=p[_+2],p[_+2]=w}}let m=new R("float32",p,d).permute(2,0,1);return{original_size:[l,i],reshaped_input_size:c,pixel_values:m}}async _call(e,...r){Array.isArray(e)||(e=[e]);let s=await Promise.all(e.map(o=>this.preprocess(o)));return{pixel_values:Ot(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,kr,!0,r);return new this(s)}};var kn={};ds(kn,{BeitFeatureExtractor:()=>Um,BitImageProcessor:()=>Fm,CHMv2ImageProcessor:()=>jm,CLIPFeatureExtractor:()=>qm,CLIPImageProcessor:()=>Nc,ChineseCLIPFeatureExtractor:()=>Gm,ConvNextFeatureExtractor:()=>Wm,ConvNextImageProcessor:()=>Rc,DINOv3ViTImageProcessor:()=>Xm,DPTFeatureExtractor:()=>Ym,DPTImageProcessor:()=>Bc,DeiTFeatureExtractor:()=>Vm,DeiTImageProcessor:()=>$c,DetrFeatureExtractor:()=>Hm,DetrImageProcessor:()=>Dc,DonutFeatureExtractor:()=>Km,DonutImageProcessor:()=>xn,EfficientNetImageProcessor:()=>Qm,GLPNFeatureExtractor:()=>Zm,Glm46VImageProcessor:()=>Jm,GroundingDinoImageProcessor:()=>e_,Idefics3ImageProcessor:()=>Uc,ImageFeatureExtractor:()=>V,ImageProcessor:()=>V,JinaCLIPImageProcessor:()=>r_,Lfm2VlImageProcessor:()=>s_,LlavaOnevisionImageProcessor:()=>n_,Mask2FormerImageProcessor:()=>a_,MaskFormerFeatureExtractor:()=>o_,MaskFormerImageProcessor:()=>yn,MobileNetV1FeatureExtractor:()=>i_,MobileNetV1ImageProcessor:()=>Fc,MobileNetV2FeatureExtractor:()=>l_,MobileNetV2ImageProcessor:()=>Gc,MobileNetV3FeatureExtractor:()=>c_,MobileNetV3ImageProcessor:()=>jc,MobileNetV4FeatureExtractor:()=>u_,MobileNetV4ImageProcessor:()=>qc,MobileViTFeatureExtractor:()=>p_,MobileViTImageProcessor:()=>Wc,NougatImageProcessor:()=>d_,OwlViTFeatureExtractor:()=>f_,OwlViTImageProcessor:()=>bn,Owlv2ImageProcessor:()=>m_,Phi3VImageProcessor:()=>g_,PixtralImageProcessor:()=>w_,PvtImageProcessor:()=>x_,Qwen2VLImageProcessor:()=>Uo,RTDetrImageProcessor:()=>y_,Sam2ImageProcessor:()=>Fo,Sam3ImageProcessor:()=>Fo,SamImageProcessor:()=>Fo,SapiensFeatureExtractor:()=>b_,SapiensImageProcessor:()=>Vc,SegformerFeatureExtractor:()=>v_,SegformerImageProcessor:()=>Hc,SiglipImageProcessor:()=>k_,SmolVLMImageProcessor:()=>Uc,Swin2SRImageProcessor:()=>E_,VLMImageProcessor:()=>t_,ViTFeatureExtractor:()=>A_,ViTImageProcessor:()=>Xc,VitMatteImageProcessor:()=>T_,VitPoseImageProcessor:()=>M_,YolosFeatureExtractor:()=>S_,YolosImageProcessor:()=>Kc});var Um=class extends V{};var Fm=class extends V{};var Gm=class extends V{};var jm=class extends V{};var Nc=class extends V{},qm=class extends Nc{};var Rc=class extends V{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}},Wm=class extends Rc{};var $c=class extends V{},Vm=class extends $c{};var Dc=class extends V{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=He(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Wr(...e)}post_process_panoptic_segmentation(...e){return Lc(...e)}post_process_instance_segmentation(...e){return zc(...e)}},Hm=class extends Dc{};var Xm=class extends V{};var xn=class extends V{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((d,m)=>-d/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},Km=class extends xn{};var Bc=class extends V{},Ym=class extends Bc{};var Qm=class extends V{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 Uo=class extends V{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 wn(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=ke(Array.from({length:i},()=>a),0));let p=a.dims[0]/i,d=a.dims[1],m=Math.floor(a.dims[2]/c),_=Math.floor(a.dims[3]/c),w=a.view(p,i,d,Math.floor(m/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*m*_,d*i*c*c),x=new R("int64",[p,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var Jm=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 wn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var Zm=class extends V{};var e_=class extends V{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=tt([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Uc=class extends V{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(P=>this.preprocess(P)));l.push(...A.map(P=>P.original_size)),c.push(...A.map(P=>P.reshaped_input_size)),A.forEach(P=>P.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let P=new Array(A.length),O=new Array(A.length);M=await Promise.all(A.map(async(E,W)=>{let X=this.get_resize_for_vision_encoder(E.pixel_values,S),U=await vt(E.pixel_values,{size:[X.height,X.width]}),{frames:H,num_splits_h:j,num_splits_w:Y}=await this.split_image(U,this.max_image_size);return P[W]=j,O[W]=Y,ke(H,0)})),a.push(P),i.push(O)}else{let P=[S,S];M=await Promise.all(A.map(O=>vt(O.pixel_values,{size:P}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(ke(M,0))}let p=o.length,[d,m,_,w]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=He([p,d,_,w],!0);else{let b=Math.max(...o.map(M=>M.dims.at(0)));k=He([p,b,_,w],!0);let A=k.data,S=b*_*w;for(let M=0;M<p;++M){let P=o[M].dims[0];if(P<b){o[M]=ke([o[M],He([b-P,m,_,w],0)],0);let O=M*S+P*_*w,E=(M+1)*S;A.fill(!1,O,E)}}x=Ot(o,0)}return{pixel_values:x,pixel_attention_mask:k,original_sizes:l,reshaped_input_sizes:c,...s?{rows:a,cols:i}:{}}}async split_image(e,{longest_edge:r}){let s=r,n=r,o=[],[a,i]=e.dims.slice(-2),l=0,c=0;if(a>s||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),d=Math.ceil(i/c);for(let w=0;w<l;++w)for(let x=0;x<c;++x){let k,b,A,S;w===l-1?(b=a-p,S=a):(b=w*p,S=(w+1)*p),x===c-1?(k=i-d,A=i):(k=x*d,A=(x+1)*d);let O=await Tc(e,[b,k],[S,A],[2,3]);o.push(O)}let m=s,_=n;(a!==m||i!==_)&&(e=await vt(e,{size:[m,_]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:c}}};var t_=class extends V{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(r=>r*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 r_=class extends V{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 rT(t,e){return Math.round(t/e)*e}function Kz(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<o?(o=c,a=l):c===o&&i>.5*n*n*l[0]*l[1]&&(a=l)}return a}function Yz(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 Qz(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,p=new Float32Array(r*a*i*l),d=n*o;for(let m=0;m<r;++m){let _=m*s*d,w=m*a*i*l;for(let x=0;x<a;++x)for(let k=0;k<i;++k){let b=w+(x*i+k)*l;for(let A=0;A<e;++A){let S=(x*e+A)*o+k*e;for(let M=0;M<e;++M){let P=S+M;for(let O=0;O<s;++O)p[b++]=c[_+O*d+P]}}}}return new R("float32",p,[r,a*i,l])}function Jz(t,e){let[,r,s]=t.dims,n=new BigInt64Array(e);n.fill(1n,0,r);let o=t;if(r<e){let a=new Float32Array(e*s);a.set(t.data),o=new R("float32",a,[1,e,s])}return{padded:o,mask:new R("int64",n,[e])}}var s_=class extends V{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;let r=this.max_image_tokens*this.downsample_factor**2,s=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(r,s)}_is_image_too_large(e,r){let s=this.encoder_patch_size*this.downsample_factor,n=Math.max(this.encoder_patch_size,rT(e,s)),o=Math.max(this.encoder_patch_size,rT(r,s));return n*o>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=Yz(this.min_tiles,this.max_tiles),[n,o]=Kz(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 d of s){let m=await Promise.all(d.map(_=>this.preprocess(_,{do_pad:!1})));for(let{pixel_values:_}of m){let[,w,x]=_.dims,k=_.unsqueeze_(0),b=this.encoder_patch_size*this.downsample_factor,A=b**2,[S,M]=wn(Math.max(b,w),Math.max(b,x),b,this.min_image_tokens*A,this.max_image_tokens*A).map(U=>Math.max(b,U)),P,O=1,E=1,W=this._is_image_too_large(w,x),X=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(W&&X){let{grid_width:U,grid_height:H,target_width:j,target_height:Y}=this._get_grid_layout(w,x);O=H,E=U;let $=await vt(k,{size:[Y,j]});P=[];for(let C=0;C<H;++C)for(let te=0;te<U;++te){let ae=C*this.tile_size,L=te*this.tile_size;P.push($.slice(null,null,[ae,ae+this.tile_size],[L,L+this.tile_size]))}this.use_thumbnail&&U*H!==1&&P.push(await vt(k,{size:[M,S]}))}else P=[await vt(k,{size:[M,S]})];for(let U of P){let[,,H,j]=U.dims,Y=Qz(U,this.encoder_patch_size),{padded:$,mask:C}=Jz(Y,this.max_num_patches);n.push($),o.push(C),a.push([Math.floor(H/this.encoder_patch_size),Math.floor(j/this.encoder_patch_size)])}i.push(O),l.push(E),c.push([M,S])}}let p={pixel_values:ke(n,0),pixel_attention_mask:Ot(o,0),spatial_shapes:new R("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(r??this.return_row_col_info)&&(p.image_rows=i,p.image_cols=l,p.image_sizes=c),p}};var n_=class extends V{};var yn=class extends V{post_process_panoptic_segmentation(...e){return Lc(...e)}post_process_instance_segmentation(...e){return zc(...e)}},o_=class extends yn{};var a_=class extends yn{};var Fc=class extends V{},i_=class extends Fc{};var Gc=class extends V{},l_=class extends Gc{};var jc=class extends V{},c_=class extends jc{};var qc=class extends V{},u_=class extends qc{};var Wc=class extends V{},p_=class extends Wc{};var d_=class extends xn{};var bn=class extends V{post_process_object_detection(...e){return Wr(...e)}},f_=class extends bn{};var m_=class extends bn{};var Rt=336,Zz=[2,3],{ceil:__,floor:vn,sqrt:h_}=Math,g_=class extends V{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,r){let{num_img_tokens:s}=this.config;return vn((vn(r/Rt)*vn(e/Rt)+1)*s+1+(vn(r/Rt)+1)*h_(s))}get_resize_output_image_size(e,r){let s=this._num_crops,[n,o]=e.size,a=n/o,i=1;for(;i*Math.ceil(i/a)<=s;)i+=1;i-=1;let l=Math.floor(i*336),c=Math.floor(l/a);return[l,c]}pad_image(e,r,s,n={}){let[o,a]=r,i=Rt*__(o/Rt),l=Rt*__(a/Rt),c=[1,1,1].map((p,d)=>(p-this.image_mean[d])/this.image_std[d]);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||h_(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:[Rt,Rt],mode:"bicubic"});if(r>0){let k=[],b=h_(r),A=vn(w/b),S=vn(_/b);for(let P=0;P<b;++P)for(let O=0;O<b;++O){let E,W,X,U;P===b-1?(W=_-S,U=_):(W=P*S,U=(P+1)*S),O===b-1?(E=w-A,X=w):(E=O*A,X=(O+1)*A);let Y=await Tc(m,[W,E],[U,X],Zz);k.push(Y)}let M=await vt(ke(k,0),{size:[Rt,Rt],mode:"bicubic"});i.push(ke([x,M],0))}else i.push(x)}let l=Ot(i,0),c=a.map(m=>m.map(_=>Rt*__(_/Rt))),p=new R("int64",c.flat(),[s,2]),d=c.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:d}}};var w_=class extends V{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let d=c*p,m=Math.floor((i-1)/d)+1,_=Math.floor((l-1)/d)+1;return[m*d,_*d]}};var x_=class extends V{};var y_=class extends V{post_process_object_detection(...e){return Wr(...e)}};var Fo=class extends V{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=_d(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;a<e.length;++a){let[i,l]=r[a],[c,p]=s[a],d=[p/l,c/i];for(let m=0;m<e[a].length;++m)for(let _=0;_<e[a][m].length;++_)for(let w=0;w<e[a][m][_].length;++w)e[a][m][_][w]*=d[w%2]}return new R("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=_d(e);if(s.length===2)s=[1,...s],e=[e];else if(s.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(s.some((n,o)=>n!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new R("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;c<r.length;++c){let p=r[c],d=s[c],m=await vt(e[c],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,d[0]],[0,d[1]]),m=await vt(m,{mode:"bilinear",size:p}),o){let _=m.data,w=new Uint8Array(_.length);for(let x=0;x<_.length;++x)_[x]>n&&(w[x]=1);m=new R("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 Vc=class extends V{post_process_semantic_segmentation(...e){return Pc(...e)}},b_=class extends Vc{};var Hc=class extends V{post_process_semantic_segmentation(...e){return Pc(...e)}},v_=class extends Hc{};var k_=class extends V{};var E_=class extends V{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 Xc=class extends V{},A_=class extends Xc{};var T_=class extends V{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:Ot(s.map((a,i)=>ke([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 M_=class extends V{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p<o;++p){let d=n[p],m=r[p],_=[];for(let w=0;w<m.length;++w){let x=m[w],k=[],b=[],A=[],S=x.at(-2)/l,M=x.at(-1)/i;for(let P=0;P<d.length;++P){let[O,E]=[0,0],W=0,X=-1/0,U=d[P];for(let j=0;j<U.length;++j){let Y=U[j];for(let $=0;$<Y.length;++$){let C=Y[$];W+=C,X=Math.max(X,C),O+=($+.5)*C,E+=j*C}}if(s!=null&&X<s)continue;let H=[S*O/W,M*E/W];k.push(H),A.push(P),b.push(X)}_.push({bbox:x,scores:b,labels:A,keypoints:k})}c.push(_)}return c}};var Kc=class extends V{post_process_object_detection(...e){return Wr(...e)}},S_=class extends Kc{};var Ce=class{static async from_pretrained(e,r={}){let s=await ut(e,kr,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=kn[n?.replace(/Fast$/,"")];return o||(n!==void 0&&Z.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${jr}.`),o=V),new o(s)}};var O_=class extends re{static tokenizer_class=oe;static image_processor_class=Ce;constructor(e,r,s){super(e,r,s);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:o,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(o??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let 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("<s>","").replaceAll("</s>","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[p,d,...m]of i)l.push(d?d.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 I_=class extends re{static image_processor_class=Ce;static feature_extractor_class=Xe;static tokenizer_class=oe;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:c,image_token:p,eoi_token:d}=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=`
|
|
12
|
+
}`,h=new Function(Object.keys(I),z)(...Object.values(I)),z=`methodCaller<(${v.map(F=>F.name)}) => ${g.name}>`,lS(Object.defineProperty(h,"name",{value:z}))}function dS(u,d){return d>>>=0,(u=$t(u>>>0))==$t(d)}function mS(u){return(u>>>=0)?(u=Rl(u),Ht(globalThis[u])):Ht(globalThis)}function _S(u){return u=Rl(u>>>0),Ht(e[u])}function hS(u,d){return d>>>=0,u=$t(u>>>0),d=$t(d),Ht(u[d])}function gS(u){9<(u>>>=0)&&(us[u+1]+=1)}function bv(u,d,h,g,v){return Hp[u>>>0](d>>>0,h>>>0,g>>>0,v>>>0)}function wS(u,d,h,g,v){return bv(u>>>0,d>>>0,h>>>0,g>>>0,v>>>0)}function xS(){return Ht([])}function yS(u){u=$t(u>>>0);for(var d=Array(u.length),h=0;h<u.length;h++)d[h]=u[h];return Ht(d)}function bS(u){return Ht(Rl(u>>>0))}function vS(){return Ht({})}function kS(u){for(var d=$t(u>>>=0);d.length;){var h=d.pop();d.pop()(h)}Fp(u)}function ES(u,d,h){d>>>=0,h>>>=0,u=$t(u>>>0),d=$t(d),h=$t(h),u[d]=h}function AS(u,d){u=Tt(u),d>>>=0,u=new Date(1e3*u),(k(),$)[d>>>2>>>0]=u.getUTCSeconds(),(k(),$)[d+4>>>2>>>0]=u.getUTCMinutes(),(k(),$)[d+8>>>2>>>0]=u.getUTCHours(),(k(),$)[d+12>>>2>>>0]=u.getUTCDate(),(k(),$)[d+16>>>2>>>0]=u.getUTCMonth(),(k(),$)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(k(),$)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(k(),$)[d+28>>>2>>>0]=u}var vv=u=>u%4==0&&(u%100!=0||u%400==0),kv=[0,31,60,91,121,152,182,213,244,274,305,335],Ev=[0,31,59,90,120,151,181,212,243,273,304,334];function TS(u,d){u=Tt(u),d>>>=0,u=new Date(1e3*u),(k(),$)[d>>>2>>>0]=u.getSeconds(),(k(),$)[d+4>>>2>>>0]=u.getMinutes(),(k(),$)[d+8>>>2>>>0]=u.getHours(),(k(),$)[d+12>>>2>>>0]=u.getDate(),(k(),$)[d+16>>>2>>>0]=u.getMonth(),(k(),$)[d+20>>>2>>>0]=u.getFullYear()-1900,(k(),$)[d+24>>>2>>>0]=u.getDay();var h=(vv(u.getFullYear())?kv:Ev)[u.getMonth()]+u.getDate()-1|0;(k(),$)[d+28>>>2>>>0]=h,(k(),$)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),h=new Date(u.getFullYear(),6,1).getTimezoneOffset();var g=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(h!=g&&u.getTimezoneOffset()==Math.min(g,h)),(k(),$)[d+32>>>2>>>0]=u}function MS(u){u>>>=0;var d=new Date((k(),$)[u+20>>>2>>>0]+1900,(k(),$)[u+16>>>2>>>0],(k(),$)[u+12>>>2>>>0],(k(),$)[u+8>>>2>>>0],(k(),$)[u+4>>>2>>>0],(k(),$)[u>>>2>>>0],0),h=(k(),$)[u+32>>>2>>>0],g=d.getTimezoneOffset(),v=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),I=Math.min(T,v);return 0>h?(k(),$)[u+32>>>2>>>0]=+(v!=T&&I==g):0<h!=(I==g)&&(v=Math.max(T,v),d.setTime(d.getTime()+6e4*((0<h?I:v)-g))),(k(),$)[u+24>>>2>>>0]=d.getDay(),h=(vv(d.getFullYear())?kv:Ev)[d.getMonth()]+d.getDate()-1|0,(k(),$)[u+28>>>2>>>0]=h,(k(),$)[u>>>2>>>0]=d.getSeconds(),(k(),$)[u+4>>>2>>>0]=d.getMinutes(),(k(),$)[u+8>>>2>>>0]=d.getHours(),(k(),$)[u+12>>>2>>>0]=d.getDate(),(k(),$)[u+16>>>2>>>0]=d.getMonth(),(k(),$)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function Av(u,d,h,g,v,T,I){return n?Ue(16,1,u,d,h,g,v,T,I):-52}function Tv(u,d,h,g,v,T){if(n)return Ue(17,1,u,d,h,g,v,T)}var to={},SS=()=>performance.timeOrigin+performance.now();function Mv(u,d){if(n)return Ue(18,1,u,d);if(to[u]&&(clearTimeout(to[u].id),delete to[u]),!d)return 0;var h=setTimeout(()=>{delete to[u],Mt(()=>rk(u,performance.timeOrigin+performance.now()))},d);return to[u]={id:h,Ce:d},0}function OS(u,d,h,g){u>>>=0,d>>>=0,h>>>=0,g>>>=0;var v=new Date().getFullYear(),T=new Date(v,0,1).getTimezoneOffset();v=new Date(v,6,1).getTimezoneOffset();var I=Math.max(T,v);(k(),C)[u>>>2>>>0]=60*I,(k(),$)[d>>>2>>>0]=+(T!=v),u=(d=z=>{var F=Math.abs(z);return`UTC${0<=z?"-":"+"}${String(Math.floor(F/60)).padStart(2,"0")}${String(F%60).padStart(2,"0")}`})(T),d=d(v),v<T?(_r(u,h,17),_r(d,g,17)):(_r(u,g,17),_r(d,h,17))}var IS=()=>Date.now(),CS=1;function PS(u,d,h){if(h>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!CS)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(k(),L)[h>>>3>>>0]=BigInt(u),0}var Xp=[],Sv=(u,d)=>{Xp.length=0;for(var h;h=(k(),H)[u++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,Xp.push(h==112?(k(),C)[d>>>2>>>0]:h==106?(k(),L)[d>>>3>>>0]:h==105?(k(),$)[d>>>2>>>0]:(k(),ae)[d>>>3>>>0]),d+=g?8:4}return Xp};function LS(u,d,h){return u>>>=0,d=Sv(d>>>0,h>>>0),uf[u](...d)}function zS(u,d,h){return u>>>=0,d=Sv(d>>>0,h>>>0),uf[u](...d)}var NS=()=>{};function RS(u,d){return M(Qs(u>>>0,d>>>0))}var $S=()=>{throw Se+=1,"unwind"};function BS(){return 4294901760}var DS=()=>1,US=()=>navigator.hardwareConcurrency;function FS(u){u>>>=0;var d=(k(),H).length;if(u<=d||4294901760<u)return!1;for(var h=1;4>=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,u+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(u,g)/65536))-Or.buffer.byteLength+65535)/65536|0;try{Or.grow(g),xe();var v=1;break e}catch{}v=void 0}if(v)return!0}return!1}var ir=u=>{var d=hr(u)+1,h=Ul(d);return _r(u,h,d),h},Kp=(u,d)=>{(k(),C)[u>>>2>>>0]=d;var h=(k(),C)[u>>>2>>>0];(k(),C)[u+4>>>2>>>0]=(d-h)/4294967296},ro=u=>(k(),C)[u>>>2>>>0]+4294967296*(k(),$)[u+4>>>2>>>0],_t=[],GS=(u,d)=>{_t[u>>>0]=d},gr=[],$l=[],Zs=(u,d)=>{$l[u]=new Promise(h=>d.finally(()=>h(u)))},ne=u=>{if(u)return _t[u>>>0]},jS=(u,d)=>{for(u=(k(),C)[u>>>2>>>0];u;u=(k(),C)[u>>>2>>>0])d[(k(),$)[u+4>>>2>>>0]](u)},Bl=(u,d,h)=>{(k(),C)[u>>>2>>>0]=d,(k(),C)[u+4>>>2>>>0]=h},Ov=u=>{var d=(k(),C)[u>>>2>>>0];return u=(k(),C)[u+4>>>2>>>0],Qs(d,u)},wr=u=>{var d=(k(),C)[u>>>2>>>0];return u=(k(),C)[u+4>>>2>>>0],d?Qs(d,u):u===0?"":void 0},qS=u=>{var d=wr(u+4),h=(h=(k(),C)[u+12>>>2>>>0])?ne(h):"auto";if(u+=16){var g=ne((k(),C)[u+4>>>2>>>0]),v=(k(),C)[u+16>>>2>>>0],T=(k(),C)[u+20>>>2>>>0];if(v){for(var I={},z=0;z<v;++z){var F=T+24*z;I[Ov(F+4)]=(k(),ae)[F+16>>>3>>>0]}v=I}else v=void 0;u={module:g,constants:v,entryPoint:wr(u+8)}}else u=void 0;return{label:d,layout:h,compute:u}},Iv=(u,d)=>{function h(g,v){g=u[g],(k(),C)[d+v>>>2>>>0]=g}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),Kp(d+64,u.maxUniformBufferBindingSize),Kp(d+72,u.maxStorageBufferBindingSize),h("maxVertexBuffers",88),Kp(d+96,u.maxBufferSize),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),u.Ae!==void 0&&h("maxImmediateSize",148)},WS=[,"validation","out-of-memory","internal"],VS=[,"compatibility","core"],Cv={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"},HS=[,"low-power","high-performance"],XS=[,"occlusion","timestamp"],KS={undefined:1,unknown:1,destroyed:2};function YS(u,d,h,g,v,T){d=Tt(d),h=Tt(h),g>>>=0,v>>>=0,T>>>=0;var I=ne(u>>>0);if(u={},T){var z=(k(),C)[T+12>>>2>>>0];if(z){var F=(k(),C)[T+16>>>2>>>0];u.requiredFeatures=Array.from((k(),C).subarray(F>>>2>>>0,F+4*z>>>2>>>0),oe=>Cv[oe])}var Y=(k(),C)[T+20>>>2>>>0];if(Y){let oe=function(St,lt,ps=!1){lt=Y+lt,(lt=(k(),C)[lt>>>2>>>0])==4294967295||ps&<==0||(Fe[St]=lt)},it=function(St,lt){lt=Y+lt;var ps=(k(),C)[lt>>>2>>>0],bI=(k(),C)[lt+4>>>2>>>0];ps==4294967295&&bI==4294967295||(Fe[St]=ro(lt))};var Oe=oe,ze=it,Fe={};oe("maxTextureDimension1D",4),oe("maxTextureDimension2D",8),oe("maxTextureDimension3D",12),oe("maxTextureArrayLayers",16),oe("maxBindGroups",20),oe("maxBindGroupsPlusVertexBuffers",24),oe("maxDynamicUniformBuffersPerPipelineLayout",32),oe("maxDynamicStorageBuffersPerPipelineLayout",36),oe("maxSampledTexturesPerShaderStage",40),oe("maxSamplersPerShaderStage",44),oe("maxStorageBuffersPerShaderStage",48),oe("maxStorageTexturesPerShaderStage",52),oe("maxUniformBuffersPerShaderStage",56),oe("minUniformBufferOffsetAlignment",80),oe("minStorageBufferOffsetAlignment",84),it("maxUniformBufferBindingSize",64),it("maxStorageBufferBindingSize",72),oe("maxVertexBuffers",88),it("maxBufferSize",96),oe("maxVertexAttributes",104),oe("maxVertexBufferArrayStride",108),oe("maxInterStageShaderVariables",112),oe("maxColorAttachments",116),oe("maxColorAttachmentBytesPerSample",120),oe("maxComputeWorkgroupStorageSize",124),oe("maxComputeInvocationsPerWorkgroup",128),oe("maxComputeWorkgroupSizeX",132),oe("maxComputeWorkgroupSizeY",136),oe("maxComputeWorkgroupSizeZ",140),oe("maxComputeWorkgroupsPerDimension",144),oe("maxImmediateSize",148,!0),u.requiredLimits=Fe}(z=(k(),C)[T+24>>>2>>>0])&&(z={label:wr(z+4)},u.defaultQueue=z),u.label=wr(T+4)}Se+=1,Zs(d,I.requestDevice(u).then(oe=>{--Se,Mt(()=>{_t[v>>>0]=oe.queue,_t[g>>>0]=oe,Se+=1,Zs(h,oe.lost.then(it=>{Mt(()=>{oe.onuncapturederror=()=>{};var St=ce(),lt=ir(it.message);ef(h,KS[it.reason],lt),le(St)}),--Se})),oe.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),Jv(g,St,it),le(lt)},"adapterInfo"in oe||(oe.adapterInfo=I.info),sf(d,1,g,0)})},oe=>{--Se,Mt(()=>{var it=ce(),St=ir(oe.message);sf(d,3,g,St),h&&ef(h,4,St),le(it)})}))}function QS(u){var d=ne(u>>>=0),h=gr[u];if(h){for(var g=0;g<h.length;++g)h[g]();delete gr[u]}d.destroy()}function JS(u,d,h){h>>>=0;var g=ne(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var T=af(16,v.byteLength);return(k(),H).set(new Uint8Array(v),T>>>0),gr[u].push(()=>Xt(T)),T}function ZS(u,d,h){h>>>=0;var g=ne(u>>>=0);h==4294967295&&(h=void 0);try{var v=g.getMappedRange(d>>>0,h)}catch{return 0}var T=af(16,v.byteLength);return(k(),H).fill(0,T,v.byteLength),gr[u].push(()=>{new Uint8Array(v).set((k(),H).subarray(T>>>0,T+v.byteLength>>>0)),Xt(T)}),T}function eO(u,d,h,g,v){u>>>=0,d=Tt(d),h=Tt(h),v>>>=0;var T=ne(u);gr[u]=[],v==4294967295&&(v=void 0),Se+=1,Zs(d,T.mapAsync(h,g>>>0,v).then(()=>{--Se,Mt(()=>{tf(d,1,0)})},I=>{--Se,Mt(()=>{ce();var z=ir(I.message);tf(d,I.name==="AbortError"?4:I.name==="OperationError"?3:0,z),delete gr[u]})}))}function tO(u){var d=ne(u>>>=0),h=gr[u];if(h){for(var g=0;g<h.length;++g)h[g]();delete gr[u],d.unmap()}}function rO(u){delete _t[u>>>0]}function sO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=!!(k(),C)[d+32>>>2>>>0];d={label:wr(d+4),usage:(k(),C)[d+16>>>2>>>0],size:ro(d+24),mappedAtCreation:g},u=ne(u);try{var v=u.createBuffer(d)}catch{return!1}return _t[h>>>0]=v,g&&(gr[h]=[]),!0}function nO(u,d,h,g){u>>>=0,d=Tt(d),g>>>=0,h=qS(h>>>0),u=ne(u),Se+=1,Zs(d,u.createComputePipelineAsync(h).then(v=>{--Se,Mt(()=>{_t[g>>>0]=v,Zp(d,1,g,0)})},v=>{--Se,Mt(()=>{var T=ce(),I=ir(v.message);Zp(d,v.reason==="validation"?3:v.reason==="internal"?4:0,g,I),le(T)})}))}function oO(u,d,h){u>>>=0,d>>>=0,h>>>=0;var g=(k(),C)[d>>>2>>>0],v=(k(),$)[g+4>>>2>>>0];d={label:wr(d+4),code:""},v===2&&(d.code=Ov(g+8)),u=ne(u).createShaderModule(d),_t[h>>>0]=u}var aO=u=>{(u=ne(u)).onuncapturederror=null,u.destroy()};function iO(u,d){d=Tt(d),u=ne(u>>>0),Se+=1,Zs(d,u.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 v=ce(),T=h?ir(h.message):0;rf(d,1,g,T),le(v)})},h=>{--Se,Mt(()=>{var g=ce(),v=ir(h.message);rf(d,1,5,v),le(g)})}))}function lO(u,d,h,g){if(d=Tt(d),g>>>=0,h>>>=0){var v={featureLevel:VS[(k(),$)[h+4>>>2>>>0]],powerPreference:HS[(k(),$)[h+8>>>2>>>0]],forceFallbackAdapter:!!(k(),C)[h+12>>>2>>>0]};(u=(k(),C)[h>>>2>>>0])!==0&&(k(),v.Fe=!!(k(),C)[u+8>>>2>>>0])}"gpu"in navigator?(Se+=1,Zs(d,navigator.gpu.requestAdapter(v).then(T=>{--Se,Mt(()=>{if(T)_t[g>>>0]=T,so(d,1,g,0);else{var I=ce(),z=ir("WebGPU not available on this browser (requestAdapter returned null)");so(d,3,g,z),le(I)}})},T=>{--Se,Mt(()=>{var I=ce(),z=ir(T.message);so(d,4,g,z),le(I)})}))):(v=ce(),u=ir("WebGPU not available on this browser (navigator.gpu is not available)"),so(d,3,g,u),le(v))}function cO(u,d,h){return u>>>=0,d>>>=0,h>>>=0,yv(async()=>{var g=[];if(h){var v=(k(),$)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(z=>setTimeout(z,v,0))}else g.length=d;for(var T=0;T<d;++T){var I=ro(u+8*T);if(!(I in $l))return I;g[T]=$l[I]}return g=await Promise.race(g),delete $l[g],g})}var Yp,Qp={},Pv=()=>{if(!Yp){var u,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(u in Qp)Qp[u]===void 0?delete d[u]:d[u]=Qp[u];var h=[];for(u in d)h.push(`${u}=${d[u]}`);Yp=h}return Yp};function Lv(u,d){if(n)return Ue(19,1,u,d);u>>>=0,d>>>=0;var h,g=0,v=0;for(h of Pv()){var T=d+g;(k(),C)[u+v>>>2>>>0]=T,g+=_r(h,T,1/0)+1,v+=4}return 0}function zv(u,d){if(n)return Ue(20,1,u,d);u>>>=0,d>>>=0;var h=Pv();for(var g of((k(),C)[u>>>2>>>0]=h.length,u=0,h))u+=hr(g)+1;return(k(),C)[d>>>2>>>0]=u,0}function Nv(u){return n?Ue(21,1,u):52}function Rv(u,d,h,g){return n?Ue(22,1,u,d,h,g):52}function $v(u,d,h,g){return n?Ue(23,1,u,d,h,g):70}var uO=[null,[],[]];function Bv(u,d,h,g){if(n)return Ue(24,1,u,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var v=0,T=0;T<h;T++){var I=(k(),C)[d>>>2>>>0],z=(k(),C)[d+4>>>2>>>0];d+=8;for(var F=0;F<z;F++){var Y=u,Oe=(k(),H)[I+F>>>0],ze=uO[Y];Oe===0||Oe===10?((Y===1?S:M)(ev(ze)),ze.length=0):ze.push(Oe)}v+=z}return(k(),C)[g>>>2>>>0]=v,0}function pO(u){return u>>>0}function fO(u,d){return Iv(ne(u>>>0).limits,d>>>0),1}function dO(u,d){return ne(u>>>0).features.has(Cv[d])}function mO(u){return BigInt(ne(u>>>0).size)}function _O(u){return BigInt(ne(u>>>0).usage)}function hO(u,d){if(u>>>=0,d>>>=0){var h=wr(d+4);h={label:h,timestampWrites:d=(d=(k(),C)[d+12>>>2>>>0])!==0?{querySet:ne((k(),C)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(k(),C)[d+8>>>2>>>0],endOfPassWriteIndex:(k(),C)[d+12>>>2>>>0]}:void 0}}return d=ne(u),u=Hv(0),h=d.beginComputePass(h),_t[u>>>0]=h,u}function gO(u,d,h,g,v,T){h=Tt(h),v=Tt(v),T=Tt(T),ne(u>>>0).copyBufferToBuffer(ne(d>>>0),h,ne(g>>>0),v,T)}function wO(u){var d=ne(u>>>0);return u=Wv(0),d=d.finish(),_t[u>>>0]=d,u}function xO(u,d,h,g,v,T){T=Tt(T),ne(u>>>0).resolveQuerySet(ne(d>>>0),h,g,ne(v>>>0),T)}function yO(u,d,h,g){ne(u>>>0).dispatchWorkgroups(d,h,g)}function bO(u,d,h){h=Tt(h),ne(u>>>0).dispatchWorkgroupsIndirect(ne(d>>>0),h)}function vO(u){ne(u>>>0).end()}function kO(u,d,h,g,v){g>>>=0,v>>>=0,u=ne(u>>>0),h=ne(h>>>0),g==0?u.setBindGroup(d,h):u.setBindGroup(d,h,(k(),C),v>>>2,g)}function EO(u,d){ne(u>>>0).setPipeline(ne(d>>>0))}function AO(u,d,h){ne(u>>>0).Ee(ne(d>>>0),h)}function TO(u,d){var h=ne(u>>>0);return u=qv(0),d=h.getBindGroupLayout(d),_t[u>>>0]=d,u}function MO(u,d){function h(v){var T=(k(),C)[v+8>>>2>>>0],I=(k(),C)[v+32>>>2>>>0],z=(k(),C)[v+36>>>2>>>0],F=0;return jS(v,{327681:Y=>{F=(k(),C)[Y+8>>>2>>>0]}}),T?((I=ro(v+24))==-1&&(I=void 0),T={buffer:ne(T),offset:ro(v+16),size:I}):T=ne(I||z||F),{binding:(k(),C)[v+4>>>2>>>0],resource:T}}u>>>=0,d={label:wr(4+(d>>>=0)),layout:ne((k(),C)[d+12>>>2>>>0]),entries:(function(v,T){for(var I=[],z=0;z<v;++z)I.push(h(T+40*z));return I})((k(),C)[d+16>>>2>>>0],(k(),C)[d+20>>>2>>>0])},u=ne(u);var g=jv(0);return GS(g,u.createBindGroup(d)),g}function SO(u,d){var h;return u>>>=0,(d>>>=0)&&(h={label:wr(d+4)}),d=ne(u),u=Vv(0),h=d.createCommandEncoder(h),_t[u>>>0]=h,u}function OO(u,d){u>>>=0,d>>>=0,d={type:XS[(k(),$)[d+12>>>2>>>0]],count:(k(),C)[d+16>>>2>>>0]};var h=ne(u);return u=Xv(0),d=h.createQuerySet(d),_t[u>>>0]=d,u}function IO(u,d){u=ne(u>>>0).adapterInfo,d>>>=0,(k(),C)[d+52>>>2>>>0]=u.subgroupMinSize,(k(),C)[d+56>>>2>>>0]=u.subgroupMaxSize;var h=u.vendor+u.architecture+u.device+u.description,g=hr(h)+1,v=en(g);return v&&_r(h,v,g),h=v,g=hr(u.vendor),Bl(d+4,h,g),h+=g,g=hr(u.architecture),Bl(d+12,h,g),h+=g,g=hr(u.device),Bl(d+20,h,g),Bl(d+28,h+g,hr(u.description)),(k(),$)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(k(),$)[d+40>>>2>>>0]=u,(k(),C)[d+44>>>2>>>0]=0,(k(),C)[d+48>>>2>>>0]=0,1}var CO={"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 PO(u,d){d>>>=0;var h=ne(u>>>0);u=en(4*h.features.size);var g=0,v=0;for(let T of h.features)0<=(h=CO[T])&&((k(),$)[u+g>>>2>>>0]=h,g+=4,v++);(k(),C)[d+4>>>2>>>0]=u,(k(),C)[d>>>2>>>0]=v}function LO(u,d){return Iv(ne(u>>>0).limits,d>>>0),1}function zO(u,d){ne(u>>>0).pushErrorScope(WS[d])}function NO(u,d,h){d>>>=0,h>>>=0,u=ne(u>>>0),d=Array.from((k(),$).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>ne(g)),u.submit(d)}function RO(u,d,h,g,v){h=Tt(h),g>>>=0,v>>>=0,u=ne(u>>>0),d=ne(d>>>0),g=(k(),H).subarray(g>>>0,g+v>>>0),u.writeBuffer(d,h,g,0,v)}n||(function(){for(var u=e.numThreads-1;u--;)H1();De.push(async()=>{var d=(async function(){if(!n)return Promise.all(Sr.map(V1))})();Me++,await d,--Me==0&&Ze&&(d=Ze,Ze=null,d())})})(),n||(Or=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),xe()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ce(),e.stackRestore=u=>le(u),e.stackAlloc=u=>Ul(u),e.setValue=function(u,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(k(),U)[u>>>0]=d;break;case"i16":(k(),j)[u>>>1>>>0]=d;break;case"i32":(k(),$)[u>>>2>>>0]=d;break;case"i64":(k(),L)[u>>>3>>>0]=BigInt(d);break;case"float":(k(),te)[u>>>2>>>0]=d;break;case"double":(k(),ae)[u>>>3>>>0]=d;break;case"*":(k(),C)[u>>>2>>>0]=d;break;default:qe(`invalid type for setValue: ${h}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(k(),U)[u>>>0];case"i16":return(k(),j)[u>>>1>>>0];case"i32":return(k(),$)[u>>>2>>>0];case"i64":return(k(),L)[u>>>3>>>0];case"float":return(k(),te)[u>>>2>>>0];case"double":return(k(),ae)[u>>>3>>>0];case"*":return(k(),C)[u>>>2>>>0];default:qe(`invalid type for getValue: ${d}`)}},e.UTF8ToString=Qs,e.stringToUTF8=_r,e.lengthBytesUTF8=hr;var Dv,Uv,Jp,Dl,Xt,en,Fv,Gv,jv,qv,Wv,Vv,Hv,Xv,Kv,Yv,Qv,Zp,ef,tf,rf,so,sf,Jv,nf,Zv,ek,tk,of,rk,sk,af,we,no,nk,le,Ul,ce,ok,lf,ak,ik,lk,cf,ck,uk,pk,fk,dk,mk,_k,hk,gk,wk,xk,yk,bk,vk,kk,Ek,Ak,Tk,Mk,Sk,Ok,Ik,Ck,Pk,Lk,zk,Nk,Rk,$k,Bk,Dk,Uk,Fk,Gk,jk,qk,Wk,Vk,Hk,xr,$O=[Xs,Zn,Y1,tv,rv,sv,nv,ov,av,iv,lv,cv,uv,pv,fv,dv,Av,Tv,Mv,Lv,zv,Nv,Rv,$v,Bv],uf={937012:(u,d,h,g,v)=>{if(e===void 0||!e.Uc)return 1;if((u=Qs(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Uc.get(u)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>u.byteLength)return 3;try{let T=u.subarray(d,d+h);switch(v){case 0:(k(),H).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}},937836:(u,d,h)=>{e.Sd(u,(k(),H).subarray(d>>>0,d+h>>>0))},937900:()=>e.me(),937942:u=>{e.jd(u)},937979:()=>typeof wasmOffsetConverter<"u"};function BO(u,d,h,g){var v=ce();try{return hk(u,d,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function DO(u,d,h){var g=ce();try{return dk(u,d,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function UO(u){var d=ce();try{ck(u)}catch(h){if(le(d),h!==h+0)throw h;we(1,0)}}function FO(u,d){var h=ce();try{return cf(u,d)}catch(g){if(le(h),g!==g+0)throw g;we(1,0)}}function GO(u,d,h){var g=ce();try{lk(u,d,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function jO(u,d){var h=ce();try{gk(u,d)}catch(g){if(le(h),g!==g+0)throw g;we(1,0)}}function qO(u,d,h,g,v,T,I){var z=ce();try{return fk(u,d,h,g,v,T,I)}catch(F){if(le(z),F!==F+0)throw F;we(1,0)}}function WO(u,d,h,g,v,T){var I=ce();try{uk(u,d,h,g,v,T)}catch(z){if(le(I),z!==z+0)throw z;we(1,0)}}function VO(u,d,h,g){var v=ce();try{_k(u,d,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function HO(u,d,h,g,v,T,I){var z=ce();try{xk(u,d,h,g,v,T,I)}catch(F){if(le(z),F!==F+0)throw F;we(1,0)}}function XO(u,d,h,g,v,T,I){var z=ce();try{yk(u,d,h,g,v,T,I)}catch(F){if(le(z),F!==F+0)throw F;we(1,0)}}function KO(u,d,h,g,v,T,I,z){var F=ce();try{Ok(u,d,h,g,v,T,I,z)}catch(Y){if(le(F),Y!==Y+0)throw Y;we(1,0)}}function YO(u,d,h,g,v,T,I,z,F,Y,Oe,ze){var Fe=ce();try{bk(u,d,h,g,v,T,I,z,F,Y,Oe,ze)}catch(oe){if(le(Fe),oe!==oe+0)throw oe;we(1,0)}}function QO(u,d,h,g,v){var T=ce();try{return wk(u,d,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;we(1,0)}}function JO(u,d,h,g,v){var T=ce();try{pk(u,d,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;we(1,0)}}function ZO(u,d,h,g,v,T,I,z){var F=ce();try{mk(u,d,h,g,v,T,I,z)}catch(Y){if(le(F),Y!==Y+0)throw Y;we(1,0)}}function eI(u){var d=ce();try{return Ik(u)}catch(h){if(le(d),h!==h+0)throw h;we(1,0)}}function tI(u,d,h){var g=ce();try{return Ck(u,d,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function rI(u,d){var h=ce();try{return jk(u,d)}catch(g){if(le(h),g!==g+0)throw g;return we(1,0),0n}}function sI(u,d,h,g,v){var T=ce();try{Pk(u,d,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;we(1,0)}}function nI(u){var d=ce();try{return vk(u)}catch(h){if(le(d),h!==h+0)throw h;return we(1,0),0n}}function oI(u,d,h,g,v,T){var I=ce();try{return Mk(u,d,h,g,v,T)}catch(z){if(le(I),z!==z+0)throw z;we(1,0)}}function aI(u,d,h,g,v,T){var I=ce();try{return Lk(u,d,h,g,v,T)}catch(z){if(le(I),z!==z+0)throw z;we(1,0)}}function iI(u,d,h,g,v,T){var I=ce();try{return zk(u,d,h,g,v,T)}catch(z){if(le(I),z!==z+0)throw z;we(1,0)}}function lI(u,d,h,g,v,T,I,z){var F=ce();try{return Sk(u,d,h,g,v,T,I,z)}catch(Y){if(le(F),Y!==Y+0)throw Y;we(1,0)}}function cI(u,d,h,g,v){var T=ce();try{return Nk(u,d,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;return we(1,0),0n}}function uI(u,d,h,g){var v=ce();try{return Rk(u,d,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function pI(u,d,h,g){var v=ce();try{return $k(u,d,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function fI(u,d,h,g,v,T,I,z,F,Y,Oe,ze){var Fe=ce();try{return Bk(u,d,h,g,v,T,I,z,F,Y,Oe,ze)}catch(oe){if(le(Fe),oe!==oe+0)throw oe;we(1,0)}}function dI(u,d,h,g,v,T,I,z,F,Y,Oe){var ze=ce();try{Dk(u,d,h,g,v,T,I,z,F,Y,Oe)}catch(Fe){if(le(ze),Fe!==Fe+0)throw Fe;we(1,0)}}function mI(u,d,h,g,v,T,I,z,F,Y,Oe,ze,Fe,oe,it,St){var lt=ce();try{Uk(u,d,h,g,v,T,I,z,F,Y,Oe,ze,Fe,oe,it,St)}catch(ps){if(le(lt),ps!==ps+0)throw ps;we(1,0)}}function _I(u,d,h,g){var v=ce();try{return Fk(u,d,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function hI(u,d,h,g,v){var T=ce();try{return Gk(u,d,h,g,v)}catch(I){if(le(T),I!==I+0)throw I;we(1,0)}}function gI(u,d,h){var g=ce();try{return Ek(u,d,h)}catch(v){if(le(g),v!==v+0)throw v;return we(1,0),0n}}function wI(u,d,h){var g=ce();try{return kk(u,d,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function xI(u,d,h){var g=ce();try{return Ak(u,d,h)}catch(v){if(le(g),v!==v+0)throw v;we(1,0)}}function yI(u,d,h,g){var v=ce();try{Tk(u,d,h,g)}catch(T){if(le(v),T!==T+0)throw T;we(1,0)}}function Fl(){if(0<Me)Ze=Fl;else if(n)w?.(e),ue();else{for(var u=De;0<u.length;)u.shift()(e);0<Me?Ze=Fl:(e.calledRun=!0,P||(ue(),w?.(e)))}}return n||(xr=await mt(),Fl()),e.PTR_SIZE=4,e.webgpuInit=u=>{let d=new WeakMap,h,g,v=1;e.webgpuRegisterDevice=z=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var F=d.get(z);if(!F){let Y=((Oe,ze=0)=>{var Fe=Qv(ze);return ze=Yv(ze,Fe),_t[Fe>>>0]=Oe.queue,_t[ze>>>0]=Oe,ze})(z,F=Gv(0));F=[v++,F,Y],d.set(z,F)}return h=z,g=F[0],F}h=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(g!==void 0){var F=g;if(g=void 0,z){let Y=Jp(F);T.set(z,Y),F===0&&u(h??ne(Y))}h=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let I=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,F,Y)=>{if(Y)return z[I]=[Y,NaN],Y;if(Y=z[I])return Y[1]++,Y[0];if((F=T.get(F))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return F=((Oe,ze=0)=>(Oe.mapState==="unmapped"||qe(),ze=Kv(ze),_t[ze>>>0]=Oe,ze))(z,F),z[I]=[F,1],F},e.webgpuUnregisterBuffer=z=>{let F=z[I];if(!F)throw Error("Buffer is not registered");F[1]--,F[1]===0&&(Fv(F[0]),delete z[I])},e.webgpuGetBuffer=z=>ne(z),e.webgpuCreateDownloader=(z,F,Y)=>{if((Y=T.get(Y))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Oe=ne(Y),ze=16*Math.ceil(Number(F)/16);return async()=>{let Fe=Oe.createBuffer({size:ze,usage:9});try{let oe=Oe.createCommandEncoder();return oe.copyBufferToBuffer(z,0,Fe,0,ze),Oe.queue.submit([oe.finish()]),await Fe.mapAsync(GPUMapMode.READ),Fe.getMappedRange().slice(0,F)}finally{Fe.destroy()}}},e.ad=(z,F)=>{var Y=F.buffer;let Oe=F.byteOffset,ze=F.byteLength;if(F=16*Math.ceil(Number(ze)/16),z=ne(z),!h){var Fe=Jp(g);h=ne(Fe)}let oe=(Fe=h.createBuffer({mappedAtCreation:!0,size:F,usage:6})).getMappedRange();new Uint8Array(oe).set(new Uint8Array(Y,Oe,ze)),Fe.unmap(),(Y=h.createCommandEncoder()).copyBufferToBuffer(Fe,0,z,0,F),h.queue.submit([Y.finish()]),Fe.destroy()}},e.webnnInit=u=>{let d=u[0];[e.me,e.jd,e.webnnEnsureTensor,e.Sd,e.webnnDownloadTensor,e.le,e.webnnEnableTraceEvent]=u.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,v,T)=>d.registerMLTensor(h,g,v,T),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterMLConstant=(h,g,v,T,I,z)=>d.registerMLConstant(h,g,v,T,I,e.Uc,z),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},J?e:new Promise((u,d)=>{w=u,x=d})}var VA,ZE,_z=be(()=>{"use strict";VA=JE,ZE=globalThis.self?.name?.startsWith("em-pthread"),ZE&&JE()}),zf,Yf,eA,Lt,HA,rc,tA,rA,Nf,sA,Rf,XA,$f,KA,od=be(()=>{"use strict";nd(),zf=typeof location>"u"?void 0:location.origin,Yf=import.meta.url>"file:"&&import.meta.url<"file;",eA=()=>{if(Yf){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,zf).href}return import.meta.url},Lt=eA(),HA=()=>{if(Lt&&!Lt.startsWith("blob:"))return Lt.substring(0,Lt.lastIndexOf("/")+1)},rc=(t,e)=>{try{let r=e??Lt;return(r?new URL(t,r):new URL(t)).origin===zf}catch{return!1}},tA=(t,e)=>{let r=e??Lt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},rA=(t,e)=>`${e??"./"}${t}`,Nf=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},sA=async t=>(await import(t)).default,Rf=(mz(),lc(jA)).default,XA=async()=>{if(!Lt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(rc(Lt))return[void 0,Rf()];let t=await Nf(Lt);return[t,Rf(t)]},$f=(_z(),lc(WA)).default,KA=async(t,e,r,s)=>{let n=$f&&!(t||e);if(n)if(Lt)n=rc(Lt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,$f];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??tA(o,e),i=r&&a&&!rc(a,e),l=i?await Nf(a):a??rA(o,e);return[i?l:void 0,await sA(l)]}}}),Bf,sc,ho,Df,nA,oA,aA,ad,Be,Ts=be(()=>{"use strict";od(),sc=!1,ho=!1,Df=!1,nA=()=>{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}},oA=()=>{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}},aA=()=>{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}},ad=async t=>{if(sc)return Promise.resolve();if(ho)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Df)throw new Error("previous call to 'initializeWebAssembly()' failed.");ho=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!aA())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!oA())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=nA();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=t.wasmBinary,[f,m]=await KA(i,o,r>1,!!p||!!c),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,b)=>{let E={numThreads:r};if(p)E.wasmBinary=p,E.locateFile=A=>A;else if(c||o)E.locateFile=A=>c??o+A;else if(i&&i.indexOf("blob:")!==0)E.locateFile=A=>new URL(A,i).href;else if(f){let A=HA();A&&(E.locateFile=S=>A+S)}m(E).then(A=>{ho=!1,sc=!0,Bf=A,x(),f&&URL.revokeObjectURL(f)},A=>{ho=!1,Df=!0,b(A)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Be=()=>{if(sc&&Bf)return Bf;throw new Error("WebAssembly is not initialized yet.")}}),zt,uc,Pe,id=be(()=>{"use strict";Ts(),zt=(t,e)=>{let r=Be(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},uc=(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")uc(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=Be(),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)}}}),YA,hz=be(()=>{"use strict";Ts(),id(),YA=t=>{let e=Be(),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&&uc(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}}}),iA,lA,cA,nc,$r,uA,QA,gz=be(()=>{"use strict";Ts(),id(),iA=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}`)}},lA=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},cA=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)},nc=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);Be()._OrtAddSessionConfigEntry(t,n,o)!==0&&Pe(`Can't set a session config entry: ${e} - ${r}.`)},$r=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);t.push([n,o])},uA=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&&nc(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&&$r(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&$r(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];$r(a,"forceCpuNodeNames",x.join(`
|
|
13
|
+
`),r)}_.validationMode&&$r(a,"validationMode",_.validationMode,r)}let m=Be().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;$r(a,"deviceId",_.toString(),r),$r(a,"webgpuInstance",w.toString(),r),$r(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=zt(o,r),l=a.length,c=0,p=0;if(l>0){c=Be()._malloc(l*Be().PTR_SIZE),r.push(c),p=Be()._malloc(l*Be().PTR_SIZE),r.push(p);for(let f=0;f<l;f++)Be().setValue(c+f*Be().PTR_SIZE,a[f][0],"*"),Be().setValue(p+f*Be().PTR_SIZE,a[f][1],"*")}await Be()._OrtAppendExecutionProvider(t,i,c,p,l)!==0&&Pe(`Can't append execution provider: ${o}.`)}},QA=async t=>{let e=Be(),r=0,s=[],n=t||{};cA(n);try{let o=iA(n.graphOptimizationLevel??"all"),a=lA(n.executionMode??"sequential"),i=typeof n.logId=="string"?zt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?zt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&Pe("Can't create session options."),n.executionProviders&&await uA(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);nc(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&&uc(n.extra,"",new WeakSet,(f,m)=>{nc(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}}}),bs,ic,cn,bo,pc,ld,cd,Qf,un=be(()=>{"use strict";bs=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},ic=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}`)}},cn=(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},bo=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}`)}},pc=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}`)}},ld=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",cd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Qf=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}`)}}}),ud,JA=be(()=>{"use strict";nd(),ud=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)}}),ZA,wz=be(()=>{"use strict";un(),ZA=(t,e)=>new(bo(e))(t)}),pA,fA,dA,mA,e2,_A,bt,t2=be(()=>{"use strict";un(),pA=["V","I","W","E","F"],fA=(t,e)=>{console.log(`[${pA[t]},${new Date().toISOString()}]${e}`)},e2=(t,e)=>{dA=t,mA=e},_A=(t,e)=>{let r=pc(t),s=pc(dA);r>=s&&fA(r,typeof e=="function"?e():e)},bt=(...t)=>{mA&&_A(...t)}}),Uf,Jf,Ff,hA,Gf,gA,jf,qf,Wf,wA,r2,xz=be(()=>{"use strict";un(),t2(),Uf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Jf=(t,e)=>{if(e==="int32")return t;let r=Uf.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(bo(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i<n;i++){let l=o[i];if(l>2147483647n||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'`)}},Ff=(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}`)}},hA=1,Gf=()=>hA++,gA=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),jf=(t,e)=>{let r=Uf.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},qf=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 jf(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=Ff(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}},Wf=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=gA.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!==jf(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=Jf(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?Ff(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()}},wA=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=Gf();return this.tensorTrackersById.set(t,new Wf(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=Gf(),a=new qf({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new Wf(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,e,r)){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 qf({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)}},r2=(...t)=>new wA(...t)}),s2={};vo(s2,{WebNNBackend:()=>n2});var go,xA,n2,yz=be(()=>{"use strict";un(),Ts(),wz(),xz(),t2(),go=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),xA=(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])},n2=class{constructor(t){this.tensorManager=r2(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,e2(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=>xA(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=go.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=go.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(!Be().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 ZA(r,e)}}registerMLTensor(t,e,r,s){let n=go.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,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":if(a){let f=Jf(new Uint8Array(c),"int64");p=new Int32Array(f.buffer),n.dataType="int32"}else p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return 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,p)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=go.get(bs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),yA,pd,fd,Br,bA,Vf,fc,dd,md,Hf,_d,hd,gd,o2=be(()=>{"use strict";As(),hz(),gz(),un(),Ts(),id(),JA(),yA=(t,e)=>{Be()._OrtInit(t,e)!==0&&Pe("Can't initialize onnxruntime.")},pd=async t=>{yA(t.wasm.numThreads,pc(t.logLevel))},fd=async(t,e)=>{Be().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"&&Be().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(yz(),lc(s2)).WebNNBackend(t);Be().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])}},Br=new Map,bA=t=>{let e=Be(),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)}},Vf=(t,e)=>{let r=Be(),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],p=[];for(let f=0;f<c;f++){let m=Number(r.getValue(n+8+f*o,"*"));p.push(m!==0?r.UTF8ToString(m):Number(r.getValue(n+8+(f+c)*o,"*")))}return[i,l,p]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},fc=t=>{let e=Be(),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]},dd=async(t,e)=>{let r,s,n=Be();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=fc(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await QA(e),e?.externalData&&n.mountExternalData){let M=[];for(let P of e.externalData){let O=typeof P=="string"?P:P.path;M.push(ud(typeof P=="string"?P:P.data).then(k=>{n.mountExternalData(O,k)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let P=M,O=P?.context,k=P?.gpuDevice,W=P?.deviceType,X=P?.powerPreference;O?n.currentContext=O:k?n.currentContext=await n.webnnCreateMLContext(k):n.currentContext=await n.webnnCreateMLContext({deviceType:W,powerPreference:X})}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]=bA(o),_=!!e?.enableGraphCapture,w=[],x=[],b=[],E=[],A=[];for(let M=0;M<f;M++){let[P,O,k]=Vf(o,M);P===0&&Pe("Can't get an input name."),c.push(P);let W=n.UTF8ToString(P);w.push(W),b.push(O===0?{name:W,isTensor:!1}:{name:W,isTensor:!0,type:ic(O),shape:k})}for(let M=0;M<m;M++){let[P,O,k]=Vf(o,M+f);P===0&&Pe("Can't get an output name."),p.push(P);let W=n.UTF8ToString(P);x.push(W),E.push(O===0?{name:W,isTensor:!1}:{name:W,isTensor:!0,type:ic(O),shape:k});{if(_&&e?.preferredOutputLocation===void 0){A.push("gpu-buffer");continue}let X=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[W]??"cpu",U=n.webnnIsGraphOutput;if(X==="cpu"&&U&&U(o,W)){A.push("ml-tensor-cpu-output");continue}if(X!=="cpu"&&X!=="cpu-pinned"&&X!=="gpu-buffer"&&X!=="ml-tensor")throw new Error(`Not supported preferred output location: ${X}.`);if(_&&X!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${X}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);A.push(X)}}let S=null;return A.some(M=>M==="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=>Qf(M))}),Br.set(o,[o,c,p,S,_,!1]),[o,w,x,b,E]}catch(f){throw c.forEach(m=>n._OrtFree(m)),p.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?.()}},md=t=>{let e=Be(),r=Br.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."),Br.delete(t)},Hf=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=Be(),l=i.PTR_SIZE,c=t[0],p=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 E=t[2].gpuBuffer;w=cn(bs(c),p);{let A=i.webgpuRegisterBuffer;if(!A)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=A(E,s)}}else if(f==="ml-tensor"){let E=t[2].mlTensor;w=cn(bs(c),p);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=A(s,E,bs(c),p)}else{let E=t[2];if(Array.isArray(E)){w=l*E.length,_=i._malloc(w),r.push(_);for(let A=0;A<E.length;A++){if(typeof E[A]!="string")throw new TypeError(`tensor data at index ${A} is not a string`);i.setValue(_+A*l,zt(E[A],r),"*")}}else{let A=i.webnnIsGraphInput,S=i.webnnIsGraphOutput;if(c!=="string"&&A&&S){let M=i.UTF8ToString(n);if(A(s,M)||S(s,M)){let P=bs(c);w=cn(P,p),m="ml-tensor";let O=i.webnnCreateTemporaryTensor,k=i.webnnUploadTensor;if(!O||!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let W=await O(s,P,p);k(W,new Uint8Array(E.buffer,E.byteOffset,E.byteLength)),_=W}else w=E.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),_)}else w=E.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),_)}}let x=i.stackSave(),b=i.stackAlloc(4*p.length);try{p.forEach((A,S)=>i.setValue(b+S*l,A,l===4?"i32":"i64"));let E=i._OrtCreateTensor(bs(c),_,w,b,p.length,Qf(m));E===0&&Pe(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(E)}finally{i.stackRestore(x)}},_d=async(t,e,r,s,n,o)=>{let a=Be(),i=a.PTR_SIZE,l=Br.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],p=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,b=s.length,E=0,A=[],S=[],M=[],P=[],O=[],k=a.stackSave(),W=a.stackAlloc(x*i),X=a.stackAlloc(x*i),U=a.stackAlloc(b*i),H=a.stackAlloc(b*i);try{[E,A]=YA(o),Ur("wasm prepareInputOutputTensor");for(let C=0;C<x;C++)await Hf(r[C],S,P,t,p[e[C]],e[C],_);for(let C=0;C<b;C++)await Hf(n[C],M,P,t,f[s[C]],x+s[C],_);Fr("wasm prepareInputOutputTensor");for(let C=0;C<x;C++)a.setValue(W+C*i,S[C],"*"),a.setValue(X+C*i,p[e[C]],"*");for(let C=0;C<b;C++)a.setValue(U+C*i,M[C],"*"),a.setValue(H+C*i,f[s[C]],"*");if(m&&!w){let{handle:C,outputPreferredLocations:te,outputPreferredLocationsEncoded:ae}=m;if(p.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${p.length}).`);Ur("wasm bindInputsOutputs");for(let L=0;L<x;L++){let N=e[L];await a._OrtBindInput(C,p[N],S[L])!==0&&Pe(`Can't bind input[${L}] for session=${t}.`)}for(let L=0;L<b;L++){let N=s[L];n[L]?.[3]?(O.push(M[L]),a._OrtBindOutput(C,f[N],M[L],0)!==0&&Pe(`Can't bind pre-allocated output[${L}] for session=${t}.`)):a._OrtBindOutput(C,f[N],0,ae[N])!==0&&Pe(`Can't bind output[${L}] to ${te[L]} for session=${t}.`)}Fr("wasm bindInputsOutputs"),Br.set(t,[c,p,f,m,_,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let j;m?j=await a._OrtRunWithBinding(c,m.handle,b,U,E):j=await a._OrtRun(c,X,W,x,H,b,U,E),j!==0&&Pe("failed to call OrtRun().");let K=[],$=[];Ur("wasm ProcessOutputTensor");for(let C=0;C<b;C++){let te=Number(a.getValue(U+C*i,"*"));if(te===M[C]||O.includes(M[C])){K.push(n[C]),te!==M[C]&&a._OrtReleaseTensor(te)!==0&&Pe("Can't release tensor.");continue}let ae=a.stackSave(),L=a.stackAlloc(4*i),N=!1,D,J=0;try{a._OrtGetTensorData(te,L,L+i,L+2*i,L+3*i)!==0&&Pe(`Can't access output tensor data on index ${C}.`);let xe=i===4?"i32":"i64",ue=Number(a.getValue(L,xe));J=a.getValue(L+i,"*");let qe=a.getValue(L+i*2,"*"),ot=Number(a.getValue(L+i*3,xe)),mt=[];for(let De=0;De<ot;De++)mt.push(Number(a.getValue(qe+De*i,xe)));a._OrtFree(qe)!==0&&Pe("Can't free memory for tensor dims.");let at=mt.reduce((De,Me)=>De*Me,1);D=ic(ue);let At=m?.outputPreferredLocations[s[C]];if(D==="string"){if(At==="gpu-buffer"||At==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let De=[];for(let Me=0;Me<at;Me++){let Ze=a.getValue(J+Me*i,"*"),nr=a.getValue(J+(Me+1)*i,"*"),Se=Me===at-1?void 0:nr-Ze;De.push(a.UTF8ToString(Ze,Se))}K.push([D,mt,De,"cpu"])}else if(At==="gpu-buffer"&&at>0){let De=a.webgpuGetBuffer;if(!De)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Me=De(J),Ze=cn(ue,at);if(Ze===void 0||!ld(D))throw new Error(`Unsupported data type: ${D}`);N=!0;{a.webgpuRegisterBuffer(Me,t,J);let nr=a.webgpuCreateDownloader(Me,Ze,t);K.push([D,mt,{gpuBuffer:Me,download:async()=>{let Se=await nr();return new(bo(D))(Se)},dispose:()=>{a._OrtReleaseTensor(te)!==0&&Pe("Can't release tensor.")}},"gpu-buffer"])}}else if(At==="ml-tensor"&&at>0){let De=a.webnnEnsureTensor,Me=a.webnnIsGraphInputOutputTypeSupported;if(!De||!Me)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(cn(ue,at)===void 0||!cd(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 Ze=await De(t,J,ue,mt,!1);N=!0,K.push([D,mt,{mlTensor:Ze,download:a.webnnCreateMLTensorDownloader(J,D),dispose:()=>{a.webnnReleaseTensorId(J),a._OrtReleaseTensor(te)}},"ml-tensor"])}else if(At==="ml-tensor-cpu-output"&&at>0){let De=a.webnnCreateMLTensorDownloader(J,D)(),Me=K.length;N=!0,$.push((async()=>{let Ze=[Me,await De];return a.webnnReleaseTensorId(J),a._OrtReleaseTensor(te),Ze})()),K.push([D,mt,[],"cpu"])}else{let De=bo(D),Me=new De(at);new Uint8Array(Me.buffer,Me.byteOffset,Me.byteLength).set(a.HEAPU8.subarray(J,J+Me.byteLength)),K.push([D,mt,Me,"cpu"])}}finally{a.stackRestore(ae),D==="string"&&J&&a._free(J),N||a._OrtReleaseTensor(te)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Pe("Can't clear bound outputs."),Br.set(t,[c,p,f,m,_,!1]));for(let[C,te]of await Promise.all($))K[C][2]=te;return Fr("wasm ProcessOutputTensor"),K}finally{a.webnnOnRunEnd?.(c),a.stackRestore(k),r.forEach(j=>{j&&j[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(j[2].gpuBuffer)}),n.forEach(j=>{j&&j[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(j[2].gpuBuffer)}),S.forEach(j=>a._OrtReleaseTensor(j)),M.forEach(j=>a._OrtReleaseTensor(j)),P.forEach(j=>a._free(j)),E!==0&&a._OrtReleaseRunOptions(E),A.forEach(j=>a._free(j))}},hd=t=>{let e=Be(),r=Br.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)},gd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Dr,Gt,ln,wo,xo,oc,Xf,ac,ws,xs,vA,a2,i2,l2,c2,u2,p2,f2,d2=be(()=>{"use strict";As(),o2(),Ts(),od(),Dr=()=>!!Ve.wasm.proxy&&typeof document<"u",ln=!1,wo=!1,xo=!1,ac=new Map,ws=(t,e)=>{let r=ac.get(t);r?r.push(e):ac.set(t,[e])},xs=()=>{if(ln||!wo||xo||!Gt)throw new Error("worker not ready")},vA=t=>{switch(t.data.type){case"init-wasm":ln=!1,t.data.err?(xo=!0,Xf[1](t.data.err)):(wo=!0,Xf[0]()),oc&&(URL.revokeObjectURL(oc),oc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ac.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},a2=async()=>{if(!wo){if(ln)throw new Error("multiple calls to 'initWasm()' detected.");if(xo)throw new Error("previous call to 'initWasm()' failed.");if(ln=!0,Dr())return new Promise((t,e)=>{Gt?.terminate(),XA().then(([r,s])=>{try{Gt=s,Gt.onerror=o=>e(o),Gt.onmessage=vA,Xf=[t,e];let n={type:"init-wasm",in:Ve};!n.in.wasm.wasmPaths&&(r||Yf)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Gt.postMessage(n),oc=r}catch(n){e(n)}},e)});try{await ad(Ve.wasm),await pd(Ve),wo=!0}catch(t){throw xo=!0,t}finally{ln=!1}}},i2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Ve}};Gt.postMessage(s)});await fd(Ve,t)},l2=async t=>Dr()?(xs(),new Promise((e,r)=>{ws("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Gt.postMessage(s,[t.buffer])})):fc(t),c2=async(t,e)=>{if(Dr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xs(),new Promise((r,s)=>{ws("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Gt.postMessage(n,o)})}else return dd(t,e)},u2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("release",[e,r]);let s={type:"release",in:t};Gt.postMessage(s)});md(t)},p2=async(t,e,r,s,n,o)=>{if(Dr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return xs(),new Promise((a,i)=>{ws("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Gt.postMessage(c,gd(l))})}else return _d(t,e,r,s,n,o)},f2=async t=>{if(Dr())return xs(),new Promise((e,r)=>{ws("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Gt.postMessage(s)});hd(t)}}),Kf,kA,m2,bz=be(()=>{"use strict";As(),d2(),un(),nd(),JA(),Kf=(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()}`)}},kA=t=>{switch(t[3]){case"cpu":return new er(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!ld(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(!cd(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]}`)}},m2=class{async fetchModelAndCopyToWasmMemory(t){return l2(await ud(t))}async loadModel(t,e){ks();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await c2(r,e),Es()}async dispose(){return u2(this.sessionId)}async run(t,e,r){ks();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)=>Kf(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?Kf(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await p2(this.sessionId,n,i,a,l,r),p={};for(let f=0;f<c.length;f++)p[this.outputNames[a[f]]]=o[f]??kA(c[f]);return Es(),p}startProfiling(){}endProfiling(){f2(this.sessionId)}}}),_2={};vo(_2,{OnnxruntimeWebAssemblyBackend:()=>ed,initializeFlags:()=>Zf,wasmBackend:()=>h2});var Zf,ed,h2,vz=be(()=>{"use strict";As(),d2(),bz(),Zf=()=>{(typeof Ve.wasm.initTimeout!="number"||Ve.wasm.initTimeout<0)&&(Ve.wasm.initTimeout=0);let t=Ve.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.`),Ve.wasm.simd=!1),typeof Ve.wasm.proxy!="boolean"&&(Ve.wasm.proxy=!1),typeof Ve.wasm.trace!="boolean"&&(Ve.wasm.trace=!1),typeof Ve.wasm.numThreads!="number"||!Number.isInteger(Ve.wasm.numThreads)||Ve.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ve.wasm.numThreads=1;else{let e=typeof navigator>"u"?ZL("node:os").cpus().length:navigator.hardwareConcurrency;Ve.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},ed=class{async init(t){Zf(),await a2(),await i2(t)}async createInferenceSessionHandler(t,e){let r=new m2;return await r.loadModel(t,e),r}},h2=new ed});As();As();As();var kz="1.25.0-dev.20260323-a99aad9d36",Ez=GA;{let t=(vz(),lc(_2)).wasmBackend;vs("webgpu",t,5),vs("webnn",t,5),vs("cpu",t,10),vs("wasm",t,10)}Object.defineProperty(Ve.versions,"web",{value:kz,enumerable:!0});async function g2(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){Z.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){Z.warn(`Failed to cache ${e}:`,n)}return s}async function w2(t){let e=await g2(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return Z.warn("Failed to read WASM binary:",r),null}}async function x2(t){if(ie.IS_SERVICE_WORKER_ENV||ie.IS_CHROME_AVAILABLE)return t;let e=await g2(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 Z.warn("Failed to read WASM factory:",r),null}}var y2="1.24.3";var b2="warning",xd={wasm:{},webgl:{},webgpu:{},versions:{common:y2},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}`);b2=t}},get logLevel(){return b2}};Object.defineProperty(xd,"logLevel",{enumerable:!0});var v2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,f=0,m=p,_=p*2,w=-1;a==="RGBA"?(f=0,m=p,_=p*2,w=p*3):a==="RGB"?(f=0,m=p,_=p*2):a==="RBG"&&(f=0,_=p,m=p*2);for(let x=0;x<o;x++)for(let b=0;b<n;b++){let E=(t.data[f++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[_++]-c[2])*l[2],M=w===-1?255:(t.data[w++]-c[3])*l[3];s.fillStyle="rgba("+E+","+A+","+S+","+M+")",s.fillRect(b,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},k2=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,E=0,A=f,S=f*2,M=-1;i==="RGBA"?(E=0,A=f,S=f*2,M=f*3):i==="RGB"?(E=0,A=f,S=f*2):i==="RBG"&&(E=0,S=f,A=f*2),s=r.createImageData(n,o);for(let P=0;P<o*n;_+=m,w+=m,x+=m,b+=m,P++)s.data[_]=(t.data[E++]-p[0])*c[0],s.data[w]=(t.data[A++]-p[1])*c[1],s.data[x]=(t.data[S++]-p[2])*c[2],s.data[b]=M===-1?255:(t.data[M++]-p[3])*c[3]}else throw new Error("Can not access image data");return s};var yd=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,E=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(b=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,b=c*2);for(let P=0;P<c;P++,m+=f,w+=f,_+=f,x+=f)p[b++]=(t[m]+a[0])/o[0],p[E++]=(t[_]+a[1])/o[1],p[A++]=(t[w]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new xt("float32",p,[1,4,r,s]):new xt("float32",p,[1,3,r,s])},E2=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let 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 p,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(p=e.resizedHeight,f=e.resizedWidth):(p=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=p,i.width=f,e!==void 0){let m=l();m.width=f,m.height=p;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,p).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=t.width,p.height=t.height;let f=c(p);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,yd(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,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,p(yd(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return yd(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},A2=(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})},T2=(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})},M2=(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})},S2=(t,e,r)=>new xt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Ms=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ko=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),O2=!1,I2=()=>{if(!O2){O2=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Ms.set("int64",BigInt64Array),ko.set(BigInt64Array,"int64")),e&&(Ms.set("uint64",BigUint64Array),ko.set(BigUint64Array,"uint64")),s?(Ms.set("float16",r),ko.set(r,"float16")):Ms.set("float16",Uint16Array)}};var C2=t=>{let e=1;for(let r=0;r<t.length;r++){let s=t[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);e*=s}return e},P2=(t,e)=>{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){I2();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=Ms.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=Ms.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=ko.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=C2(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 E2(e,r)}static fromTexture(e,r){return A2(e,r)}static fromGpuBuffer(e,r){return T2(e,r)}static fromMLTensor(e,r){return M2(e,r)}static fromPinnedBuffer(e,r,s){return S2(e,r,s)}toDataURL(e){return v2(this,e)}toImageData(e){return k2(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 P2(this,e)}};var dc=xt;var Az=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 R2(t){return t<=Ot.DEBUG?0:t<=Ot.INFO?2:t<=Ot.WARNING||t<=Ot.ERROR?3:4}var Tz={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},jt=[],bd,fn,L2=Symbol.for("onnxruntime");if(L2 in globalThis)fn=globalThis[L2];else if(ie.IS_NODE_ENV){switch(fn=Sf,process.platform){case"win32":jt.push("dml");break;case"linux":process.arch==="x64"&&jt.push("cuda");break;case"darwin":jt.push("coreml");break}jt.push("webgpu"),jt.push("cpu"),bd=["cpu"]}else fn=wd,ie.IS_WEBNN_AVAILABLE&&jt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),ie.IS_WEBGPU_AVAILABLE&&jt.push("webgpu"),jt.push("wasm"),bd=["wasm"];var Mz=fn.InferenceSession;function $2(t=null){if(!t)return bd;switch(t){case"auto":return jt;case"gpu":return jt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(jt.includes(t))return[Az[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${jt.join(", ")}.`)}var z2=Promise.resolve(),pn=null;async function Sz(){if(pn)return pn;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 pn=Promise.resolve(),pn}return pn=(async()=>{let e=st.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!bf(e.wasm)?(async()=>{try{let s=await w2(vf(e.wasm));s&&(st.wasm.wasmBinary=s,r=!0)}catch(s){Z.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!bf(e.mjs)?(async()=>{try{let s=await x2(vf(e.mjs));s&&(st.wasm.wasmPaths.mjs=s)}catch(s){Z.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(st.wasm.wasmPaths.mjs=e.mjs)})(),pn}async function mc(t,e,r){await Sz();let s=R2(me.logLevel??Ot.WARNING),n=()=>Mz.create(t,{logSeverityLevel:s,...e}),o=await(ie.IS_WEB_ENV?z2=z2.then(n):n());return o.config=r,o}var N2=Promise.resolve();async function _c(t,e){let r=()=>t.run(e);return ie.IS_WEB_ENV?N2=N2.then(r):r()}function hc(t){return t instanceof fn.Tensor}var st=fn?.env;function Eo(){return st?.wasm?.proxy}if(st){let t=function(e){let r=R2(e);st.logLevel=Tz[r]};if(st.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&st.versions?.web&&!st.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${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 Gr=async(t,e,r)=>{let s=await mc(new Uint8Array(t),e);return(async n=>{let o=Eo(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await _c(s,a);return Array.isArray(r)?r.map(l=>new R(i[l])):new R(i[r])})},ur=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Gr([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=Gr([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=Gr([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=Gr([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=Gr([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=Gr([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=Gr([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=Gr([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 B2=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"}),vd=ie.IS_NODE_ENV?"cpu":"wasm";function gc(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 (${vd}).`),vd):vd}var F2=(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"}),D2=yt.fp32,U2=Object.freeze({[B2.wasm]:yt.q8}),jr=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 wc(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=U2[r]??D2}else o&&yt.hasOwnProperty(o)?i=o:i=U2[r]??D2;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var vr=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 R=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 hc(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new dc(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;n<e;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(e){let[r,...s]=this.dims;if(e=pr(e,r),s.length>0){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<r.length;++s)if(r[s]==e)return s;return-1}_subarray(e,r,s){let n=e*r,o=(e+1)*r,a="subarray"in this.data?this.data.subarray(n,o):this.data.slice(n,o);return new t(this.type,a,s)}item(){let e=this.data;if(e.length!==1)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return Oz(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=1/(1+Math.exp(-e[r]));return this}map(e){return this.clone().map_(e)}map_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]=e(r[s],s,r);return this}mul(e){return this.clone().mul_(e)}mul_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]-=e;return this}clone(){return new t(this.type,this.data.slice(),this.dims.slice())}slice(...e){let r=[],s=[];for(let p=0;p<this.dims.length;++p){let f=e[p];if(f==null)s.push([0,this.dims[p]]),r.push(this.dims[p]);else if(typeof f=="number")f=pr(f,this.dims[p],p),s.push([f,f+1]);else if(Array.isArray(f)&&f.length===2){let[m,_]=f;if(m=m===null?0:pr(m,this.dims[p],p,!1),_=_===null?this.dims[p]:pr(_,this.dims[p],p,!1),m>_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[p])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([p,f])=>f-p),o=n.reduce((p,f)=>p*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let p=1;p<n.length;++p)if(s[p][0]!==0||s[p][1]!==this.dims[p]){c=!1;break}if(c){let p=s[0][0]*l[0],f=s[0][1]*l[0];if(ArrayBuffer.isView(a))i.set(a.subarray(p,f));else if(Array.isArray(a)){let m=a.slice(p,f);for(let _=0;_<m.length;++_)i[_]=m[_]}else throw new Error("Unsupported data type for slicing")}else for(let p=0;p<o;++p){let f=0;for(let m=n.length-1,_=p;m>=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[p]=a[f]}return new t(this.type,i,r)}permute(...e){return Iz(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,p]=Ao(a,this,r,s);if(e!==1)for(let f=0;f<c.length;++f)c[f]=c[f]**(1/e);return new t(l,c,p)}normalize_(e=2,r=1){r=pr(r,this.dims.length);let s=this.norm(e,r,!0),n=this.data,o=s.data;for(let a=0;a<n.length;++a){let i=0;for(let l=this.dims.length-1,c=a,p=1;l>=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*p,p*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return kd(this.dims)}squeeze(e=null){return new t(this.type,this.data,G2(this.dims,e))}squeeze_(e=null){return this.dims=G2(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,j2(this.dims,e))}unsqueeze_(e){return this.dims=j2(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;n<e.length;++n)if(e[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}let s=this.data;if(r!==-1){let n=e.reduce((o,a,i)=>i!==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;r<e.length;++r)e[r]=-e[r];return this}neg(){return this.clone().neg_()}gt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>e?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;n<s.length;++n)r[n]=s[n]<e?1:0;return new t("bool",r,this.dims)}clamp_(e,r){let s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],e),r);return this}clamp(e,r){return this.clone().clamp_(e,r)}round_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=Math.round(e[r]);return this}round(){return this.clone().round_()}mean(e=null,r=!1){return bc(this,e,r)}min(e=null,r=!1){if(e===null){let a=mo(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Ao((a,i)=>Math.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]=Ao((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=mo(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.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${e.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(e.every(p=>p===1)){if(e.length===this.dims.length)return this.clone();let p=e.length-this.dims.length,f=Array(p).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((p,f)=>p*e[f]),o=n.reduce((p,f)=>p*f,1),a=this.data,i=new a.constructor(o),l=kd(s),c=kd(n);for(let p=0;p<o;++p){let f=p,m=0;for(let _=0;_<n.length;++_){let w=Math.floor(f/c[_]);f=f%c[_];let x=w%s[_];m+=x*l[_]}i[p]=a[m]}return new t(this.type,i,n)}tile(...e){if(e.length<this.dims.length){let r=this.dims.length-e.length;e=Array(r).fill(1).concat(e)}return this.repeat(...e)}to(e){if(this.type===e)return this;if(!vr.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);let r,s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(e);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=o=>BigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,YE(this.data),this.dims);return new t(e,vr[e].from(this.data,r),this.dims)}};function Oz(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.length<e[o]?l.push(i):a.push([i]),a},[[]]);return n[0]}function Iz(t,e){let[r,s]=qE(t.data,t.dims,e);return new R(t.type,r,s)}function Ed(t,[e,r],s="bilinear",n=!1){let o=t.dims.at(-3)??1,a=t.dims.at(-2),i=t.dims.at(-1),l=jE(t.data,[o,a,i],[e,r],s,n);return new R(t.type,l,[o,e,r])}async function vt(t,{size:e=null,mode:r="bilinear"}={}){if(t.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!e)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(e.length===2)s=[...t.dims.slice(0,2),...e];else if(e.length===3)s=[t.dims[0],...e];else if(e.length===4)s=e;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await ur.nearest_interpolate_4d;else if(r==="bilinear")n=await ur.bilinear_interpolate_4d;else if(r==="bicubic")n=await ur.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new R("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function q2(t,e){return await(await ur.matmul)({a:t,b:e})}async function dB(t,e){return await(await ur.rfft)({x:t,a:e})}async function tr(t,e){let r=await ur.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new R("int64",[BigInt(e)],[1])})}var xc=t=>new R("int64",t,[t.length]);async function yc(t,e,r,s,n){return await(await ur.slice)({x:t,s:xc(e),e:xc(r),a:xc(s),t:xc(n??new Array(s.length).fill(1))})}function W2(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let p=0;p<a;++p){let f=p*l*i;for(let m=0;m<l;++m){let _=0,w=0,x=p*i,b=f+m;for(let A=0;A<i;++A){let S=Number(s[x+A]);w+=S,_+=r[b+A*l]*S}let E=_/w;o[c++]=E}}return new R(t.type,o,n)}function mB(t,e,{eps:r=1e-5}={}){if(t.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[s,n]=t.dims;if(e.length!==1&&e[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[o,a]=Ad(t,1,0,!0),i=o.data,l=a.data,c=t.data,p=new c.constructor(c.length);for(let f=0;f<s;++f){let m=f*n;for(let _=0;_<n;++_){let w=m+_;p[w]=(c[w]-l[f])/(i[f]+r)}}return new R(t.type,p,t.dims)}function G2(t,e){return t=t.slice(),e===null?t=t.filter(r=>r!==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 j2(t,e){return e=pr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function pr(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 ke(t,e=0){e=pr(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<t.length;++i){let{data:l,dims:c}=t[i];for(let p=0;p<l.length;++p){let f=0;for(let m=c.length-1,_=p,w=1;m>=0;--m){let x=c[m],b=_%x;m===e&&(b+=a),f+=b*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[p]}a+=c[e]}}return new R(o,n,r)}function It(t,e=0){return ke(t.map(r=>r.unsqueeze(e)),e)}function Ao(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=pr(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<o.length;++c){let p=0;for(let f=a.length-1,m=c,_=1;f>=0;--f){let w=a[f];if(f!==r){let x=m%w;p+=x*_,_*=i[f]}m=Math.floor(m/w)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function Ad(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((E,A)=>E+A,0)/n.length,w=Math.sqrt(n.reduce((E,A)=>E+(A-_)**2,0)/(n.length-r)),x=new R(t.type,[_],[]);return[new R(t.type,[w],[]),x]}e=pr(e,o.length);let a=bc(t,e,s),i=a.data,[l,c,p]=Ao((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;m<c.length;++m)c[m]=Math.sqrt(c[m]/(o[e]-r));return[new R(l,c,p),a]}function bc(t,e=null,r=!1){let s=t.dims,n=t.data;if(e===null){let l=n.reduce((c,p)=>c+p,0);return new R(t.type,[l/n.length],[])}e=pr(e,s.length);let[o,a,i]=Ao((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l<a.length;++l)a[l]/=s[e];return new R(o,a,i)}function kd(t){let e=new Array(t.length);for(let r=t.length-1,s=1;r>=0;--r)e[r]=s,s*=t[r];return e}function Td(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new R(r,new s(n).fill(e),t)}function He(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 Td(t,e,r,s)}function To(t,e){return He(t.dims,e)}function tt(t){return Td(t,1n,"int64",BigInt64Array)}function vc(t){return tt(t.dims)}function Md(t){return Td(t,0n,"int64",BigInt64Array)}function Sd(t){return Md(t.dims)}function _B(t){let e=t.reduce((r,s)=>r*s,1);return new R("float32",Float32Array.from({length:e},()=>hs.random()),t)}function V2(t){let e=t.reduce((r,s)=>r*s,1);return new R("float32",Float32Array.from({length:e},()=>hs.gauss()),t)}function H2(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;i<o.length;++i){let l=o[i]>0?1:0,c=Math.floor(i/8),p=i%8;a[c]|=l<<7-p,r&&p===0&&(a[c]-=128)}return new R(s,a,[t.dims[0],t.dims[1]/8])}async function dn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Ft(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Od(t,e){let r=await dn(t);return await Promise.all(r.map(s=>ut(t,s,!0,e)))}function Id(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 Cz=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Pz(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 Lz(t,e){for(let r of Object.keys(t))t[r].length=e}function Ss(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 zz(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var q=class extends et{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new xE(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Ss(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ss(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ss(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ss(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ss(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ss(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=zz(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 Od(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),p;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");p=e.map((m,_)=>this._encode_plus(m,{text_pair:r[_],add_special_tokens:s,return_token_type_ids:l}))}else p=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).");p=[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?(Z.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&&(Z.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(p.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;m<p.length;++m)p[m].input_ids.length!==a&&(p[m].input_ids.length>a?o&&Lz(p[m],a):n&&Pz(p[m],a,_=>_==="input_ids"?this.pad_token_id:0,this.padding_side));let f={};if(i){if(!(n&&o)&&p.some(_=>{for(let w of Object.keys(_))if(_[w].length!==p[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=[p.length,p[0].input_ids.length];for(let _ of Object.keys(p[0]))f[_]=new R("int64",BigInt64Array.from(p.flatMap(w=>w[_]).map(BigInt)),m)}else{for(let m of Object.keys(p[0]))f[m]=p.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 R&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof R&&(e=Id(e)),!Array.isArray(e)||e.length===0||!tE(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:p=!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 CE(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let E of Cz){let A=Ss(this.config,E);A&&(x[E]=A)}let b=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,..._});if(a){let E=this._call(b,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:p,...m});return f?E:E.input_ids}return b}};function mn(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var bm={};ds(bm,{AlbertTokenizer:()=>Cd,AutoTokenizer:()=>se,BartTokenizer:()=>Pd,BertTokenizer:()=>Ld,BlenderbotSmallTokenizer:()=>zd,BlenderbotTokenizer:()=>Nd,BloomTokenizer:()=>Rd,CLIPTokenizer:()=>Bd,CamembertTokenizer:()=>$d,CodeGenTokenizer:()=>Ud,CodeLlamaTokenizer:()=>Dd,CohereTokenizer:()=>Fd,ConvBertTokenizer:()=>Gd,DebertaTokenizer:()=>qd,DebertaV2Tokenizer:()=>jd,DistilBertTokenizer:()=>Wd,ElectraTokenizer:()=>Vd,EsmTokenizer:()=>Hd,FalconTokenizer:()=>Xd,GPT2Tokenizer:()=>Qd,GPTNeoXTokenizer:()=>Yd,GemmaTokenizer:()=>Kd,HerbertTokenizer:()=>Jd,LlamaTokenizer:()=>Zd,M2M100Tokenizer:()=>em,MBart50Tokenizer:()=>rm,MBartTokenizer:()=>Mo,MPNetTokenizer:()=>om,MarianTokenizer:()=>tm,MgpstrTokenizer:()=>sm,MobileBertTokenizer:()=>nm,NllbTokenizer:()=>am,NougatTokenizer:()=>im,PreTrainedTokenizer:()=>q,Qwen2Tokenizer:()=>lm,RoFormerTokenizer:()=>um,RobertaTokenizer:()=>cm,SiglipTokenizer:()=>pm,SpeechT5Tokenizer:()=>fm,SqueezeBertTokenizer:()=>dm,T5Tokenizer:()=>mm,TokenizersBackend:()=>q,VitsTokenizer:()=>hm,Wav2Vec2CTCTokenizer:()=>gm,WhisperTokenizer:()=>wm,XLMRobertaTokenizer:()=>xm,XLMTokenizer:()=>ym});var Cd=class extends q{return_token_type_ids=!0};var Pd=class extends q{};var Ld=class extends q{return_token_type_ids=!0};var zd=class extends q{};var Nd=class extends q{};var Rd=class extends q{};var $d=class extends q{};var Bd=class extends q{};var Dd=class extends q{};var Ud=class extends q{};var Fd=class extends q{};var Gd=class extends q{return_token_type_ids=!0};var jd=class extends q{return_token_type_ids=!0};var qd=class extends q{return_token_type_ids=!0};var Wd=class extends q{};var Vd=class extends q{return_token_type_ids=!0};var Hd=class extends q{};var Xd=class extends q{};var Kd=class extends q{};var Yd=class extends q{};var Qd=class extends q{};var Jd=class extends q{return_token_type_ids=!0};var Zd=class extends q{padding_side="left"};var em=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var tm=class extends q{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)),Z.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)||Z.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 Mo=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var rm=class extends Mo{};var sm=class extends q{};var nm=class extends q{return_token_type_ids=!0};var om=class extends q{};var am=class extends q{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return mn(this,e,r,s)}};var im=class extends q{};var lm=class extends q{};var cm=class extends q{};var um=class extends q{return_token_type_ids=!0};var pm=class extends q{};var fm=class extends q{};var dm=class extends q{return_token_type_ids=!0};var mm=class extends q{};var _m=class extends Dt{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},hm=class extends q{constructor(e,r){super(e,r),this._tokenizer.decoder=new _m({type:"VitsDecoder"})}};var gm=class extends q{};var X2=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],So=new Map(X2),Nz=new Map([...X2.map(([t,e])=>[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 K2(t){t=t.toLowerCase();let e=Nz.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),So.has(t))e=t;else{let n=t.length===2?So.keys():So.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var Rz="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Y2=new RegExp(`^[${Rz}]+$`,"gu"),wm=class extends q{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],p=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],b=[],E=!1,A=null,S=new Set(this.all_special_ids);for(let O of e){let k=O.tokens,W=i?O.token_timestamps:null,X=null,U=m;if("stride"in O){let[K,$,C]=O.stride;if(f-=$,A=K-C,$&&(U=$/n+m),C)for(let te=k.length-1;te>=0;--te){let ae=Number(k[te]);if(ae>=m){if(X!==null&&(ae-m)*n<A)break;X=ae}}}let H=[],j=[];for(let K=0;K<k.length;++K){let $=Number(k[K]);if(S.has($)){let C=this.decode([$]),te=So.get(C.slice(2,-2));if(te!==void 0){if(a!==null&&te!==a&&!r){x.push(H);let ae=this.findLongestCommonSequence(x)[0],L=this.decode(ae);p.text=L,c.push(p),x=[],H=[],p=l()}a=p.language=te}}else if($>=m&&$<=w){let C=($-m)*n+f,te=gs(C,2);if(X!==null&&$>=X)E=!0;else if(E||x.length>0&&$<U)E=!1;else if(p.timestamp[0]===null)p.timestamp[0]=te;else if(te!==p.timestamp[0]){p.timestamp[1]=te,x.push(H),i&&b.push(j);let[ae,L]=this.findLongestCommonSequence(x,b),N=this.decode(ae);p.text=N,i&&(p.words=this.collateWordTimestamps(ae,L,a)),c.push(p),x=[],H=[],b=[],j=[],p=l()}}else if(H.push($),i){let C=gs(W[K]+f,2),te;if(K+1<W.length){te=gs(W[K+1]+f,2);let ae=this.decode([$]);Y2.test(ae)&&(te=gs(Math.min(C+n,te),2))}else te=null;j.push([C,te])}}if("stride"in O){let[K,$,C]=O.stride;f+=K-C}H.length>0?(x.push(H),i&&b.push(j)):x.every(K=>K.length===0)&&(p=l(),x=[],H=[],b=[],j=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[O,k]=this.findLongestCommonSequence(x,b),W=this.decode(O);p.text=W,i&&(p.words=this.collateWordTimestamps(O,k,a)),c.push(p)}let M=Object.create(null),P=c.map(O=>O.text).join("");if(r||s){for(let O=0;O<c.length;++O){let k=c[O];r||delete k.timestamp,s||delete k.language}if(i){let O=[];for(let k of c)for(let W of k.words)O.push(W);M={chunks:O}}else M={chunks:c}}return[P,M]}findLongestCommonSequence(e,r=null){let s=e[0],n=s.length,o=[],a=Array.isArray(r)&&r.length>0,i=a?[]:null,l=a?r[0]:null;for(let c=1;c<e.length;++c){let p=e[c],f=0,m=[n,n,0,0],_=p.length;for(let M=1;M<n+_;++M){let P=Math.max(0,n-M),O=Math.min(n,n+_-M),k=s.slice(P,O),W=Math.max(0,M-n),X=Math.min(_,M),U=p.slice(W,X);if(k.length!==U.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let H;a?H=k.filter(($,C)=>$===U[C]&&l[P+C]<=r[c][W+C]).length:H=k.filter(($,C)=>$===U[C]).length;let j=M/1e4,K=H/M+j;H>1&&K>f&&(f=K,m=[P,O,W,X])}let[w,x,b,E]=m,A=Math.floor((x+w)/2),S=Math.floor((E+b)/2);o.push(...s.slice(0,A)),s=p.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.length;++l){let c=a[l];i.push({text:n[l],timestamp:[r[c.at(0)][0],r[c.at(-1)][1]]})}return i}combineTokensIntoWords(e,r,s=`"'\u201C\xA1\xBF([{-`,n=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){r=r??"english";let o,a,i;return["chinese","japanese","thai","lao","myanmar"].includes(r)?[o,a,i]=this.splitTokensOnUnicode(e):[o,a,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(o,a,i,s,n)}decode(e,r){let s;return r?.decode_with_timestamps?(e instanceof R&&(e=Id(e)),s=this.decodeWithTimestamps(e,r)):s=super.decode(e,r),s}decodeWithTimestamps(e,r){let s=r?.time_precision??.02,n=this.all_special_ids.at(-1)+1,o=[[]];for(let a of e)if(a=Number(a),a>=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let p=0;p<e.length;++p){let f=e[p];i.push(f),l.push(p);let m=this.decode(i,{decode_with_timestamps:!0});(!m.includes(s)||r[c+m.indexOf(s)]===s)&&(n.push(m),o.push(i),a.push(l),i=[],l=[],c+=m.length)}return[n,o,a]}splitTokensOnSpaces(e){let[r,s,n]=this.splitTokensOnUnicode(e),o=[],a=[],i=[];for(let l=0;l<r.length;++l){let c=r[l],p=s[l],f=n[l],m=p[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=c.startsWith(" "),w=c.trim(),x=Y2.test(w);if(m||_||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let b=o.length-1;o[b]+=c,a[b].push(...p),i[b].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=gt(i[c],i[p]),l[p]=gt(l[c],l[p]),a[c]="",i[c]=[],l[c]=[]):p=c,--c;for(c=0,p=1;p<a.length;)!a[c].endsWith(" ")&&o.includes(a[p])?(a[c]+=a[p],i[c]=gt(i[c],i[p]),l[c]=gt(l[c],l[p]),a[p]="",i[p]=[],l[p]=[]):c=p,++p;return[a.filter(f=>f),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var xm=class extends q{};var ym=class extends q{return_token_type_ids=!0;constructor(e,r){super(e,r),Z.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var se=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Od(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=bm[c];return p||(Z.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=q),new p(i,l)}};var qr="https://github.com/huggingface/transformers.js/issues/new/choose";var Oo="preprocessor_config.json",kr=Oo,Q2="processor_config.json",J2="chat_template.jinja";var re=class extends et{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,Q2,!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?Af(e,J2,!0,r):null]);return new this(s,n,o)}};var Xc={};ds(Xc,{ChatterboxProcessor:()=>Bm,Florence2Processor:()=>I_,Gemma3Processor:()=>C_,Gemma3nProcessor:()=>P_,Glm46VProcessor:()=>L_,GraniteSpeechProcessor:()=>z_,GroundingDinoProcessor:()=>N_,Idefics3Processor:()=>qc,JinaCLIPProcessor:()=>$_,Lfm2VlProcessor:()=>B_,LlavaProcessor:()=>D_,MgpstrProcessor:()=>U_,MoonshineProcessor:()=>F_,OwlViTProcessor:()=>G_,PaliGemmaProcessor:()=>j_,Phi3VProcessor:()=>q_,PixtralProcessor:()=>W_,Processor:()=>re,PyAnnoteProcessor:()=>V_,Qwen2VLProcessor:()=>Is,Qwen2_5_VLProcessor:()=>$o,Qwen3VLProcessor:()=>H_,Sam2Processor:()=>Wc,Sam2VideoProcessor:()=>X_,SamProcessor:()=>Bo,SmolVLMProcessor:()=>qc,SpeechT5Processor:()=>K_,UltravoxProcessor:()=>Y_,VLChatProcessor:()=>R_,VoxtralProcessor:()=>Q_,VoxtralRealtimeProcessor:()=>Z_,Wav2Vec2Processor:()=>eh,Wav2Vec2ProcessorWithLM:()=>th,WhisperProcessor:()=>rh});var Ee=class extends et{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await ut(e,Oo,!0,r);return new this(s)}};function $e(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 zo={};ds(zo,{ASTFeatureExtractor:()=>Em,ChatterboxFeatureExtractor:()=>Am,ClapFeatureExtractor:()=>Tm,DacFeatureExtractor:()=>Po,EncodecFeatureExtractor:()=>Co,FeatureExtractor:()=>Ee,Gemma3nAudioFeatureExtractor:()=>Mm,GraniteSpeechFeatureExtractor:()=>Sm,MoonshineFeatureExtractor:()=>Om,ParakeetFeatureExtractor:()=>Im,PyAnnoteFeatureExtractor:()=>Lo,SeamlessM4TFeatureExtractor:()=>Cm,SnacFeatureExtractor:()=>Pm,SpeechT5FeatureExtractor:()=>Lm,VoxtralRealtimeFeatureExtractor:()=>Rm,Wav2Vec2FeatureExtractor:()=>zm,WeSpeakerFeatureExtractor:()=>Nm,WhisperFeatureExtractor:()=>$m});var $z=()=>{};var Z2={fromWeb:$z};var Bz=()=>{};var eT=Bz;async function kc(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=Z2.fromWeb(r),n=ht.createWriteStream(t);await eT(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function km(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 Lr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&Z.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;c<n.length;++c)o[c]=a*(i[c]+l[c])/2}else o=n.getChannelData(0);return o}function sT(t,e){if(t<1)return new Float64Array;if(t===1)return new Float64Array([1]);let r=1-e,s=2*Math.PI/(t-1),n=new Float64Array(t);for(let o=0;o<t;++o)n[o]=e-r*Math.cos(o*s);return n}function tT(t){return sT(t,.5)}function Dz(t){return sT(t,.54)}var Uz={htk:t=>2595*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 vm(t,e="htk"){let r=Uz[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 Fz={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 Gz(t,e="htk"){let r=Fz[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 jz(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;a<t.length;++a){let i=s[a];for(let l=0;l<e.length;++l)i[l]=e[l]-t[a]}let n=e.length-2,o=Array.from({length:n},()=>new Array(t.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<n;++l){let c=-i[l]/r[l],p=i[l+2]/r[l+1];o[l][a]=Math.max(0,Math.min(c,p))}}return o}function rT(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+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=vm(r,a),c=vm(s,a),p=rT(l,c,e+2),f=Gz(p,a),m;if(i){let w=n/((t-1)*2);m=vm(Float64Array.from({length:t},(x,b)=>b*w),a),f=p}else m=rT(0,Math.floor(n/2),t);let _=jz(m,f);if(o!==null&&o==="slaney")for(let w=0;w<e;++w){let x=_[w],b=2/(f[w+2]-f[w]);for(let E=0;E<t;++E)x[E]*=b}return _}function qz(t,e,r){let s=new t.constructor(t.length+e+r),n=t.length-1;for(let o=0;o<t.length;++o)s[e+o]=t[o];for(let o=1;o<=e;++o)s[e-o]=t[rn(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[rn(n-o,n)];return s}function nT(t,e,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);let o=Math.log10(r);for(let a=0;a<t.length;++a)t[a]=e*Math.log10(Math.max(s,t[a])-o);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");let a=Ce(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function Wz(t,e=1,r=1e-5,s=null){return nT(t,20,e,r,s)}function Vz(t,e=1,r=1e-10,s=null){return nT(t,10,e,r,s)}async function ft(t,e,r,s,{fft_length:n=null,power:o=1,center:a=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:c=null,preemphasis_htk_flavor:p=!0,mel_filters:f=null,mel_floor:m=1e-10,log_mel:_=null,max_log_mel:w=null,reference:x=1,min_value:b=1e-10,db_range:E=null,remove_dc_offset:A=null,min_num_frames:S=null,max_num_frames:M=null,do_pad:P=!0,transpose:O=!1,mel_offset:k=0}={}){let W=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(W!==r)throw new Error(`Length of the window (${W}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!p)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a)switch(i){case"reflect":{let D=Math.floor((n-1)/2)+1;t=qz(t,D,D);break}case"constant":{let D=Math.floor(n/2),J=new t.constructor(t.length+2*D);J.set(t,D),t=J;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let X=Math.floor(1+Math.floor((t.length-r)/s));S!==null&&X<S&&(X=S);let U=l?Math.floor(n/2)+1:n,H=X,j=X;M!==null&&(M>X?P&&(j=M):j=H=M);let K=new ec(n),$=new Float64Array(n),C=new Float64Array(K.outputBufferSize),te=new Float32Array(U*j);for(let D=0;D<H;++D){let J=D*s,xe=Math.min(t.length-J,r);xe!==r&&$.fill(0,0,r);for(let ue=0;ue<xe;++ue)$[ue]=t[J+ue];if(A){let ue=0;for(let ot=0;ot<xe;++ot)ue+=$[ot];let qe=ue/xe;for(let ot=0;ot<xe;++ot)$[ot]-=qe}if(c!==null){for(let ue=xe-1;ue>=1;--ue)$[ue]-=c*$[ue-1];$[0]*=1-c}for(let ue=0;ue<e.length;++ue)$[ue]*=e[ue];K.realTransform(C,$);for(let ue=0;ue<U;++ue){let qe=ue<<1;te[ue*j+D]=C[qe]**2+C[qe+1]**2}}if(o!==null&&o!==2){let D=o/2;for(let J=0;J<te.length;++J)te[J]**=D}let ae=f.length,L=await q2(new R("float32",f.flat(),[ae,U]),new R("float32",te,[U,j]));O&&(L=L.transpose(1,0));let N=L.data;for(let D=0;D<N.length;++D)N[D]=k+Math.max(m,N[D]);if(o!==null&&_!==null){let D=Math.min(N.length,H*ae);switch(_){case"log":for(let J=0;J<D;++J)N[J]=Math.log(N[J]);break;case"log10":for(let J=0;J<D;++J)N[J]=Math.log10(N[J]);break;case"log10_max_norm":{for(let ue=0;ue<D;++ue)N[ue]=Math.log10(N[ue]);let xe=(w??Ce(N)[0])-8;for(let ue=0;ue<D;++ue)N[ue]=(Math.max(N[ue],xe)+4)/4;break}case"dB":if(o===1)Wz(N,x,b,E);else if(o===2)Vz(N,x,b,E);else throw new Error(`Cannot use log_mel option '${_}' with power ${o}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${_}'`)}}return L}function dt(t,e,{periodic:r=!0,frame_length:s=null,center:n=!0}={}){let o=r?t+1:t,a;switch(e){case"boxcar":a=new Float64Array(o).fill(1);break;case"hann":case"hann_window":a=tT(o);break;case"hamming":a=Dz(o);break;case"povey":a=tT(o).map(i=>Math.pow(i,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);return a}function Hz(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return Ec(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),Ec(n,8,"WAVE"),Ec(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),Ec(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function Ec(t,e,r){for(let s=0;s<r.length;++s)t.setUint8(e+s,r.charCodeAt(s))}var Io=class{constructor(e,r){this.audio=e,this.sampling_rate=r}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((n,o)=>n+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]),Hz(e,this.sampling_rate)}async save(e){return kc(e,this.toBlob())}};var Em=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){$e(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;o<n.length;++o)n[o]=(n[o]-this.mean)/s}return{input_values:r.unsqueeze_(0)}}};var Co=class extends Ee{async _call(e){$e(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=this.config.feature_size;if(e.length%r!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${r}).`);let s=[1,r,e.length/r];return{input_values:new R("float32",e,s)}}};var Am=class extends Ee{async _call(e){$e(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new R("float32",e,r)}}};var Tm=class extends Ee{constructor(e){super(e),this.mel_filters=nt(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=nt(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=dt(this.config.fft_window_size,"hann")}async _get_input_mel(e,r,s,n){let o,a=!1,i=e.length-r;if(i>0)if(s==="rand_trunc"){a=!0;let l=Math.floor(hs.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c<r;c+=e.length)l.set(e.subarray(0,Math.min(e.length,r-c)),c);else if(n==="repeatpad")for(let c=e.length;c<-i;c+=e.length)l.set(e,c);e=l}if(s==="fusion")throw new Error(`Truncation strategy "${s}" not implemented`);o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return o.unsqueeze_(0)}async _extract_fbank_features(e,r,s=null){return ft(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:r,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:r=null}={}){return $e(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,r??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}};var Po=class extends Co{};var Mm=class extends Ee{constructor(e){super(e);let{fft_length:r,feature_size:s,min_frequency:n,max_frequency:o,sampling_rate:a,frame_length:i}=this.config,l=nt(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=dt(i,"hann")}async _extract_fbank_features(e,r){return ft(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:r=48e4,truncation:s=!0,padding:n=!0,pad_to_multiple_of:o=128}={}){if($e(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>r&&(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=He([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Sm=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){$e(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 Om=class extends Ee{async _call(e){$e(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new R("float32",e,r)}}};var Xz=1e-5,Im=class extends Ee{constructor(e){super(e),this.config.mel_filters??=nt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let r=dt(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let s=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(r,s)}async _extract_fbank_features(e){let r=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=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){$e(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;f<s;++f){let m=f*a;for(let _=0;_<a;++_){let w=n[m+_];i[_]+=w,l[_]+=w*w}}let c=s>1?s-1:1;for(let f=0;f<a;++f){let m=i[f]/s,_=(l[f]-s*m*m)/c,x=1/(Math.sqrt(_)+Xz);for(let b=0;b<s;++b){let E=b*a+f;n[E]=(n[E]-m)*x}}let p=new BigInt64Array(o);return p.fill(1n,0,s),{input_features:r.unsqueeze_(0),attention_mask:new R("int64",p,[1,o])}}};var Lo=class extends Ee{async _call(e){$e(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new R("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<o.length;++l){let c=Ne(o[l]),[p,f]=Ce(c),[m,_]=[l,l+1];f!==i?(i=f,a.push({id:f,start:m,end:_,score:p})):(a.at(-1).end=_,a.at(-1).score+=p)}n.push(a.map(({id:l,start:c,end:p,score:f})=>({id:l,start:c*s,end:p*s,confidence:f/(p-c)})))}return n}};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,"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}={}){$e(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,b=a.data;for(let E=0;E<x;++E){let A=0;for(let O=0;O<w;++O)A+=b[O*x+E];let S=A/w,M=0;for(let O=0;O<w;++O)M+=(b[O*x+E]-S)**2;M/=w-1;let P=Math.sqrt(M+1e-7);for(let O=0;O<w;++O){let k=O*x+E;b[k]=(b[k]-S)/P}}}let i;if(r){let[w,x]=a.dims,b=a.data,E=w%s;if(E>0){let A=new Float32Array(x*(w+E));A.set(b),A.fill(this.config.padding_value,b.length);let S=w+E;a=new R(a.type,A,[S,x]),o&&(i=new R("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,p=this.config.stride;if(l%p!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${p}).`);let m=a.view(1,Math.floor(l/p),c*p),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let b=i.data;for(let E=1,A=0;E<l;E+=p,++A)x[A]=b[E]}else x.fill(1n);_.attention_mask=new R("int64",x,[1,w])}return _}};var Pm=class extends Po{};var Lm=class extends Ee{};var zm=class extends Ee{_zero_mean_unit_var_norm(e){let s=e.reduce((o,a)=>o+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){$e(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 R("float32",r,s),attention_mask:new R("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Nm=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){$e(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;l<o;++l){let c=l*a*i,p=l*i;for(let f=0;f<a;++f){let m=c+f*i;for(let _=0;_<i;++_)n[m+_]-=s[p+_]}}}return{input_features:r}}};var Rm=class extends Ee{constructor(e){super(e),this.config.mel_filters??=nt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=dt(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:r=!0}={}){let{n_fft:s,hop_length:n,mel_filters:o,global_log_mel_max:a}=this.config,i=Math.floor(r?e.length/n:(e.length-s)/n);return await ft(e,this.window,s,n,{power:2,mel_filters:o,log_mel:"log10_max_norm",max_log_mel:a,center:r,max_num_frames:i,do_pad:!1})}async _call(e,{center:r=!0}={}){return $e(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:r})).unsqueeze_(0)}}};var $m=class extends Ee{constructor(e){super(e),this.config.mel_filters??=nt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=dt(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await ft(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:r=null}={}){$e(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&Z.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 Xe=class{static async from_pretrained(e,r={}){let s=await ut(e,Oo,!0,r),n=s.feature_extractor_type,o=zo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${qr}.`);return new o(s)}};var Bm=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var Ac={};var Os,oT,Wr;if(ie.IS_WEB_ENV)Os=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},Wr=self.createImageBitmap,oT=self.ImageData;else if(Ac)Wr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Ye(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 Kz={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},Yz=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Ye=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 Lr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(ie.IS_WEB_ENV){let r=await Wr(e),s=Os(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=Ac(await e.arrayBuffer());return await Wr(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r<this.data.length;r+=this.channels){let n=this.data[r],o=this.data[r+1],a=this.data[r+2];e[s++]=Math.round(.2989*n+.587*o+.114*a)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2],e[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${e.channels}`);let r=this.data,s=e.data,n=this.width*this.height;if(this.channels===3){let o=new Uint8ClampedArray(n*4);for(let a=0,i=0,l=0;a<n;++a)o[l++]=r[i++],o[l++]=r[i++],o[l++]=r[i++],o[l++]=s[a];return this._update(o,this.width,this.height,4)}else if(this.channels===4){for(let o=0;o<n;++o)r[4*o+3]=s[o];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(e,r,{resample:s=2}={}){if(this.width===e&&this.height===r)return this;let n=Kz[s]??s,o=_f(e),a=_f(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),ie.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=Os(e,r).getContext("2d");return c.drawImage(l,0,0,e,r),new t(c.getImageData(0,0,e,r).data,e,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(Z.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([e/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:e,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await Wr(i)}}async pad([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),e===0&&r===0&&s===0&&n===0)return this;if(ie.IS_WEB_ENV){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,c=Os(i,l).getContext("2d");return c.drawImage(a,0,0,this.width,this.height,e,s,this.width,this.height),new t(c.getImageData(0,0,i,l).data,i,l,4).convert(o)}else{let o=this.toSharp().extend({left:e,right:r,top:s,bottom:n});return await Wr(o)}}async crop([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),e===0&&r===0&&s===this.width-1&&n===this.height-1)return this;let o=s-e+1,a=n-r+1;if(ie.IS_WEB_ENV){let i=this.channels,l=this.toCanvas(),c=Os(o,a).getContext("2d");return c.drawImage(l,e,r,o,a,0,0,o,a),new t(c.getImageData(0,0,o,a).data,o,a,4).convert(i)}else{let i=this.toSharp().extract({left:e,top:r,width:o,height:a});return await Wr(i)}}async center_crop(e,r){if(this.width===e&&this.height===r)return this;let s=(this.width-e)/2,n=(this.height-r)/2;if(ie.IS_WEB_ENV){let o=this.channels,a=this.toCanvas(),i=Os(e,r).getContext("2d"),l=0,c=0,p=0,f=0;return s>=0?l=s:p=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,p,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await Wr(o)}}async toBlob(e="image/png",r=1){if(!ie.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new R("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=Os(e.width,e.height),s=new oT(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;l<a;++l){let c=n*l;for(let p=0;p<n;++p)i[p][l]=e[c+p]}return i.map(l=>new 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=Yz.get(r)??"image/png",n=await this.toBlob(s);return kc(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 Ac(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},Qz=Ye.read.bind(Ye);function aT(t,e,r=0,s=null){let n=t/e,o=XE(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function iT([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function Dm([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Vr(t,e=.5,r=null,s=!1){let n=t.logits,o=t.pred_boxes,[a,i,l]=n.dims;if(r!==null&&r.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let p=0;p<a;++p){let f=r!==null?r[p]:null,m={boxes:[],classes:[],scores:[]},_=n[p],w=o[p];for(let x=0;x<i;++x){let b=_[x],E=[],A;if(s){A=b.sigmoid().data;for(let S=0;S<A.length;++S)A[S]>e&&E.push(S)}else{let S=Ce(b.data)[1];if(S===l-1||(A=Ne(b.data),A[S]<e))continue;E.push(S)}for(let S of E){let M=w[x].data;M=Dm(M),f!==null&&(M=M.map((P,O)=>P*f[(O+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(A[S])}}c.push(m)}return c}function Tc(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;o<s;++o){let a=e!==null?e[o]:null,i=r[o];a!==null&&(i=Ed(i,a,"bilinear",!1));let[l,c]=a??i.dims.slice(-2),p=new R("int32",new Int32Array(l*c),[l,c]),f=i[0].data,m=p.data;for(let x=1;x<i.dims[0];++x){let b=i[x].data;for(let E=0;E<b.length;++E)b[E]>f[E]&&(f[E]=b[E],m[E]=x)}let _=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let b=m[x];_[b]=b}let w=_.filter(x=>x!==void 0);n.push({segmentation:p,labels:w})}return n}function Jz(t,e,r,s){let n=[],o=[],a=[];for(let i=0;i<t.dims[0];++i){let l=t[i],c=e[i],p=Ce(l.data)[1];if(p===s)continue;let m=Ne(l.data)[p];m>r&&(n.push(c),o.push(m),a.push(p))}return[n,o,a]}function Zz(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let p=0;p<t.length;++p)t[p]===r&&(o.push(p),++a),l[p]>=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function eN(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new R("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=Ed(t[x],a,"bilinear",!1);let f=new Int32Array(t[0].data.length),m=new Float32Array(t[0].data.length);for(let x=0;x<t.length;++x){let b=e[x],E=t[x].data;for(let A=0;A<E.length;++A)E[A]*=b,E[A]>m[A]&&(f[A]=x,m[A]=E[A])}let _=0,w=c.data;for(let x=0;x<r.length;++x){let b=r[x],[E,A]=Zz(f,t,x,s,n);if(E){++_;for(let S of A)w[S]=_;p.push({id:_,label_id:b,score:e[x]})}}return[c,p]}function _n(t,e,r=28,s=3136,n=784*1280,o=1){if(t<r||e<r){let l=Math.max(r/t,r/e);t=Math.round(t*l),e=Math.round(e*l)}if(Math.max(t,e)/Math.min(t,e)>200)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*i<s){let l=Math.sqrt(s/(o*t*e));a=Math.ceil(t*l/r)*r,i=Math.ceil(e*l/r)*r}return[i,a]}function Mc(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(Z.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);let a=t.class_queries_logits??t.logits,l=(t.masks_queries_logits??t.pred_masks).sigmoid(),[c,p,f]=a.dims;if(f-=1,o!==null&&o.length!==c)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let m=[];for(let _=0;_<c;++_){let w=o!==null?o[_]:null,x=a[_],b=l[_],[E,A,S]=Jz(x,b,e,f);if(S.length===0){let[O,k]=w??b.dims.slice(-2),W=new R("int32",new Int32Array(O*k).fill(-1),[O,k]);m.push({segmentation:W,segments_info:[]});continue}let[M,P]=eN(E,A,S,r,s,n,w);m.push({segmentation:M,segments_info:P})}return m}function Sc(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var V=class extends et{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,r,s=2){let n=e.height,o=e.width,a=r.height,i=r.width,l=Math.min(n,a),c=Math.min(o,i);return l===n&&c===o?e:(n>o?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=mo(s.data)[0],a=Ce(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,p=0,f=0,m=s.data;for(let _=0;_<s.height;++_){let w=_*s.width;for(let x=0;x<s.width;++x)(m[w+x]-n)/a<i&&(l=Math.min(l,x),c=Math.min(c,_),p=Math.max(p,x),f=Math.max(f,_))}return e=await e.crop([l,c,p,f]),e}pad_image(e,r,s,{mode:n="constant",center:o=!1,constant_values:a=0}={}){let[i,l,c]=r,p,f;if(typeof s=="number"?(p=s,f=s):s==="square"?p=f=Math.max(i,l):(p=s.width,f=s.height),p!==l||f!==i){let m=new Float32Array(p*f*c);if(Array.isArray(a))for(let x=0;x<m.length;++x)m[x]=a[x%c];else a!==0&&m.fill(a);let[_,w]=o?[Math.floor((p-l)/2),Math.floor((f-i)/2)]:[0,0];for(let x=0;x<i;++x){let b=(x+w)*p,E=x*l;for(let A=0;A<l;++A){let S=(b+A+_)*c,M=(E+A)*c;for(let P=0;P<c;++P)m[S+P]=e[M+P]}}if(n==="symmetric"){if(o)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let x=i-1,b=l-1;for(let E=0;E<f;++E){let A=E*p,S=rn(E,x)*l;for(let M=0;M<p;++M){if(E<i&&M<l)continue;let P=(A+M)*c,O=(S+rn(M,b))*c;for(let k=0;k<c;++k)m[P+k]=e[O+k]}}}e=m,r=[f,p,c]}return[e,r]}rescale(e){for(let r=0;r<e.length;++r)e[r]=this.rescale_factor*e[r]}get_resize_output_image_size(e,r){let[s,n]=e.size,o,a;if(this.do_thumbnail){let{height:i,width:l}=r;o=Math.min(i,l)}else Number.isInteger(r)?(o=r,a=this.config.max_size??o):r!==void 0&&(o=r.shortest_edge,a=r.longest_edge);if(o!==void 0||a!==void 0){let i=o===void 0?1:Math.max(o/s,o/n),l=s*i,c=n*i,p=a===void 0?1:Math.min(a/l,a/c),f=Math.floor(Number((l*p).toFixed(2))),m=Math.floor(Number((c*p).toFixed(2)));return this.size_divisibility!==void 0&&([f,m]=iT([f,m],this.size_divisibility)),[f,m]}else if(r!==void 0&&r.width!==void 0&&r.height!==void 0){let i=r.width,l=r.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let c=l/n,p=i/s;Math.abs(1-p)<Math.abs(1-c)?c=p:p=c,l=aT(c*n,this.config.ensure_multiple_of),i=aT(p*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return iT([s,n],this.size_divisibility);throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(r)}`)}}async resize(e){let[r,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(r,s,{resample:this.resample})}async preprocess(e,{do_normalize:r=null,do_pad:s=null,do_convert_rgb:n=null,do_convert_grayscale:o=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[i,l]=e.size;if(n??this.do_convert_rgb?e=e.rgb():o&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,w;Number.isInteger(this.crop_size)?(_=this.crop_size,w=this.crop_size):(_=this.crop_size.width,w=this.crop_size.height),e=await e.center_crop(_,w)}let c=[e.height,e.width],p=Float32Array.from(e.data),f=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(p),r??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let w=this.image_std;if(Array.isArray(this.image_std)||(w=new Array(e.channels).fill(w)),_.length!==e.channels||w.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${w.length}) must match the number of channels in the image (${e.channels}).`);for(let x=0;x<p.length;x+=e.channels)for(let b=0;b<e.channels;++b)p[x+b]=(p[x+b]-_[b])/w[b]}if(s??this.do_pad){if(this.pad_size)[p,f]=this.pad_image(p,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let _=Math.ceil(f[1]/this.size_divisibility)*this.size_divisibility,w=Math.ceil(f[0]/this.size_divisibility)*this.size_divisibility;[p,f]=this.pad_image(p,f,{width:_,height:w})}}if(a??this.do_flip_channel_order){if(f[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<p.length;_+=3){let w=p[_];p[_]=p[_+2],p[_+2]=w}}let m=new R("float32",p,f).permute(2,0,1);return{original_size:[l,i],reshaped_input_size:c,pixel_values:m}}async _call(e,...r){Array.isArray(e)||(e=[e]);let s=await Promise.all(e.map(o=>this.preprocess(o)));return{pixel_values:It(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,kr,!0,r);return new this(s)}};var yn={};ds(yn,{BeitFeatureExtractor:()=>Um,BitImageProcessor:()=>Fm,CHMv2ImageProcessor:()=>jm,CLIPFeatureExtractor:()=>qm,CLIPImageProcessor:()=>Oc,ChineseCLIPFeatureExtractor:()=>Gm,ConvNextFeatureExtractor:()=>Wm,ConvNextImageProcessor:()=>Ic,DINOv3ViTImageProcessor:()=>Xm,DPTFeatureExtractor:()=>Ym,DPTImageProcessor:()=>Lc,DeiTFeatureExtractor:()=>Vm,DeiTImageProcessor:()=>Cc,DetrFeatureExtractor:()=>Hm,DetrImageProcessor:()=>Pc,DonutFeatureExtractor:()=>Km,DonutImageProcessor:()=>hn,EfficientNetImageProcessor:()=>Qm,GLPNFeatureExtractor:()=>e_,Gemma3ImageProcessor:()=>Jm,Glm46VImageProcessor:()=>Zm,GroundingDinoImageProcessor:()=>t_,Idefics3ImageProcessor:()=>zc,ImageFeatureExtractor:()=>V,ImageProcessor:()=>V,JinaCLIPImageProcessor:()=>s_,Lfm2VlImageProcessor:()=>n_,LlavaOnevisionImageProcessor:()=>o_,Mask2FormerImageProcessor:()=>i_,MaskFormerFeatureExtractor:()=>a_,MaskFormerImageProcessor:()=>gn,MobileNetV1FeatureExtractor:()=>l_,MobileNetV1ImageProcessor:()=>Nc,MobileNetV2FeatureExtractor:()=>c_,MobileNetV2ImageProcessor:()=>Rc,MobileNetV3FeatureExtractor:()=>u_,MobileNetV3ImageProcessor:()=>$c,MobileNetV4FeatureExtractor:()=>p_,MobileNetV4ImageProcessor:()=>Bc,MobileViTFeatureExtractor:()=>f_,MobileViTImageProcessor:()=>Dc,NougatImageProcessor:()=>d_,OwlViTFeatureExtractor:()=>m_,OwlViTImageProcessor:()=>wn,Owlv2ImageProcessor:()=>__,Phi3VImageProcessor:()=>w_,PixtralImageProcessor:()=>x_,PvtImageProcessor:()=>y_,Qwen2VLImageProcessor:()=>No,RTDetrImageProcessor:()=>b_,Sam2ImageProcessor:()=>Ro,Sam3ImageProcessor:()=>Ro,SamImageProcessor:()=>Ro,SapiensFeatureExtractor:()=>v_,SapiensImageProcessor:()=>Uc,SegformerFeatureExtractor:()=>k_,SegformerImageProcessor:()=>Fc,SiglipImageProcessor:()=>E_,SmolVLMImageProcessor:()=>zc,Swin2SRImageProcessor:()=>A_,VLMImageProcessor:()=>r_,ViTFeatureExtractor:()=>T_,ViTImageProcessor:()=>Gc,VitMatteImageProcessor:()=>M_,VitPoseImageProcessor:()=>S_,YolosFeatureExtractor:()=>O_,YolosImageProcessor:()=>jc});var Um=class extends V{};var Fm=class extends V{};var Gm=class extends V{};var jm=class extends V{};var Oc=class extends V{},qm=class extends Oc{};var Ic=class extends V{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}},Wm=class extends Ic{};var Cc=class extends V{},Vm=class extends Cc{};var Pc=class extends V{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=He(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Vr(...e)}post_process_panoptic_segmentation(...e){return Mc(...e)}post_process_instance_segmentation(...e){return Sc(...e)}},Hm=class extends Pc{};var Xm=class extends V{};var hn=class extends V{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let p=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:p,...n})}},Km=class extends hn{};var Lc=class extends V{},Ym=class extends Lc{};var Qm=class extends V{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 Jm=class extends V{};var No=class extends V{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 _n(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=ke(Array.from({length:i},()=>a),0));let p=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/c),_=Math.floor(a.dims[3]/c),w=a.view(p,i,f,Math.floor(m/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*m*_,f*i*c*c),x=new R("int64",[p,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var Zm=class extends No{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return _n(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var e_=class extends V{};var t_=class extends V{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=tt([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var zc=class extends V{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 E of n){let A=await Promise.all(E.map(P=>this.preprocess(P)));l.push(...A.map(P=>P.original_size)),c.push(...A.map(P=>P.reshaped_input_size)),A.forEach(P=>P.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let P=new Array(A.length),O=new Array(A.length);M=await Promise.all(A.map(async(k,W)=>{let X=this.get_resize_for_vision_encoder(k.pixel_values,S),U=await vt(k.pixel_values,{size:[X.height,X.width]}),{frames:H,num_splits_h:j,num_splits_w:K}=await this.split_image(U,this.max_image_size);return P[W]=j,O[W]=K,ke(H,0)})),a.push(P),i.push(O)}else{let P=[S,S];M=await Promise.all(A.map(O=>vt(O.pixel_values,{size:P}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(ke(M,0))}let p=o.length,[f,m,_,w]=o[0].dims,x,b;if(p===1)x=o[0].unsqueeze_(0),b=He([p,f,_,w],!0);else{let E=Math.max(...o.map(M=>M.dims.at(0)));b=He([p,E,_,w],!0);let A=b.data,S=E*_*w;for(let M=0;M<p;++M){let P=o[M].dims[0];if(P<E){o[M]=ke([o[M],He([E-P,m,_,w],0)],0);let O=M*S+P*_*w,k=(M+1)*S;A.fill(!1,O,k)}}x=It(o,0)}return{pixel_values:x,pixel_attention_mask:b,original_sizes:l,reshaped_input_sizes:c,...s?{rows:a,cols:i}:{}}}async split_image(e,{longest_edge:r}){let s=r,n=r,o=[],[a,i]=e.dims.slice(-2),l=0,c=0;if(a>s||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let p=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;w<l;++w)for(let x=0;x<c;++x){let b,E,A,S;w===l-1?(E=a-p,S=a):(E=w*p,S=(w+1)*p),x===c-1?(b=i-f,A=i):(b=x*f,A=(x+1)*f);let O=await yc(e,[E,b],[S,A],[2,3]);o.push(O)}let m=s,_=n;(a!==m||i!==_)&&(e=await vt(e,{size:[m,_]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:c}}};var r_=class extends V{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(r=>r*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 s_=class extends V{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 lT(t,e){return Math.round(t/e)*e}function tN(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<o?(o=c,a=l):c===o&&i>.5*n*n*l[0]*l[1]&&(a=l)}return a}function rN(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 sN(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,p=new Float32Array(r*a*i*l),f=n*o;for(let m=0;m<r;++m){let _=m*s*f,w=m*a*i*l;for(let x=0;x<a;++x)for(let b=0;b<i;++b){let E=w+(x*i+b)*l;for(let A=0;A<e;++A){let S=(x*e+A)*o+b*e;for(let M=0;M<e;++M){let P=S+M;for(let O=0;O<s;++O)p[E++]=c[_+O*f+P]}}}}return new R("float32",p,[r,a*i,l])}function nN(t,e){let[,r,s]=t.dims,n=new BigInt64Array(e);n.fill(1n,0,r);let o=t;if(r<e){let a=new Float32Array(e*s);a.set(t.data),o=new R("float32",a,[1,e,s])}return{padded:o,mask:new R("int64",n,[e])}}var n_=class extends V{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;let r=this.max_image_tokens*this.downsample_factor**2,s=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(r,s)}_is_image_too_large(e,r){let s=this.encoder_patch_size*this.downsample_factor,n=Math.max(this.encoder_patch_size,lT(e,s)),o=Math.max(this.encoder_patch_size,lT(r,s));return n*o>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=rN(this.min_tiles,this.max_tiles),[n,o]=tN(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,b=_.unsqueeze_(0),E=this.encoder_patch_size*this.downsample_factor,A=E**2,[S,M]=_n(Math.max(E,w),Math.max(E,x),E,this.min_image_tokens*A,this.max_image_tokens*A).map(U=>Math.max(E,U)),P,O=1,k=1,W=this._is_image_too_large(w,x),X=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(W&&X){let{grid_width:U,grid_height:H,target_width:j,target_height:K}=this._get_grid_layout(w,x);O=H,k=U;let $=await vt(b,{size:[K,j]});P=[];for(let C=0;C<H;++C)for(let te=0;te<U;++te){let ae=C*this.tile_size,L=te*this.tile_size;P.push($.slice(null,null,[ae,ae+this.tile_size],[L,L+this.tile_size]))}this.use_thumbnail&&U*H!==1&&P.push(await vt(b,{size:[M,S]}))}else P=[await vt(b,{size:[M,S]})];for(let U of P){let[,,H,j]=U.dims,K=sN(U,this.encoder_patch_size),{padded:$,mask:C}=nN(K,this.max_num_patches);n.push($),o.push(C),a.push([Math.floor(H/this.encoder_patch_size),Math.floor(j/this.encoder_patch_size)])}i.push(O),l.push(k),c.push([M,S])}}let p={pixel_values:ke(n,0),pixel_attention_mask:It(o,0),spatial_shapes:new R("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(r??this.return_row_col_info)&&(p.image_rows=i,p.image_cols=l,p.image_sizes=c),p}};var o_=class extends V{};var gn=class extends V{post_process_panoptic_segmentation(...e){return Mc(...e)}post_process_instance_segmentation(...e){return Sc(...e)}},a_=class extends gn{};var i_=class extends gn{};var Nc=class extends V{},l_=class extends Nc{};var Rc=class extends V{},c_=class extends Rc{};var $c=class extends V{},u_=class extends $c{};var Bc=class extends V{},p_=class extends Bc{};var Dc=class extends V{},f_=class extends Dc{};var d_=class extends hn{};var wn=class extends V{post_process_object_detection(...e){return Vr(...e)}},m_=class extends wn{};var __=class extends wn{};var Rt=336,oN=[2,3],{ceil:h_,floor:xn,sqrt:g_}=Math,w_=class extends V{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,r){let{num_img_tokens:s}=this.config;return xn((xn(r/Rt)*xn(e/Rt)+1)*s+1+(xn(r/Rt)+1)*g_(s))}get_resize_output_image_size(e,r){let s=this._num_crops,[n,o]=e.size,a=n/o,i=1;for(;i*Math.ceil(i/a)<=s;)i+=1;i-=1;let l=Math.floor(i*336),c=Math.floor(l/a);return[l,c]}pad_image(e,r,s,n={}){let[o,a]=r,i=Rt*h_(o/Rt),l=Rt*h_(a/Rt),c=[1,1,1].map((p,f)=>(p-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||g_(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:[Rt,Rt],mode:"bicubic"});if(r>0){let b=[],E=g_(r),A=xn(w/E),S=xn(_/E);for(let P=0;P<E;++P)for(let O=0;O<E;++O){let k,W,X,U;P===E-1?(W=_-S,U=_):(W=P*S,U=(P+1)*S),O===E-1?(k=w-A,X=w):(k=O*A,X=(O+1)*A);let K=await yc(m,[W,k],[U,X],oN);b.push(K)}let M=await vt(ke(b,0),{size:[Rt,Rt],mode:"bicubic"});i.push(ke([x,M],0))}else i.push(x)}let l=It(i,0),c=a.map(m=>m.map(_=>Rt*h_(_/Rt))),p=new R("int64",c.flat(),[s,2]),f=c.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:f}}};var x_=class extends V{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");let f=c*p,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var y_=class extends V{};var b_=class extends V{post_process_object_detection(...e){return Vr(...e)}};var Ro=class extends V{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=hf(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;a<e.length;++a){let[i,l]=r[a],[c,p]=s[a],f=[p/l,c/i];for(let m=0;m<e[a].length;++m)for(let _=0;_<e[a][m].length;++_)for(let w=0;w<e[a][m][_].length;++w)e[a][m][_][w]*=f[w%2]}return new R("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=hf(e);if(s.length===2)s=[1,...s],e=[e];else if(s.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(s.some((n,o)=>n!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new R("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;c<r.length;++c){let p=r[c],f=s[c],m=await vt(e[c],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,f[0]],[0,f[1]]),m=await vt(m,{mode:"bilinear",size:p}),o){let _=m.data,w=new Uint8Array(_.length);for(let x=0;x<_.length;++x)_[x]>n&&(w[x]=1);m=new R("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 Uc=class extends V{post_process_semantic_segmentation(...e){return Tc(...e)}},v_=class extends Uc{};var Fc=class extends V{post_process_semantic_segmentation(...e){return Tc(...e)}},k_=class extends Fc{};var E_=class extends V{};var A_=class extends V{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 Gc=class extends V{},T_=class extends Gc{};var M_=class extends V{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:It(s.map((a,i)=>ke([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 S_=class extends V{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let p=0;p<o;++p){let f=n[p],m=r[p],_=[];for(let w=0;w<m.length;++w){let x=m[w],b=[],E=[],A=[],S=x.at(-2)/l,M=x.at(-1)/i;for(let P=0;P<f.length;++P){let[O,k]=[0,0],W=0,X=-1/0,U=f[P];for(let j=0;j<U.length;++j){let K=U[j];for(let $=0;$<K.length;++$){let C=K[$];W+=C,X=Math.max(X,C),O+=($+.5)*C,k+=j*C}}if(s!=null&&X<s)continue;let H=[S*O/W,M*k/W];b.push(H),A.push(P),E.push(X)}_.push({bbox:x,scores:E,labels:A,keypoints:b})}c.push(_)}return c}};var jc=class extends V{post_process_object_detection(...e){return Vr(...e)}},O_=class extends jc{};var Ae=class{static async from_pretrained(e,r={}){let s=await ut(e,kr,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=yn[n?.replace(/Fast$/,"")];return o||(n!==void 0&&Z.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${qr}.`),o=V),new o(s)}};var I_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;constructor(e,r,s){super(e,r,s);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:o,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(o??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let 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("<s>","").replaceAll("</s>","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[p,f,...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 C_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
14
|
+
|
|
15
|
+
${n}${i}${a}
|
|
16
|
+
|
|
17
|
+
`}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 P_=class extends re{static image_processor_class=Ae;static feature_extractor_class=Xe;static tokenizer_class=se;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:c,image_token:p,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
|
|
14
18
|
|
|
15
19
|
${o}${m}${i}
|
|
16
20
|
|
|
17
21
|
`,this.image_token_id=l,this.boi_token=c,this.image_token=p;let _=p.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
18
22
|
|
|
19
|
-
${c}${_}${
|
|
23
|
+
${c}${_}${f}
|
|
20
24
|
|
|
21
|
-
`}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
|
|
25
|
+
`}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 Is=class extends re{static image_processor_class=Ae;static tokenizer_class=se;static image_token="<|image_pad|>";async _call(e,r=null,...s){Array.isArray(e)||(e=[e]);let n,o;if(r&&(n=await this.image_processor(r),o=n.image_grid_thw),o){let i=this.image_processor.config.merge_size**2,l=0,c=this.constructor.image_token,p=o.tolist();e=e.map(f=>{for(;f.includes(c);){let m=Number(p[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 L_=class extends Is{static image_token="<|image|>"};var z_=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;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 R("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 aN(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 N_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=a.dims.at(1),p=a.sigmoid(),f=p.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>Dm(x))),_=[];for(let w=0;w<l;++w){let x=o!==null?o[w]:null;x!==null&&(m[w]=m[w].map(M=>M.map((P,O)=>P*x[(O+1)%2])));let b=f[w],E=[],A=[],S=[];for(let M=0;M<c;++M){let P=b[M];if(P<=s)continue;let O=m[w][M],k=p[w][M];E.push(P),S.push(O);let W=aN(k.gt(n),r[w]);A.push(W)}_.push({scores:E,boxes:S,labels:this.batch_decode(A)})}return _}};function iN(t,e,r,s,n,o){let a="";for(let i=0;i<e;++i){for(let l=0;l<r;++l)a+=s+`<row_${i+1}_col_${l+1}>`+n.repeat(t);a+=`
|
|
22
26
|
`}return a+=`
|
|
23
|
-
${s}${o}`+n.repeat(t)+`${s}`,a}function
|
|
24
|
-
`}var
|
|
25
|
-
`}):(Z.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(c=>nN(c,n,o,En,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var nT="<|image|>",oN=/<\|image_\d+\|>/g,G_=class extends re{static image_processor_class=Ce;static tokenizer_class=oe;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((d,m)=>d.split(oN).join(nT.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id(nT);a.input_ids.map_(d=>d==p?-d:d)}else a=this.tokenizer(e);return{...a,...i}}};var j_=class extends re{static tokenizer_class=oe;static image_processor_class=Ce;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:c,image_end_token:p,patch_size:d,spatial_merge_size:m}=this.config,_=d*m,w=Math.floor(a/_),x=Math.floor(i/_);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let k=0;k<r.length;++k){let b=l.repeat(x),A=b+c,S=b+p,M=A.repeat(w-1)+S;r[k]=r[k].replace(l,M)}}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var q_=class extends re{static feature_extractor_class=Do;async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}};var Go=class extends Os{};var W_=class extends Go{};var jo=class extends re{static image_processor_class=Ce;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}};var Qc=class extends jo{},V_=class extends Qc{};var H_=class extends re{static tokenizer_class=oe;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var X_=class extends re{static tokenizer_class=oe;static feature_extractor_class=Xe;static uses_processor_config=!0;async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let a=r.length,{input_features:i}=await this.feature_extractor(r,{...s,max_length:a}),l=Math.round(a/this.config.encoder_ds_factor+1e-4),c=1+Math.ceil(l/this.config.stack_factor);n.audio_token_len=[c],n.audio_values=i;let p=this.config.audio_placeholder;if(!e.includes(p))throw new Error(`The input text does not contain the image token ${p}.`);e=e.replaceAll(p,p.repeat(c))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var Jc="[AUDIO]",aN="[BEGIN_AUDIO]",iN=375;function lN(t,e){let r=[];for(let s=0;s<t.length;s+=e)r.push(t.subarray(s,Math.min(s+e,t.length)));return r}var K_=class extends re{static tokenizer_class=oe;static feature_extractor_class=Xe;static uses_processor_config=!1;async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){if(!e.includes(Jc))throw new Error(`The input text does not contain the audio token ${Jc}.`);Array.isArray(r)||(r=[r]);let a=e.split(Jc),i=a.length-1;if(i!==r.length)throw new Error(`The number of audio inputs (${r.length}) does not match the number of audio tokens in the text (${i}).`);let l=this.feature_extractor.config.n_samples,c=r.map(w=>lN(w,l)),p=c.map(w=>w.length),d=c.flat(),m=(await Promise.all(d.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=m.length>1?ke(m,0):m[0];let _=a[0];for(let w=0;w<p.length;++w){_+=aN;for(let x=0;x<p[w];++x)_+=Jc.repeat(iN);_+=a[w+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var oT=32,Y_=6,Zc=8,cN=10,uN=32,Q_=class extends re{static tokenizer_class=oe;static feature_extractor_class=Xe;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(Y_+1)*Zc}get num_samples_first_audio_chunk(){let{hop_length:e,n_fft:r}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(r/2)}get num_samples_per_audio_chunk(){let{hop_length:e,n_fft:r}=this.feature_extractor.config;return Zc*e+r}get num_right_pad_tokens(){return Y_+1+cN}get audio_length_per_tok(){return Zc}get raw_audio_length_per_tok(){return Zc*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:r=!1,is_first_audio_chunk:s=!0}={}){if($e(e,"VoxtralRealtimeProcessor"),!r&&!s)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(s)if(r){let n=oT*this.raw_audio_length_per_tok,o=new Float32Array(n+e.length);o.set(e,n);let a=await this.feature_extractor(o,{center:!0}),l=1+(oT+Y_),c=new BigInt64Array(l).fill(BigInt(uN));return c[0]=1n,{input_ids:new R("int64",c,[1,l]),...a}}else{let n=this.num_right_pad_tokens*this.raw_audio_length_per_tok,o=new Float32Array(e.length+n);return o.set(e),await this.feature_extractor(o,{center:!0})}else return await this.feature_extractor(e,{center:!1})}};var J_=class extends re{static tokenizer_class=oe;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var Z_=class extends re{static tokenizer_class=oe;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var eh=class extends re{static tokenizer_class=oe;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var tu=class{static async from_pretrained(e,r={}){let s=await ut(e,kr,!0,r),{image_processor_type:n,feature_extractor_type:o,processor_class:a}=s;if(a&&eu[a])return eu[a].from_pretrained(e,r);if(!n&&!o)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let i={};if(n){let c=kn[n.replace(/Fast$/,"")];if(!c)throw new Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new c(s)}if(o){let c=kn[o];if(c)i.image_processor=new c(s);else{let p=Bo[o];if(!p)throw new Error(`Unknown feature_extractor_type: '${o}'.`);i.feature_extractor=new p(s)}}let l={};return new re(l,i,null)}};async function pN(t,e){return await ut(t,"config.json",!0,e)}function An(t){let e={},r={};switch(t.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=An(t.text_config);break;case"moondream1":r=An(t.phi_config);break;case"musicgen":r=An(t.decoder);break;case"multi_modality":r=An(t.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":e.num_heads="num_attention_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size",e.num_attention_heads="num_attention_heads",e.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="head_dim";break;case"openelm":e.num_heads="num_kv_heads",e.num_layers="num_transformer_layers",e.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":e.num_heads="num_heads",e.num_layers="num_layers",e.hidden_size="hidden_size";break;case"bloom":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="hidden_size";break;case"mpt":e.num_heads="n_heads",e.num_layers="n_layers",e.hidden_size="d_model";break;case"exaone":e.num_heads="num_key_value_heads",e.num_layers="num_layers",e.dim_kv="head_dim",e.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"glm_moe_dsa":case"mistral4":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="qk_head_dim",e.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":e.num_decoder_layers="num_decoder_layers",e.num_decoder_heads="num_heads",e.decoder_dim_kv="d_kv",e.num_encoder_layers="num_layers",e.num_encoder_heads="num_heads",e.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="d_model",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="d_model";break;case"speecht5":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="hidden_size",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="hidden_size";break;case"trocr":e.num_encoder_layers=e.num_decoder_layers="decoder_layers",e.num_encoder_heads=e.num_decoder_heads="decoder_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="d_model";break;case"musicgen_decoder":e.num_encoder_layers=e.num_decoder_layers="num_hidden_layers",e.num_encoder_heads=e.num_decoder_heads="num_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"moonshine":e.num_decoder_layers="decoder_num_hidden_layers",e.num_decoder_heads="decoder_num_key_value_heads",e.num_encoder_layers="encoder_num_hidden_layers",e.num_encoder_heads="encoder_num_key_value_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":let n=An(t.decoder),o="num_decoder_layers"in n,a=Ke(t,["model_type","is_encoder_decoder"]);return o?(a.num_decoder_layers=n.num_decoder_layers,a.num_decoder_heads=n.num_decoder_heads,a.decoder_hidden_size=n.decoder_hidden_size,a.num_encoder_layers=n.num_encoder_layers,a.num_encoder_heads=n.num_encoder_heads,a.encoder_hidden_size=n.encoder_hidden_size):(a.num_layers=n.num_layers,a.num_heads=n.num_heads,a.hidden_size=n.hidden_size),a}let s={...r,...Ke(t,["model_type","multi_query","is_encoder_decoder"])};for(let n in e)s[n]=t[e[n]];return s}function Is(t,e){t instanceof Tn||(t=new Tn(t));let r=e?.batch_size??1;if(["lfm2","lfm2_moe"].includes(t.model_type)){let s=e?.prefix??"past_key_values",n=s==="present"?"present":"past",o={},{layer_types:a,num_attention_heads:i,num_key_value_heads:l,hidden_size:c,conv_L_cache:p}=t,d=c/i;for(let m=0;m<a.length;++m)if(a[m]==="full_attention")for(let _ of["key","value"])o[`${s}.${m}.${_}`]=[r,l,0,d];else if(a[m]==="conv")o[`${n}_conv.${m}`]=[r,c,p];else throw new Error(`Unsupported layer type: ${a[m]}`);return o}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(t.model_type)){let s=e?.prefix??"past_key_values",n=s==="present"?"present":"past",o=t,a=o.layer_types??o.layers_block_type,i=o.num_hidden_layers??a?.length,l=o.num_key_value_heads,c=o.head_dim??o.hidden_size/o.num_attention_heads,p=o.mamba_n_heads??o.mamba_num_heads,d=o.mamba_d_head??o.mamba_head_dim,m=o.mamba_d_state??o.ssm_state_size,_=o.mamba_n_groups??o.n_groups,w=o.mamba_d_conv??o.conv_kernel,k=(o.mamba_d_ssm??(o.mamba_expand?o.mamba_expand*o.hidden_size:p*d))+2*_*m,b={};for(let A=0;A<i;++A)if((!a||a[A]==="mamba")&&(b[`${n}_conv.${A}`]=[r,k,w],b[`${n}_ssm.${A}`]=[r,p,d,m]),!a||a[A]==="attention")for(let S of["key","value"])b[`${s}.${A}.${S}`]=[r,l,0,c];return b}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(t.model_type)){let s=e?.prefix??"past_key_values",n=s==="present"?"present":"past",o={},{head_dim:a,layer_types:i,num_attention_heads:l,num_key_value_heads:c,hidden_size:p,linear_num_value_heads:d,linear_num_key_heads:m,linear_key_head_dim:_,linear_value_head_dim:w,linear_conv_kernel_dim:x}=t,k=_*m,b=w*d,A=a??p/l;for(let S=0;S<i.length;++S)if(i[S]==="full_attention")for(let M of["key","value"])o[`${s}.${S}.${M}`]=[r,c,0,A];else if(i[S]==="linear_attention"){if(t.model_type==="olmo_hybrid")o[`${n}_conv.${S}.key`]=[r,k,x],o[`${n}_conv.${S}.value`]=[r,b,x],o[`${n}_conv.${S}.query`]=[r,k,x];else{let M=k*2+b;o[`${n}_conv.${S}`]=[r,M,x]}o[`${n}_recurrent.${S}`]=[r,d,_,w]}else throw new Error(`Unsupported layer type: ${i[S]}`);return o}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(t.model_type)){let s;return t.model_type==="voxtral_realtime"&&e?.session_name==="audio_encoder"?s=t.audio_config:s=t.text_config,Is(s,e)}return dN(t,e)}function dN(t,{prefix:e="past_key_values",batch_size:r=1}={}){let s={},n=t.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){let o=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,a=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,i=[r,n.num_encoder_heads,0,o],l=[r,n.num_decoder_heads,0,a];for(let c=0;c<n.num_decoder_layers;++c)s[`${e}.${c}.encoder.key`]=i,s[`${e}.${c}.encoder.value`]=i,s[`${e}.${c}.decoder.key`]=l,s[`${e}.${c}.decoder.value`]=l}else{let o=n.num_heads,a=n.num_layers,i=n.dim_kv??n.hidden_size/(n.num_attention_heads??o);if(n.model_type==="falcon"){let l=[r*o,0,i];for(let c=0;c<a;++c)s[`${e}.${c}.key`]=l,s[`${e}.${c}.value`]=l}else if(n.multi_query){let l=[r*o,0,2*i];for(let c=0;c<a;++c)s[`${e}.${c}.key_value`]=l}else if(n.model_type==="bloom"){let l=[r*o,i,0],c=[r*o,0,i];for(let p=0;p<a;++p)s[`${e}.${p}.key`]=l,s[`${e}.${p}.value`]=c}else if(n.model_type==="openelm")for(let l=0;l<a;++l){let c=[r,o[l],0,i];s[`${e}.${l}.key`]=c,s[`${e}.${l}.value`]=c}else{let l=[r,o,0,i];for(let c=0;c<a;++c)s[`${e}.${c}.key`]=l,s[`${e}.${c}.value`]=l}}return s}var Tn=class t{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=An(this)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){s&&!(s instanceof t)&&(s=new t(s));let i=s??await pN(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(i)}},jt=class{static async from_pretrained(...e){return Tn.from_pretrained(...e)}};function th(t,e,r){return t?typeof t=="object"&&t!==null?t.hasOwnProperty(e)?+t[e]:t.hasOwnProperty(r)?+t[r]:0:+t:0}function rh(t,e){let r=[];for(let s=0;s<e;++s)r.push(`${t}_data${s===0?"":"_"+s}`);return r}async function aT(t,e,r,s){let n=`${e}${s}.onnx`,o=`${r.subfolder??""}/${n}`;return await go(t,o,!0,r,ie.IS_NODE_ENV)}async function iT(t,e,r,s,n,o={}){let a=`${e}${r}.onnx`,i=ie.IS_NODE_ENV,l=[],c=th(n,a,e);if(c>0){if(c>rc)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${rc}).`);let p=rh(a,c);for(let d of p){let m=`${s.subfolder??""}/${d}`;l.push(new Promise(async(_,w)=>{let x=await go(t,m,!0,s,i);_(x instanceof Uint8Array?{path:d,data:x}:d)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async p=>{if(typeof p.data=="string"){let d=await go(t,p.data,!0,s);return{...p,data:d}}return p}));return Promise.all(l)}async function fN(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=kc(r.device??o.device,e,{warn:M=>Z.info(M)}),i=C2(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=Ec(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:M=>Z.info(M)});if(Oo.hasOwnProperty(c)){if(a==="webgpu"&&!ie.IS_NODE_ENV&&c===yt.fp16&&!await N2())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 p=o.kv_cache_dtype,d=p?typeof p=="string"?p:p[c]??"float32":void 0;if(d&&!["float32","float16"].includes(d))throw new Error(`Invalid kv_cache_dtype: ${d}. Should be one of: float32, float16`);let m=Oo[c],_={...r.session_options};_.executionProviders??=i;let w=o.free_dimension_overrides;w?_.freeDimensionOverrides??=w:a.startsWith("webnn")&&!_.freeDimensionOverrides&&Z.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=aT(t,e,r,m),k=r.use_external_data_format??o.use_external_data_format,b=await iT(t,e,m,r,k,_);if(b.length>0&&!ie.IS_NODE_ENV&&(_.externalData=b),s&&a==="webgpu"&&p!==!1){let M=Is(r.config,{prefix:"present",session_name:n});if(Object.keys(M).length>0&&!So()){let P={};for(let O in M)P[O]="gpu-buffer";_.preferredOutputLocation=P}}return{buffer_or_path:await x,session_options:_,session_config:{dtype:c,kv_cache_dtype:d,device:a}}}async function lT(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 fN(t,e[n],r,o,n),c=await yc(a,i,l);return[n,c]})))}function cT(t){for(let e in t)vc(t[e])?t[e]=new R(t[e]):typeof t[e]=="object"&&cT(t[e]);return t}async function de(t,e){let r=mN(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 bc(t,s);return cT(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 Z.error(`An error occurred during model execution: "${s}".`),Z.error("Inputs given to model:",n),s}}function mN(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof R)){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));Z.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Re=class{};var G=class extends Re{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},he=class extends Re{constructor({logits:e}){super(),this.logits=e}},ge=class extends Re{constructor({logits:e}){super(),this.logits=e}},Ae=class extends Re{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},kt=class extends Re{constructor({logits:e}){super(),this.logits=e}};var ru=class extends Re{constructor({alphas:e}){super(),this.alphas=e}};var qt=class extends et{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},qo=class extends et{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Cs=class extends et{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()}},su=class extends qt{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===1){let n=r[s].data;n.fill(-1/0),n[this.bos_token_id]=0}return r}},nu=class extends qt{constructor(e,r){super(),this.max_length=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){let n=r[s].data;n.fill(-1/0);for(let o of this.eos_token_id)n[o]=0}return r}},Mn=class extends qt{constructor(e,r){super(),this.begin_suppress_tokens=e,this.begin_index=r}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){let n=r[s].data;for(let o of this.begin_suppress_tokens)n[o]=-1/0}return r}},ou=class extends qt{constructor(e,r){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=r.length,r.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data;if(n[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index-1){n.fill(-1/0),n[this.timestamp_begin]=0;continue}let o=e[s].slice(this.begin_index),a=o.length>=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 d=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(d+1).fill(-1/0)}let l=Td(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((d,m)=>d+m)),p=Oe(l.subarray(0,this.timestamp_begin))[0];c>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},au=class extends qt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o<r+1-this.no_repeat_ngram_size;++o){let a=[];for(let i=0;i<this.no_repeat_ngram_size;++i)a.push(e[o+i]);s.push(a.map(Number))}let n=new Map;for(let o of s){let a=o.slice(0,o.length-1),i=JSON.stringify(a),l=n.get(i)??[];l.push(o[o.length-1]),n.set(i,l)}return n}getGeneratedNgrams(e,r){let s=r.slice(r.length+1-this.no_repeat_ngram_size,r.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){let r=[];if(e.length+1<this.no_repeat_ngram_size)return r;{let s=this.getNgrams(e);return this.getGeneratedNgrams(s,e)}}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data,o=this.calcBannedNgramTokens(e[s]);for(let a of o)n[a]=-1/0}return r}},iu=class extends qt{constructor(e){super(),this.penalty=e}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data;for(let o of new Set(e[s])){let a=Number(o);n[a]<0?n[a]*=this.penalty:n[a]/=this.penalty}}return r}},lu=class extends qt{constructor(e,r){super(),this.min_length=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){let n=r[s].data;for(let o of this.eos_token_id)n[o]=-1/0}return r}},cu=class extends qt{constructor(e,r,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=r,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){let o=r[s].data;for(let a of this.eos_token_id)o[a]=-1/0}return r}},uu=class extends qt{constructor(e,r){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data,o=e[s];for(let a of this.bad_words_ids){if(o.length<a.length-1)continue;let i=!0;for(let l=1;l<=a.length-1;++l)if(a.at(-l-1)!=o.at(-l)){i=!1;break}i&&(n[a.at(-1)]=-1/0)}}return r}},pu=class extends qt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,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;a<o.data.length;++a)o.data[a]+=(n.data[a]-o.data[a])*this.guidance_scale;return o}},du=class extends qo{constructor(e){if(super(),typeof e!="number"||e<=0){let r=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;e===0&&(r+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,r){let s=r.data;for(let n=0;n<s.length;++n)s[n]/=this.temperature;return r}},uT=class extends qo{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=s}},pT=class extends 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 Sn=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,Ke(e,Object.getOwnPropertyNames(this)))}};var Vr=class extends et{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},On=class t extends et{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof Vr&&(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;a<s.length;++a)s[a]||=o[a]}return s}[Symbol.iterator](){return this.criteria.values()}},fu=class extends Vr{constructor(e,r=null){super(),this.max_length=e,this.max_position_embeddings=r}_call(e){return e.map(r=>r.length>=this.max_length)}},mu=class extends Vr{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)})}},dT=class extends Vr{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var Ps=class extends et{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 ME(e)}static getSampler(e){if(e.do_sample)return new nh(e);if(e.num_beams>1)return new oh(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 sh(e)}},sh=class extends Ps{async sample(e){let r=Oe(e.data)[1];return[[BigInt(r),0]]}},nh=class extends Ps{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await er(e,r),o=Ne(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},oh=class extends Ps{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await er(e,r),o=Ne(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var ah=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 R))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=ah;var Ls=null;function mT(t){Ls=t}function ih(t){if(t instanceof R)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 R("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new R("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function lh(t){return new R("bool",[t],[1])}var K={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,MultimodalLanguageModelOnly:16,VoxtralRealtime:17},In={[K.DecoderOnly]:{can_generate:!0,forward:It,prepare_inputs:Cn,sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[K.DecoderOnlyWithoutHead]:{can_generate:!1,forward:It,prepare_inputs:Cn,sessions:(t,e)=>({model:e.model_file_name??"model"})},[K.Seq2Seq]:{can_generate:!0,forward:_u,prepare_inputs:Ho,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.Vision2Seq]:{can_generate:!0,forward:_u,prepare_inputs:Ho,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.Musicgen]:{can_generate:!0,forward:_u,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"}},[K.EncoderDecoder]:{can_generate:!1,forward:_u,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[K.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[K.ImageTextToText]:{can_generate:!0,forward:fT,prepare_inputs:Vo,sessions:t=>{let e={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};return t.is_encoder_decoder&&(e.model="encoder_model"),e},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.AudioTextToText]:{can_generate:!0,forward:hN,prepare_inputs:Vo,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Vo,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"}),optional_configs:{generation_config:"generation_config.json"}},[K.Phi3V]:{can_generate:!0,prepare_inputs:Vo,sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[K.MultiModality]:{can_generate:!0,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"}},[K.AutoEncoder]:{can_generate:!1,forward:_N,sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[K.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[K.Chatterbox]:{can_generate:!0,forward:Wt,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"}},[K.MultimodalLanguageModelOnly]:{can_generate:!0,forward:fT,prepare_inputs:Vo,sessions:()=>({embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[K.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Cn,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{can_generate:!1,forward:Wt,sessions:(t,e)=>({model:e.model_file_name??"model"})}};function _T(t,e,r={}){let s=In[t]??In.default;return{sessions:s.sessions(e,r),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}var tr=new Map,hu=new Map,zs=new Map,y=class extends et{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=zs.get(this.constructor),o=tr.get(n),a=In[o]??In.default;this.can_generate=a.can_generate,this._forward=a.forward,this._prepare_inputs_for_generation=a.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:p=null,use_external_data_format:d=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:p,use_external_data_format:d,session_options:m},w=zs.get(this),x=tr.get(w);s=_.config=await jt.from_pretrained(e,_);let k=In[x]??In.default;if(x===void 0){let M=w??s?.model_type;M!=="custom"&&Z.warn(`Model type for '${M}' not found, assuming encoder-only architecture. Please report this at ${jr}.`)}let b=k.sessions(s,_),A=[lT(e,b,_,k.cache_sessions)];k.optional_configs&&A.push(wN(e,k.optional_configs,_));let S=await Promise.all(A);return new this(s,...S)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new Cs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new iu(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new au(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new uu(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new lu(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 cu(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new su(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new nu(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new Mn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new pu(e.guidance_scale)),e.temperature===0&&e.do_sample&&(Z.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 du(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=Sn){let n={...this.config};for(let a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);let o=new s(n);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),r&&Object.assign(o,Ke(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new On;return e.max_length!==null&&s.push(new fu(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new mu(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[Ls.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Ls.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Ls.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Ls.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=zs.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 R("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s:s.attention_mask=ke([s.attention_mask,tt([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=Ke(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...c}=r,p=await this._prepare_inputs_embeds(r);r={...c,...Ke(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Wt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=ke([o,Co(o,0)],0),"attention_mask"in r&&(r.attention_mask=ke([r.attention_mask,Sf(r.attention_mask)],0));else if(r.decoder_input_ids){let a=ih(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=ke(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 R)){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=ih(i)}return s.decoder_attention_mask=Sc(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),p=this.config.is_encoder_decoder;p&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let d;p?{input_ids:d,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}):d=l[c];let m=d.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),k=Ps.getSampler(r),b=new Array(x).fill(0),A=d.tolist();o&&o.put(A);let S,M={},P={};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 j=this.getAttentions(S);for(let Y in j)Y in M||(M[Y]=[]),M[Y].push(j[Y])}else this._return_dict_in_generate_keys&&Object.assign(P,Ke(S,this._return_dict_in_generate_keys));let W=S.logits.slice(null,-1,null).to("float32"),X=_(A,W),U=[];for(let j=0;j<X.dims.at(0);++j){let Y=X[j],$=await k(Y);for(let[C,te]of $){let ae=BigInt(C);b[j]+=te,A[j].push(ae),U.push([ae]);break}}if(o&&o.put(U),w(A).every(j=>j))break;l=this._update_model_kwargs_for_generation({generated_input_ids:U,outputs:S,model_inputs:l,is_encoder_decoder:p})}o&&o.end();let O=this.getPastKeyValues(S,l.past_key_values,!0),E=new R("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:E,past_key_values:O,...M,...P};for(let W of Object.values(S))W.location==="gpu-buffer"&&W.dispose();return E}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"?vr.float16:vr.float32,i=Is(this.config,{batch_size:n});for(let l in i){let c=i[l].reduce((p,d)=>p*d,1);e[l]=new R(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 de(n,Ke(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 _u(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,...o}=e;if(!r){let a=Ke(e,t.sessions.model.inputNames);r=(await Wt(t,a)).last_hidden_state}return o.input_ids=n,o.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=e.attention_mask),await It(t,o,!0)}async function Wt(t,e){let r=t.sessions.model,s=Ke(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=Sf(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=tt([n[0],n[2],n[3]])}return await de(r,s)}async function _N(t,e){let r=await t.encode(e);return await t.decode(r)}async function It(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=lh(!!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=gN(o,n,i)}s.inputNames.includes("num_logits_to_keep")&&!o.num_logits_to_keep&&(o.num_logits_to_keep=new R("int64",[0n],[])),t.addPastKeyValues(o,n);let a=Ke(o,s.inputNames);return await de(s,a)}async function hT(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:d=null,...m}){if(!l){l=await t.encode_text({input_ids:o,...m});let w=Ke(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],k=c.get_seq_length();a=ke([tt([o.dims[0],k]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(t.config.model_type)){let{image_grid_thw:w,video_grid_thw:x}=m;[i]=t.get_rope_index(o,w,x,a)}return await It(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:p,logits_processor:d},!0)}async function hN(t,e){return await hT(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 fT(t,e){return await hT(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 ch(t,e=0){let[r,s]=t.dims,n=t.data,o=new BigInt64Array(n.length);for(let a=0;a<r;++a){let i=a*s,l=BigInt(e);for(let c=0;c<s;++c){let p=i+c;n[p]===0n?o[p]=BigInt(1):(o[p]=l,l+=n[p])}}return{data:o,dims:t.dims}}function gN(t,e=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:o}=t,{data:a,dims:i}=ch(o,r),l=new R("int64",a,i);if(e){let c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function Cn(t,e,r,s){let n=r.past_key_values?r.past_key_values.get_seq_length():0;if((t.sessions.decoder_model_merged??t.sessions.model)?.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new R("int64",[1n],[])),!r.attention_mask){let a;for(let i of["input_ids","inputs_embeds","position_ids"])if(r[i]){a=r[i].dims;break}if(!a)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=tt([a[0],n+a[1]])}if(r.past_key_values){let{input_ids:a,attention_mask:i}=r;i&&i.dims[1]>a.dims[1]||n<a.dims[1]&&(r.input_ids=a.slice(null,[n,null]))}return r}function Ho(t,e,r,s){return r.past_key_values&&(e=e.map(n=>[n.at(-1)])),{...r,decoder_input_ids:ih(e)}}function Vo(t,...e){return t.config.is_encoder_decoder?Ho(t,...e):Cn(t,...e)}function gT({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((p,d,m)=>(d==t&&p.push(m),p),[])),a=o.reduce((c,p)=>c+p.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let c=0;c<o.length;++c){let p=o[c],d=e[c];for(let m=0;m<p.length;++m)d[p[m]].data.set(r[l++].data)}return{inputs_embeds:e,attention_mask:n}}function Pn({image_token_id:t,inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return gT({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}function gu({audio_token_id:t,inputs_embeds:e,audio_features:r,input_ids:s,attention_mask:n}){return gT({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}async function wN(t,e,r){return Object.fromEntries(await Promise.all(Object.keys(e).map(async s=>{let n=await ut(t,e[s],!1,r);return[s,n]})))}var il={};ds(il,{ASTForAudioClassification:()=>bh,ASTModel:()=>yh,ASTPreTrainedModel:()=>Qo,AfmoeForCausalLM:()=>gh,AfmoeModel:()=>hh,AfmoePreTrainedModel:()=>Ko,AlbertForMaskedLM:()=>fh,AlbertForQuestionAnswering:()=>dh,AlbertForSequenceClassification:()=>ph,AlbertModel:()=>uh,AlbertPreTrainedModel:()=>Ns,ApertusForCausalLM:()=>_h,ApertusModel:()=>mh,ApertusPreTrainedModel:()=>Xo,ArceeForCausalLM:()=>xh,ArceeModel:()=>wh,ArceePreTrainedModel:()=>Yo,BartForConditionalGeneration:()=>kh,BartForSequenceClassification:()=>Eh,BartModel:()=>vh,BartPretrainedModel:()=>Ln,BeitForImageClassification:()=>Th,BeitModel:()=>Ah,BeitPreTrainedModel:()=>Jo,BertForMaskedLM:()=>Sh,BertForQuestionAnswering:()=>Ch,BertForSequenceClassification:()=>Oh,BertForTokenClassification:()=>Ih,BertModel:()=>Mh,BertPreTrainedModel:()=>Hr,BlenderbotForConditionalGeneration:()=>Lh,BlenderbotModel:()=>Ph,BlenderbotPreTrainedModel:()=>Zo,BlenderbotSmallForConditionalGeneration:()=>Nh,BlenderbotSmallModel:()=>zh,BlenderbotSmallPreTrainedModel:()=>ea,BloomForCausalLM:()=>$h,BloomModel:()=>Rh,BloomPreTrainedModel:()=>ta,CHMv2ForDepthEstimation:()=>qh,CHMv2PreTrainedModel:()=>yu,CLIPModel:()=>Vh,CLIPPreTrainedModel:()=>dr,CLIPSegForImageSegmentation:()=>Qh,CLIPSegModel:()=>Yh,CLIPSegPreTrainedModel:()=>aa,CLIPTextModel:()=>Hh,CLIPTextModelWithProjection:()=>oa,CLIPVisionModel:()=>Xh,CLIPVisionModelWithProjection:()=>Kh,CamembertForMaskedLM:()=>Bh,CamembertForQuestionAnswering:()=>Gh,CamembertForSequenceClassification:()=>Uh,CamembertForTokenClassification:()=>Fh,CamembertModel:()=>Dh,CamembertPreTrainedModel:()=>Xr,ChatterboxModel:()=>ra,ChatterboxPreTrainedModel:()=>wu,ChineseCLIPModel:()=>jh,ChineseCLIPPreTrainedModel:()=>xu,ClapAudioModelWithProjection:()=>na,ClapModel:()=>Wh,ClapPreTrainedModel:()=>zn,ClapTextModelWithProjection:()=>sa,CodeGenForCausalLM:()=>Zh,CodeGenModel:()=>Jh,CodeGenPreTrainedModel:()=>ia,Cohere2ForCausalLM:()=>sg,Cohere2Model:()=>rg,Cohere2PreTrainedModel:()=>ca,CohereForCausalLM:()=>tg,CohereModel:()=>eg,CoherePreTrainedModel:()=>la,ConvBertForMaskedLM:()=>og,ConvBertForQuestionAnswering:()=>lg,ConvBertForSequenceClassification:()=>ag,ConvBertForTokenClassification:()=>ig,ConvBertModel:()=>ng,ConvBertPreTrainedModel:()=>Kr,ConvNextForImageClassification:()=>ug,ConvNextModel:()=>cg,ConvNextPreTrainedModel:()=>ua,ConvNextV2ForImageClassification:()=>dg,ConvNextV2Model:()=>pg,ConvNextV2PreTrainedModel:()=>pa,DFineForObjectDetection:()=>hg,DFineModel:()=>_g,DFinePreTrainedModel:()=>fa,DINOv3ConvNextModel:()=>Gg,DINOv3ConvNextPreTrainedModel:()=>Mu,DINOv3ViTModel:()=>jg,DINOv3ViTPreTrainedModel:()=>Su,DPTForDepthEstimation:()=>Qg,DPTModel:()=>Yg,DPTPreTrainedModel:()=>ya,DacDecoderModel:()=>_a,DacDecoderOutput:()=>vu,DacEncoderModel:()=>ma,DacEncoderOutput:()=>bu,DacModel:()=>gg,DacPreTrainedModel:()=>Nn,DebertaForMaskedLM:()=>xg,DebertaForQuestionAnswering:()=>vg,DebertaForSequenceClassification:()=>yg,DebertaForTokenClassification:()=>bg,DebertaModel:()=>wg,DebertaPreTrainedModel:()=>Yr,DebertaV2ForMaskedLM:()=>Tg,DebertaV2ForQuestionAnswering:()=>Og,DebertaV2ForSequenceClassification:()=>Mg,DebertaV2ForTokenClassification:()=>Sg,DebertaV2Model:()=>Ag,DebertaV2PreTrainedModel:()=>Qr,DecisionTransformerModel:()=>Ig,DecisionTransformerPreTrainedModel:()=>ku,DeepseekV3ForCausalLM:()=>Eg,DeepseekV3Model:()=>kg,DeepseekV3PreTrainedModel:()=>ha,DeiTForImageClassification:()=>Pg,DeiTModel:()=>Cg,DeiTPreTrainedModel:()=>ga,DepthAnythingForDepthEstimation:()=>Lg,DepthAnythingPreTrainedModel:()=>Eu,DepthProForDepthEstimation:()=>zg,DepthProPreTrainedModel:()=>Au,DetrForObjectDetection:()=>Rg,DetrForSegmentation:()=>$g,DetrModel:()=>Ng,DetrObjectDetectionOutput:()=>$n,DetrPreTrainedModel:()=>Rn,DetrSegmentationOutput:()=>Tu,Dinov2ForImageClassification:()=>Bg,Dinov2Model:()=>Dg,Dinov2PreTrainedModel:()=>wa,Dinov2WithRegistersForImageClassification:()=>Fg,Dinov2WithRegistersModel:()=>Ug,Dinov2WithRegistersPreTrainedModel:()=>xa,DistilBertForMaskedLM:()=>Xg,DistilBertForQuestionAnswering:()=>Hg,DistilBertForSequenceClassification:()=>Wg,DistilBertForTokenClassification:()=>Vg,DistilBertModel:()=>qg,DistilBertPreTrainedModel:()=>Jr,DonutSwinModel:()=>Kg,DonutSwinPreTrainedModel:()=>Ou,EdgeTamModel:()=>sb,EfficientNetForImageClassification:()=>Zg,EfficientNetModel:()=>Jg,EfficientNetPreTrainedModel:()=>ba,ElectraForMaskedLM:()=>tw,ElectraForQuestionAnswering:()=>nw,ElectraForSequenceClassification:()=>rw,ElectraForTokenClassification:()=>sw,ElectraModel:()=>ew,ElectraPreTrainedModel:()=>Zr,Ernie4_5ForCausalLM:()=>aw,Ernie4_5Model:()=>ow,Ernie4_5PretrainedModel:()=>va,EsmForMaskedLM:()=>lw,EsmForSequenceClassification:()=>cw,EsmForTokenClassification:()=>uw,EsmModel:()=>iw,EsmPreTrainedModel:()=>Rs,EuroBertForMaskedLM:()=>dw,EuroBertForSequenceClassification:()=>fw,EuroBertForTokenClassification:()=>mw,EuroBertModel:()=>pw,EuroBertPreTrainedModel:()=>$s,ExaoneForCausalLM:()=>hw,ExaoneModel:()=>_w,ExaonePreTrainedModel:()=>ka,FalconForCausalLM:()=>ww,FalconH1ForCausalLM:()=>yw,FalconH1Model:()=>xw,FalconH1PreTrainedModel:()=>Aa,FalconModel:()=>gw,FalconPreTrainedModel:()=>Ea,FastViTForImageClassification:()=>vw,FastViTModel:()=>bw,FastViTPreTrainedModel:()=>Ta,Florence2ForConditionalGeneration:()=>kw,Florence2PreTrainedModel:()=>Iu,GLPNForDepthEstimation:()=>Rw,GLPNModel:()=>Nw,GLPNPreTrainedModel:()=>La,GPT2LMHeadModel:()=>Vw,GPT2Model:()=>Ww,GPT2PreTrainedModel:()=>Da,GPTBigCodeForCausalLM:()=>Dw,GPTBigCodeModel:()=>$w,GPTBigCodePreTrainedModel:()=>za,GPTJForCausalLM:()=>Xw,GPTJModel:()=>Hw,GPTJPreTrainedModel:()=>Ba,GPTNeoForCausalLM:()=>Uw,GPTNeoModel:()=>Bw,GPTNeoPreTrainedModel:()=>Na,GPTNeoXForCausalLM:()=>Gw,GPTNeoXModel:()=>Fw,GPTNeoXPreTrainedModel:()=>Ra,Gemma2ForCausalLM:()=>Mw,Gemma2Model:()=>Tw,Gemma2PreTrainedModel:()=>Sa,Gemma3ForCausalLM:()=>Ow,Gemma3Model:()=>Sw,Gemma3PreTrainedModel:()=>Oa,Gemma3nForCausalLM:()=>Ia,Gemma3nForConditionalGeneration:()=>Dn,Gemma3nPreTrainedModel:()=>Cu,GemmaForCausalLM:()=>Aw,GemmaModel:()=>Ew,GemmaPreTrainedModel:()=>Ma,GlmForCausalLM:()=>Cw,GlmModel:()=>Iw,GlmMoeDsaForCausalLM:()=>Lw,GlmMoeDsaModel:()=>Pw,GlmMoeDsaPreTrainedModel:()=>Pa,GlmOcrForConditionalGeneration:()=>zw,GlmPreTrainedModel:()=>Ca,GptOssForCausalLM:()=>qw,GptOssModel:()=>jw,GptOssPreTrainedModel:()=>$a,GraniteForCausalLM:()=>Yw,GraniteModel:()=>Kw,GraniteMoeHybridForCausalLM:()=>Jw,GraniteMoeHybridModel:()=>Qw,GraniteMoeHybridPreTrainedModel:()=>Fa,GranitePreTrainedModel:()=>Ua,GraniteSpeechForConditionalGeneration:()=>Zw,GroundingDinoForObjectDetection:()=>ex,GroundingDinoPreTrainedModel:()=>zu,GroupViTModel:()=>tx,GroupViTPreTrainedModel:()=>Nu,HeliumForCausalLM:()=>sx,HeliumModel:()=>rx,HeliumPreTrainedModel:()=>Ga,HieraForImageClassification:()=>ox,HieraModel:()=>nx,HieraPreTrainedModel:()=>ja,HubertForCTC:()=>dx,HubertForSequenceClassification:()=>fx,HubertModel:()=>px,HubertPreTrainedModel:()=>ux,HunYuanDenseV1ForCausalLM:()=>_x,HunYuanDenseV1Model:()=>mx,HunYuanDenseV1PreTrainedModel:()=>qa,IJepaForImageClassification:()=>yx,IJepaModel:()=>xx,IJepaPreTrainedModel:()=>Wa,Idefics3ForConditionalGeneration:()=>wx,JAISLMHeadModel:()=>vx,JAISModel:()=>bx,JAISPreTrainedModel:()=>Va,JinaCLIPModel:()=>kx,JinaCLIPPreTrainedModel:()=>Un,JinaCLIPTextModel:()=>Ha,JinaCLIPVisionModel:()=>Ex,Lfm2ForCausalLM:()=>Tx,Lfm2Model:()=>Ax,Lfm2MoeForCausalLM:()=>Ox,Lfm2MoeModel:()=>Sx,Lfm2MoePreTrainedModel:()=>Ka,Lfm2PreTrainedModel:()=>Xa,Lfm2VlForConditionalGeneration:()=>Ix,LightOnOcrForConditionalGeneration:()=>Mx,LiteWhisperForConditionalGeneration:()=>w1,Llama4ForCausalLM:()=>Lx,Llama4PreTrainedModel:()=>$u,LlamaForCausalLM:()=>Px,LlamaModel:()=>Cx,LlamaPreTrainedModel:()=>Ya,LlavaForConditionalGeneration:()=>Ct,LlavaOnevisionForConditionalGeneration:()=>Ct,LlavaPreTrainedModel:()=>Ru,LlavaQwen2ForCausalLM:()=>gx,LongT5ForConditionalGeneration:()=>Nx,LongT5Model:()=>zx,LongT5PreTrainedModel:()=>Qa,M2M100ForConditionalGeneration:()=>$x,M2M100Model:()=>Rx,M2M100PreTrainedModel:()=>Ja,MBartForCausalLM:()=>Wx,MBartForConditionalGeneration:()=>jx,MBartForSequenceClassification:()=>qx,MBartModel:()=>Gx,MBartPreTrainedModel:()=>Gs,MPNetForMaskedLM:()=>Cy,MPNetForQuestionAnswering:()=>zy,MPNetForSequenceClassification:()=>Py,MPNetForTokenClassification:()=>Ly,MPNetModel:()=>Iy,MPNetPreTrainedModel:()=>es,MT5ForConditionalGeneration:()=>Dy,MT5Model:()=>$y,MT5PreTrainedModel:()=>pi,MarianMTModel:()=>Bx,MarianModel:()=>Dx,MarianPreTrainedModel:()=>Za,MaskFormerForInstanceSegmentation:()=>Fx,MaskFormerModel:()=>Ux,MaskFormerPreTrainedModel:()=>ei,Metric3DForDepthEstimation:()=>Vx,Metric3DPreTrainedModel:()=>Du,Metric3Dv2ForDepthEstimation:()=>Hx,Metric3Dv2PreTrainedModel:()=>Bu,MgpstrForSceneTextRecognition:()=>Xx,MgpstrModelOutput:()=>Uu,MgpstrPreTrainedModel:()=>Fu,MimiDecoderModel:()=>ri,MimiDecoderOutput:()=>ju,MimiEncoderModel:()=>ti,MimiEncoderOutput:()=>Gu,MimiModel:()=>Kx,MimiPreTrainedModel:()=>Fn,Mistral4ForCausalLM:()=>Zx,Mistral4Model:()=>Jx,Mistral4PreTrainedModel:()=>ni,MistralForCausalLM:()=>Qx,MistralModel:()=>Yx,MistralPreTrainedModel:()=>si,MobileBertForMaskedLM:()=>ty,MobileBertForQuestionAnswering:()=>sy,MobileBertForSequenceClassification:()=>ry,MobileBertModel:()=>ey,MobileBertPreTrainedModel:()=>js,MobileLLMForCausalLM:()=>oy,MobileLLMModel:()=>ny,MobileLLMPreTrainedModel:()=>oi,MobileNetV1ForImageClassification:()=>iy,MobileNetV1ForSemanticSegmentation:()=>ly,MobileNetV1Model:()=>ay,MobileNetV1PreTrainedModel:()=>Gn,MobileNetV2ForImageClassification:()=>uy,MobileNetV2ForSemanticSegmentation:()=>py,MobileNetV2Model:()=>cy,MobileNetV2PreTrainedModel:()=>jn,MobileNetV3ForImageClassification:()=>fy,MobileNetV3ForSemanticSegmentation:()=>my,MobileNetV3Model:()=>dy,MobileNetV3PreTrainedModel:()=>qn,MobileNetV4ForImageClassification:()=>hy,MobileNetV4ForSemanticSegmentation:()=>gy,MobileNetV4Model:()=>_y,MobileNetV4PreTrainedModel:()=>Wn,MobileViTForImageClassification:()=>xy,MobileViTModel:()=>wy,MobileViTPreTrainedModel:()=>ai,MobileViTV2ForImageClassification:()=>by,MobileViTV2Model:()=>yy,MobileViTV2PreTrainedModel:()=>ii,ModernBertDecoderForCausalLM:()=>My,ModernBertDecoderModel:()=>Ty,ModernBertDecoderPreTrainedModel:()=>li,ModernBertForMaskedLM:()=>ky,ModernBertForSequenceClassification:()=>Ey,ModernBertForTokenClassification:()=>Ay,ModernBertModel:()=>vy,ModernBertPreTrainedModel:()=>qs,Moondream1ForConditionalGeneration:()=>hx,MoonshineForConditionalGeneration:()=>Oy,MoonshineModel:()=>Sy,MoonshinePreTrainedModel:()=>ci,MptForCausalLM:()=>Ry,MptModel:()=>Ny,MptPreTrainedModel:()=>ui,MultiModalityCausalLM:()=>By,MultiModalityPreTrainedModel:()=>qu,MusicgenForCausalLM:()=>Fy,MusicgenForConditionalGeneration:()=>fi,MusicgenModel:()=>Uy,MusicgenPreTrainedModel:()=>di,NanoChatForCausalLM:()=>jy,NanoChatModel:()=>Gy,NanoChatPreTrainedModel:()=>mi,NemotronHForCausalLM:()=>Wy,NemotronHModel:()=>qy,NemotronHPreTrainedModel:()=>_i,NeoBertForMaskedLM:()=>Hy,NeoBertForQuestionAnswering:()=>Yy,NeoBertForSequenceClassification:()=>Xy,NeoBertForTokenClassification:()=>Ky,NeoBertModel:()=>Vy,NeoBertPreTrainedModel:()=>ts,NomicBertModel:()=>Qy,NomicBertPreTrainedModel:()=>Wu,OPTForCausalLM:()=>c0,OPTModel:()=>l0,OPTPreTrainedModel:()=>bi,Olmo2ForCausalLM:()=>t0,Olmo2Model:()=>e0,Olmo2PreTrainedModel:()=>gi,Olmo3ForCausalLM:()=>s0,Olmo3Model:()=>r0,Olmo3PreTrainedModel:()=>wi,OlmoForCausalLM:()=>Zy,OlmoHybridForCausalLM:()=>o0,OlmoHybridModel:()=>n0,OlmoHybridPreTrainedModel:()=>xi,OlmoModel:()=>Jy,OlmoPreTrainedModel:()=>hi,OpenELMForCausalLM:()=>i0,OpenELMModel:()=>a0,OpenELMPreTrainedModel:()=>yi,OwlViTForObjectDetection:()=>f0,OwlViTModel:()=>d0,OwlViTPreTrainedModel:()=>ki,Owlv2ForObjectDetection:()=>p0,Owlv2Model:()=>u0,Owlv2PreTrainedModel:()=>vi,PaliGemmaForConditionalGeneration:()=>m0,ParakeetForCTC:()=>_0,ParakeetPreTrainedModel:()=>Vu,PatchTSMixerForPrediction:()=>g0,PatchTSMixerModel:()=>h0,PatchTSMixerPreTrainedModel:()=>Ei,PatchTSTForPrediction:()=>x0,PatchTSTModel:()=>w0,PatchTSTPreTrainedModel:()=>Ai,Phi3ForCausalLM:()=>k0,Phi3Model:()=>v0,Phi3PreTrainedModel:()=>Mi,Phi3VForCausalLM:()=>Si,Phi3VPreTrainedModel:()=>Hu,PhiForCausalLM:()=>b0,PhiModel:()=>y0,PhiPreTrainedModel:()=>Ti,PreTrainedModel:()=>y,PvtForImageClassification:()=>A0,PvtModel:()=>E0,PvtPreTrainedModel:()=>Oi,PyAnnoteForAudioFrameClassification:()=>M0,PyAnnoteModel:()=>T0,PyAnnotePreTrainedModel:()=>Ii,Qwen2ForCausalLM:()=>O0,Qwen2Model:()=>S0,Qwen2MoeForCausalLM:()=>C0,Qwen2MoeModel:()=>I0,Qwen2MoePreTrainedModel:()=>Pi,Qwen2PreTrainedModel:()=>Ci,Qwen2VLForCausalLM:()=>Ds,Qwen2VLForConditionalGeneration:()=>Bn,Qwen2VLPreTrainedModel:()=>Pu,Qwen2_5_VLForCausalLM:()=>Us,Qwen2_5_VLForConditionalGeneration:()=>Bs,Qwen3ForCausalLM:()=>L0,Qwen3Model:()=>P0,Qwen3MoeForCausalLM:()=>N0,Qwen3MoeModel:()=>z0,Qwen3MoePreTrainedModel:()=>zi,Qwen3NextForCausalLM:()=>$0,Qwen3NextModel:()=>R0,Qwen3NextPreTrainedModel:()=>Ni,Qwen3PreTrainedModel:()=>Li,Qwen3VLForCausalLM:()=>Vs,Qwen3VLForConditionalGeneration:()=>Ws,Qwen3VLMoeForCausalLM:()=>Ri,Qwen3VLMoeForConditionalGeneration:()=>D0,Qwen3_5ForCausalLM:()=>Hs,Qwen3_5ForConditionalGeneration:()=>Vn,Qwen3_5MoeForCausalLM:()=>$i,Qwen3_5MoeForConditionalGeneration:()=>B0,RFDetrForObjectDetection:()=>j0,RFDetrModel:()=>G0,RFDetrObjectDetectionOutput:()=>Xu,RFDetrPreTrainedModel:()=>Bi,RTDetrForObjectDetection:()=>mg,RTDetrModel:()=>fg,RTDetrObjectDetectionOutput:()=>fr,RTDetrPreTrainedModel:()=>da,RTDetrV2ForObjectDetection:()=>tb,RTDetrV2Model:()=>eb,RTDetrV2ObjectDetectionOutput:()=>Ku,RTDetrV2PreTrainedModel:()=>Ui,ResNetForImageClassification:()=>F0,ResNetModel:()=>U0,ResNetPreTrainedModel:()=>Di,RoFormerForMaskedLM:()=>Y0,RoFormerForQuestionAnswering:()=>Z0,RoFormerForSequenceClassification:()=>Q0,RoFormerForTokenClassification:()=>J0,RoFormerModel:()=>K0,RoFormerPreTrainedModel:()=>ss,RobertaForMaskedLM:()=>W0,RobertaForQuestionAnswering:()=>X0,RobertaForSequenceClassification:()=>V0,RobertaForTokenClassification:()=>H0,RobertaModel:()=>q0,RobertaPreTrainedModel:()=>rs,Sam2ImageSegmentationOutput:()=>Ju,Sam2Model:()=>Fi,Sam2PreTrainedModel:()=>Zu,Sam3TrackerModel:()=>nb,SamImageSegmentationOutput:()=>Yu,SamModel:()=>rb,SamPreTrainedModel:()=>Qu,SapiensForDepthEstimation:()=>ab,SapiensForNormalEstimation:()=>ib,SapiensForSemanticSegmentation:()=>ob,SapiensPreTrainedModel:()=>Hn,SegformerForImageClassification:()=>cb,SegformerForSemanticSegmentation:()=>ub,SegformerModel:()=>lb,SegformerPreTrainedModel:()=>Xn,SiglipModel:()=>pb,SiglipPreTrainedModel:()=>Gi,SiglipTextModel:()=>ji,SiglipVisionModel:()=>db,SmolLM3ForCausalLM:()=>mb,SmolLM3Model:()=>fb,SmolLM3PreTrainedModel:()=>qi,SnacDecoderModel:()=>Vi,SnacEncoderModel:()=>Wi,SnacModel:()=>_b,SnacPreTrainedModel:()=>Kn,SolarOpenForCausalLM:()=>gb,SolarOpenModel:()=>hb,SolarOpenPreTrainedModel:()=>Hi,SpeechT5ForSpeechToText:()=>xb,SpeechT5ForTextToSpeech:()=>yb,SpeechT5HifiGan:()=>bb,SpeechT5Model:()=>wb,SpeechT5PreTrainedModel:()=>Yn,SqueezeBertForMaskedLM:()=>kb,SqueezeBertForQuestionAnswering:()=>Ab,SqueezeBertForSequenceClassification:()=>Eb,SqueezeBertModel:()=>vb,SqueezeBertPreTrainedModel:()=>Xs,StableLmForCausalLM:()=>Mb,StableLmModel:()=>Tb,StableLmPreTrainedModel:()=>Xi,Starcoder2ForCausalLM:()=>Ob,Starcoder2Model:()=>Sb,Starcoder2PreTrainedModel:()=>Ki,StyleTextToSpeech2Model:()=>Ib,StyleTextToSpeech2PreTrainedModel:()=>ep,SupertonicForConditionalGeneration:()=>Yi,SupertonicPreTrainedModel:()=>tp,Swin2SRForImageSuperResolution:()=>Nb,Swin2SRModel:()=>zb,Swin2SRPreTrainedModel:()=>Qi,SwinForImageClassification:()=>Pb,SwinForSemanticSegmentation:()=>Lb,SwinModel:()=>Cb,SwinPreTrainedModel:()=>Qn,T5ForConditionalGeneration:()=>$b,T5Model:()=>Rb,T5PreTrainedModel:()=>Ji,TableTransformerForObjectDetection:()=>Bb,TableTransformerModel:()=>Db,TableTransformerObjectDetectionOutput:()=>rp,TableTransformerPreTrainedModel:()=>Zi,TrOCRForCausalLM:()=>Ub,TrOCRPreTrainedModel:()=>sp,UltravoxModel:()=>Fs,UltravoxPreTrainedModel:()=>Lu,UniSpeechForCTC:()=>Gb,UniSpeechForSequenceClassification:()=>jb,UniSpeechModel:()=>Fb,UniSpeechPreTrainedModel:()=>Jn,UniSpeechSatForAudioFrameClassification:()=>Hb,UniSpeechSatForCTC:()=>Wb,UniSpeechSatForSequenceClassification:()=>Vb,UniSpeechSatModel:()=>qb,UniSpeechSatPreTrainedModel:()=>Ks,VaultGemmaForCausalLM:()=>Kb,VaultGemmaModel:()=>Xb,VaultGemmaPreTrainedModel:()=>el,ViTForImageClassification:()=>Jb,ViTMAEModel:()=>Zb,ViTMAEPreTrainedModel:()=>np,ViTMSNForImageClassification:()=>t1,ViTMSNModel:()=>e1,ViTMSNPreTrainedModel:()=>rl,ViTModel:()=>Qb,ViTPreTrainedModel:()=>tl,VisionEncoderDecoderModel:()=>Yb,VitMatteForImageMatting:()=>r1,VitMattePreTrainedModel:()=>op,VitPoseForPoseEstimation:()=>s1,VitPosePreTrainedModel:()=>ap,VitsModel:()=>n1,VitsModelOutput:()=>ip,VitsPreTrainedModel:()=>lp,VoxtralForConditionalGeneration:()=>o1,VoxtralRealtimeForConditionalGeneration:()=>sl,VoxtralRealtimePreTrainedModel:()=>cp,Wav2Vec2BertForCTC:()=>c1,Wav2Vec2BertForSequenceClassification:()=>u1,Wav2Vec2BertModel:()=>l1,Wav2Vec2BertPreTrainedModel:()=>Zn,Wav2Vec2ForAudioFrameClassification:()=>cx,Wav2Vec2ForCTC:()=>ix,Wav2Vec2ForSequenceClassification:()=>lx,Wav2Vec2Model:()=>ax,Wav2Vec2PreTrainedModel:()=>rr,WavLMForAudioFrameClassification:()=>_1,WavLMForCTC:()=>d1,WavLMForSequenceClassification:()=>f1,WavLMForXVector:()=>m1,WavLMModel:()=>p1,WavLMPreTrainedModel:()=>ns,WeSpeakerResNetModel:()=>h1,WeSpeakerResNetPreTrainedModel:()=>pp,WhisperForConditionalGeneration:()=>fp,WhisperModel:()=>g1,WhisperPreTrainedModel:()=>nl,XLMForQuestionAnswering:()=>k1,XLMForSequenceClassification:()=>b1,XLMForTokenClassification:()=>v1,XLMModel:()=>x1,XLMPreTrainedModel:()=>os,XLMRobertaForMaskedLM:()=>A1,XLMRobertaForQuestionAnswering:()=>S1,XLMRobertaForSequenceClassification:()=>T1,XLMRobertaForTokenClassification:()=>M1,XLMRobertaModel:()=>E1,XLMRobertaPreTrainedModel:()=>as,XLMWithLMHeadModel:()=>y1,XVectorOutput:()=>up,YolosForObjectDetection:()=>I1,YolosModel:()=>O1,YolosObjectDetectionOutput:()=>mp,YolosPreTrainedModel:()=>ol,YoutuForCausalLM:()=>P1,YoutuModel:()=>C1,YoutuPreTrainedModel:()=>al});var Ns=class extends y{},uh=class extends Ns{},ph=class extends Ns{async _call(e){return new G(await super._call(e))}},dh=class extends Ns{async _call(e){return new Ae(await super._call(e))}},fh=class extends Ns{async _call(e){return new ge(await super._call(e))}};var Xo=class extends y{},mh=class extends Xo{},_h=class extends Xo{};var Ko=class extends y{},hh=class extends Ko{},gh=class extends Ko{};var Yo=class extends y{},wh=class extends Yo{},xh=class extends Yo{};var Qo=class extends y{},yh=class extends Qo{},bh=class extends Qo{};var Ln=class extends y{},vh=class extends Ln{},kh=class extends Ln{},Eh=class extends Ln{async _call(e){return new G(await super._call(e))}};var Jo=class extends y{},Ah=class extends Jo{},Th=class extends Jo{async _call(e){return new G(await super._call(e))}};var Hr=class extends y{},Mh=class extends Hr{},Sh=class extends Hr{async _call(e){return new ge(await super._call(e))}},Oh=class extends Hr{async _call(e){return new G(await super._call(e))}},Ih=class extends Hr{async _call(e){return new he(await super._call(e))}},Ch=class extends Hr{async _call(e){return new Ae(await super._call(e))}};var Zo=class extends y{},Ph=class extends Zo{},Lh=class extends Zo{};var ea=class extends y{},zh=class extends ea{},Nh=class extends ea{};var ta=class extends y{},Rh=class extends ta{},$h=class extends ta{};var Xr=class extends y{},Dh=class extends Xr{},Bh=class extends Xr{async _call(e){return new ge(await super._call(e))}},Uh=class extends Xr{async _call(e){return new G(await super._call(e))}},Fh=class extends Xr{async _call(e){return new he(await super._call(e))}},Gh=class extends Xr{async _call(e){return new Ae(await super._call(e))}};var xN=4299n,wT=6561n,wu=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"]},ra=class extends wu{async encode_speech(e){return de(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,audio_features:p=null,audio_tokens:d=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 R)){let S=e.dims[0];if(n==null)n=He([S],.5);else if(typeof n=="number")n=He([S],n);else if(Array.isArray(n))n=new R("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 de(this.sessions.embed_tokens,A),p&&d&&m&&_&&(x={audio_features:p,audio_tokens:d,speaker_embeddings:m,speaker_features:_}),x||s)x??=await this.encode_speech(s),a=ke([x.audio_features,a],1),r=tt([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=tt([a.dims[0],M+S])}}return{...await It(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c},!1),...x}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==wT)-1);r.position_ids=new R("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=wT?0:i++)});r.position_ids=new R("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=He([a.dims[0],3],xN),l=ke([s,a,i],1),{waveform:c}=await de(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var xu=class extends y{},jh=class extends xu{};var yu=class extends y{},qh=class extends yu{};var zn=class extends y{},Wh=class extends zn{},sa=class extends zn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},na=class extends zn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var dr=class extends y{},Vh=class extends dr{},Hh=class extends dr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},oa=class extends dr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Xh=class extends dr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},Kh=class extends dr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var aa=class extends y{},Yh=class extends aa{},Qh=class extends aa{};var ia=class extends y{},Jh=class extends ia{},Zh=class extends ia{};var la=class extends y{},eg=class extends la{},tg=class extends la{};var ca=class extends y{},rg=class extends ca{},sg=class extends ca{};var Kr=class extends y{},ng=class extends Kr{},og=class extends Kr{async _call(e){return new ge(await super._call(e))}},ag=class extends Kr{async _call(e){return new G(await super._call(e))}},ig=class extends Kr{async _call(e){return new he(await super._call(e))}},lg=class extends Kr{async _call(e){return new Ae(await super._call(e))}};var ua=class extends y{},cg=class extends ua{},ug=class extends ua{async _call(e){return new G(await super._call(e))}};var pa=class extends y{},pg=class extends pa{},dg=class extends pa{async _call(e){return new G(await super._call(e))}};var da=class extends y{},fg=class extends da{},mg=class extends da{async _call(e){return new fr(await super._call(e))}},fr=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var fa=class extends y{},_g=class extends fa{},hg=class extends fa{async _call(e){return new fr(await super._call(e))}};var bu=class extends Re{constructor({audio_codes:e}){super(),this.audio_codes=e}},vu=class extends Re{constructor({audio_values:e}){super(),this.audio_values=e}},Nn=class extends y{main_input_name="input_values";forward_params=["input_values"]},gg=class extends Nn{async encode(e){return new bu(await de(this.sessions.encoder_model,e))}async decode(e){return new vu(await de(this.sessions.decoder_model,e))}},ma=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},_a=class extends Nn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Yr=class extends y{},wg=class extends Yr{},xg=class extends Yr{async _call(e){return new ge(await super._call(e))}},yg=class extends Yr{async _call(e){return new G(await super._call(e))}},bg=class extends Yr{async _call(e){return new he(await super._call(e))}},vg=class extends Yr{async _call(e){return new Ae(await super._call(e))}};var ha=class extends y{},kg=class extends ha{},Eg=class extends ha{};var Qr=class extends y{},Ag=class extends Qr{},Tg=class extends Qr{async _call(e){return new ge(await super._call(e))}},Mg=class extends Qr{async _call(e){return new G(await super._call(e))}},Sg=class extends Qr{async _call(e){return new he(await super._call(e))}},Og=class extends Qr{async _call(e){return new Ae(await super._call(e))}};var ku=class extends y{},Ig=class extends ku{};var ga=class extends y{},Cg=class extends ga{},Pg=class extends ga{async _call(e){return new G(await super._call(e))}};var Eu=class extends y{},Lg=class extends Eu{};var Au=class extends y{},zg=class extends Au{};var Rn=class extends y{},Ng=class extends Rn{},Rg=class extends Rn{async _call(e){return new $n(await super._call(e))}},$g=class extends Rn{async _call(e){return new Tu(await super._call(e))}},$n=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},Tu=class extends Re{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var wa=class extends y{},Dg=class extends wa{},Bg=class extends wa{async _call(e){return new G(await super._call(e))}};var xa=class extends y{},Ug=class extends xa{},Fg=class extends xa{async _call(e){return new G(await super._call(e))}};var Mu=class extends y{},Gg=class extends Mu{};var Su=class extends y{},jg=class extends Su{};var Jr=class extends y{},qg=class extends Jr{},Wg=class extends Jr{async _call(e){return new G(await super._call(e))}},Vg=class extends Jr{async _call(e){return new he(await super._call(e))}},Hg=class extends Jr{async _call(e){return new Ae(await super._call(e))}},Xg=class extends Jr{async _call(e){return new ge(await super._call(e))}};var Ou=class extends y{},Kg=class extends Ou{};var ya=class extends y{},Yg=class extends ya{},Qg=class extends ya{};var ba=class extends y{},Jg=class extends ba{},Zg=class extends ba{async _call(e){return new G(await super._call(e))}};var Zr=class extends y{},ew=class extends Zr{},tw=class extends Zr{async _call(e){return new ge(await super._call(e))}},rw=class extends Zr{async _call(e){return new G(await super._call(e))}},sw=class extends Zr{async _call(e){return new he(await super._call(e))}},nw=class extends Zr{async _call(e){return new Ae(await super._call(e))}};var va=class extends y{},ow=class extends va{},aw=class extends va{};var Rs=class extends y{},iw=class extends Rs{},lw=class extends Rs{async _call(e){return new ge(await super._call(e))}},cw=class extends Rs{async _call(e){return new G(await super._call(e))}},uw=class extends Rs{async _call(e){return new he(await super._call(e))}};var $s=class extends y{},pw=class extends $s{},dw=class extends $s{async _call(e){return new ge(await super._call(e))}},fw=class extends $s{async _call(e){return new G(await super._call(e))}},mw=class extends $s{async _call(e){return new he(await super._call(e))}};var ka=class extends y{},_w=class extends ka{},hw=class extends ka{};var Ea=class extends y{},gw=class extends Ea{},ww=class extends Ea{};var Aa=class extends y{},xw=class extends Aa{},yw=class extends Aa{};var Ta=class extends y{},bw=class extends Ta{},vw=class extends Ta{async _call(e){return new G(await super._call(e))}};var Iu=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"},kw=class extends Iu{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:ke([r,e],1),attention_mask:ke([tt(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:d}=await Wt(this,{inputs_embeds:l,attention_mask:s});a=d}if(!c){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:n})}return await It(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var Ma=class extends y{},Ew=class extends Ma{},Aw=class extends Ma{};var Sa=class extends y{},Tw=class extends Sa{},Mw=class extends Sa{};var Oa=class extends y{},Sw=class extends Oa{},Ow=class extends Oa{};var Cu=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 Cu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:d=null,...m}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await de(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:w}=await de(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 de(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:w,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await It(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,attention_mask:r,position_ids:a,generation_config:p,logits_processor:d},!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 gu({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},Ia=class extends Dn{};var Ca=class extends y{},Iw=class extends Ca{},Cw=class extends Ca{};var Pa=class extends y{},Pw=class extends Pa{},Lw=class extends Pa{};var Pu=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Bn=class extends Pu{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,r){if(r){let{data:s,dims:n}=ch(r),o=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),a=Array.from({length:n[0]},(i,l)=>Oe(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return[new R("int64",o,[3,...n]),new R("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 R("int64",o,[3,...e.dims]),Mf([s,1])]}}_reorder_and_write_positions(e,r,s,n){let o=e.reduce((c,p)=>c+p.length,0),a=new Array(o),i=0;for(let c=0;c<3;++c)for(let p of e){let d=p.length/3;for(let m=c*d;m<(c+1)*d;++m)a[i++]=p[m]}let l=0;for(let c=0;c<r.length;++c)if(r[c]==1){for(let p=0;p<3;++p)s[p][n][c]=a[p*o/3+l];++l}return a}_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,video_token_id:i,vision_start_token_id:l}=this.config,c=e,d=c.reduce((A,S,M)=>(S==l&&A.push(M),A),[]).map(A=>c[A+1]),m=d.filter(A=>A==a).length,_=d.filter(A=>A==i).length,w=[],x=0,k=m,b=_;for(let A=0;A<d.length;++A){let S=c.findIndex((J,xe)=>xe>x&&J==a),M=c.findIndex((J,xe)=>xe>x&&J==i),P=k>0&&S!==-1?S:c.length+1,O=b>0&&M!==-1?M:c.length+1,E,W,X,U;P<O?([W,X,U]=r[o.image_index],++o.image_index,--k,E=P):([W,X,U]=s[o.video_index],++o.video_index,--b,E=O);let[H,j,Y]=[Number(W),Math.floor(Number(X)/n),Math.floor(Number(U)/n)],$=E-x,C=w.length>0?Oe(w.at(-1))[0]+1:0;w.push(Array.from({length:3*$},(J,xe)=>C+xe%$));let te=$+C,ae=H*j*Y,L=Array.from({length:ae},(J,xe)=>te+Math.floor(xe/(j*Y))),N=Array.from({length:ae},(J,xe)=>te+Math.floor(xe/Y)%j),B=Array.from({length:ae},(J,xe)=>te+xe%Y);w.push([L,N,B].flat()),x=E+ae}if(x<c.length){let A=w.length>0?Oe(w.at(-1))[0]+1:0,S=c.length-x;w.push(Array.from({length:3*S},(M,P)=>A+P%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=Sc(e));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),p=r?r.tolist():[],d=s?s.tolist():[],m={image_index:0,video_index:0},_=[];for(let w=0;w<i.length;++w){let x=i[w].filter((A,S)=>l[w][S]==1),k=this._get_multimodal_rope_positions({filtered_ids:x,image_grid_thw_list:p,video_grid_thw_list:d,spatial_merge_size:a,state:m}),b=this._reorder_and_write_positions(k,l[w],c,w);_.push(Oe(b)[0]+1-i[w].length)}return[new R("int64",c.flat(1/0),[3,e.dims[0],e.dims[1]]),new R("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 de(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)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 n=r.past_key_values.get_seq_length();if(n<r.input_ids.dims[1]){let[o,a]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);r.rope_deltas=a,r.position_ids=o.slice(null,null,[n,null]),r.input_ids=r.input_ids.slice(null,[n,null])}else{r.rope_deltas||([,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask));let o=BigInt(n),a=r.rope_deltas.map(i=>o+i);r.position_ids=Ot([a,a,a],0)}}return r}},Ds=class extends Bn{};var Bs=class extends Bn{image_grid_thw_name="image_grid_thw"},Us=class extends Ds{image_grid_thw_name="image_grid_thw"};var zw=class extends Bs{get_vision_position_ids(e,r,s,n){let o=Math.floor(r[0]/s),a=Math.floor(r[1]/n),i=Math.floor(r[2]/n),l=a*i*o,c=Array.from({length:l},()=>e),p=Array.from({length:l},(m,_)=>e+Math.floor(_/(i*o))),d=Array.from({length:l},(m,_)=>e+_%i);return[...c,...p,...d]}_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 _=m<e.length?e[m]==a?1:0:-1;_!==c&&(i.push([c,l,m]),l=m,c=_)}let p=0,d=[];for(let[m,_,w]of i)if(m===0){let x=w-_;d.push(Array.from({length:3*x},(k,b)=>p+b%x)),p+=x}else{let x=r[o.image_index++].map(Number),k=x[0];d.push(this.get_vision_position_ids(p,x,k,n)),p+=Math.max(x[1],x[2])/n}return d}};var La=class extends y{},Nw=class extends La{},Rw=class extends La{};var za=class extends y{},$w=class extends za{},Dw=class extends za{};var Na=class extends y{},Bw=class extends Na{},Uw=class extends Na{};var Ra=class extends y{},Fw=class extends Ra{},Gw=class extends Ra{};var $a=class extends y{},jw=class extends $a{},qw=class extends $a{};var Da=class extends y{},Ww=class extends Da{},Vw=class extends Da{};var Ba=class extends y{},Hw=class extends Ba{},Xw=class extends Ba{};var Ua=class extends y{},Kw=class extends Ua{},Yw=class extends Ua{};var Fa=class extends y{},Qw=class extends Fa{},Jw=class extends Fa{};var Lu=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Fs=class extends Lu{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return gu({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}};var Zw=class extends Fs{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var zu=class extends y{},ex=class extends zu{};var Nu=class extends y{},tx=class extends Nu{};var Ga=class extends y{},rx=class extends Ga{},sx=class extends Ga{};var ja=class extends y{},nx=class extends ja{},ox=class extends ja{async _call(e){return new G(await super._call(e))}};var rr=class extends y{},ax=class extends rr{},ix=class extends rr{async _call(e){return new kt(await super._call(e))}},lx=class extends rr{async _call(e){return new G(await super._call(e))}},cx=class extends rr{async _call(e){return new he(await super._call(e))}};var ux=class extends y{},px=class extends rr{},dx=class extends rr{async _call(e){return new kt(await super._call(e))}},fx=class extends rr{async _call(e){return new G(await super._call(e))}};var qa=class extends y{},mx=class extends qa{},_x=class extends qa{};var Ru=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Ct=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})}},hx=class extends Ct{},gx=class extends Ct{};var wx=class extends Ct{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var Wa=class extends y{},xx=class extends Wa{},yx=class extends Wa{async _call(e){return new G(await super._call(e))}};var Va=class extends y{},bx=class extends Va{},vx=class extends Va{};var Un=class extends y{},kx=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=tt([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=He([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}},Ha=class extends Un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Ex=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 Xa=class extends y{},Ax=class extends Xa{},Tx=class extends Xa{};var Mx=class extends Ct{};var Ka=class extends y{},Sx=class extends Ka{},Ox=class extends Ka{};var Ix=class extends Ct{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var Ya=class extends y{},Cx=class extends Ya{},Px=class extends Ya{};var $u=class extends y{},Lx=class extends $u{};var Qa=class extends y{},zx=class extends Qa{},Nx=class extends Qa{};var Ja=class extends y{},Rx=class extends Ja{},$x=class extends Ja{};var Za=class extends y{},Dx=class extends Za{},Bx=class extends Za{};var ei=class extends y{},Ux=class extends ei{},Fx=class extends ei{};var Gs=class extends y{},Gx=class extends Gs{},jx=class extends Gs{},qx=class extends Gs{async _call(e){return new G(await super._call(e))}},Wx=class extends Gs{};var Du=class extends y{},Vx=class extends Du{};var Bu=class extends y{},Hx=class extends Bu{};var Uu=class extends Re{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Fu=class extends y{},Xx=class extends Fu{async _call(e){return new Uu(await super._call(e))}};var Gu=class extends Re{constructor({audio_codes:e}){super(),this.audio_codes=e}},ju=class extends Re{constructor({audio_values:e}){super(),this.audio_values=e}},Fn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Kx=class extends Fn{async encode(e){return new Gu(await de(this.sessions.encoder_model,e))}async decode(e){return new ju(await de(this.sessions.decoder_model,e))}},ti=class extends Fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ri=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 si=class extends y{},Yx=class extends si{},Qx=class extends si{};var ni=class extends y{},Jx=class extends ni{},Zx=class extends ni{};var js=class extends y{},ey=class extends js{},ty=class extends js{async _call(e){return new ge(await super._call(e))}},ry=class extends js{async _call(e){return new G(await super._call(e))}},sy=class extends js{async _call(e){return new Ae(await super._call(e))}};var oi=class extends y{},ny=class extends oi{},oy=class extends oi{};var Gn=class extends y{},ay=class extends Gn{},iy=class extends Gn{async _call(e){return new G(await super._call(e))}},ly=class extends Gn{};var jn=class extends y{},cy=class extends jn{},uy=class extends jn{async _call(e){return new G(await super._call(e))}},py=class extends jn{};var qn=class extends y{},dy=class extends qn{},fy=class extends qn{async _call(e){return new G(await super._call(e))}},my=class extends qn{};var Wn=class extends y{},_y=class extends Wn{},hy=class extends Wn{async _call(e){return new G(await super._call(e))}},gy=class extends Wn{};var ai=class extends y{},wy=class extends ai{},xy=class extends ai{async _call(e){return new G(await super._call(e))}};var ii=class extends y{},yy=class extends ii{},by=class extends ii{async _call(e){return new G(await super._call(e))}};var qs=class extends y{},vy=class extends qs{},ky=class extends qs{async _call(e){return new ge(await super._call(e))}},Ey=class extends qs{async _call(e){return new G(await super._call(e))}},Ay=class extends qs{async _call(e){return new he(await super._call(e))}};var li=class extends y{},Ty=class extends li{},My=class extends li{};var ci=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Sy=class extends ci{},Oy=class extends ci{};var es=class extends y{},Iy=class extends es{},Cy=class extends es{async _call(e){return new ge(await super._call(e))}},Py=class extends es{async _call(e){return new G(await super._call(e))}},Ly=class extends es{async _call(e){return new he(await super._call(e))}},zy=class extends es{async _call(e){return new Ae(await super._call(e))}};var ui=class extends y{},Ny=class extends ui{},Ry=class extends ui{};var pi=class extends y{},$y=class extends pi{},Dy=class extends pi{};var qu=class extends y{},By=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=Ke(e,l.inputNames);s=await de(l,c)}else{let l=this.sessions.gen_img_embeds,c=Ke({image_ids:e.input_ids},l.inputNames);s=await de(l,c)}let n={...e,...s},o=await It(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await de(a,Ke(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=ke([r.input_ids,r.input_ids],0):(r.input_ids=ke([r.input_ids,Co(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=ke([r.attention_mask,Co(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=He([0,0,3,384,384],1)),n&&(r.images_seq_mask=new R("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new R("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 de(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let p=Ye.fromTensor(c);l.push(p)}return l}};var di=class extends y{},Uy=class extends di{},Fy=class extends di{},fi=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;c<e.size;++c){if(e.data[c]==this.config.decoder.pad_token_id)continue;let p=c%s,d=Math.floor(c/s)%n,m=p-d;m>0&&m<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new R(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<o.length;++a)for(let i=0;i<o[a].length;++i)a%this.config.decoder.num_codebooks>=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),Ho(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 de(this.sessions.encodec_decode,{audio_codes:s});return n}};var mi=class extends y{},Gy=class extends mi{},jy=class extends mi{};var _i=class extends y{},qy=class extends _i{},Wy=class extends _i{};var ts=class extends y{},Vy=class extends ts{},Hy=class extends ts{async _call(e){return new ge(await super._call(e))}},Xy=class extends ts{async _call(e){return new G(await super._call(e))}},Ky=class extends ts{async _call(e){return new he(await super._call(e))}},Yy=class extends ts{async _call(e){return new Ae(await super._call(e))}};var Wu=class extends y{},Qy=class extends Wu{};var hi=class extends y{},Jy=class extends hi{},Zy=class extends hi{};var gi=class extends y{},e0=class extends gi{},t0=class extends gi{};var wi=class extends y{},r0=class extends wi{},s0=class extends wi{};var xi=class extends y{},n0=class extends xi{},o0=class extends xi{};var yi=class extends y{},a0=class extends yi{},i0=class extends yi{};var bi=class extends y{},l0=class extends bi{},c0=class extends bi{};var vi=class extends y{},u0=class extends vi{},p0=class extends vi{};var ki=class extends y{},d0=class extends ki{},f0=class extends ki{};var m0=class extends Ct{};var Vu=class extends y{},_0=class extends Vu{async _call(e){return new kt(await super._call(e))}};var Ei=class extends y{},h0=class extends Ei{},g0=class extends Ei{};var Ai=class extends y{},w0=class extends Ai{},x0=class extends Ai{};var Ti=class extends y{},y0=class extends Ti{},b0=class extends Ti{};var Mi=class extends y{},v0=class extends Mi{},k0=class extends Mi{};var Hu=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Si=class extends Hu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,...p}){if(!a){let 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 de(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let _=this.config.normalized_config.hidden_size;m=new R("float32",[],[0,_])}({inputs_embeds:a}=await de(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await It(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var Oi=class extends y{},E0=class extends Oi{},A0=class extends Oi{async _call(e){return new G(await super._call(e))}};var Ii=class extends y{},T0=class extends Ii{},M0=class extends Ii{async _call(e){return new he(await super._call(e))}};var Ci=class extends y{},S0=class extends Ci{},O0=class extends Ci{};var Pi=class extends y{},I0=class extends Pi{},C0=class extends Pi{};var Li=class extends y{},P0=class extends Li{},L0=class extends Li{};var zi=class extends y{},z0=class extends zi{},N0=class extends zi{};var Ni=class extends y{},R0=class extends Ni{},$0=class extends Ni{};var Ws=class extends Bs{},Vs=class extends Us{};var D0=class extends Ws{},Ri=class extends Vs{};var Vn=class extends Ws{},Hs=class extends Vn{};var B0=class extends Vn{},$i=class extends Hs{};var Di=class extends y{},U0=class extends Di{},F0=class extends Di{async _call(e){return new G(await super._call(e))}};var Bi=class extends y{},G0=class extends Bi{},j0=class extends Bi{async _call(e){return new Xu(await super._call(e))}},Xu=class extends fr{};var rs=class extends y{},q0=class extends rs{},W0=class extends rs{async _call(e){return new ge(await super._call(e))}},V0=class extends rs{async _call(e){return new G(await super._call(e))}},H0=class extends rs{async _call(e){return new he(await super._call(e))}},X0=class extends rs{async _call(e){return new Ae(await super._call(e))}};var ss=class extends y{},K0=class extends ss{},Y0=class extends ss{async _call(e){return new ge(await super._call(e))}},Q0=class extends ss{async _call(e){return new G(await super._call(e))}},J0=class extends ss{async _call(e){return new he(await super._call(e))}},Z0=class extends ss{async _call(e){return new Ae(await super._call(e))}};var Ui=class extends y{},eb=class extends Ui{},tb=class extends Ui{async _call(e){return new Ku(await super._call(e))}},Ku=class extends fr{};var Yu=class extends Re{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},Qu=class extends y{},rb=class extends Qu{async get_image_embeddings({pixel_values:e}){return await Wt(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??=tt(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 de(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new Yu(await super._call(e))}};var Ju=class extends Re{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},Zu=class extends y{},Fi=class extends Zu{async get_image_embeddings({pixel_values:e}){return await Wt(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??=tt(a.slice(0,-1)),e.input_boxes??=He([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=He([a[0],a[1],0],-1n),e.input_points=He([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=Ke(e,n.inputNames);return await de(n,o)}async _call(e){return new Ju(await super._call(e))}},sb=class extends Fi{},nb=class extends Fi{};var Hn=class extends y{},ob=class extends Hn{},ab=class extends Hn{},ib=class extends Hn{};var Xn=class extends y{},lb=class extends Xn{},cb=class extends Xn{},ub=class extends Xn{};var Gi=class extends y{},pb=class extends Gi{},ji=class extends Gi{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},db=class extends dr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var qi=class extends y{},fb=class extends qi{},mb=class extends qi{};var Kn=class extends y{main_input_name="input_values";forward_params=["input_values"]},_b=class extends Kn{async encode(e){return await de(this.sessions.encoder_model,e)}async decode(e){return await de(this.sessions.decoder_model,e)}},Wi=class extends Kn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Vi=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 Hi=class extends y{},hb=class extends Hi{},gb=class extends Hi{};var Yn=class extends y{},wb=class extends Yn{},xb=class extends Yn{},yb=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 Wt(this,i),p=l.dims[1]/this.config.reduction_factor,d=Math.floor(p*o),m=Math.floor(p*n),_=this.config.num_mel_bins,w=[],x=null,k=null,b=0;for(;;){++b;let M=lh(!!k),P;k?P=k.output_sequence_out:P=new R("float32",new Float32Array(_),[1,1,_]);let O={use_cache_branch:M,output_sequence:P,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(O,x),k=await de(this.sessions.decoder_model_merged,O),x=this.getPastKeyValues(k,x);let{prob:E,spectrum:W}=k;if(w.push(W),b>=m&&(Array.from(E.data).filter(X=>X>=s).length>0||b>=d))break}let A=ke(w),{waveform:S}=await de(a.sessions.model,{spectrogram:A});return{spectrogram:A,waveform:S}}},bb=class extends y{main_input_name="spectrogram"};var Xs=class extends y{},vb=class extends Xs{},kb=class extends Xs{async _call(e){return new ge(await super._call(e))}},Eb=class extends Xs{async _call(e){return new G(await super._call(e))}},Ab=class extends Xs{async _call(e){return new Ae(await super._call(e))}};var Xi=class extends y{},Tb=class extends Xi{},Mb=class extends Xi{};var Ki=class extends y{},Sb=class extends Ki{},Ob=class extends Ki{};var ep=class extends y{},Ib=class extends ep{};var tp=class extends y{},Yi=class extends tp{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:c}=this.config,{last_hidden_state:p,durations:d}=await de(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=d.div(o).mul_(a),_=l*i,w=m.data,x=Int32Array.from(w,U=>Math.ceil(U/_)),k=Math.max(...x),b=e.dims[0],A=new BigInt64Array(b*k);for(let U=0;U<b;++U)A.fill(1n,U*k,U*k+x[U]);let S=new R("int64",A,[b,k]),M=c*i,P=M*k,O=U2([b,M,k]),E=O.data;for(let U=0;U<b;++U)if(x[U]!==k)for(let H=0;H<M;++H)E.fill(0,U*P+H*k+x[U],U*P+(H+1)*k);let W=He([b],n);for(let U=0;U<n;++U){let H=He([b],U);({denoised_latents:O}=await de(this.sessions.latent_denoiser,{style:s,noisy_latents:O,latent_mask:S,encoder_outputs:p,attention_mask:r,timestep:H,num_inference_steps:W}))}let{waveform:X}=await de(this.sessions.voice_decoder,{latents:O});return{waveform:X,durations:m}}};var Qn=class extends y{},Cb=class extends Qn{},Pb=class extends Qn{async _call(e){return new G(await super._call(e))}},Lb=class extends Qn{};var Qi=class extends y{},zb=class extends Qi{},Nb=class extends Qi{};var Ji=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},Rb=class extends Ji{},$b=class extends Ji{};var Zi=class extends y{},Db=class extends Zi{},Bb=class extends Zi{async _call(e){return new rp(await super._call(e))}},rp=class extends $n{};var sp=class extends y{},Ub=class extends sp{};var Jn=class extends y{},Fb=class extends Jn{},Gb=class extends Jn{async _call(e){return new kt(await super._call(e))}},jb=class extends Jn{async _call(e){return new G(await super._call(e))}};var Ks=class extends y{},qb=class extends Ks{},Wb=class extends Ks{async _call(e){return new kt(await super._call(e))}},Vb=class extends Ks{async _call(e){return new G(await super._call(e))}},Hb=class extends Ks{async _call(e){return new he(await super._call(e))}};var el=class extends y{},Xb=class extends el{},Kb=class extends el{};var Yb=class extends y{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]};var tl=class extends y{},Qb=class extends tl{},Jb=class extends tl{async _call(e){return new G(await super._call(e))}};var np=class extends y{},Zb=class extends np{};var rl=class extends y{},e1=class extends rl{},t1=class extends rl{async _call(e){return new G(await super._call(e))}};var op=class extends y{},r1=class extends op{async _call(e){return new ru(await super._call(e))}};var ap=class extends y{},s1=class extends ap{};var ip=class extends Re{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}},lp=class extends y{},n1=class extends lp{async _call(e){return new ip(await super._call(e))}};var o1=class extends Fs{};var xT=2,yN=1,a1=new WeakMap;function bN(t,e){let{text_config:r,audio_config:s}=t.config,n=t.sessions.audio_encoder,{num_mel_bins:o,hidden_size:a}=s,i=o+a,l=new Wo,c=n?.config?.kv_cache_dtype??"float32",p=c==="float16"?vr.float16:vr.float32,d=Is(s,{batch_size:1});for(let w in d){let x=d[w].reduce((k,b)=>k*b,1);l[w]=new R(c,new p(x),d[w])}let m=new R(c,new p(i*xT),[1,i,xT]),_=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 vN(t,e){let r=e.dims[2],s=Math.floor((yN+r-3)/2)+1,n=new R("int64",BigInt64Array.from({length:s},(p,d)=>BigInt(t.enc_past_seq_len+d)),[1,s]),o=t.enc_past_seq_len+s,a=tt([1,o]),{audio_embeds:i,present_padding_cache:l,...c}=await de(t.encoder_session,{input_features:e,attention_mask:a,position_ids:n,past_padding_cache:t.enc_padding_cache,...t.enc_kv_cache});t.enc_padding_cache.location==="gpu-buffer"&&t.enc_padding_cache.dispose(),t.enc_padding_cache=l;for(let p in c)if(p.startsWith("present.")){let d=p.replace("present","past_key_values"),m=t.enc_kv_cache[d];m?.location==="gpu-buffer"&&m.dispose(),t.enc_kv_cache[d]=c[p]}return t.enc_past_seq_len=o,i}async function kN(t,e){for(;t.audio_embed_total_tokens<e&&!t.stream_exhausted;){let r=await t.chunks_iter.next();if(r.done){t.stream_exhausted=!0;break}let s=await vN(t,r.value);t.audio_embed_queue.push({data:s.data,tokens:s.dims[1]}),t.audio_embed_total_tokens+=s.dims[1]}}function EN(t,e,r){if(t.audio_embed_queue.length===0)return;let s=e.data,n=0,o=r;for(;o>0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let p=0;p<l*t.text_hidden_size;++p)s[n*t.text_hidden_size+p]+=a.data[c+p];n+=l,o-=l,t.audio_queue_offset+=l,t.audio_queue_offset>=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var i1=class extends Vr{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)}},cp=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},sl=class extends cp{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=a1.get(this);o&&await kN(o,o.audio_consumed+n);let{inputs_embeds:a}=await de(this.sessions.embed_tokens,{input_ids:e});o&&EN(o,a,n);let i={inputs_embeds:a,...s};this.addPastKeyValues(i,r);let l=this.sessions.decoder_model_merged,c=Ke(i,l.inputNames);return await de(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=bN(this,e);a1.set(this,n);let o=new On;o.push(new i1(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),a1.delete(this)}}};var Zn=class extends y{},l1=class extends Zn{},c1=class extends Zn{async _call(e){return new kt(await super._call(e))}},u1=class extends Zn{async _call(e){return new G(await super._call(e))}};var up=class extends Re{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},ns=class extends y{},p1=class extends ns{},d1=class extends ns{async _call(e){return new kt(await super._call(e))}},f1=class extends ns{async _call(e){return new G(await super._call(e))}},m1=class extends ns{async _call(e){return new up(await super._call(e))}},_1=class extends ns{async _call(e){return new he(await super._call(e))}};var pp=class extends y{},h1=class extends pp{};var dp=class extends Sn{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1};var nl=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"]},g1=class extends nl{},fp=class extends nl{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,dp)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(Z.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${j2(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&&(Z.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 Cs,s.push(new ou(r,a))),r.begin_suppress_tokens&&(s??=new Cs,s.push(new Mn(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");r.task==="translate"&&Z.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}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)),i}_extract_token_timestamps(e,r,s=null,n=.02){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&&Z.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 o=this.config.median_filter_width;o===void 0&&(Z.warn("Model config has no `median_filter_width`, using default value of 7."),o=7);let a=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(x,k)=>ke(a.map(b=>b[k]),2)),l=Ot(r.map(([x,k])=>{if(x>=i.length)throw new Error(`Layer index ${x} is out of bounds for cross attentions (length ${i.length}).`);return s?i[x].slice(null,k,null,[0,s]):i[x].slice(null,k)})).transpose(1,0,2,3),[c,p]=Af(l,-2,0,!0),d=l.clone();for(let x=0;x<d.dims[0];++x){let k=d[x];for(let b=0;b<k.dims[0];++b){let A=k[b],S=c[x][b][0].data,M=p[x][b][0].data;for(let P=0;P<A.dims[0];++P){let O=A[P].data;for(let E=0;E<O.length;++E)O[E]=(O[E]-M[E])/S[E];O.set(FE(O,o))}}}let m=[Mc(d,1)],_=e.sequences.dims,w=new R("float32",new Float32Array(_[0]*_[1]),_);for(let x=0;x<_[0];++x){let k=m[x].neg().squeeze_(0),[b,A]=jE(k.tolist()),S=Array.from({length:b.length-1},(O,E)=>b[E+1]-b[E]),M=gt([1],S).map(O=>!!O),P=[];for(let O=0;O<M.length;++O)M[O]&&P.push(A[O]*n);w[x].data.set(P,1)}return w}},w1=class extends fp{};var os=class extends y{},x1=class extends os{},y1=class extends os{async _call(e){return new ge(await super._call(e))}},b1=class extends os{async _call(e){return new G(await super._call(e))}},v1=class extends os{async _call(e){return new he(await super._call(e))}},k1=class extends os{async _call(e){return new Ae(await super._call(e))}};var as=class extends y{},E1=class extends as{},A1=class extends as{async _call(e){return new ge(await super._call(e))}},T1=class extends as{async _call(e){return new G(await super._call(e))}},M1=class extends as{async _call(e){return new he(await super._call(e))}},S1=class extends as{async _call(e){return new Ae(await super._call(e))}};var ol=class extends y{},O1=class extends ol{},I1=class extends ol{async _call(e){return new mp(await super._call(e))}},mp=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var al=class extends y{},C1=class extends al{},P1=class extends al{};var AN=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"]]),TN=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),MN=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),SN=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"]]),yT=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),bT=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),vT=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),kT=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"]]),ET=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"]]),AT=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),TT=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_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"]]),ON=new Map([["multi_modality","MultiModalityCausalLM"]]),MT=new Map([["bert","BertForMaskedLM"],["eurobert","EuroBertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),ST=new Map([["bert","BertForQuestionAnswering"],["neobert","NeoBertForQuestionAnswering"],["roformer","RoFormerForQuestionAnswering"],["electra","ElectraForQuestionAnswering"],["convbert","ConvBertForQuestionAnswering"],["camembert","CamembertForQuestionAnswering"],["deberta","DebertaForQuestionAnswering"],["deberta-v2","DebertaV2ForQuestionAnswering"],["mpnet","MPNetForQuestionAnswering"],["albert","AlbertForQuestionAnswering"],["distilbert","DistilBertForQuestionAnswering"],["roberta","RobertaForQuestionAnswering"],["xlm","XLMForQuestionAnswering"],["xlm-roberta","XLMRobertaForQuestionAnswering"],["mobilebert","MobileBertForQuestionAnswering"],["squeezebert","SqueezeBertForQuestionAnswering"]]),OT=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),IT=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"],["gemma3n","Gemma3nForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),CT=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),IN=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),PT=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),LT=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),zT=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),eo=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),NT=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),RT=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),$T=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),DT=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),BT=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),UT=new Map([["wavlm","WavLMForXVector"]]),FT=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),GT=new Map([["vitmatte","VitMatteForImageMatting"]]),CN=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),jT=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),qT=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),WT=new Map([["sapiens","SapiensForNormalEstimation"]]),VT=new Map([["vitpose","VitPoseForPoseEstimation"]]),HT=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),L1=[[AN,K.EncoderOnly],[TN,K.EncoderDecoder],[SN,K.DecoderOnlyWithoutHead],[MN,K.AutoEncoder],[kT,K.EncoderOnly],[ET,K.EncoderOnly],[AT,K.Seq2Seq],[yT,K.Seq2Seq],[TT,K.DecoderOnly],[ON,K.MultiModality],[MT,K.EncoderOnly],[ST,K.EncoderOnly],[OT,K.Vision2Seq],[IT,K.ImageTextToText],[CT,K.AudioTextToText],[PT,K.EncoderOnly],[eo,K.EncoderOnly],[RT,K.EncoderOnly],[NT,K.EncoderOnly],[GT,K.EncoderOnly],[CN,K.EncoderOnly],[jT,K.EncoderOnly],[qT,K.EncoderOnly],[WT,K.EncoderOnly],[VT,K.EncoderOnly],[LT,K.EncoderOnly],[zT,K.EncoderOnly],[$T,K.MaskGeneration],[DT,K.EncoderOnly],[BT,K.EncoderOnly],[bT,K.Seq2Seq],[vT,K.EncoderOnly],[UT,K.EncoderOnly],[FT,K.EncoderOnly],[HT,K.EncoderOnly]];for(let[t,e]of L1)for(let r of t.values()){tr.set(r,e);let s=il[r];zs.set(s,r),hu.set(r,s)}var PN=[["MusicgenForConditionalGeneration",fi,K.Musicgen],["Phi3VForCausalLM",Si,K.Phi3V],["CLIPTextModelWithProjection",oa,K.EncoderOnly],["SiglipTextModel",ji,K.EncoderOnly],["JinaCLIPTextModel",Ha,K.EncoderOnly],["ClapTextModelWithProjection",sa,K.EncoderOnly],["ClapAudioModelWithProjection",na,K.EncoderOnly],["DacEncoderModel",ma,K.EncoderOnly],["DacDecoderModel",_a,K.EncoderOnly],["MimiEncoderModel",ti,K.EncoderOnly],["MimiDecoderModel",ri,K.EncoderOnly],["SnacEncoderModel",Wi,K.EncoderOnly],["SnacDecoderModel",Vi,K.EncoderOnly],["Gemma3nForConditionalGeneration",Dn,K.ImageAudioTextToText],["SupertonicForConditionalGeneration",Yi,K.Supertonic],["ChatterboxModel",ra,K.Chatterbox],["Qwen2VLForCausalLM",Ds,K.MultimodalLanguageModelOnly],["Qwen2_5_VLForCausalLM",Us,K.MultimodalLanguageModelOnly],["Qwen3VLForCausalLM",Vs,K.MultimodalLanguageModelOnly],["Qwen3VLMoeForCausalLM",Ri,K.MultimodalLanguageModelOnly],["Qwen3_5ForCausalLM",Hs,K.MultimodalLanguageModelOnly],["Qwen3_5MoeForCausalLM",$i,K.MultimodalLanguageModelOnly],["Gemma3nForCausalLM",Ia,K.MultimodalLanguageModelOnly],["VoxtralRealtimeForConditionalGeneration",sl,K.VoxtralRealtime]];for(let[t,e,r]of PN)tr.set(t,r),zs.set(e,t),hu.set(t,e);var XT=new Map([["modnet",eo],["birefnet",eo],["isnet",eo],["ben",eo]]);for(let[t,e]of XT.entries())e.set(t,"PreTrainedModel"),tr.set(t,K.EncoderOnly),hu.set(t,y);var KT=new Set(XT.keys());tr.set("PreTrainedModel",K.EncoderOnly);zs.set(y,"PreTrainedModel");var Pe={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:kT,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:ET,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:bT,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:vT,MODEL_FOR_MASKED_LM_MAPPING_NAMES:MT,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:ST,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:PT,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:eo,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:NT,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:RT,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:LT,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:zT,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:$T,MODEL_FOR_CTC_MAPPING_NAMES:DT,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:BT,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:UT,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:FT,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:IN,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:GT,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:jT,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:qT,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:WT,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:VT,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:HT,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:IT,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:CT,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:AT,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:yT,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:TT,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:OT};mT(Pe);var Se=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let r of this.MODEL_CLASS_MAPPINGS)if(r.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:p=null,use_external_data_format:d=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:p,use_external_data_format:d,session_options:m};if(_.config=await jt.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 k=x.get(w);if(!k){for(let b of x.values())if(b[0]===w){k=b;break}if(!k)continue}return await il[k].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return KT.has(w)||Z.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,_);throw Error(`Unsupported model type: ${w}`)}},Er=class extends Se{static MODEL_CLASS_MAPPINGS=L1.map(e=>e[0]);static BASE_IF_FAIL=!0},ll=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},_p=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},to=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},hp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},gp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},wp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},xp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},yp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},bp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},vp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},kp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},cl=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},ul=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},pl=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},Ep=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Ap=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},YT=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},Tp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_CTC_MAPPING_NAMES]},Mp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},QT=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},JT=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},Sp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},ZT=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},Op=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},Ip=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},eM=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},tM=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},Cp=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},rM=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},sM=class extends Se{static MODEL_CLASS_MAPPINGS=[Pe.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function Je(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Ye.read(e)))}async function is(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?km(r,e):r instanceof Float64Array?new Float32Array(r):r))}function dl(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 fe=class extends et{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 fl=class extends fe{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 R("float32",Ne(c.data),c.dims),l=[];for(let c of n.logits){let p=i(c),d=await er(p,r),m=d[0].tolist(),w=d[1].tolist().map((x,k)=>({label:a?a[x]:`LABEL_${x}`,score:m[k]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var ml=class extends fe{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;c<a.dims[0];++c){let p=n.input_ids[c],d=a[c],m=[];for(let _=0;_<d.dims[0];++_){let w=d[_],x=Oe(w.data)[1],k=i?i[x]:`LABEL_${x}`;if(r.includes(k))continue;let b=this.tokenizer.decode([p[_].item()],{skip_special_tokens:!0});if(b==="")continue;let A=Ne(w.data);m.push({entity:k,score:A[x],index:_,word:b})}l.push(m)}return s?l:l[0]}};var _l=class extends fe{async _call(e,r,{top_k:s=1}={}){let n=this.tokenizer(e,{text_pair:r,padding:!0,truncation:!0}),o=Array.isArray(e),{start_logits:a,end_logits:i}=await this.model(n),l=n.input_ids.tolist(),c=n.attention_mask.tolist(),{all_special_ids:p,sep_token_id:d}=this.tokenizer,m=[];for(let _=0;_<a.dims[0];++_){let w=l[_],x=w.findIndex(O=>O==d),k=a[_].tolist(),b=i[_].tolist();for(let O=1;O<k.length;++O)(c[_]==0||O<=x||p.findIndex(E=>E==w[O])!==-1)&&(k[O]=-1/0,b[O]=-1/0);let A=Ne(k).map((O,E)=>[O,E]),S=Ne(b).map((O,E)=>[O,E]);A[0][0]=0,S[0][0]=0;let M=Yk(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,E)=>E[2]-O[2]),P=[];for(let O=0;O<Math.min(M.length,s);++O){let[E,W,X]=M[O],U=w.slice(E,W+1),H=this.tokenizer.decode(U,{skip_special_tokens:!0});P.push({answer:H,score:X})}s===1?m.push(...P):m.push(P)}return o?m:m[0]}};var hl=class extends fe{async _call(e,{top_k:r=5}={}){let{mask_token_id:s,mask_token:n}=this.tokenizer,o=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(o),i=[],l=o.input_ids.tolist();for(let c=0;c<l.length;++c){let p=l[c],d=p.findIndex(k=>k==s);if(d===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][d],_=await er(new R("float32",Ne(m.data),m.dims),r),w=_[0].tolist(),x=_[1].tolist();i.push(x.map((k,b)=>{let A=p.slice();return A[d]=k,{score:w[b],token:Number(k),token_str:this.tokenizer.decode([k]),sequence:this.tokenizer.decode(A,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Ar=class extends fe{_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 gl=class extends Ar{_key="summary_text"};var wl=class extends Ar{_key="translation_text"};function nM(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var xl=class extends fe{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(nM(e))e=[e];else if(Array.isArray(e)&&e.every(nM))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}),p=await this.model.generate({...c,...r}),d=this.tokenizer.batch_decode(p,{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<d.length;++w){let x=Math.floor(w/p.dims[0]*e.length);m&&(d[w]=d[w].slice(m[x])),_[x].push({generated_text:n?[...e[x],{role:"assistant",content:d[w]}]:d[w]})}return!s&&_.length===1?_[0]:_}};var yl=class extends fe{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([r,s])=>[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(Z.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&&(Z.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let p=[];for(let _ of a){let w=this.tokenizer(c,{text_pair:_,padding:!0,truncation:!0}),x=await this.model(w);i?p.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):p.push(x.logits.data[this.entailment_id])}let m=(i?p.map(_=>Ne(_)[1]):Ne(p)).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 bl=class extends fe{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await is(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),p=(await this.model(l)).logits[0],d=await er(new R("float32",Ne(p.data),p.dims),r),m=d[0].tolist(),w=d[1].tolist().map((x,k)=>({label:o?o[x]:`LABEL_${x}`,score:m[k]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var vl=class extends fe{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(p=>s.replace("{}",p)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await is(e,i),c=[];for(let p of l){let d=await this.processor(p),m=await this.model({...a,...d}),_=Ne(m.logits_per_audio.data);c.push([..._].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var kl=class extends fe{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);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&Z.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&Z.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 is(n,o),i=[];for(let l of a){let c=await this.processor(l),d=(await this.model(c)).logits[0],m=[];for(let w of d)m.push(Oe(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=!1);let l=!Array.isArray(e),c=l?[e]:e,p=this.processor.feature_extractor.config,d=p.chunk_length/this.model.config.max_source_positions,m=p.hop_length,_=p.sampling_rate,w=await is(c,_),x=[];for(let k 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,P=_*a,O=M-2*P,E=0;for(;;){let W=E+M,X=k.subarray(E,W),U=await this.processor(X),H=E===0,j=W>=k.length;if(b.push({stride:[X.length,H?0:P,j?0:P],input_features:U.input_features,is_last:j}),j)break;E+=O}}else b=[{stride:[k.length,0,0],input_features:(await this.processor(k)).input_features,is_last:!0}];for(let M of b){i.num_frames=Math.floor(M.stride[0]/m);let P=await this.model.generate({inputs:M.input_features,...i});s==="word"?(M.tokens=P.sequences.tolist()[0],M.token_timestamps=P.token_timestamps.tolist()[0].map(O=>hs(O,2))):M.tokens=P[0].tolist(),M.stride=M.stride.map(O=>O/_)}let[A,S]=this.tokenizer._decode_asr(b,{time_precision:d,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 is(n,o),i=[];for(let l of a){let c=await this.processor(l),p=Math.floor(l.length/o)*6,d=await this.model.generate({max_new_tokens:p,...r,...c}),m=this.processor.batch_decode(d,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}};var El=class extends fe{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 R("float32",e,[e.length]);else if(!(e instanceof R))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,c=[];for(let p=0;p<a;++p){let d=l?Math.min(Math.ceil(l[p]),i):i,m=p*i;c.push(new No(o.slice(m,m+d),s))}return Array.isArray(e)?c:c[0]}async _call(e,r){return this.processor?this._call_text_to_spectrogram(e,r):this.model.config.model_type==="supertonic"?this._call_supertonic(e,r):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:r,num_inference_steps:s,speed:n}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:o,style_dim:a}=this.model.config,i=this.tokenizer(e,{padding:!0,truncation:!0}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,a);let{waveform:c,durations:p}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(e,c,o,p)}async _call_text_to_waveform(e){let r=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(r),n=this.model.config.sampling_rate;return this._postprocess_waveform(e,s,n)}async _call_text_to_spectrogram(e,{speaker_embeddings:r}){this.vocoder||(Z.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Er.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:s}=this.tokenizer(e,{padding:!0,truncation:!0}),n=s.dims[0];r=await this._prepare_speaker_embeddings(r,n),r=r.view(n,-1);let{waveform:o}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,o,a)}};var Al=class extends fe{async _call(e,r={}){let s=Array.isArray(e),n=await Je(e),{pixel_values:o}=await this.processor(n),a=[];for(let i of o){i.dims=[1,...i.dims];let l=await this.model.generate({inputs:i,...r}),c=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(p=>({generated_text:p.trim()}));a.push(c)}return s?a:a[0]}};var Tl=class extends fe{async _call(e,{top_k:r=5}={}){let s=await Je(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 er(new R("float32",Ne(l.data),l.dims),r),p=c[0].tolist(),m=c[1].tolist().map((_,w)=>({label:a?a[_]:`LABEL_${_}`,score:p[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var oM={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Ys=class extends fe{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 Je(e),p=c.map(A=>[A.height,A.width]),d=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 d)throw Error(`Input name ${A} already exists in the inputs.`);d[A]=d.pixel_values}let w=await this.model(d),x=null;if(i!==null)x=oM[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(oM))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=A;break}}let k=this.model.config.id2label,b=[];if(i)if(i==="panoptic"||i==="instance"){let A=x(w,r,s,n,o,a??p)[0],S=A.segmentation;for(let M of A.segments_info){let P=new Uint8ClampedArray(S.data.length);for(let E=0;E<S.data.length;++E)S.data[E]===M.id&&(P[E]=255);let O=new Ye(P,S.dims[1],S.dims[0],1);b.push({score:M.score,label:k[M.label_id],mask:O})}}else if(i==="semantic"){let{segmentation:A,labels:S}=x(w,a??p)[0];for(let M of S){let P=new Uint8ClampedArray(A.data.length);for(let E=0;E<A.data.length;++E)A.data[E]===M&&(P[E]=255);let O=new Ye(P,A.dims[1],A.dims[0],1);b.push({score:null,label:k[M],mask:O})}}else throw Error(`Subtask ${i} not supported.`);else{let S=w[_[0]];for(let M=0;M<p.length;++M){let P=p[M],O=S[M];O.data.some(W=>W<-1e-5||W>1+1e-5)&&O.sigmoid_();let E=await Ye.fromTensor(O.mul_(255).to("uint8")).resize(P[1],P[0]);b.push({label:null,score:null,mask:E})}}return b}};var Ml=class extends Ys{async _call(e,r={}){let s=await Je(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 Sl=class extends fe{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await Je(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}),p=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Ne(m.data),d=[];for(let m of c.logits_per_image){let w=[...p(m)].map((x,k)=>({score:x,label:r[k]}));w.sort((x,k)=>k.score-x.score),d.push(w)}return n?d:d[0]}};var Ol=class extends fe{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 Je(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}),p=this.processor.image_processor.post_process_object_detection(c,r,a),{id2label:d}=this.model.config,m=p.map(_=>_.boxes.map((w,x)=>({score:_.scores[x],label:d[_.classes[x]],box:dl(w,!s)})));return n?m:m[0]}};var Il=class extends fe{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await Je(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=await this.processor(i),p=[];for(let d=0;d<i.length;++d){let m=i[d],_=o?null:[[m.height,m.width]],w=c.pixel_values[d].unsqueeze_(0),x=await this.model({...l,pixel_values:w}),k;if("post_process_grounded_object_detection"in this.processor){let b=this.processor.post_process_grounded_object_detection(x,l.input_ids,{box_threshold:s,text_threshold:s,target_sizes:_})[0];k=b.boxes.map((A,S)=>({score:b.scores[S],label:b.labels[S],box:dl(A,!o)}))}else{let b=this.processor.image_processor.post_process_object_detection(x,s,_,!0)[0];k=b.boxes.map((A,S)=>({score:b.scores[S],label:r[b.classes[S]],box:dl(A,!o)}))}k.sort((b,A)=>A.score-b.score),n!==null&&(k=k.slice(0,n)),p.push(k)}return a?p:p[0]}};var Cl=class extends fe{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 Je(e))[0],{pixel_values:o}=await this.processor(n),a=`<s_docvqa><s_question>${r}</s_question><s_answer>`,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}),p=this.tokenizer.batch_decode(l)[0].match(/<s_answer>(.*?)<\/s_answer>/),d=null;return p&&p.length>=2&&(d=p[1].trim()),[{answer:d}]}};var Pl=class extends fe{async _call(e){let r=await Je(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(Ye.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var Ll=class extends fe{async _call(e){let r=await Je(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a<r.length;++a){let i=n[a],[l,c]=i.dims.slice(-2),[p,d]=r[a].size,m=(await vt(i.view(1,1,l,c),{size:[d,p],mode:"bilinear"})).view(d,p),_=m.min().item(),w=m.max().item(),x=m.sub(_).div_(w-_).mul_(255).to("uint8").unsqueeze(0),k=Ye.fromTensor(x);o.push({predicted_depth:m,depth:k})}return Array.isArray(e)?o:o[0]}};var zl=class extends fe{async _call(e,{pooling:r="none",normalize:s=!1,quantize:n=!1,precision:o="binary"}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(a),l=i.last_hidden_state??i.logits??i.token_embeddings;switch(r){case"none":break;case"mean":l=B2(l,a.attention_mask);break;case"first_token":case"cls":l=l.slice(null,0);break;case"last_token":case"eos":l=l.slice(null,-1);break;default:throw Error(`Pooling method '${r}' not supported.`)}return s&&(l=l.normalize(2,-1)),n&&(l=F2(l,o)),l}};var Nl=class extends fe{async _call(e,{pool:r=null}={}){let s=await Je(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),a;if(r){if(!("pooler_output"in o))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=o.pooler_output}else a=o.last_hidden_state??o.logits??o.image_embeds;return a}};var ro=Object.freeze({"text-classification":{pipeline:fl,model:ll,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:ml,model:_p,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:_l,model:bp,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:hl,model:yp,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:gl,model:to,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:wl,model:to,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:Ar,model:to,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:xl,model:xp,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:yl,model:ll,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:bl,model:Mp,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:vl,model:Er,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:kl,model:[hp,Tp],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:El,model:[wp,gp],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:Al,model:vp,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Tl,model:kp,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Ys,model:[cl,ul,pl],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:Ml,model:[cl,ul,pl],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:Sl,model:Er,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:Ol,model:Ep,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:Il,model:Ap,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:Cl,model:Sp,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Pl,model:Op,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ll,model:Ip,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:zl,model:Er,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:Nl,model:[Cp,Er],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),Pp=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});function LN(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return jt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=JSON.stringify([t,r,s,n]);return nc(o,()=>jt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n}))}async function Lp(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await LN(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,p=r??a.dtype,d,m=e.architectures||[],_=!1;for(let b of m){let A=tr.get(b);if(A!==void 0){d=A,_=!0;break}}if(!_&&e.model_type){let b=tr.get(e.model_type);if(b!==void 0&&(d=b,_=!0),!_){for(let A of Object.values(Ls))if(A.has(e.model_type)){d=tr.get(A.get(e.model_type)),_=!0;break}}}if(!_){let b=m.length>0?m.join(", "):"(none)";Z.warn(`[get_model_files] Architecture(s) not found in MODEL_TYPE_MAPPING: [${b}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${jr}`),d=K.EncoderOnly}let w=(b,A=null)=>{A=A??b;let S=kc(c,b),M=Ec(p,b,S),P=Oo[M]??"",O=`${A}${P}.onnx`,E=l?`${l}/${O}`:O;o.push(E);let W=th(i,O,b);for(let X of rh(O,W)){let U=l?`${l}/${X}`:X;o.push(U)}},{sessions:x,optional_configs:k}=_T(d,e,{model_file_name:n});for(let[b,A]of Object.entries(x))w(b,A);if(k)for(let b of Object.values(k))o.push(b);return o}async function zp(t){if(!t)throw new Error("modelId is required");return(await cr(t,kr,{})).exists?[kr]:[]}async function Tr(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null,include_tokenizer:o=!0,include_processor:a=!0}={}){let i=await Lp(t,{config:e,dtype:r,device:s,model_file_name:n});if(o){let l=await hn(t);i.push(...l)}if(a){let l=await zp(t);i.push(...l)}return i}async function Mr(t,e,r={}){t=Pp[t]??t;let s=ro[t];if(!s)throw new Error(`Unsupported pipeline task: ${t}. Must be one of [${Object.keys(ro).join(", ")}]`);let{type:n}=s;return Tr(e,{...r,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"})}async function Jie(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:p=null,model_file_name:d=null,session_options:m={}}={}){t=Pp[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,Z.info(`No model specified. Using default model: "${e}".`),!l&&_.default.dtype&&(l=_.default.dtype));let w=await Mr(t,e,{device:i,dtype:l}),x={};r&&(await Promise.all(w.map(async H=>cr(e,H)))).forEach((H,j)=>{H.exists&&(x[w[j]]={loaded:0,total:H.size??0})});let k={progress_callback:r?U=>{if(U.status==="progress"){x[U.file]={loaded:U.loaded,total:U.total};let H=Object.values(x).reduce(($,C)=>$+C.loaded,0),j=Object.values(x).reduce(($,C)=>$+C.total,0),Y=j>0?H/j*100:0;r({status:"progress_total",name:U.name,progress:Y,loaded:H,total:j,files:structuredClone(x)})}r(U)}:void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:p,model_file_name:d,session_options:m},b=w.includes("tokenizer.json"),A=w.includes("preprocessor_config.json"),S=_.model,M;if(Array.isArray(S)){let U=s??await jt.from_pretrained(e,k),{model_type:H}=U,j=S.find(Y=>Y.supports(H));if(!j)throw Error(`Unsupported model type "${H}" for task "${t}". None of the candidate model classes support this type.`);M=j.from_pretrained(e,{...k,config:U})}else M=S.from_pretrained(e,k);let[P,O,E]=await Promise.all([b?oe.from_pretrained(e,k):null,A?tu.from_pretrained(e,k):null,M]),W={task:t,model:E};P&&(W.tokenizer=P),O&&(W.processor=O),yr(r,{status:"ready",task:t,model:e});let X=_.pipeline;return new X(W)}var zN=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,z1=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},aM=ie.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),N1=class extends z1{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??aM,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(`
|
|
26
|
-
`)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&
|
|
27
|
-
`)}},iM=class extends N1{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:c=!0,decode_kwargs:p={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,callback_function:s,token_callback_function:n,decode_kwargs:p}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var Rl=class{constructor(e,r){this.image=e,this.timestamp=r}},Np=class{constructor(e,r){e.length>0&&e[0]instanceof Ye&&(e=e.map((s,n)=>new Rl(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 NN(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(d=>n.onloadedmetadata=d),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 d=0;d<a;++d)l.push(e===1?o/2:d*i);let c=document.createElement("canvas");c.width=n.videoWidth,c.height=n.videoHeight;let p=c.getContext("2d",{willReadFrequently:!0});for(let d of l){n.currentTime=d,await new Promise(x=>{n.onseeked=x}),p.drawImage(n,0,0,c.width,c.height);let m=p.getImageData(0,0,c.width,c.height),_=new Ye(m.data,c.width,c.height,4),w=new Rl(_,d);s.push(w)}return n.remove(),new Np(s,o)}async function Rp(t,e,r={}){let s=await Jt(r?.cache_dir);if(!s)return{allCached:!1,files:e.map(a=>({file:a,cached:!1}))};let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=zr(t,o,r,s),l=await Nr(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function lM(t,e,r={}){let s=await Jt(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=zr(t,e,r,s);return!!await Nr(s,n,o)}async function cM(t,e={}){if(!t)throw new Error("modelId is required");if(!await lM(t,"config.json",e))return!1;let r=await Tr(t,e);return(await Rp(t,r,e)).allCached}async function uM(t,e={}){if(!t)throw new Error("modelId is required");let r=await Tr(t,e);return await Rp(t,r,e)}async function pM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await lM(e,"config.json",r))return!1;let s=await Mr(t,e,r);return(await Rp(e,s,r)).allCached}async function dM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Mr(t,e,r);return await Rp(e,s,r)}async function fM(t,e,r={}){let s=await Jt(r?.cache_dir);if(!s)return{filesDeleted:0,filesCached:0,files:e.map(o=>({file:o,deleted:!1,wasCached:!1}))};if(!s.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=zr(t,o,r,s),c=!!await Nr(s,a,i),p=!1;if(c){let d=await s.delete(i),m=!d&&i!==a?await s.delete(a):!1;p=d||m}return{file:o,deleted:p,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function mM(t,e={}){if(!t)throw new Error("modelId is required");let r=await Tr(t,e);return await fM(t,r,e)}async function _M(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Mr(t,e,r);return await fM(e,s,r)}var R1=class{static async get_files(e,r={}){return Tr(e,r)}static async get_pipeline_files(e,r,s={}){return Mr(e,r,s)}static async get_model_files(e,r={}){return Lp(e,r)}static async get_tokenizer_files(e){return hn(e)}static async get_processor_files(e){return zp(e)}static async is_cached(e,r={}){return cM(e,r)}static async is_cached_files(e,r={}){return uM(e,r)}static async is_pipeline_cached(e,r,s={}){return pM(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return dM(e,r,s)}static async get_file_metadata(e,r,s={}){return cr(e,r,s)}static async clear_cache(e,r={}){return mM(e,r)}static async clear_pipeline_cache(e,r,s={}){return _M(e,r,s)}};export{Em as ASTFeatureExtractor,bh as ASTForAudioClassification,yh as ASTModel,Qo as ASTPreTrainedModel,gh as AfmoeForCausalLM,hh as AfmoeModel,Ko as AfmoePreTrainedModel,fh as AlbertForMaskedLM,dh as AlbertForQuestionAnswering,ph as AlbertForSequenceClassification,uh as AlbertModel,Ns as AlbertPreTrainedModel,Cf as AlbertTokenizer,_h as ApertusForCausalLM,mh as ApertusModel,Xo as ApertusPreTrainedModel,xh as ArceeForCausalLM,wh as ArceeModel,Yo as ArceePreTrainedModel,bl as AudioClassificationPipeline,jt as AutoConfig,Xe as AutoFeatureExtractor,Ce as AutoImageProcessor,Er as AutoModel,Mp as AutoModelForAudioClassification,JT as AutoModelForAudioFrameClassification,sM as AutoModelForAudioTextToText,Tp as AutoModelForCTC,xp as AutoModelForCausalLM,Ip as AutoModelForDepthEstimation,Sp as AutoModelForDocumentQuestionAnswering,kp as AutoModelForImageClassification,Cp as AutoModelForImageFeatureExtraction,ZT as AutoModelForImageMatting,cl as AutoModelForImageSegmentation,rM as AutoModelForImageTextToText,Op as AutoModelForImageToImage,YT as AutoModelForMaskGeneration,yp as AutoModelForMaskedLM,eM as AutoModelForNormalEstimation,Ep as AutoModelForObjectDetection,tM as AutoModelForPoseEstimation,bp as AutoModelForQuestionAnswering,ul as AutoModelForSemanticSegmentation,to as AutoModelForSeq2SeqLM,ll as AutoModelForSequenceClassification,hp as AutoModelForSpeechSeq2Seq,gp as AutoModelForTextToSpectrogram,wp as AutoModelForTextToWaveform,_p as AutoModelForTokenClassification,pl as AutoModelForUniversalSegmentation,vp as AutoModelForVision2Seq,QT as AutoModelForXVector,Ap as AutoModelForZeroShotObjectDetection,tu as AutoProcessor,oe as AutoTokenizer,kl as AutomaticSpeechRecognitionPipeline,Ml as BackgroundRemovalPipeline,kh as BartForConditionalGeneration,Eh as BartForSequenceClassification,vh as BartModel,Ln as BartPretrainedModel,Pf as BartTokenizer,z1 as BaseStreamer,Um as BeitFeatureExtractor,Th as BeitForImageClassification,Ah as BeitModel,Jo as BeitPreTrainedModel,Sh as BertForMaskedLM,Ch as BertForQuestionAnswering,Oh as BertForSequenceClassification,Ih as BertForTokenClassification,Mh as BertModel,Hr as BertPreTrainedModel,Lf as BertTokenizer,Fm as BitImageProcessor,Lh as BlenderbotForConditionalGeneration,Ph as BlenderbotModel,Zo as BlenderbotPreTrainedModel,Nh as BlenderbotSmallForConditionalGeneration,zh as BlenderbotSmallModel,ea as BlenderbotSmallPreTrainedModel,zf as BlenderbotSmallTokenizer,Nf as BlenderbotTokenizer,$h as BloomForCausalLM,Rh as BloomModel,ta as BloomPreTrainedModel,Rf as BloomTokenizer,qh as CHMv2ForDepthEstimation,jm as CHMv2ImageProcessor,yu as CHMv2PreTrainedModel,qm as CLIPFeatureExtractor,Nc as CLIPImageProcessor,Vh as CLIPModel,dr as CLIPPreTrainedModel,Qh as CLIPSegForImageSegmentation,Yh as CLIPSegModel,aa as CLIPSegPreTrainedModel,Hh as CLIPTextModel,oa as CLIPTextModelWithProjection,Df as CLIPTokenizer,Xh as CLIPVisionModel,Kh as CLIPVisionModelWithProjection,Bh as CamembertForMaskedLM,Gh as CamembertForQuestionAnswering,Uh as CamembertForSequenceClassification,Fh as CamembertForTokenClassification,Dh as CamembertModel,Xr as CamembertPreTrainedModel,$f as CamembertTokenizer,Am as ChatterboxFeatureExtractor,ra as ChatterboxModel,wu as ChatterboxPreTrainedModel,Dm as ChatterboxProcessor,Gm as ChineseCLIPFeatureExtractor,jh as ChineseCLIPModel,xu as ChineseCLIPPreTrainedModel,na as ClapAudioModelWithProjection,Tm as ClapFeatureExtractor,Wh as ClapModel,zn as ClapPreTrainedModel,sa as ClapTextModelWithProjection,pu as ClassifierFreeGuidanceLogitsProcessor,Zh as CodeGenForCausalLM,Jh as CodeGenModel,ia as CodeGenPreTrainedModel,Uf as CodeGenTokenizer,Bf as CodeLlamaTokenizer,sg as Cohere2ForCausalLM,rg as Cohere2Model,ca as Cohere2PreTrainedModel,tg as CohereForCausalLM,eg as CohereModel,la as CoherePreTrainedModel,Ff as CohereTokenizer,og as ConvBertForMaskedLM,lg as ConvBertForQuestionAnswering,ag as ConvBertForSequenceClassification,ig as ConvBertForTokenClassification,ng as ConvBertModel,Kr as ConvBertPreTrainedModel,Gf as ConvBertTokenizer,Wm as ConvNextFeatureExtractor,ug as ConvNextForImageClassification,Rc as ConvNextImageProcessor,cg as ConvNextModel,ua as ConvNextPreTrainedModel,dg as ConvNextV2ForImageClassification,pg as ConvNextV2Model,pa as ConvNextV2PreTrainedModel,hg as DFineForObjectDetection,_g as DFineModel,fa as DFinePreTrainedModel,Gg as DINOv3ConvNextModel,Mu as DINOv3ConvNextPreTrainedModel,Xm as DINOv3ViTImageProcessor,jg as DINOv3ViTModel,Su as DINOv3ViTPreTrainedModel,Ym as DPTFeatureExtractor,Qg as DPTForDepthEstimation,Bc as DPTImageProcessor,Yg as DPTModel,ya as DPTPreTrainedModel,_a as DacDecoderModel,vu as DacDecoderOutput,ma as DacEncoderModel,bu as DacEncoderOutput,$o as DacFeatureExtractor,gg as DacModel,Nn as DacPreTrainedModel,xg as DebertaForMaskedLM,vg as DebertaForQuestionAnswering,yg as DebertaForSequenceClassification,bg as DebertaForTokenClassification,wg as DebertaModel,Yr as DebertaPreTrainedModel,qf as DebertaTokenizer,Tg as DebertaV2ForMaskedLM,Og as DebertaV2ForQuestionAnswering,Mg as DebertaV2ForSequenceClassification,Sg as DebertaV2ForTokenClassification,Ag as DebertaV2Model,Qr as DebertaV2PreTrainedModel,jf as DebertaV2Tokenizer,Ig as DecisionTransformerModel,ku as DecisionTransformerPreTrainedModel,Eg as DeepseekV3ForCausalLM,kg as DeepseekV3Model,ha as DeepseekV3PreTrainedModel,Vm as DeiTFeatureExtractor,Pg as DeiTForImageClassification,$c as DeiTImageProcessor,Cg as DeiTModel,ga as DeiTPreTrainedModel,Lg as DepthAnythingForDepthEstimation,Eu as DepthAnythingPreTrainedModel,Ll as DepthEstimationPipeline,zg as DepthProForDepthEstimation,Au as DepthProPreTrainedModel,Hm as DetrFeatureExtractor,Rg as DetrForObjectDetection,$g as DetrForSegmentation,Dc as DetrImageProcessor,Ng as DetrModel,$n as DetrObjectDetectionOutput,Rn as DetrPreTrainedModel,Tu as DetrSegmentationOutput,Bg as Dinov2ForImageClassification,Dg as Dinov2Model,wa as Dinov2PreTrainedModel,Fg as Dinov2WithRegistersForImageClassification,Ug as Dinov2WithRegistersModel,xa as Dinov2WithRegistersPreTrainedModel,Xg as DistilBertForMaskedLM,Hg as DistilBertForQuestionAnswering,Wg as DistilBertForSequenceClassification,Vg as DistilBertForTokenClassification,qg as DistilBertModel,Jr as DistilBertPreTrainedModel,Wf as DistilBertTokenizer,Cl as DocumentQuestionAnsweringPipeline,Km as DonutFeatureExtractor,xn as DonutImageProcessor,Kg as DonutSwinModel,Ou as DonutSwinPreTrainedModel,Wo as DynamicCache,sb as EdgeTamModel,Zg as EfficientNetForImageClassification,Qm as EfficientNetImageProcessor,Jg as EfficientNetModel,ba as EfficientNetPreTrainedModel,tw as ElectraForMaskedLM,nw as ElectraForQuestionAnswering,rw as ElectraForSequenceClassification,sw as ElectraForTokenClassification,ew as ElectraModel,Zr as ElectraPreTrainedModel,Vf as ElectraTokenizer,Ro as EncodecFeatureExtractor,mu as EosTokenCriteria,aw as Ernie4_5ForCausalLM,ow as Ernie4_5Model,va as Ernie4_5PretrainedModel,lw as EsmForMaskedLM,cw as EsmForSequenceClassification,uw as EsmForTokenClassification,iw as EsmModel,Rs as EsmPreTrainedModel,Hf as EsmTokenizer,dw as EuroBertForMaskedLM,fw as EuroBertForSequenceClassification,mw as EuroBertForTokenClassification,pw as EuroBertModel,$s as EuroBertPreTrainedModel,hw as ExaoneForCausalLM,_w as ExaoneModel,ka as ExaonePreTrainedModel,ww as FalconForCausalLM,yw as FalconH1ForCausalLM,xw as FalconH1Model,Aa as FalconH1PreTrainedModel,gw as FalconModel,Ea as FalconPreTrainedModel,Xf as FalconTokenizer,vw as FastViTForImageClassification,bw as FastViTModel,Ta as FastViTPreTrainedModel,zl as FeatureExtractionPipeline,Ee as FeatureExtractor,hl as FillMaskPipeline,kw as Florence2ForConditionalGeneration,Iu as Florence2PreTrainedModel,O_ as Florence2Processor,su as ForcedBOSTokenLogitsProcessor,nu as ForcedEOSTokenLogitsProcessor,Zm as GLPNFeatureExtractor,Rw as GLPNForDepthEstimation,Nw as GLPNModel,La as GLPNPreTrainedModel,Vw as GPT2LMHeadModel,Ww as GPT2Model,Da as GPT2PreTrainedModel,Qf as GPT2Tokenizer,Dw as GPTBigCodeForCausalLM,$w as GPTBigCodeModel,za as GPTBigCodePreTrainedModel,Xw as GPTJForCausalLM,Hw as GPTJModel,Ba as GPTJPreTrainedModel,Uw as GPTNeoForCausalLM,Bw as GPTNeoModel,Na as GPTNeoPreTrainedModel,Gw as GPTNeoXForCausalLM,Fw as GPTNeoXModel,Ra as GPTNeoXPreTrainedModel,Yf as GPTNeoXTokenizer,Mw as Gemma2ForCausalLM,Tw as Gemma2Model,Sa as Gemma2PreTrainedModel,Ow as Gemma3ForCausalLM,Sw as Gemma3Model,Oa as Gemma3PreTrainedModel,Mm as Gemma3nAudioFeatureExtractor,Ia as Gemma3nForCausalLM,Dn as Gemma3nForConditionalGeneration,Cu as Gemma3nPreTrainedModel,I_ as Gemma3nProcessor,Aw as GemmaForCausalLM,Ew as GemmaModel,Ma as GemmaPreTrainedModel,Kf as GemmaTokenizer,Jm as Glm46VImageProcessor,C_ as Glm46VProcessor,Cw as GlmForCausalLM,Iw as GlmModel,Lw as GlmMoeDsaForCausalLM,Pw as GlmMoeDsaModel,Pa as GlmMoeDsaPreTrainedModel,zw as GlmOcrForConditionalGeneration,Ca as GlmPreTrainedModel,qw as GptOssForCausalLM,jw as GptOssModel,$a as GptOssPreTrainedModel,Yw as GraniteForCausalLM,Kw as GraniteModel,Jw as GraniteMoeHybridForCausalLM,Qw as GraniteMoeHybridModel,Fa as GraniteMoeHybridPreTrainedModel,Ua as GranitePreTrainedModel,Sm as GraniteSpeechFeatureExtractor,Zw as GraniteSpeechForConditionalGeneration,P_ as GraniteSpeechProcessor,ex as GroundingDinoForObjectDetection,e_ as GroundingDinoImageProcessor,zu as GroundingDinoPreTrainedModel,L_ as GroundingDinoProcessor,tx as GroupViTModel,Nu as GroupViTPreTrainedModel,sx as HeliumForCausalLM,rx as HeliumModel,Ga as HeliumPreTrainedModel,Jf as HerbertTokenizer,ox as HieraForImageClassification,nx as HieraModel,ja as HieraPreTrainedModel,dx as HubertForCTC,fx as HubertForSequenceClassification,px as HubertModel,ux as HubertPreTrainedModel,_x as HunYuanDenseV1ForCausalLM,mx as HunYuanDenseV1Model,qa as HunYuanDenseV1PreTrainedModel,yx as IJepaForImageClassification,xx as IJepaModel,Wa as IJepaPreTrainedModel,wx as Idefics3ForConditionalGeneration,Uc as Idefics3ImageProcessor,Yc as Idefics3Processor,Tl as ImageClassificationPipeline,Nl as ImageFeatureExtractionPipeline,V as ImageFeatureExtractor,V as ImageProcessor,Ys as ImageSegmentationPipeline,Pl as ImageToImagePipeline,Al as ImageToTextPipeline,dT as InterruptableStoppingCriteria,vx as JAISLMHeadModel,bx as JAISModel,Va as JAISPreTrainedModel,r_ as JinaCLIPImageProcessor,kx as JinaCLIPModel,Un as JinaCLIPPreTrainedModel,N_ as JinaCLIPProcessor,Ha as JinaCLIPTextModel,Ex as JinaCLIPVisionModel,Tx as Lfm2ForCausalLM,Ax as Lfm2Model,Ox as Lfm2MoeForCausalLM,Sx as Lfm2MoeModel,Ka as Lfm2MoePreTrainedModel,Xa as Lfm2PreTrainedModel,Ix as Lfm2VlForConditionalGeneration,s_ as Lfm2VlImageProcessor,R_ as Lfm2VlProcessor,Mx as LightOnOcrForConditionalGeneration,w1 as LiteWhisperForConditionalGeneration,Lx as Llama4ForCausalLM,$u as Llama4PreTrainedModel,Px as LlamaForCausalLM,Cx as LlamaModel,Ya as LlamaPreTrainedModel,Zf as LlamaTokenizer,Ct as LlavaForConditionalGeneration,Ct as LlavaOnevisionForConditionalGeneration,n_ as LlavaOnevisionImageProcessor,Ru as LlavaPreTrainedModel,$_ as LlavaProcessor,gx as LlavaQwen2ForCausalLM,St as LogLevel,qt as LogitsProcessor,Cs as LogitsProcessorList,qo as LogitsWarper,Nx as LongT5ForConditionalGeneration,zx as LongT5Model,Qa as LongT5PreTrainedModel,$x as M2M100ForConditionalGeneration,Rx as M2M100Model,Ja as M2M100PreTrainedModel,em as M2M100Tokenizer,rm as MBart50Tokenizer,Wx as MBartForCausalLM,jx as MBartForConditionalGeneration,qx as MBartForSequenceClassification,Gx as MBartModel,Gs as MBartPreTrainedModel,Po as MBartTokenizer,Cy as MPNetForMaskedLM,zy as MPNetForQuestionAnswering,Py as MPNetForSequenceClassification,Ly as MPNetForTokenClassification,Iy as MPNetModel,es as MPNetPreTrainedModel,om as MPNetTokenizer,Dy as MT5ForConditionalGeneration,$y as MT5Model,pi as MT5PreTrainedModel,Bx as MarianMTModel,Dx as MarianModel,Za as MarianPreTrainedModel,tm as MarianTokenizer,a_ as Mask2FormerImageProcessor,o_ as MaskFormerFeatureExtractor,Fx as MaskFormerForInstanceSegmentation,yn as MaskFormerImageProcessor,Ux as MaskFormerModel,ei as MaskFormerPreTrainedModel,fu as MaxLengthCriteria,Vx as Metric3DForDepthEstimation,Du as Metric3DPreTrainedModel,Hx as Metric3Dv2ForDepthEstimation,Bu as Metric3Dv2PreTrainedModel,Xx as MgpstrForSceneTextRecognition,Uu as MgpstrModelOutput,Fu as MgpstrPreTrainedModel,D_ as MgpstrProcessor,sm as MgpstrTokenizer,ri as MimiDecoderModel,ju as MimiDecoderOutput,ti as MimiEncoderModel,Gu as MimiEncoderOutput,Kx as MimiModel,Fn as MimiPreTrainedModel,lu as MinLengthLogitsProcessor,cu as MinNewTokensLengthLogitsProcessor,Zx as Mistral4ForCausalLM,Jx as Mistral4Model,ni as Mistral4PreTrainedModel,Qx as MistralForCausalLM,Yx as MistralModel,si as MistralPreTrainedModel,ty as MobileBertForMaskedLM,sy as MobileBertForQuestionAnswering,ry as MobileBertForSequenceClassification,ey as MobileBertModel,js as MobileBertPreTrainedModel,nm as MobileBertTokenizer,oy as MobileLLMForCausalLM,ny as MobileLLMModel,oi as MobileLLMPreTrainedModel,i_ as MobileNetV1FeatureExtractor,iy as MobileNetV1ForImageClassification,ly as MobileNetV1ForSemanticSegmentation,Fc as MobileNetV1ImageProcessor,ay as MobileNetV1Model,Gn as MobileNetV1PreTrainedModel,l_ as MobileNetV2FeatureExtractor,uy as MobileNetV2ForImageClassification,py as MobileNetV2ForSemanticSegmentation,Gc as MobileNetV2ImageProcessor,cy as MobileNetV2Model,jn as MobileNetV2PreTrainedModel,c_ as MobileNetV3FeatureExtractor,fy as MobileNetV3ForImageClassification,my as MobileNetV3ForSemanticSegmentation,jc as MobileNetV3ImageProcessor,dy as MobileNetV3Model,qn as MobileNetV3PreTrainedModel,u_ as MobileNetV4FeatureExtractor,hy as MobileNetV4ForImageClassification,gy as MobileNetV4ForSemanticSegmentation,qc as MobileNetV4ImageProcessor,_y as MobileNetV4Model,Wn as MobileNetV4PreTrainedModel,p_ as MobileViTFeatureExtractor,xy as MobileViTForImageClassification,Wc as MobileViTImageProcessor,wy as MobileViTModel,ai as MobileViTPreTrainedModel,by as MobileViTV2ForImageClassification,yy as MobileViTV2Model,ii as MobileViTV2PreTrainedModel,R1 as ModelRegistry,My as ModernBertDecoderForCausalLM,Ty as ModernBertDecoderModel,li as ModernBertDecoderPreTrainedModel,ky as ModernBertForMaskedLM,Ey as ModernBertForSequenceClassification,Ay as ModernBertForTokenClassification,vy as ModernBertModel,qs as ModernBertPreTrainedModel,hx as Moondream1ForConditionalGeneration,Om as MoonshineFeatureExtractor,Oy as MoonshineForConditionalGeneration,Sy as MoonshineModel,ci as MoonshinePreTrainedModel,B_ as MoonshineProcessor,Ry as MptForCausalLM,Ny as MptModel,ui as MptPreTrainedModel,By as MultiModalityCausalLM,qu as MultiModalityPreTrainedModel,Fy as MusicgenForCausalLM,fi as MusicgenForConditionalGeneration,Uy as MusicgenModel,di as MusicgenPreTrainedModel,jy as NanoChatForCausalLM,Gy as NanoChatModel,mi as NanoChatPreTrainedModel,Wy as NemotronHForCausalLM,qy as NemotronHModel,_i as NemotronHPreTrainedModel,Hy as NeoBertForMaskedLM,Yy as NeoBertForQuestionAnswering,Xy as NeoBertForSequenceClassification,Ky as NeoBertForTokenClassification,Vy as NeoBertModel,ts as NeoBertPreTrainedModel,am as NllbTokenizer,uu as NoBadWordsLogitsProcessor,au as NoRepeatNGramLogitsProcessor,Qy as NomicBertModel,Wu as NomicBertPreTrainedModel,d_ as NougatImageProcessor,im as NougatTokenizer,c0 as OPTForCausalLM,l0 as OPTModel,bi as OPTPreTrainedModel,Ol as ObjectDetectionPipeline,t0 as Olmo2ForCausalLM,e0 as Olmo2Model,gi as Olmo2PreTrainedModel,s0 as Olmo3ForCausalLM,r0 as Olmo3Model,wi as Olmo3PreTrainedModel,Zy as OlmoForCausalLM,o0 as OlmoHybridForCausalLM,n0 as OlmoHybridModel,xi as OlmoHybridPreTrainedModel,Jy as OlmoModel,hi as OlmoPreTrainedModel,i0 as OpenELMForCausalLM,a0 as OpenELMModel,yi as OpenELMPreTrainedModel,f_ as OwlViTFeatureExtractor,f0 as OwlViTForObjectDetection,bn as OwlViTImageProcessor,d0 as OwlViTModel,ki as OwlViTPreTrainedModel,U_ as OwlViTProcessor,p0 as Owlv2ForObjectDetection,m_ as Owlv2ImageProcessor,u0 as Owlv2Model,vi as Owlv2PreTrainedModel,m0 as PaliGemmaForConditionalGeneration,F_ as PaliGemmaProcessor,Im as ParakeetFeatureExtractor,_0 as ParakeetForCTC,Vu as ParakeetPreTrainedModel,g0 as PatchTSMixerForPrediction,h0 as PatchTSMixerModel,Ei as PatchTSMixerPreTrainedModel,x0 as PatchTSTForPrediction,w0 as PatchTSTModel,Ai as PatchTSTPreTrainedModel,k0 as Phi3ForCausalLM,v0 as Phi3Model,Mi as Phi3PreTrainedModel,Si as Phi3VForCausalLM,g_ as Phi3VImageProcessor,Hu as Phi3VPreTrainedModel,G_ as Phi3VProcessor,b0 as PhiForCausalLM,y0 as PhiModel,Ti as PhiPreTrainedModel,w_ as PixtralImageProcessor,j_ as PixtralProcessor,y as PreTrainedModel,q as PreTrainedTokenizer,Tn as PretrainedConfig,re as Processor,A0 as PvtForImageClassification,x_ as PvtImageProcessor,E0 as PvtModel,Oi as PvtPreTrainedModel,Do as PyAnnoteFeatureExtractor,M0 as PyAnnoteForAudioFrameClassification,T0 as PyAnnoteModel,Ii as PyAnnotePreTrainedModel,q_ as PyAnnoteProcessor,_l as QuestionAnsweringPipeline,O0 as Qwen2ForCausalLM,S0 as Qwen2Model,C0 as Qwen2MoeForCausalLM,I0 as Qwen2MoeModel,Pi as Qwen2MoePreTrainedModel,Ci as Qwen2PreTrainedModel,lm as Qwen2Tokenizer,Ds as Qwen2VLForCausalLM,Bn as Qwen2VLForConditionalGeneration,Uo as Qwen2VLImageProcessor,Pu as Qwen2VLPreTrainedModel,Os as Qwen2VLProcessor,Us as Qwen2_5_VLForCausalLM,Bs as Qwen2_5_VLForConditionalGeneration,Go as Qwen2_5_VLProcessor,L0 as Qwen3ForCausalLM,P0 as Qwen3Model,N0 as Qwen3MoeForCausalLM,z0 as Qwen3MoeModel,zi as Qwen3MoePreTrainedModel,$0 as Qwen3NextForCausalLM,R0 as Qwen3NextModel,Ni as Qwen3NextPreTrainedModel,Li as Qwen3PreTrainedModel,Vs as Qwen3VLForCausalLM,Ws as Qwen3VLForConditionalGeneration,Ri as Qwen3VLMoeForCausalLM,D0 as Qwen3VLMoeForConditionalGeneration,W_ as Qwen3VLProcessor,Hs as Qwen3_5ForCausalLM,Vn as Qwen3_5ForConditionalGeneration,$i as Qwen3_5MoeForCausalLM,B0 as Qwen3_5MoeForConditionalGeneration,j0 as RFDetrForObjectDetection,G0 as RFDetrModel,Xu as RFDetrObjectDetectionOutput,Bi as RFDetrPreTrainedModel,mg as RTDetrForObjectDetection,y_ as RTDetrImageProcessor,fg as RTDetrModel,fr as RTDetrObjectDetectionOutput,da as RTDetrPreTrainedModel,tb as RTDetrV2ForObjectDetection,eb as RTDetrV2Model,Ku as RTDetrV2ObjectDetectionOutput,Ui as RTDetrV2PreTrainedModel,No as RawAudio,Ye as RawImage,Np as RawVideo,Rl as RawVideoFrame,iu as RepetitionPenaltyLogitsProcessor,F0 as ResNetForImageClassification,U0 as ResNetModel,Di as ResNetPreTrainedModel,Y0 as RoFormerForMaskedLM,Z0 as RoFormerForQuestionAnswering,Q0 as RoFormerForSequenceClassification,J0 as RoFormerForTokenClassification,K0 as RoFormerModel,ss as RoFormerPreTrainedModel,um as RoFormerTokenizer,W0 as RobertaForMaskedLM,X0 as RobertaForQuestionAnswering,V0 as RobertaForSequenceClassification,H0 as RobertaForTokenClassification,q0 as RobertaModel,rs as RobertaPreTrainedModel,cm as RobertaTokenizer,Fo as Sam2ImageProcessor,Ju as Sam2ImageSegmentationOutput,Fi as Sam2Model,Zu as Sam2PreTrainedModel,Qc as Sam2Processor,V_ as Sam2VideoProcessor,Fo as Sam3ImageProcessor,nb as Sam3TrackerModel,Fo as SamImageProcessor,Yu as SamImageSegmentationOutput,rb as SamModel,Qu as SamPreTrainedModel,jo as SamProcessor,b_ as SapiensFeatureExtractor,ab as SapiensForDepthEstimation,ib as SapiensForNormalEstimation,ob as SapiensForSemanticSegmentation,Vc as SapiensImageProcessor,Hn as SapiensPreTrainedModel,Cm as SeamlessM4TFeatureExtractor,v_ as SegformerFeatureExtractor,cb as SegformerForImageClassification,ub as SegformerForSemanticSegmentation,Hc as SegformerImageProcessor,lb as SegformerModel,Xn as SegformerPreTrainedModel,k_ as SiglipImageProcessor,pb as SiglipModel,Gi as SiglipPreTrainedModel,ji as SiglipTextModel,pm as SiglipTokenizer,db as SiglipVisionModel,mb as SmolLM3ForCausalLM,fb as SmolLM3Model,qi as SmolLM3PreTrainedModel,Uc as SmolVLMImageProcessor,Yc as SmolVLMProcessor,Vi as SnacDecoderModel,Wi as SnacEncoderModel,Pm as SnacFeatureExtractor,_b as SnacModel,Kn as SnacPreTrainedModel,gb as SolarOpenForCausalLM,hb as SolarOpenModel,Hi as SolarOpenPreTrainedModel,Lm as SpeechT5FeatureExtractor,xb as SpeechT5ForSpeechToText,yb as SpeechT5ForTextToSpeech,bb as SpeechT5HifiGan,wb as SpeechT5Model,Yn as SpeechT5PreTrainedModel,H_ as SpeechT5Processor,dm as SpeechT5Tokenizer,kb as SqueezeBertForMaskedLM,Ab as SqueezeBertForQuestionAnswering,Eb as SqueezeBertForSequenceClassification,vb as SqueezeBertModel,Xs as SqueezeBertPreTrainedModel,fm as SqueezeBertTokenizer,Mb as StableLmForCausalLM,Tb as StableLmModel,Xi as StableLmPreTrainedModel,Ob as Starcoder2ForCausalLM,Sb as Starcoder2Model,Ki as Starcoder2PreTrainedModel,Vr as StoppingCriteria,On as StoppingCriteriaList,Ib as StyleTextToSpeech2Model,ep as StyleTextToSpeech2PreTrainedModel,gl as SummarizationPipeline,Yi as SupertonicForConditionalGeneration,tp as SupertonicPreTrainedModel,Mn as SuppressTokensAtBeginLogitsProcessor,Nb as Swin2SRForImageSuperResolution,E_ as Swin2SRImageProcessor,zb as Swin2SRModel,Qi as Swin2SRPreTrainedModel,Pb as SwinForImageClassification,Lb as SwinForSemanticSegmentation,Cb as SwinModel,Qn as SwinPreTrainedModel,$b as T5ForConditionalGeneration,Rb as T5Model,Ji as T5PreTrainedModel,mm as T5Tokenizer,Bb as TableTransformerForObjectDetection,Db as TableTransformerModel,rp as TableTransformerObjectDetectionOutput,Zi as TableTransformerPreTrainedModel,du as TemperatureLogitsWarper,R as Tensor,Ar as Text2TextGenerationPipeline,fl as TextClassificationPipeline,xl as TextGenerationPipeline,N1 as TextStreamer,El as TextToAudioPipeline,ml as TokenClassificationPipeline,q as TokenizersBackend,pT as TopKLogitsWarper,uT as TopPLogitsWarper,Ub as TrOCRForCausalLM,sp as TrOCRPreTrainedModel,wl as TranslationPipeline,Fs as UltravoxModel,Lu as UltravoxPreTrainedModel,X_ as UltravoxProcessor,Gb as UniSpeechForCTC,jb as UniSpeechForSequenceClassification,Fb as UniSpeechModel,Jn as UniSpeechPreTrainedModel,Hb as UniSpeechSatForAudioFrameClassification,Wb as UniSpeechSatForCTC,Vb as UniSpeechSatForSequenceClassification,qb as UniSpeechSatModel,Ks as UniSpeechSatPreTrainedModel,z_ as VLChatProcessor,t_ as VLMImageProcessor,Kb as VaultGemmaForCausalLM,Xb as VaultGemmaModel,el as VaultGemmaPreTrainedModel,A_ as ViTFeatureExtractor,Jb as ViTForImageClassification,Xc as ViTImageProcessor,Zb as ViTMAEModel,np as ViTMAEPreTrainedModel,t1 as ViTMSNForImageClassification,e1 as ViTMSNModel,rl as ViTMSNPreTrainedModel,Qb as ViTModel,tl as ViTPreTrainedModel,Yb as VisionEncoderDecoderModel,r1 as VitMatteForImageMatting,T_ as VitMatteImageProcessor,op as VitMattePreTrainedModel,s1 as VitPoseForPoseEstimation,M_ as VitPoseImageProcessor,ap as VitPosePreTrainedModel,n1 as VitsModel,ip as VitsModelOutput,lp as VitsPreTrainedModel,hm as VitsTokenizer,o1 as VoxtralForConditionalGeneration,K_ as VoxtralProcessor,Rm as VoxtralRealtimeFeatureExtractor,sl as VoxtralRealtimeForConditionalGeneration,cp as VoxtralRealtimePreTrainedModel,Q_ as VoxtralRealtimeProcessor,c1 as Wav2Vec2BertForCTC,u1 as Wav2Vec2BertForSequenceClassification,l1 as Wav2Vec2BertModel,Zn as Wav2Vec2BertPreTrainedModel,gm as Wav2Vec2CTCTokenizer,zm as Wav2Vec2FeatureExtractor,cx as Wav2Vec2ForAudioFrameClassification,ix as Wav2Vec2ForCTC,lx as Wav2Vec2ForSequenceClassification,ax as Wav2Vec2Model,rr as Wav2Vec2PreTrainedModel,J_ as Wav2Vec2Processor,Z_ as Wav2Vec2ProcessorWithLM,_1 as WavLMForAudioFrameClassification,d1 as WavLMForCTC,f1 as WavLMForSequenceClassification,m1 as WavLMForXVector,p1 as WavLMModel,ns as WavLMPreTrainedModel,Nm as WeSpeakerFeatureExtractor,h1 as WeSpeakerResNetModel,pp as WeSpeakerResNetPreTrainedModel,$m as WhisperFeatureExtractor,fp as WhisperForConditionalGeneration,g1 as WhisperModel,nl as WhisperPreTrainedModel,eh as WhisperProcessor,iM as WhisperTextStreamer,ou as WhisperTimeStampLogitsProcessor,wm as WhisperTokenizer,k1 as XLMForQuestionAnswering,b1 as XLMForSequenceClassification,v1 as XLMForTokenClassification,x1 as XLMModel,os as XLMPreTrainedModel,A1 as XLMRobertaForMaskedLM,S1 as XLMRobertaForQuestionAnswering,T1 as XLMRobertaForSequenceClassification,M1 as XLMRobertaForTokenClassification,E1 as XLMRobertaModel,as as XLMRobertaPreTrainedModel,xm as XLMRobertaTokenizer,ym as XLMTokenizer,y1 as XLMWithLMHeadModel,up as XVectorOutput,S_ as YolosFeatureExtractor,I1 as YolosForObjectDetection,Kc as YolosImageProcessor,O1 as YolosModel,mp as YolosObjectDetectionOutput,ol as YolosPreTrainedModel,P1 as YoutuForCausalLM,C1 as YoutuModel,al as YoutuPreTrainedModel,vl as ZeroShotAudioClassificationPipeline,yl as ZeroShotClassificationPipeline,Sl as ZeroShotImageClassificationPipeline,Il as ZeroShotObjectDetectionPipeline,ke as cat,GL as cos_sim,BE as dot,me as env,He as full,Co as full_like,Ef as interpolate,vt as interpolate_4d,iD as layer_norm,Wz as load_image,NN as load_video,Td as log_softmax,D2 as matmul,Mc as mean,B2 as mean_pooling,tt as ones,Sc as ones_like,Ez as permute,Jie as pipeline,F2 as quantize_embeddings,lD as rand,U2 as randn,_s as random,km as read_audio,aD as rfft,Tc as slice,Ne as softmax,Ot as stack,Af as std_mean,er as topk,Mf as zeros,Sf as zeros_like};
|
|
27
|
+
${s}${o}`+n.repeat(t)+`${s}`,a}function lN(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function cN(t,e,r,s,n,o){return t===0&&e===0?lN(r,s,n,o):iN(r,t,e,s,n,o)}var qc=class extends re{static image_processor_class=Ae;static tokenizer_class=se;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";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;f<e.length;++f){let m=e[f],_=o[f],w=a[f];l.push(sE(m,this.image_token));let x=_.map((A,S)=>cN(A,w[S],i,this.fake_image_token,this.image_token,this.global_img_token)),b=m.split(this.image_token);if(b.length===0)throw new Error("The image token should be present in the text.");let E=b[0];for(let A=0;A<x.length;++A)E+=x[A]+b[A+1];c.push(E)}return{...this.tokenizer(c),...n}}};var R_=class extends re{static image_processor_class=Ae;static tokenizer_class=se;static uses_processor_config=!0;constructor(e,r,s){super(e,r,s),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(e,{images:r=null,chat_template:s="default"}={}){r?Array.isArray(r)||(r=[r]):r=await Promise.all(e.filter(b=>b.images).flatMap(b=>b.images).map(b=>Ye.read(b)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=b=>n.encode(b,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[c,p,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),m=a(i[0]),_=new Array(m.length).fill(!1);for(let b=1;b<i.length;++b){let E=new Array(this.num_image_tokens).fill(c),A=a(i[b]);m=gt(m,[p],E,[f],A);let S=new Array(this.num_image_tokens).fill(!0);_=gt(_,[!1],S,[!1],new Array(A.length).fill(!1))}let w=[1,m.length],x={input_ids:new R("int64",m,w),attention_mask:new R("int64",new Array(m.length).fill(1),w),images_seq_mask:new R("bool",_,w),images_emb_mask:new R("bool",new Array(l*this.num_image_tokens).fill(!0),[1,l,this.num_image_tokens])};if(r&&r.length>0){let b=await this.image_processor(r);return b.pixel_values.unsqueeze_(0),{...x,...b}}return x}};var $_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;async _call(e=null,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},o=r?await this.image_processor(r,s):{};return{...n,...o}}};var B_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;async _call(e,r=null,s={}){let{image_rows:n,image_cols:o,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(r){let l=this.config.image_token??"<image>",{tile_size:c=512,downsample_factor:p=2,encoder_patch_size:f=16,use_thumbnail:m=!0}=this.image_processor.config,_=S=>Math.ceil(Math.floor(S/f)/p),w=_(c)**2,x=this.config.image_start_token??"<|image_start|>",b=this.config.image_end_token??"<|image_end|>",E=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(P=>{let O=A++,[k,W]=a[O],X=n[O],U=o[O],H=_(k)*_(W),j=x;if(X>1||U>1){let K=l.repeat(w);for(let $=0;$<X;++$)for(let C=0;C<U;++C)j+=`<|img_row_${$+1}_col_${C+1}|>`+K;m&&(j+=E+l.repeat(H))}else j+=l.repeat(H);return j+b+P}).join("")})}return{...i,...r?this.tokenizer(r,s):{}}}};var D_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:c,num_additional_image_tokens:p}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+p;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let m=0;m<r.length;++m)r[m]=r[m].replace(l,l.repeat(f))}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var cT={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},U_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(e,r){if(!cT.hasOwnProperty(r))throw new Error(`Format ${r} is not supported.`);let[s,n]=cT[r],o=this[s].bind(this),[a,i]=e.dims,l=[],c=[],p=e.tolist();for(let m=0;m<a;++m){let _=p[m],w=[],x=[];for(let E=1;E<i;++E){let[A,S]=Ce(Ne(_[E]));if(x.push(A),S==n)break;w.push(S)}let b=x.length>0?x.reduce((E,A)=>E*A,1):0;c.push(w),l.push(b)}return[o(c),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,c]=this._decode_helper(s,"wp"),p=[],f=[];for(let m=0;m<n.length;++m){let[_,w]=Ce([o[m],i[m],c[m]]);p.push([n[m],a[m],l[m]][w]),f.push(_)}return{generated_text:p,scores:f,char_preds:n,bpe_preds:a,wp_preds:l}}static async from_pretrained(...e){let r=await super.from_pretrained(...e),s=await se.from_pretrained("Xenova/gpt2"),n=await se.from_pretrained("Xenova/bert-base-uncased");return r.components={image_processor:r.image_processor,char_tokenizer:r.tokenizer,bpe_tokenizer:s,wp_tokenizer:n},r}async _call(e,r=null){let s=await this.image_processor(e);return r&&(s.labels=this.tokenizer(r).input_ids),s}};var F_=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var G_=class extends re{static tokenizer_class=se;static image_processor_class=Ae};var bn="<image>";function uN(t,e,r,s,n){return`${s.repeat(r*n)}${e}${t}
|
|
28
|
+
`}var j_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;static uses_processor_config=!1;async _call(e,r=null,s={}){r||(Z.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),r=""),Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let n=this.tokenizer.bos_token,o=this.image_processor.config.image_seq_length,a;r.some(c=>c.includes(bn))?a=r.map(c=>{let p=c.replaceAll(bn,bn.repeat(o)),f=p.lastIndexOf(bn),m=f===-1?0:f+bn.length;return p.slice(0,m)+n+p.slice(m)+`
|
|
29
|
+
`}):(Z.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(c=>uN(c,n,o,bn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var uT="<|image|>",pN=/<\|image_\d+\|>/g,q_=class extends re{static image_processor_class=Ae;static tokenizer_class=se;async _call(e,r=null,{padding:s=!0,truncation:n=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(r){i=await this.image_processor(r,{num_crops:o});let{num_img_tokens:l}=i,c=e.map((f,m)=>f.split(pN).join(uT.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id(uT);a.input_ids.map_(f=>f==p?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var W_=class extends re{static tokenizer_class=se;static image_processor_class=Ae;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:c,image_end_token:p,patch_size:f,spatial_merge_size:m}=this.config,_=f*m,w=Math.floor(a/_),x=Math.floor(i/_);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let b=0;b<r.length;++b){let E=l.repeat(x),A=E+c,S=E+p,M=A.repeat(w-1)+S;r[b]=r[b].replace(l,M)}}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var V_=class extends re{static feature_extractor_class=Lo;async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}};var $o=class extends Is{};var H_=class extends $o{};var Bo=class extends re{static image_processor_class=Ae;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}};var Wc=class extends Bo{},X_=class extends Wc{};var K_=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var Y_=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;static uses_processor_config=!0;async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let a=r.length,{input_features:i}=await this.feature_extractor(r,{...s,max_length:a}),l=Math.round(a/this.config.encoder_ds_factor+1e-4),c=1+Math.ceil(l/this.config.stack_factor);n.audio_token_len=[c],n.audio_values=i;let p=this.config.audio_placeholder;if(!e.includes(p))throw new Error(`The input text does not contain the image token ${p}.`);e=e.replaceAll(p,p.repeat(c))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var Vc="[AUDIO]",fN="[BEGIN_AUDIO]",dN=375;function mN(t,e){let r=[];for(let s=0;s<t.length;s+=e)r.push(t.subarray(s,Math.min(s+e,t.length)));return r}var Q_=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;static uses_processor_config=!1;async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){if(!e.includes(Vc))throw new Error(`The input text does not contain the audio token ${Vc}.`);Array.isArray(r)||(r=[r]);let a=e.split(Vc),i=a.length-1;if(i!==r.length)throw new Error(`The number of audio inputs (${r.length}) does not match the number of audio tokens in the text (${i}).`);let l=this.feature_extractor.config.n_samples,c=r.map(w=>mN(w,l)),p=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?ke(m,0):m[0];let _=a[0];for(let w=0;w<p.length;++w){_+=fN;for(let x=0;x<p[w];++x)_+=Vc.repeat(dN);_+=a[w+1]}e=_}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var pT=32,J_=6,Hc=8,_N=10,hN=32,Z_=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(J_+1)*Hc}get num_samples_first_audio_chunk(){let{hop_length:e,n_fft:r}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(r/2)}get num_samples_per_audio_chunk(){let{hop_length:e,n_fft:r}=this.feature_extractor.config;return Hc*e+r}get num_right_pad_tokens(){return J_+1+_N}get audio_length_per_tok(){return Hc}get raw_audio_length_per_tok(){return Hc*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:r=!1,is_first_audio_chunk:s=!0}={}){if($e(e,"VoxtralRealtimeProcessor"),!r&&!s)throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(s)if(r){let n=pT*this.raw_audio_length_per_tok,o=new Float32Array(n+e.length);o.set(e,n);let a=await this.feature_extractor(o,{center:!0}),l=1+(pT+J_),c=new BigInt64Array(l).fill(BigInt(hN));return c[0]=1n,{input_ids:new R("int64",c,[1,l]),...a}}else{let n=this.num_right_pad_tokens*this.raw_audio_length_per_tok,o=new Float32Array(e.length+n);return o.set(e),await this.feature_extractor(o,{center:!0})}else return await this.feature_extractor(e,{center:!1})}};var eh=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var th=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var rh=class extends re{static tokenizer_class=se;static feature_extractor_class=Xe;async _call(e){return await this.feature_extractor(e)}};var Kc=class{static async from_pretrained(e,r={}){let s=await ut(e,kr,!0,r),{image_processor_type:n,feature_extractor_type:o,processor_class:a}=s;if(a&&Xc[a])return Xc[a].from_pretrained(e,r);if(!n&&!o)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let i={};if(n){let c=yn[n.replace(/Fast$/,"")];if(!c)throw new Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new c(s)}if(o){let c=yn[o];if(c)i.image_processor=new c(s);else{let p=zo[o];if(!p)throw new Error(`Unknown feature_extractor_type: '${o}'.`);i.feature_extractor=new p(s)}}let l={};return new re(l,i,null)}};async function gN(t,e){return await ut(t,"config.json",!0,e)}function vn(t){let e={},r={};switch(t.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":r=vn(t.text_config);break;case"moondream1":r=vn(t.phi_config);break;case"musicgen":r=vn(t.decoder);break;case"multi_modality":r=vn(t.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":e.num_heads="num_attention_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.hidden_size="hidden_size",e.num_attention_heads="num_attention_heads",e.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="head_dim";break;case"openelm":e.num_heads="num_kv_heads",e.num_layers="num_transformer_layers",e.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":e.num_heads="num_heads",e.num_layers="num_layers",e.hidden_size="hidden_size";break;case"bloom":e.num_heads="n_head",e.num_layers="n_layer",e.hidden_size="hidden_size";break;case"mpt":e.num_heads="n_heads",e.num_layers="n_layers",e.hidden_size="d_model";break;case"exaone":e.num_heads="num_key_value_heads",e.num_layers="num_layers",e.dim_kv="head_dim",e.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"glm_moe_dsa":case"mistral4":e.num_heads="num_key_value_heads",e.num_layers="num_hidden_layers",e.dim_kv="qk_head_dim",e.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":e.num_decoder_layers="num_decoder_layers",e.num_decoder_heads="num_heads",e.decoder_dim_kv="d_kv",e.num_encoder_layers="num_layers",e.num_encoder_heads="num_heads",e.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="d_model",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="d_model";break;case"speecht5":e.num_decoder_layers="decoder_layers",e.num_decoder_heads="decoder_attention_heads",e.decoder_hidden_size="hidden_size",e.num_encoder_layers="encoder_layers",e.num_encoder_heads="encoder_attention_heads",e.encoder_hidden_size="hidden_size";break;case"trocr":e.num_encoder_layers=e.num_decoder_layers="decoder_layers",e.num_encoder_heads=e.num_decoder_heads="decoder_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="d_model";break;case"musicgen_decoder":e.num_encoder_layers=e.num_decoder_layers="num_hidden_layers",e.num_encoder_heads=e.num_decoder_heads="num_attention_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"moonshine":e.num_decoder_layers="decoder_num_hidden_layers",e.num_decoder_heads="decoder_num_key_value_heads",e.num_encoder_layers="encoder_num_hidden_layers",e.num_encoder_heads="encoder_num_key_value_heads",e.encoder_hidden_size=e.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":let n=vn(t.decoder),o="num_decoder_layers"in n,a=Ke(t,["model_type","is_encoder_decoder"]);return o?(a.num_decoder_layers=n.num_decoder_layers,a.num_decoder_heads=n.num_decoder_heads,a.decoder_hidden_size=n.decoder_hidden_size,a.num_encoder_layers=n.num_encoder_layers,a.num_encoder_heads=n.num_encoder_heads,a.encoder_hidden_size=n.encoder_hidden_size):(a.num_layers=n.num_layers,a.num_heads=n.num_heads,a.hidden_size=n.hidden_size),a}let s={...r,...Ke(t,["model_type","multi_query","is_encoder_decoder"])};for(let n in e)s[n]=t[e[n]];return s}function Cs(t,e){t instanceof kn||(t=new kn(t));let r=e?.batch_size??1;if(["lfm2","lfm2_moe"].includes(t.model_type)){let s=e?.prefix??"past_key_values",n=s==="present"?"present":"past",o={},{layer_types:a,num_attention_heads:i,num_key_value_heads:l,hidden_size:c,conv_L_cache:p}=t,f=c/i;for(let m=0;m<a.length;++m)if(a[m]==="full_attention")for(let _ of["key","value"])o[`${s}.${m}.${_}`]=[r,l,0,f];else if(a[m]==="conv")o[`${n}_conv.${m}`]=[r,c,p];else throw new Error(`Unsupported layer type: ${a[m]}`);return o}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(t.model_type)){let s=e?.prefix??"past_key_values",n=s==="present"?"present":"past",o=t,a=o.layer_types??o.layers_block_type,i=o.num_hidden_layers??a?.length,l=o.num_key_value_heads,c=o.head_dim??o.hidden_size/o.num_attention_heads,p=o.mamba_n_heads??o.mamba_num_heads,f=o.mamba_d_head??o.mamba_head_dim,m=o.mamba_d_state??o.ssm_state_size,_=o.mamba_n_groups??o.n_groups,w=o.mamba_d_conv??o.conv_kernel,b=(o.mamba_d_ssm??(o.mamba_expand?o.mamba_expand*o.hidden_size:p*f))+2*_*m,E={};for(let A=0;A<i;++A)if((!a||a[A]==="mamba")&&(E[`${n}_conv.${A}`]=[r,b,w],E[`${n}_ssm.${A}`]=[r,p,f,m]),!a||a[A]==="attention")for(let S of["key","value"])E[`${s}.${A}.${S}`]=[r,l,0,c];return E}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(t.model_type)){let s=e?.prefix??"past_key_values",n=s==="present"?"present":"past",o={},{head_dim:a,layer_types:i,num_attention_heads:l,num_key_value_heads:c,hidden_size:p,linear_num_value_heads:f,linear_num_key_heads:m,linear_key_head_dim:_,linear_value_head_dim:w,linear_conv_kernel_dim:x}=t,b=_*m,E=w*f,A=a??p/l;for(let S=0;S<i.length;++S)if(i[S]==="full_attention")for(let M of["key","value"])o[`${s}.${S}.${M}`]=[r,c,0,A];else if(i[S]==="linear_attention"){if(t.model_type==="olmo_hybrid")o[`${n}_conv.${S}.key`]=[r,b,x],o[`${n}_conv.${S}.value`]=[r,E,x],o[`${n}_conv.${S}.query`]=[r,b,x];else{let M=b*2+E;o[`${n}_conv.${S}`]=[r,M,x]}o[`${n}_recurrent.${S}`]=[r,f,_,w]}else throw new Error(`Unsupported layer type: ${i[S]}`);return o}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(t.model_type)){let s;return t.model_type==="voxtral_realtime"&&e?.session_name==="audio_encoder"?s=t.audio_config:s=t.text_config,Cs(s,e)}return wN(t,e)}function wN(t,{prefix:e="past_key_values",batch_size:r=1}={}){let s={},n=t.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n){let o=n.encoder_dim_kv??n.encoder_hidden_size/n.num_encoder_heads,a=n.decoder_dim_kv??n.decoder_hidden_size/n.num_decoder_heads,i=[r,n.num_encoder_heads,0,o],l=[r,n.num_decoder_heads,0,a];for(let c=0;c<n.num_decoder_layers;++c)s[`${e}.${c}.encoder.key`]=i,s[`${e}.${c}.encoder.value`]=i,s[`${e}.${c}.decoder.key`]=l,s[`${e}.${c}.decoder.value`]=l}else{let o=n.num_heads,a=n.num_layers,i=n.dim_kv??n.hidden_size/(n.num_attention_heads??o);if(n.model_type==="falcon"){let l=[r*o,0,i];for(let c=0;c<a;++c)s[`${e}.${c}.key`]=l,s[`${e}.${c}.value`]=l}else if(n.multi_query){let l=[r*o,0,2*i];for(let c=0;c<a;++c)s[`${e}.${c}.key_value`]=l}else if(n.model_type==="bloom"){let l=[r*o,i,0],c=[r*o,0,i];for(let p=0;p<a;++p)s[`${e}.${p}.key`]=l,s[`${e}.${p}.value`]=c}else if(n.model_type==="openelm")for(let l=0;l<a;++l){let c=[r,o[l],0,i];s[`${e}.${l}.key`]=c,s[`${e}.${l}.value`]=c}else{let l=[r,o,0,i];for(let c=0;c<a;++c)s[`${e}.${c}.key`]=l,s[`${e}.${c}.value`]=l}}return s}var kn=class t{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=vn(this)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){s&&!(s instanceof t)&&(s=new t(s));let i=s??await gN(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(i)}},qt=class{static async from_pretrained(...e){return kn.from_pretrained(...e)}};function sh(t,e,r){return t?typeof t=="object"&&t!==null?t.hasOwnProperty(e)?+t[e]:t.hasOwnProperty(r)?+t[r]:0:+t:0}function nh(t,e){let r=[];for(let s=0;s<e;++s)r.push(`${t}_data${s===0?"":"_"+s}`);return r}async function fT(t,e,r,s){let n=`${e}${s}.onnx`,o=`${r.subfolder??""}/${n}`;return await fo(t,o,!0,r,ie.IS_NODE_ENV)}async function dT(t,e,r,s,n,o={}){let a=`${e}${r}.onnx`,i=ie.IS_NODE_ENV,l=[],c=sh(n,a,e);if(c>0){if(c>Yl)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${Yl}).`);let p=nh(a,c);for(let f of p){let m=`${s.subfolder??""}/${f}`;l.push(new Promise(async(_,w)=>{let x=await fo(t,m,!0,s,i);_(x instanceof Uint8Array?{path:f,data:x}:f)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async p=>{if(typeof p.data=="string"){let f=await fo(t,p.data,!0,s);return{...p,data:f}}return p}));return Promise.all(l)}async function xN(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=gc(r.device??o.device,e,{warn:M=>Z.info(M)}),i=$2(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=wc(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:M=>Z.info(M)});if(jr.hasOwnProperty(c)){if(a==="webgpu"&&!ie.IS_NODE_ENV&&c===yt.fp16&&!await F2())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 p=o.kv_cache_dtype,f=p?typeof p=="string"?p:p[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=jr[c],_={...r.session_options};_.executionProviders??=i;let w=o.free_dimension_overrides;w?_.freeDimensionOverrides??=w:a.startsWith("webnn")&&!_.freeDimensionOverrides&&Z.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=fT(t,e,r,m),b=r.use_external_data_format??o.use_external_data_format,E=await dT(t,e,m,r,b,_);if(E.length>0&&!ie.IS_NODE_ENV&&(_.externalData=E),s&&a==="webgpu"&&p!==!1){let M=Cs(r.config,{prefix:"present",session_name:n});if(Object.keys(M).length>0&&!Eo()){let P={};for(let O in M)P[O]="gpu-buffer";_.preferredOutputLocation=P}}return{buffer_or_path:await x,session_options:_,session_config:{dtype:c,kv_cache_dtype:f,device:a}}}async function mT(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 xN(t,e[n],r,o,n),c=await mc(a,i,l);return[n,c]})))}function _T(t){for(let e in t)hc(t[e])?t[e]=new R(t[e]):typeof t[e]=="object"&&_T(t[e]);return t}async function fe(t,e){let r=yN(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 _c(t,s);return _T(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 Z.error(`An error occurred during model execution: "${s}".`),Z.error("Inputs given to model:",n),s}}function yN(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof R)){s.push(a);continue}r[a]=Eo()?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));Z.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Re=class{};var G=class extends Re{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},he=class extends Re{constructor({logits:e}){super(),this.logits=e}},ge=class extends Re{constructor({logits:e}){super(),this.logits=e}},Te=class extends Re{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},kt=class extends Re{constructor({logits:e}){super(),this.logits=e}};var Yc=class extends Re{constructor({alphas:e}){super(),this.alphas=e}};var Wt=class extends et{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Do=class extends et{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Ps=class extends et{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()}},Qc=class extends Wt{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===1){let n=r[s].data;n.fill(-1/0),n[this.bos_token_id]=0}return r}},Jc=class extends Wt{constructor(e,r){super(),this.max_length=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){let n=r[s].data;n.fill(-1/0);for(let o of this.eos_token_id)n[o]=0}return r}},En=class extends Wt{constructor(e,r){super(),this.begin_suppress_tokens=e,this.begin_index=r}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){let n=r[s].data;for(let o of this.begin_suppress_tokens)n[o]=-1/0}return r}},Zc=class extends Wt{constructor(e,r){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=r.length,r.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data;if(n[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index-1){n.fill(-1/0),n[this.timestamp_begin]=0;continue}let o=e[s].slice(this.begin_index),a=o.length>=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=Mf(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),p=Ce(l.subarray(0,this.timestamp_begin))[0];c>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},eu=class extends Wt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o<r+1-this.no_repeat_ngram_size;++o){let a=[];for(let i=0;i<this.no_repeat_ngram_size;++i)a.push(e[o+i]);s.push(a.map(Number))}let n=new Map;for(let o of s){let a=o.slice(0,o.length-1),i=JSON.stringify(a),l=n.get(i)??[];l.push(o[o.length-1]),n.set(i,l)}return n}getGeneratedNgrams(e,r){let s=r.slice(r.length+1-this.no_repeat_ngram_size,r.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){let r=[];if(e.length+1<this.no_repeat_ngram_size)return r;{let s=this.getNgrams(e);return this.getGeneratedNgrams(s,e)}}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data,o=this.calcBannedNgramTokens(e[s]);for(let a of o)n[a]=-1/0}return r}},tu=class extends Wt{constructor(e){super(),this.penalty=e}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data;for(let o of new Set(e[s])){let a=Number(o);n[a]<0?n[a]*=this.penalty:n[a]/=this.penalty}}return r}},ru=class extends Wt{constructor(e,r){super(),this.min_length=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){let n=r[s].data;for(let o of this.eos_token_id)n[o]=-1/0}return r}},su=class extends Wt{constructor(e,r,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=r,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,r){for(let s=0;s<e.length;++s)if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){let o=r[s].data;for(let a of this.eos_token_id)o[a]=-1/0}return r}},nu=class extends Wt{constructor(e,r){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(r)?r:[r]}_call(e,r){for(let s=0;s<e.length;++s){let n=r[s].data,o=e[s];for(let a of this.bad_words_ids){if(o.length<a.length-1)continue;let i=!0;for(let l=1;l<=a.length-1;++l)if(a.at(-l-1)!=o.at(-l)){i=!1;break}i&&(n[a.at(-1)]=-1/0)}}return r}},ou=class extends Wt{constructor(e){if(super(),e<=1)throw new Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,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;a<o.data.length;++a)o.data[a]+=(n.data[a]-o.data[a])*this.guidance_scale;return o}},au=class extends Do{constructor(e){if(super(),typeof e!="number"||e<=0){let r=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;e===0&&(r+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,r){let s=r.data;for(let n=0;n<s.length;++n)s[n]/=this.temperature;return r}},hT=class extends Do{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),e<0||e>1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(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}},gT=class extends Do{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 An=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,Ke(e,Object.getOwnPropertyNames(this)))}};var Hr=class extends et{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Tn=class t extends et{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof Hr&&(e=[e]),this.criteria.push(...e)}_call(e,r){let s=new Array(e.length).fill(!1);for(let n of this.criteria){let o=n(e,r);for(let a=0;a<s.length;++a)s[a]||=o[a]}return s}[Symbol.iterator](){return this.criteria.values()}},iu=class extends Hr{constructor(e,r=null){super(),this.max_length=e,this.max_position_embeddings=r}_call(e){return e.map(r=>r.length>=this.max_length)}},lu=class extends Hr{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(s=>{let n=s.at(-1);return this.eos_token_id.some(o=>n==o)})}},wT=class extends Hr{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var Ls=class extends et{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 LE(e)}static getSampler(e){if(e.do_sample)return new ah(e);if(e.num_beams>1)return new ih(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 oh(e)}},oh=class extends Ls{async sample(e){let r=Ce(e.data)[1];return[[BigInt(r),0]]}},ah=class extends Ls{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=Ne(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},ih=class extends Ls{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=Ne(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var lh=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 R))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)}},Uo=lh;var zs=null;function yT(t){zs=t}function ch(t){if(t instanceof R)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 R("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new R("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function uh(t){return new R("bool",[t],[1])}var Q={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},pu={[Q.DecoderOnly]:{can_generate:!0,forward:Ct,prepare_inputs:Mn,sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[Q.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Ct,prepare_inputs:Mn,sessions:(t,e)=>({model:e.model_file_name??"model"})},[Q.Seq2Seq]:{can_generate:!0,forward:cu,prepare_inputs:Fo,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[Q.Vision2Seq]:{can_generate:!0,forward:cu,prepare_inputs:Fo,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[Q.Musicgen]:{can_generate:!0,forward:cu,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"}},[Q.EncoderDecoder]:{can_generate:!1,forward:cu,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[Q.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[Q.ImageTextToText]:{can_generate:!0,forward:kN,prepare_inputs:uu,sessions:(t,e,r)=>{let s={embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"};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"}},[Q.AudioTextToText]:{can_generate:!0,forward:vN,prepare_inputs:uu,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[Q.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:uu,sessions:(t,e,r)=>{let s={embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},optional_configs:{generation_config:"generation_config.json"}},[Q.Phi3V]:{can_generate:!0,prepare_inputs:uu,sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[Q.MultiModality]:{can_generate:!0,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"}},[Q.AutoEncoder]:{can_generate:!1,forward:bN,sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[Q.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[Q.Chatterbox]:{can_generate:!0,forward:Vt,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"}},[Q.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Mn,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{can_generate:!1,forward:Vt,sessions:(t,e)=>({model:e.model_file_name??"model"})}};function fu(t,e,r={}){let s=pu[t]??pu.default;return{sessions:s.sessions(e,r),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function xT(t,e){let r=rr.get(t),s=!1,n=e?.architectures?.[0];if(n&&n!==t&&t?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let o=rr.get(n);o!==void 0&&(r=o,s=!0)}return{typeConfig:pu[r]??pu.default,textOnly:s,modelType:r}}var rr=new Map,du=new Map,Ns=new Map,y=class extends et{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=Ns.get(this.constructor),{typeConfig:o}=xT(n,e);this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:p=null,use_external_data_format:f=null,session_options: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:p,use_external_data_format:f,session_options:m},w=Ns.get(this);s=_.config=await qt.from_pretrained(e,_);let{typeConfig:x,textOnly:b,modelType:E}=xT(w,s);if(E===void 0){let P=w??s?.model_type;P!=="custom"&&Z.warn(`Model type for '${P}' not found, assuming encoder-only architecture. Please report this at ${qr}.`)}let A=x.sessions(s,_,b),S=[mT(e,A,_,x.cache_sessions)];x.optional_configs&&S.push(AN(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 Ps;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new tu(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new eu(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new nu(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new ru(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 su(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new Qc(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new Jc(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new En(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new ou(e.guidance_scale)),e.temperature===0&&e.do_sample&&(Z.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 au(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=An){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,Ke(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Tn;return e.max_length!==null&&s.push(new iu(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new lu(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[zs.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,zs.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,zs.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,zs.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Ns.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 R("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s:s.attention_mask=ke([s.attention_mask,tt([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=Ke(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...c}=r,p=await this._prepare_inputs_embeds(r);r={...c,...Ke(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Vt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=ke([o,To(o,0)],0),"attention_mask"in r&&(r.attention_mask=ke([r.attention_mask,Sd(r.attention_mask)],0));else if(r.decoder_input_ids){let a=ch(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=ke(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 R)){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=ch(i)}return s.decoder_attention_mask=vc(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),p=this.config.is_encoder_decoder;p&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let f;p?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];let 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),b=Ls.getSampler(r),E=new Array(x).fill(0),A=f.tolist();o&&o.put(A);let S,M={},P={};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 j=this.getAttentions(S);for(let K in j)K in M||(M[K]=[]),M[K].push(j[K])}else this._return_dict_in_generate_keys&&Object.assign(P,Ke(S,this._return_dict_in_generate_keys));let W=S.logits.slice(null,-1,null).to("float32"),X=_(A,W),U=[];for(let j=0;j<X.dims.at(0);++j){let K=X[j],$=await b(K);for(let[C,te]of $){let ae=BigInt(C);E[j]+=te,A[j].push(ae),U.push([ae]);break}}if(o&&o.put(U),w(A).every(j=>j))break;l=this._update_model_kwargs_for_generation({generated_input_ids:U,outputs:S,model_inputs:l,is_encoder_decoder:p})}o&&o.end();let O=this.getPastKeyValues(S,l.past_key_values,!0),k=new R("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:k,past_key_values:O,...M,...P};for(let W of Object.values(S))W.location==="gpu-buffer"&&W.dispose();return k}getPastKeyValues(e,r,s=!1){let n=Object.create(null);for(let o in e)if(o.startsWith("present")){let a=o.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values"),i=o.includes("encoder");if(i&&r?n[a]=r[a]:n[a]=e[o],r&&(!i||s)){let l=r[a];l.location==="gpu-buffer"&&l.dispose()}}return new Uo(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"?vr.float16:vr.float32,i=Cs(this.config,{batch_size:n});for(let l in i){let c=i[l].reduce((p,f)=>p*f,1);e[l]=new R(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,Ke(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 cu(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,...o}=e;if(!r){let a=Ke(e,t.sessions.model.inputNames);r=(await Vt(t,a)).last_hidden_state}return o.input_ids=n,o.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(o.encoder_attention_mask=e.attention_mask),await Ct(t,o,!0)}async function Vt(t,e){let r=t.sessions.model,s=Ke(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=Sd(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=tt([n[0],n[2],n[3]])}return await fe(r,s)}async function bN(t,e){let r=await t.encode(e);return await t.decode(r)}async function Ct(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=uh(!!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=EN(o,n,i)}s.inputNames.includes("num_logits_to_keep")&&!o.num_logits_to_keep&&(o.num_logits_to_keep=new R("int64",[0n],[])),t.addPastKeyValues(o,n);let a=Ke(o,s.inputNames);return await fe(s,a)}async function bT(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:f=null,...m}){if(!l){l=await t.encode_text({input_ids:o,...m});let w=Ke(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],b=c.get_seq_length();a=ke([tt([o.dims[0],b]),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 Ct(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:p,logits_processor:f},!0)}async function vN(t,e){return await bT(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 kN(t,e){return await bT(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 ph(t,e=0){let[r,s]=t.dims,n=t.data,o=new BigInt64Array(n.length);for(let a=0;a<r;++a){let i=a*s,l=BigInt(e);for(let c=0;c<s;++c){let p=i+c;n[p]===0n?o[p]=BigInt(1):(o[p]=l,l+=n[p])}}return{data:o,dims:t.dims}}function EN(t,e=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:o}=t,{data:a,dims:i}=ph(o,r),l=new R("int64",a,i);if(e){let c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function Mn(t,e,r,s){let n=r.past_key_values?r.past_key_values.get_seq_length():0;if((t.sessions.decoder_model_merged??t.sessions.model)?.inputNames.includes("num_logits_to_keep")&&!r.num_logits_to_keep&&(r.num_logits_to_keep=new R("int64",[1n],[])),!r.attention_mask){let a;for(let i of["input_ids","inputs_embeds","position_ids"])if(r[i]){a=r[i].dims;break}if(!a)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=tt([a[0],n+a[1]])}if(r.past_key_values){let{input_ids:a,attention_mask:i}=r;i&&i.dims[1]>a.dims[1]||n<a.dims[1]&&(r.input_ids=a.slice(null,[n,null]))}return r}function Fo(t,e,r,s){return r.past_key_values&&(e=e.map(n=>[n.at(-1)])),{...r,decoder_input_ids:ch(e)}}function uu(t,...e){return t.config.is_encoder_decoder?Fo(t,...e):Mn(t,...e)}function vT({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((p,f,m)=>(f==t&&p.push(m),p),[])),a=o.reduce((c,p)=>c+p.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let c=0;c<o.length;++c){let p=o[c],f=e[c];for(let m=0;m<p.length;++m)f[p[m]].data.set(r[l++].data)}return{inputs_embeds:e,attention_mask:n}}function Sn({image_token_id:t,inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return vT({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}function mu({audio_token_id:t,inputs_embeds:e,audio_features:r,input_ids:s,attention_mask:n}){return vT({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}async function AN(t,e,r){return Object.fromEntries(await Promise.all(Object.keys(e).map(async s=>{let n=await ut(t,e[s],!1,r);return[s,n]})))}var tl={};ds(tl,{ASTForAudioClassification:()=>kh,ASTModel:()=>vh,ASTPreTrainedModel:()=>Wo,AfmoeForCausalLM:()=>xh,AfmoeModel:()=>wh,AfmoePreTrainedModel:()=>jo,AlbertForMaskedLM:()=>_h,AlbertForQuestionAnswering:()=>mh,AlbertForSequenceClassification:()=>dh,AlbertModel:()=>fh,AlbertPreTrainedModel:()=>Rs,ApertusForCausalLM:()=>gh,ApertusModel:()=>hh,ApertusPreTrainedModel:()=>Go,ArceeForCausalLM:()=>bh,ArceeModel:()=>yh,ArceePreTrainedModel:()=>qo,BartForConditionalGeneration:()=>Ah,BartForSequenceClassification:()=>Th,BartModel:()=>Eh,BartPretrainedModel:()=>On,BeitForImageClassification:()=>Sh,BeitModel:()=>Mh,BeitPreTrainedModel:()=>Vo,BertForMaskedLM:()=>Ih,BertForQuestionAnswering:()=>Lh,BertForSequenceClassification:()=>Ch,BertForTokenClassification:()=>Ph,BertModel:()=>Oh,BertPreTrainedModel:()=>Xr,BlenderbotForConditionalGeneration:()=>Nh,BlenderbotModel:()=>zh,BlenderbotPreTrainedModel:()=>Ho,BlenderbotSmallForConditionalGeneration:()=>$h,BlenderbotSmallModel:()=>Rh,BlenderbotSmallPreTrainedModel:()=>Xo,BloomForCausalLM:()=>Dh,BloomModel:()=>Bh,BloomPreTrainedModel:()=>Ko,CHMv2ForDepthEstimation:()=>Vh,CHMv2PreTrainedModel:()=>gu,CLIPModel:()=>Xh,CLIPPreTrainedModel:()=>fr,CLIPSegForImageSegmentation:()=>Zh,CLIPSegModel:()=>Jh,CLIPSegPreTrainedModel:()=>ea,CLIPTextModel:()=>Kh,CLIPTextModelWithProjection:()=>Zo,CLIPVisionModel:()=>Yh,CLIPVisionModelWithProjection:()=>Qh,CamembertForMaskedLM:()=>Fh,CamembertForQuestionAnswering:()=>qh,CamembertForSequenceClassification:()=>Gh,CamembertForTokenClassification:()=>jh,CamembertModel:()=>Uh,CamembertPreTrainedModel:()=>Kr,ChatterboxModel:()=>Yo,ChatterboxPreTrainedModel:()=>_u,ChineseCLIPModel:()=>Wh,ChineseCLIPPreTrainedModel:()=>hu,ClapAudioModelWithProjection:()=>Jo,ClapModel:()=>Hh,ClapPreTrainedModel:()=>In,ClapTextModelWithProjection:()=>Qo,CodeGenForCausalLM:()=>tg,CodeGenModel:()=>eg,CodeGenPreTrainedModel:()=>ta,Cohere2ForCausalLM:()=>og,Cohere2Model:()=>ng,Cohere2PreTrainedModel:()=>sa,CohereForCausalLM:()=>sg,CohereModel:()=>rg,CoherePreTrainedModel:()=>ra,ConvBertForMaskedLM:()=>ig,ConvBertForQuestionAnswering:()=>ug,ConvBertForSequenceClassification:()=>lg,ConvBertForTokenClassification:()=>cg,ConvBertModel:()=>ag,ConvBertPreTrainedModel:()=>Yr,ConvNextForImageClassification:()=>fg,ConvNextModel:()=>pg,ConvNextPreTrainedModel:()=>na,ConvNextV2ForImageClassification:()=>mg,ConvNextV2Model:()=>dg,ConvNextV2PreTrainedModel:()=>oa,DFineForObjectDetection:()=>wg,DFineModel:()=>gg,DFinePreTrainedModel:()=>ia,DINOv3ConvNextModel:()=>qg,DINOv3ConvNextPreTrainedModel:()=>Eu,DINOv3ViTModel:()=>Wg,DINOv3ViTPreTrainedModel:()=>Au,DPTForDepthEstimation:()=>Zg,DPTModel:()=>Jg,DPTPreTrainedModel:()=>ma,DacDecoderModel:()=>ca,DacDecoderOutput:()=>xu,DacEncoderModel:()=>la,DacEncoderOutput:()=>wu,DacModel:()=>xg,DacPreTrainedModel:()=>Cn,DebertaForMaskedLM:()=>bg,DebertaForQuestionAnswering:()=>Eg,DebertaForSequenceClassification:()=>vg,DebertaForTokenClassification:()=>kg,DebertaModel:()=>yg,DebertaPreTrainedModel:()=>Qr,DebertaV2ForMaskedLM:()=>Sg,DebertaV2ForQuestionAnswering:()=>Cg,DebertaV2ForSequenceClassification:()=>Og,DebertaV2ForTokenClassification:()=>Ig,DebertaV2Model:()=>Mg,DebertaV2PreTrainedModel:()=>Jr,DecisionTransformerModel:()=>Pg,DecisionTransformerPreTrainedModel:()=>yu,DeepseekV3ForCausalLM:()=>Tg,DeepseekV3Model:()=>Ag,DeepseekV3PreTrainedModel:()=>ua,DeiTForImageClassification:()=>zg,DeiTModel:()=>Lg,DeiTPreTrainedModel:()=>pa,DepthAnythingForDepthEstimation:()=>Ng,DepthAnythingPreTrainedModel:()=>bu,DepthProForDepthEstimation:()=>Rg,DepthProPreTrainedModel:()=>vu,DetrForObjectDetection:()=>Bg,DetrForSegmentation:()=>Dg,DetrModel:()=>$g,DetrObjectDetectionOutput:()=>Ln,DetrPreTrainedModel:()=>Pn,DetrSegmentationOutput:()=>ku,Dinov2ForImageClassification:()=>Fg,Dinov2Model:()=>Ug,Dinov2PreTrainedModel:()=>fa,Dinov2WithRegistersForImageClassification:()=>jg,Dinov2WithRegistersModel:()=>Gg,Dinov2WithRegistersPreTrainedModel:()=>da,DistilBertForMaskedLM:()=>Yg,DistilBertForQuestionAnswering:()=>Kg,DistilBertForSequenceClassification:()=>Hg,DistilBertForTokenClassification:()=>Xg,DistilBertModel:()=>Vg,DistilBertPreTrainedModel:()=>Zr,DonutSwinModel:()=>Qg,DonutSwinPreTrainedModel:()=>Tu,EdgeTamModel:()=>lb,EfficientNetForImageClassification:()=>tw,EfficientNetModel:()=>ew,EfficientNetPreTrainedModel:()=>_a,ElectraForMaskedLM:()=>sw,ElectraForQuestionAnswering:()=>aw,ElectraForSequenceClassification:()=>nw,ElectraForTokenClassification:()=>ow,ElectraModel:()=>rw,ElectraPreTrainedModel:()=>es,Ernie4_5ForCausalLM:()=>lw,Ernie4_5Model:()=>iw,Ernie4_5PretrainedModel:()=>ha,EsmForMaskedLM:()=>uw,EsmForSequenceClassification:()=>pw,EsmForTokenClassification:()=>fw,EsmModel:()=>cw,EsmPreTrainedModel:()=>$s,EuroBertForMaskedLM:()=>mw,EuroBertForSequenceClassification:()=>_w,EuroBertForTokenClassification:()=>hw,EuroBertModel:()=>dw,EuroBertPreTrainedModel:()=>Bs,ExaoneForCausalLM:()=>ww,ExaoneModel:()=>gw,ExaonePreTrainedModel:()=>ga,FalconForCausalLM:()=>yw,FalconH1ForCausalLM:()=>vw,FalconH1Model:()=>bw,FalconH1PreTrainedModel:()=>xa,FalconModel:()=>xw,FalconPreTrainedModel:()=>wa,FastViTForImageClassification:()=>Ew,FastViTModel:()=>kw,FastViTPreTrainedModel:()=>ya,Florence2ForConditionalGeneration:()=>Aw,Florence2PreTrainedModel:()=>Mu,GLPNForDepthEstimation:()=>Fw,GLPNModel:()=>Uw,GLPNPreTrainedModel:()=>Ma,GPT2LMHeadModel:()=>Qw,GPT2Model:()=>Yw,GPT2PreTrainedModel:()=>Pa,GPTBigCodeForCausalLM:()=>jw,GPTBigCodeModel:()=>Gw,GPTBigCodePreTrainedModel:()=>Sa,GPTJForCausalLM:()=>Zw,GPTJModel:()=>Jw,GPTJPreTrainedModel:()=>La,GPTNeoForCausalLM:()=>Ww,GPTNeoModel:()=>qw,GPTNeoPreTrainedModel:()=>Oa,GPTNeoXForCausalLM:()=>Hw,GPTNeoXModel:()=>Vw,GPTNeoXPreTrainedModel:()=>Ia,Gemma2ForCausalLM:()=>Ow,Gemma2Model:()=>Sw,Gemma2PreTrainedModel:()=>va,Gemma3ForCausalLM:()=>Lw,Gemma3ForConditionalGeneration:()=>Iu,Gemma3Model:()=>Pw,Gemma3PreTrainedModel:()=>Ou,Gemma3nForCausalLM:()=>zw,Gemma3nForConditionalGeneration:()=>zn,Gemma3nPreTrainedModel:()=>Cu,GemmaForCausalLM:()=>Mw,GemmaModel:()=>Tw,GemmaPreTrainedModel:()=>ba,GlmForCausalLM:()=>Rw,GlmModel:()=>Nw,GlmMoeDsaForCausalLM:()=>Bw,GlmMoeDsaModel:()=>$w,GlmMoeDsaPreTrainedModel:()=>Ea,GlmOcrForConditionalGeneration:()=>Dw,GlmPreTrainedModel:()=>ka,GptOssForCausalLM:()=>Kw,GptOssModel:()=>Xw,GptOssPreTrainedModel:()=>Ca,GraniteForCausalLM:()=>tx,GraniteModel:()=>ex,GraniteMoeHybridForCausalLM:()=>sx,GraniteMoeHybridModel:()=>rx,GraniteMoeHybridPreTrainedModel:()=>Na,GranitePreTrainedModel:()=>za,GraniteSpeechForConditionalGeneration:()=>nx,GroundingDinoForObjectDetection:()=>ox,GroundingDinoPreTrainedModel:()=>zu,GroupViTModel:()=>ax,GroupViTPreTrainedModel:()=>Nu,HeliumForCausalLM:()=>lx,HeliumModel:()=>ix,HeliumPreTrainedModel:()=>Ra,HieraForImageClassification:()=>ux,HieraModel:()=>cx,HieraPreTrainedModel:()=>$a,HubertForCTC:()=>gx,HubertForSequenceClassification:()=>wx,HubertModel:()=>hx,HubertPreTrainedModel:()=>_x,HunYuanDenseV1ForCausalLM:()=>yx,HunYuanDenseV1Model:()=>xx,HunYuanDenseV1PreTrainedModel:()=>Ba,IJepaForImageClassification:()=>kx,IJepaModel:()=>vx,IJepaPreTrainedModel:()=>Da,Idefics3ForConditionalGeneration:()=>bx,JAISLMHeadModel:()=>Ax,JAISModel:()=>Ex,JAISPreTrainedModel:()=>Ua,JinaCLIPModel:()=>Tx,JinaCLIPPreTrainedModel:()=>Rn,JinaCLIPTextModel:()=>Fa,JinaCLIPVisionModel:()=>Mx,Lfm2ForCausalLM:()=>Ox,Lfm2Model:()=>Sx,Lfm2MoeForCausalLM:()=>Px,Lfm2MoeModel:()=>Cx,Lfm2MoePreTrainedModel:()=>ja,Lfm2PreTrainedModel:()=>Ga,Lfm2VlForConditionalGeneration:()=>Lx,LightOnOcrForConditionalGeneration:()=>Ix,LiteWhisperForConditionalGeneration:()=>k1,Llama4ForCausalLM:()=>Rx,Llama4PreTrainedModel:()=>Ru,LlamaForCausalLM:()=>Nx,LlamaModel:()=>zx,LlamaPreTrainedModel:()=>qa,LlavaForConditionalGeneration:()=>Et,LlavaOnevisionForConditionalGeneration:()=>Et,LlavaPreTrainedModel:()=>Su,LlavaQwen2ForCausalLM:()=>Cw,LongT5ForConditionalGeneration:()=>Bx,LongT5Model:()=>$x,LongT5PreTrainedModel:()=>Wa,M2M100ForConditionalGeneration:()=>Ux,M2M100Model:()=>Dx,M2M100PreTrainedModel:()=>Va,MBartForCausalLM:()=>Xx,MBartForConditionalGeneration:()=>Vx,MBartForSequenceClassification:()=>Hx,MBartModel:()=>Wx,MBartPreTrainedModel:()=>Fs,MPNetForMaskedLM:()=>zy,MPNetForQuestionAnswering:()=>$y,MPNetForSequenceClassification:()=>Ny,MPNetForTokenClassification:()=>Ry,MPNetModel:()=>Ly,MPNetPreTrainedModel:()=>ts,MT5ForConditionalGeneration:()=>Fy,MT5Model:()=>Uy,MT5PreTrainedModel:()=>oi,MarianMTModel:()=>Gx,MarianModel:()=>Fx,MarianPreTrainedModel:()=>Ha,MaskFormerForInstanceSegmentation:()=>qx,MaskFormerModel:()=>jx,MaskFormerPreTrainedModel:()=>Xa,Metric3DForDepthEstimation:()=>Kx,Metric3DPreTrainedModel:()=>$u,Metric3Dv2ForDepthEstimation:()=>Yx,Metric3Dv2PreTrainedModel:()=>Bu,MgpstrForSceneTextRecognition:()=>Qx,MgpstrModelOutput:()=>Du,MgpstrPreTrainedModel:()=>Uu,MimiDecoderModel:()=>Ya,MimiDecoderOutput:()=>Gu,MimiEncoderModel:()=>Ka,MimiEncoderOutput:()=>Fu,MimiModel:()=>Jx,MimiPreTrainedModel:()=>$n,Mistral4ForCausalLM:()=>ry,Mistral4Model:()=>ty,Mistral4PreTrainedModel:()=>Ja,MistralForCausalLM:()=>ey,MistralModel:()=>Zx,MistralPreTrainedModel:()=>Qa,MobileBertForMaskedLM:()=>ny,MobileBertForQuestionAnswering:()=>ay,MobileBertForSequenceClassification:()=>oy,MobileBertModel:()=>sy,MobileBertPreTrainedModel:()=>Gs,MobileLLMForCausalLM:()=>ly,MobileLLMModel:()=>iy,MobileLLMPreTrainedModel:()=>Za,MobileNetV1ForImageClassification:()=>uy,MobileNetV1ForSemanticSegmentation:()=>py,MobileNetV1Model:()=>cy,MobileNetV1PreTrainedModel:()=>Bn,MobileNetV2ForImageClassification:()=>dy,MobileNetV2ForSemanticSegmentation:()=>my,MobileNetV2Model:()=>fy,MobileNetV2PreTrainedModel:()=>Dn,MobileNetV3ForImageClassification:()=>hy,MobileNetV3ForSemanticSegmentation:()=>gy,MobileNetV3Model:()=>_y,MobileNetV3PreTrainedModel:()=>Un,MobileNetV4ForImageClassification:()=>xy,MobileNetV4ForSemanticSegmentation:()=>yy,MobileNetV4Model:()=>wy,MobileNetV4PreTrainedModel:()=>Fn,MobileViTForImageClassification:()=>vy,MobileViTModel:()=>by,MobileViTPreTrainedModel:()=>ei,MobileViTV2ForImageClassification:()=>Ey,MobileViTV2Model:()=>ky,MobileViTV2PreTrainedModel:()=>ti,ModernBertDecoderForCausalLM:()=>Iy,ModernBertDecoderModel:()=>Oy,ModernBertDecoderPreTrainedModel:()=>ri,ModernBertForMaskedLM:()=>Ty,ModernBertForSequenceClassification:()=>My,ModernBertForTokenClassification:()=>Sy,ModernBertModel:()=>Ay,ModernBertPreTrainedModel:()=>js,Moondream1ForConditionalGeneration:()=>Iw,MoonshineForConditionalGeneration:()=>Py,MoonshineModel:()=>Cy,MoonshinePreTrainedModel:()=>si,MptForCausalLM:()=>Dy,MptModel:()=>By,MptPreTrainedModel:()=>ni,MultiModalityCausalLM:()=>Gy,MultiModalityPreTrainedModel:()=>ju,MusicgenForCausalLM:()=>qy,MusicgenForConditionalGeneration:()=>ii,MusicgenModel:()=>jy,MusicgenPreTrainedModel:()=>ai,NanoChatForCausalLM:()=>Vy,NanoChatModel:()=>Wy,NanoChatPreTrainedModel:()=>li,NemotronHForCausalLM:()=>Xy,NemotronHModel:()=>Hy,NemotronHPreTrainedModel:()=>ci,NeoBertForMaskedLM:()=>Yy,NeoBertForQuestionAnswering:()=>Zy,NeoBertForSequenceClassification:()=>Qy,NeoBertForTokenClassification:()=>Jy,NeoBertModel:()=>Ky,NeoBertPreTrainedModel:()=>rs,NomicBertModel:()=>e0,NomicBertPreTrainedModel:()=>qu,OPTForCausalLM:()=>f0,OPTModel:()=>p0,OPTPreTrainedModel:()=>_i,Olmo2ForCausalLM:()=>n0,Olmo2Model:()=>s0,Olmo2PreTrainedModel:()=>pi,Olmo3ForCausalLM:()=>a0,Olmo3Model:()=>o0,Olmo3PreTrainedModel:()=>fi,OlmoForCausalLM:()=>r0,OlmoHybridForCausalLM:()=>l0,OlmoHybridModel:()=>i0,OlmoHybridPreTrainedModel:()=>di,OlmoModel:()=>t0,OlmoPreTrainedModel:()=>ui,OpenELMForCausalLM:()=>u0,OpenELMModel:()=>c0,OpenELMPreTrainedModel:()=>mi,OwlViTForObjectDetection:()=>h0,OwlViTModel:()=>_0,OwlViTPreTrainedModel:()=>gi,Owlv2ForObjectDetection:()=>m0,Owlv2Model:()=>d0,Owlv2PreTrainedModel:()=>hi,PaliGemmaForConditionalGeneration:()=>g0,ParakeetForCTC:()=>w0,ParakeetPreTrainedModel:()=>Wu,PatchTSMixerForPrediction:()=>y0,PatchTSMixerModel:()=>x0,PatchTSMixerPreTrainedModel:()=>wi,PatchTSTForPrediction:()=>v0,PatchTSTModel:()=>b0,PatchTSTPreTrainedModel:()=>xi,Phi3ForCausalLM:()=>T0,Phi3Model:()=>A0,Phi3PreTrainedModel:()=>bi,Phi3VForCausalLM:()=>vi,Phi3VPreTrainedModel:()=>Vu,PhiForCausalLM:()=>E0,PhiModel:()=>k0,PhiPreTrainedModel:()=>yi,PreTrainedModel:()=>y,PvtForImageClassification:()=>S0,PvtModel:()=>M0,PvtPreTrainedModel:()=>ki,PyAnnoteForAudioFrameClassification:()=>I0,PyAnnoteModel:()=>O0,PyAnnotePreTrainedModel:()=>Ei,Qwen2ForCausalLM:()=>P0,Qwen2Model:()=>C0,Qwen2MoeForCausalLM:()=>z0,Qwen2MoeModel:()=>L0,Qwen2MoePreTrainedModel:()=>Ti,Qwen2PreTrainedModel:()=>Ai,Qwen2VLForCausalLM:()=>Aa,Qwen2VLForConditionalGeneration:()=>Nn,Qwen2VLPreTrainedModel:()=>Pu,Qwen2_5_VLForCausalLM:()=>Ta,Qwen2_5_VLForConditionalGeneration:()=>Ds,Qwen3ForCausalLM:()=>R0,Qwen3Model:()=>N0,Qwen3MoeForCausalLM:()=>B0,Qwen3MoeModel:()=>$0,Qwen3MoePreTrainedModel:()=>Si,Qwen3NextForCausalLM:()=>U0,Qwen3NextModel:()=>D0,Qwen3NextPreTrainedModel:()=>Oi,Qwen3PreTrainedModel:()=>Mi,Qwen3VLForCausalLM:()=>Ii,Qwen3VLForConditionalGeneration:()=>qs,Qwen3VLMoeForCausalLM:()=>G0,Qwen3VLMoeForConditionalGeneration:()=>F0,Qwen3_5ForCausalLM:()=>Ci,Qwen3_5ForConditionalGeneration:()=>Gn,Qwen3_5MoeForCausalLM:()=>q0,Qwen3_5MoeForConditionalGeneration:()=>j0,RFDetrForObjectDetection:()=>X0,RFDetrModel:()=>H0,RFDetrObjectDetectionOutput:()=>Hu,RFDetrPreTrainedModel:()=>Li,RTDetrForObjectDetection:()=>hg,RTDetrModel:()=>_g,RTDetrObjectDetectionOutput:()=>dr,RTDetrPreTrainedModel:()=>aa,RTDetrV2ForObjectDetection:()=>ab,RTDetrV2Model:()=>ob,RTDetrV2ObjectDetectionOutput:()=>Xu,RTDetrV2PreTrainedModel:()=>zi,ResNetForImageClassification:()=>V0,ResNetModel:()=>W0,ResNetPreTrainedModel:()=>Pi,RoFormerForMaskedLM:()=>tb,RoFormerForQuestionAnswering:()=>nb,RoFormerForSequenceClassification:()=>rb,RoFormerForTokenClassification:()=>sb,RoFormerModel:()=>eb,RoFormerPreTrainedModel:()=>ns,RobertaForMaskedLM:()=>Y0,RobertaForQuestionAnswering:()=>Z0,RobertaForSequenceClassification:()=>Q0,RobertaForTokenClassification:()=>J0,RobertaModel:()=>K0,RobertaPreTrainedModel:()=>ss,Sam2ImageSegmentationOutput:()=>Qu,Sam2Model:()=>Ni,Sam2PreTrainedModel:()=>Ju,Sam3TrackerModel:()=>cb,SamImageSegmentationOutput:()=>Ku,SamModel:()=>ib,SamPreTrainedModel:()=>Yu,SapiensForDepthEstimation:()=>pb,SapiensForNormalEstimation:()=>fb,SapiensForSemanticSegmentation:()=>ub,SapiensPreTrainedModel:()=>jn,SegformerForImageClassification:()=>mb,SegformerForSemanticSegmentation:()=>_b,SegformerModel:()=>db,SegformerPreTrainedModel:()=>qn,SiglipModel:()=>hb,SiglipPreTrainedModel:()=>Ri,SiglipTextModel:()=>$i,SiglipVisionModel:()=>gb,SmolLM3ForCausalLM:()=>xb,SmolLM3Model:()=>wb,SmolLM3PreTrainedModel:()=>Bi,SnacDecoderModel:()=>Ui,SnacEncoderModel:()=>Di,SnacModel:()=>yb,SnacPreTrainedModel:()=>Wn,SolarOpenForCausalLM:()=>vb,SolarOpenModel:()=>bb,SolarOpenPreTrainedModel:()=>Fi,SpeechT5ForSpeechToText:()=>Eb,SpeechT5ForTextToSpeech:()=>Ab,SpeechT5HifiGan:()=>Tb,SpeechT5Model:()=>kb,SpeechT5PreTrainedModel:()=>Vn,SqueezeBertForMaskedLM:()=>Sb,SqueezeBertForQuestionAnswering:()=>Ib,SqueezeBertForSequenceClassification:()=>Ob,SqueezeBertModel:()=>Mb,SqueezeBertPreTrainedModel:()=>Ws,StableLmForCausalLM:()=>Pb,StableLmModel:()=>Cb,StableLmPreTrainedModel:()=>Gi,Starcoder2ForCausalLM:()=>zb,Starcoder2Model:()=>Lb,Starcoder2PreTrainedModel:()=>ji,StyleTextToSpeech2Model:()=>Nb,StyleTextToSpeech2PreTrainedModel:()=>Zu,SupertonicForConditionalGeneration:()=>qi,SupertonicPreTrainedModel:()=>ep,Swin2SRForImageSuperResolution:()=>Ub,Swin2SRModel:()=>Db,Swin2SRPreTrainedModel:()=>Wi,SwinForImageClassification:()=>$b,SwinForSemanticSegmentation:()=>Bb,SwinModel:()=>Rb,SwinPreTrainedModel:()=>Hn,T5ForConditionalGeneration:()=>Gb,T5Model:()=>Fb,T5PreTrainedModel:()=>Vi,TableTransformerForObjectDetection:()=>qb,TableTransformerModel:()=>jb,TableTransformerObjectDetectionOutput:()=>tp,TableTransformerPreTrainedModel:()=>Hi,TrOCRForCausalLM:()=>Wb,TrOCRPreTrainedModel:()=>rp,UltravoxModel:()=>Us,UltravoxPreTrainedModel:()=>Lu,UniSpeechForCTC:()=>Hb,UniSpeechForSequenceClassification:()=>Xb,UniSpeechModel:()=>Vb,UniSpeechPreTrainedModel:()=>Xn,UniSpeechSatForAudioFrameClassification:()=>Jb,UniSpeechSatForCTC:()=>Yb,UniSpeechSatForSequenceClassification:()=>Qb,UniSpeechSatModel:()=>Kb,UniSpeechSatPreTrainedModel:()=>Vs,VaultGemmaForCausalLM:()=>e1,VaultGemmaModel:()=>Zb,VaultGemmaPreTrainedModel:()=>Xi,ViTForImageClassification:()=>s1,ViTMAEModel:()=>n1,ViTMAEPreTrainedModel:()=>sp,ViTMSNForImageClassification:()=>a1,ViTMSNModel:()=>o1,ViTMSNPreTrainedModel:()=>Yi,ViTModel:()=>r1,ViTPreTrainedModel:()=>Ki,VisionEncoderDecoderModel:()=>t1,VitMatteForImageMatting:()=>i1,VitMattePreTrainedModel:()=>np,VitPoseForPoseEstimation:()=>l1,VitPosePreTrainedModel:()=>op,VitsModel:()=>c1,VitsModelOutput:()=>ap,VitsPreTrainedModel:()=>ip,VoxtralForConditionalGeneration:()=>u1,VoxtralRealtimeForConditionalGeneration:()=>Qi,VoxtralRealtimePreTrainedModel:()=>lp,Wav2Vec2BertForCTC:()=>m1,Wav2Vec2BertForSequenceClassification:()=>_1,Wav2Vec2BertModel:()=>d1,Wav2Vec2BertPreTrainedModel:()=>Kn,Wav2Vec2ForAudioFrameClassification:()=>mx,Wav2Vec2ForCTC:()=>fx,Wav2Vec2ForSequenceClassification:()=>dx,Wav2Vec2Model:()=>px,Wav2Vec2PreTrainedModel:()=>sr,WavLMForAudioFrameClassification:()=>y1,WavLMForCTC:()=>g1,WavLMForSequenceClassification:()=>w1,WavLMForXVector:()=>x1,WavLMModel:()=>h1,WavLMPreTrainedModel:()=>os,WeSpeakerResNetModel:()=>b1,WeSpeakerResNetPreTrainedModel:()=>up,WhisperForConditionalGeneration:()=>fp,WhisperModel:()=>v1,WhisperPreTrainedModel:()=>Ji,XLMForQuestionAnswering:()=>S1,XLMForSequenceClassification:()=>T1,XLMForTokenClassification:()=>M1,XLMModel:()=>E1,XLMPreTrainedModel:()=>as,XLMRobertaForMaskedLM:()=>I1,XLMRobertaForQuestionAnswering:()=>L1,XLMRobertaForSequenceClassification:()=>C1,XLMRobertaForTokenClassification:()=>P1,XLMRobertaModel:()=>O1,XLMRobertaPreTrainedModel:()=>is,XLMWithLMHeadModel:()=>A1,XVectorOutput:()=>cp,YolosForObjectDetection:()=>N1,YolosModel:()=>z1,YolosObjectDetectionOutput:()=>dp,YolosPreTrainedModel:()=>Zi,YoutuForCausalLM:()=>$1,YoutuModel:()=>R1,YoutuPreTrainedModel:()=>el});var Rs=class extends y{},fh=class extends Rs{},dh=class extends Rs{async _call(e){return new G(await super._call(e))}},mh=class extends Rs{async _call(e){return new Te(await super._call(e))}},_h=class extends Rs{async _call(e){return new ge(await super._call(e))}};var Go=class extends y{},hh=class extends Go{},gh=class extends Go{};var jo=class extends y{},wh=class extends jo{},xh=class extends jo{};var qo=class extends y{},yh=class extends qo{},bh=class extends qo{};var Wo=class extends y{},vh=class extends Wo{},kh=class extends Wo{};var On=class extends y{},Eh=class extends On{},Ah=class extends On{},Th=class extends On{async _call(e){return new G(await super._call(e))}};var Vo=class extends y{},Mh=class extends Vo{},Sh=class extends Vo{async _call(e){return new G(await super._call(e))}};var Xr=class extends y{},Oh=class extends Xr{},Ih=class extends Xr{async _call(e){return new ge(await super._call(e))}},Ch=class extends Xr{async _call(e){return new G(await super._call(e))}},Ph=class extends Xr{async _call(e){return new he(await super._call(e))}},Lh=class extends Xr{async _call(e){return new Te(await super._call(e))}};var Ho=class extends y{},zh=class extends Ho{},Nh=class extends Ho{};var Xo=class extends y{},Rh=class extends Xo{},$h=class extends Xo{};var Ko=class extends y{},Bh=class extends Ko{},Dh=class extends Ko{};var Kr=class extends y{},Uh=class extends Kr{},Fh=class extends Kr{async _call(e){return new ge(await super._call(e))}},Gh=class extends Kr{async _call(e){return new G(await super._call(e))}},jh=class extends Kr{async _call(e){return new he(await super._call(e))}},qh=class extends Kr{async _call(e){return new Te(await super._call(e))}};var TN=4299n,kT=6561n,_u=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"]},Yo=class extends _u{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:p=null,audio_tokens:f=null,speaker_embeddings:m=null,speaker_features:_=null,...w}){let x;if(!a){let E=this.sessions.embed_tokens.inputNames,A={input_ids:e};if(E.includes("exaggeration")){if(!(n instanceof R)){let S=e.dims[0];if(n==null)n=He([S],.5);else if(typeof n=="number")n=He([S],n);else if(Array.isArray(n))n=new R("float32",n,[S]);else throw new Error("Unsupported type for `exaggeration` input")}A.exaggeration=n}if(E.includes("position_ids")&&(A.position_ids=o),{inputs_embeds:a}=await fe(this.sessions.embed_tokens,A),p&&f&&m&&_&&(x={audio_features:p,audio_tokens:f,speaker_embeddings:m,speaker_features:_}),x||s)x??=await this.encode_speech(s),a=ke([x.audio_features,a],1),r=tt([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=tt([a.dims[0],M+S])}}return{...await Ct(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c},!1),...x}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==kT)-1);r.position_ids=new R("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=kT?0:i++)});r.position_ids=new R("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),Mn(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=He([a.dims[0],3],TN),l=ke([s,a,i],1),{waveform:c}=await fe(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var hu=class extends y{},Wh=class extends hu{};var gu=class extends y{},Vh=class extends gu{};var In=class extends y{},Hh=class extends In{},Qo=class extends In{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Jo=class extends In{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var fr=class extends y{},Xh=class extends fr{},Kh=class extends fr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Zo=class extends fr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Yh=class extends fr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},Qh=class extends fr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var ea=class extends y{},Jh=class extends ea{},Zh=class extends ea{};var ta=class extends y{},eg=class extends ta{},tg=class extends ta{};var ra=class extends y{},rg=class extends ra{},sg=class extends ra{};var sa=class extends y{},ng=class extends sa{},og=class extends sa{};var Yr=class extends y{},ag=class extends Yr{},ig=class extends Yr{async _call(e){return new ge(await super._call(e))}},lg=class extends Yr{async _call(e){return new G(await super._call(e))}},cg=class extends Yr{async _call(e){return new he(await super._call(e))}},ug=class extends Yr{async _call(e){return new Te(await super._call(e))}};var na=class extends y{},pg=class extends na{},fg=class extends na{async _call(e){return new G(await super._call(e))}};var oa=class extends y{},dg=class extends oa{},mg=class extends oa{async _call(e){return new G(await super._call(e))}};var aa=class extends y{},_g=class extends aa{},hg=class extends aa{async _call(e){return new dr(await super._call(e))}},dr=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var ia=class extends y{},gg=class extends ia{},wg=class extends ia{async _call(e){return new dr(await super._call(e))}};var wu=class extends Re{constructor({audio_codes:e}){super(),this.audio_codes=e}},xu=class extends Re{constructor({audio_values:e}){super(),this.audio_values=e}},Cn=class extends y{main_input_name="input_values";forward_params=["input_values"]},xg=class extends Cn{async encode(e){return new wu(await fe(this.sessions.encoder_model,e))}async decode(e){return new xu(await fe(this.sessions.decoder_model,e))}},la=class extends Cn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ca=class extends Cn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Qr=class extends y{},yg=class extends Qr{},bg=class extends Qr{async _call(e){return new ge(await super._call(e))}},vg=class extends Qr{async _call(e){return new G(await super._call(e))}},kg=class extends Qr{async _call(e){return new he(await super._call(e))}},Eg=class extends Qr{async _call(e){return new Te(await super._call(e))}};var ua=class extends y{},Ag=class extends ua{},Tg=class extends ua{};var Jr=class extends y{},Mg=class extends Jr{},Sg=class extends Jr{async _call(e){return new ge(await super._call(e))}},Og=class extends Jr{async _call(e){return new G(await super._call(e))}},Ig=class extends Jr{async _call(e){return new he(await super._call(e))}},Cg=class extends Jr{async _call(e){return new Te(await super._call(e))}};var yu=class extends y{},Pg=class extends yu{};var pa=class extends y{},Lg=class extends pa{},zg=class extends pa{async _call(e){return new G(await super._call(e))}};var bu=class extends y{},Ng=class extends bu{};var vu=class extends y{},Rg=class extends vu{};var Pn=class extends y{},$g=class extends Pn{},Bg=class extends Pn{async _call(e){return new Ln(await super._call(e))}},Dg=class extends Pn{async _call(e){return new ku(await super._call(e))}},Ln=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},ku=class extends Re{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var fa=class extends y{},Ug=class extends fa{},Fg=class extends fa{async _call(e){return new G(await super._call(e))}};var da=class extends y{},Gg=class extends da{},jg=class extends da{async _call(e){return new G(await super._call(e))}};var Eu=class extends y{},qg=class extends Eu{};var Au=class extends y{},Wg=class extends Au{};var Zr=class extends y{},Vg=class extends Zr{},Hg=class extends Zr{async _call(e){return new G(await super._call(e))}},Xg=class extends Zr{async _call(e){return new he(await super._call(e))}},Kg=class extends Zr{async _call(e){return new Te(await super._call(e))}},Yg=class extends Zr{async _call(e){return new ge(await super._call(e))}};var Tu=class extends y{},Qg=class extends Tu{};var ma=class extends y{},Jg=class extends ma{},Zg=class extends ma{};var _a=class extends y{},ew=class extends _a{},tw=class extends _a{async _call(e){return new G(await super._call(e))}};var es=class extends y{},rw=class extends es{},sw=class extends es{async _call(e){return new ge(await super._call(e))}},nw=class extends es{async _call(e){return new G(await super._call(e))}},ow=class extends es{async _call(e){return new he(await super._call(e))}},aw=class extends es{async _call(e){return new Te(await super._call(e))}};var ha=class extends y{},iw=class extends ha{},lw=class extends ha{};var $s=class extends y{},cw=class extends $s{},uw=class extends $s{async _call(e){return new ge(await super._call(e))}},pw=class extends $s{async _call(e){return new G(await super._call(e))}},fw=class extends $s{async _call(e){return new he(await super._call(e))}};var Bs=class extends y{},dw=class extends Bs{},mw=class extends Bs{async _call(e){return new ge(await super._call(e))}},_w=class extends Bs{async _call(e){return new G(await super._call(e))}},hw=class extends Bs{async _call(e){return new he(await super._call(e))}};var ga=class extends y{},gw=class extends ga{},ww=class extends ga{};var wa=class extends y{},xw=class extends wa{},yw=class extends wa{};var xa=class extends y{},bw=class extends xa{},vw=class extends xa{};var ya=class extends y{},kw=class extends ya{},Ew=class extends ya{async _call(e){return new G(await super._call(e))}};var Mu=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"},Aw=class extends Mu{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:ke([r,e],1),attention_mask:ke([tt(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 Ct(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var ba=class extends y{},Tw=class extends ba{},Mw=class extends ba{};var va=class extends y{},Sw=class extends va{},Ow=class extends va{};var Su=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Et=class extends Su{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Sn({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},Iw=class extends Et{},Cw=class extends Et{};var Ou=class extends y{},Pw=class extends Ou{},Iu=class extends Et{},Lw=class extends Iu{};var Cu=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"]},zn=class extends Cu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:c=null,generation_config:p=null,logits_processor:f=null,...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 Ct(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,attention_mask:r,position_ids:a,generation_config:p,logits_processor:f},!0)}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Sn({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 mu({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},zw=class extends zn{};var ka=class extends y{},Nw=class extends ka{},Rw=class extends ka{};var Ea=class extends y{},$w=class extends Ea{},Bw=class extends Ea{};var Pu=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Nn=class extends Pu{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,r){if(r){let{data:s,dims:n}=ph(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 R("int64",o,[3,...n]),new R("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 R("int64",o,[3,...e.dims]),Md([s,1])]}}_reorder_and_write_positions(e,r,s,n){let o=e.reduce((c,p)=>c+p.length,0),a=new Array(o),i=0;for(let c=0;c<3;++c)for(let p of e){let f=p.length/3;for(let m=c*f;m<(c+1)*f;++m)a[i++]=p[m]}let l=0;for(let c=0;c<r.length;++c)if(r[c]==1){for(let p=0;p<3;++p)s[p][n][c]=a[p*o/3+l];++l}return a}_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,video_token_id:i,vision_start_token_id:l}=this.config,c=e,f=c.reduce((A,S,M)=>(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,b=m,E=_;for(let A=0;A<f.length;++A){let S=c.findIndex((J,xe)=>xe>x&&J==a),M=c.findIndex((J,xe)=>xe>x&&J==i),P=b>0&&S!==-1?S:c.length+1,O=E>0&&M!==-1?M:c.length+1,k,W,X,U;P<O?([W,X,U]=r[o.image_index],++o.image_index,--b,k=P):([W,X,U]=s[o.video_index],++o.video_index,--E,k=O);let[H,j,K]=[Number(W),Math.floor(Number(X)/n),Math.floor(Number(U)/n)],$=k-x,C=w.length>0?Ce(w.at(-1))[0]+1:0;w.push(Array.from({length:3*$},(J,xe)=>C+xe%$));let te=$+C,ae=H*j*K,L=Array.from({length:ae},(J,xe)=>te+Math.floor(xe/(j*K))),N=Array.from({length:ae},(J,xe)=>te+Math.floor(xe/K)%j),D=Array.from({length:ae},(J,xe)=>te+xe%K);w.push([L,N,D].flat()),x=k+ae}if(x<c.length){let A=w.length>0?Ce(w.at(-1))[0]+1:0,S=c.length-x;w.push(Array.from({length:3*S},(M,P)=>A+P%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=vc(e));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),p=r?r.tolist():[],f=s?s.tolist():[],m={image_index:0,video_index:0},_=[];for(let w=0;w<i.length;++w){let x=i[w].filter((A,S)=>l[w][S]==1),b=this._get_multimodal_rope_positions({filtered_ids:x,image_grid_thw_list:p,video_grid_thw_list:f,spatial_merge_size:a,state:m}),E=this._reorder_and_write_positions(b,l[w],c,w);_.push(Ce(E)[0]+1-i[w].length)}return[new R("int64",c.flat(1/0),[3,e.dims[0],e.dims[1]]),new R("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 Sn({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(o<r.input_ids.dims[1]){let[a,i]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);r.rope_deltas=i,r.position_ids=a.slice(null,null,[o,null]),r.input_ids=r.input_ids.slice(null,[o,null])}else{r.rope_deltas||([,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask));let a=BigInt(o),i=r.rope_deltas.map(l=>a+l);r.position_ids=It([i,i,i],0)}}return r}},Aa=class extends Nn{};var Ds=class extends Nn{image_grid_thw_name="image_grid_thw"},Ta=class extends Aa{image_grid_thw_name="image_grid_thw"};var Dw=class extends Ds{get_vision_position_ids(e,r,s,n){let o=Math.floor(r[0]/s),a=Math.floor(r[1]/n),i=Math.floor(r[2]/n),l=a*i*o,c=Array.from({length:l},()=>e),p=Array.from({length:l},(m,_)=>e+Math.floor(_/(i*o))),f=Array.from({length:l},(m,_)=>e+_%i);return[...c,...p,...f]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:o}){let{image_token_id:a}=this.config,i=[],l=0,c=e[0]==a?1:0;for(let m=1;m<=e.length;++m){let _=m<e.length?e[m]==a?1:0:-1;_!==c&&(i.push([c,l,m]),l=m,c=_)}let p=0,f=[];for(let[m,_,w]of i)if(m===0){let x=w-_;f.push(Array.from({length:3*x},(b,E)=>p+E%x)),p+=x}else{let x=r[o.image_index++].map(Number),b=x[0];f.push(this.get_vision_position_ids(p,x,b,n)),p+=Math.max(x[1],x[2])/n}return f}};var Ma=class extends y{},Uw=class extends Ma{},Fw=class extends Ma{};var Sa=class extends y{},Gw=class extends Sa{},jw=class extends Sa{};var Oa=class extends y{},qw=class extends Oa{},Ww=class extends Oa{};var Ia=class extends y{},Vw=class extends Ia{},Hw=class extends Ia{};var Ca=class extends y{},Xw=class extends Ca{},Kw=class extends Ca{};var Pa=class extends y{},Yw=class extends Pa{},Qw=class extends Pa{};var La=class extends y{},Jw=class extends La{},Zw=class extends La{};var za=class extends y{},ex=class extends za{},tx=class extends za{};var Na=class extends y{},rx=class extends Na{},sx=class extends Na{};var Lu=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Us=class extends Lu{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return mu({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}};var nx=class extends Us{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var zu=class extends y{},ox=class extends zu{};var Nu=class extends y{},ax=class extends Nu{};var Ra=class extends y{},ix=class extends Ra{},lx=class extends Ra{};var $a=class extends y{},cx=class extends $a{},ux=class extends $a{async _call(e){return new G(await super._call(e))}};var sr=class extends y{},px=class extends sr{},fx=class extends sr{async _call(e){return new kt(await super._call(e))}},dx=class extends sr{async _call(e){return new G(await super._call(e))}},mx=class extends sr{async _call(e){return new he(await super._call(e))}};var _x=class extends y{},hx=class extends sr{},gx=class extends sr{async _call(e){return new kt(await super._call(e))}},wx=class extends sr{async _call(e){return new G(await super._call(e))}};var Ba=class extends y{},xx=class extends Ba{},yx=class extends Ba{};var bx=class extends Et{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var Da=class extends y{},vx=class extends Da{},kx=class extends Da{async _call(e){return new G(await super._call(e))}};var Ua=class extends y{},Ex=class extends Ua{},Ax=class extends Ua{};var Rn=class extends y{},Tx=class extends Rn{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=tt([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=He([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}},Fa=class extends Rn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Mx=class extends Rn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Ga=class extends y{},Sx=class extends Ga{},Ox=class extends Ga{};var Ix=class extends Et{};var ja=class extends y{},Cx=class extends ja{},Px=class extends ja{};var Lx=class extends Et{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var qa=class extends y{},zx=class extends qa{},Nx=class extends qa{};var Ru=class extends y{},Rx=class extends Ru{};var Wa=class extends y{},$x=class extends Wa{},Bx=class extends Wa{};var Va=class extends y{},Dx=class extends Va{},Ux=class extends Va{};var Ha=class extends y{},Fx=class extends Ha{},Gx=class extends Ha{};var Xa=class extends y{},jx=class extends Xa{},qx=class extends Xa{};var Fs=class extends y{},Wx=class extends Fs{},Vx=class extends Fs{},Hx=class extends Fs{async _call(e){return new G(await super._call(e))}},Xx=class extends Fs{};var $u=class extends y{},Kx=class extends $u{};var Bu=class extends y{},Yx=class extends Bu{};var Du=class extends Re{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Uu=class extends y{},Qx=class extends Uu{async _call(e){return new Du(await super._call(e))}};var Fu=class extends Re{constructor({audio_codes:e}){super(),this.audio_codes=e}},Gu=class extends Re{constructor({audio_values:e}){super(),this.audio_values=e}},$n=class extends y{main_input_name="input_values";forward_params=["input_values"]},Jx=class extends $n{async encode(e){return new Fu(await fe(this.sessions.encoder_model,e))}async decode(e){return new Gu(await fe(this.sessions.decoder_model,e))}},Ka=class extends $n{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Ya=class extends $n{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Qa=class extends y{},Zx=class extends Qa{},ey=class extends Qa{};var Ja=class extends y{},ty=class extends Ja{},ry=class extends Ja{};var Gs=class extends y{},sy=class extends Gs{},ny=class extends Gs{async _call(e){return new ge(await super._call(e))}},oy=class extends Gs{async _call(e){return new G(await super._call(e))}},ay=class extends Gs{async _call(e){return new Te(await super._call(e))}};var Za=class extends y{},iy=class extends Za{},ly=class extends Za{};var Bn=class extends y{},cy=class extends Bn{},uy=class extends Bn{async _call(e){return new G(await super._call(e))}},py=class extends Bn{};var Dn=class extends y{},fy=class extends Dn{},dy=class extends Dn{async _call(e){return new G(await super._call(e))}},my=class extends Dn{};var Un=class extends y{},_y=class extends Un{},hy=class extends Un{async _call(e){return new G(await super._call(e))}},gy=class extends Un{};var Fn=class extends y{},wy=class extends Fn{},xy=class extends Fn{async _call(e){return new G(await super._call(e))}},yy=class extends Fn{};var ei=class extends y{},by=class extends ei{},vy=class extends ei{async _call(e){return new G(await super._call(e))}};var ti=class extends y{},ky=class extends ti{},Ey=class extends ti{async _call(e){return new G(await super._call(e))}};var js=class extends y{},Ay=class extends js{},Ty=class extends js{async _call(e){return new ge(await super._call(e))}},My=class extends js{async _call(e){return new G(await super._call(e))}},Sy=class extends js{async _call(e){return new he(await super._call(e))}};var ri=class extends y{},Oy=class extends ri{},Iy=class extends ri{};var si=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},Cy=class extends si{},Py=class extends si{};var ts=class extends y{},Ly=class extends ts{},zy=class extends ts{async _call(e){return new ge(await super._call(e))}},Ny=class extends ts{async _call(e){return new G(await super._call(e))}},Ry=class extends ts{async _call(e){return new he(await super._call(e))}},$y=class extends ts{async _call(e){return new Te(await super._call(e))}};var ni=class extends y{},By=class extends ni{},Dy=class extends ni{};var oi=class extends y{},Uy=class extends oi{},Fy=class extends oi{};var ju=class extends y{},Gy=class extends ju{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=Ke(e,l.inputNames);s=await fe(l,c)}else{let l=this.sessions.gen_img_embeds,c=Ke({image_ids:e.input_ids},l.inputNames);s=await fe(l,c)}let n={...e,...s},o=await Ct(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await fe(a,Ke(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=ke([r.input_ids,r.input_ids],0):(r.input_ids=ke([r.input_ids,To(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=ke([r.attention_mask,To(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=He([0,0,3,384,384],1)),n&&(r.images_seq_mask=new R("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new R("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 p=Ye.fromTensor(c);l.push(p)}return l}};var ai=class extends y{},jy=class extends ai{},qy=class extends ai{},ii=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;c<e.size;++c){if(e.data[c]==this.config.decoder.pad_token_id)continue;let p=c%s,f=Math.floor(c/s)%n,m=p-f;m>0&&m<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new R(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<o.length;++a)for(let i=0;i<o[a].length;++i)a%this.config.decoder.num_codebooks>=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),Fo(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 li=class extends y{},Wy=class extends li{},Vy=class extends li{};var ci=class extends y{},Hy=class extends ci{},Xy=class extends ci{};var rs=class extends y{},Ky=class extends rs{},Yy=class extends rs{async _call(e){return new ge(await super._call(e))}},Qy=class extends rs{async _call(e){return new G(await super._call(e))}},Jy=class extends rs{async _call(e){return new he(await super._call(e))}},Zy=class extends rs{async _call(e){return new Te(await super._call(e))}};var qu=class extends y{},e0=class extends qu{};var ui=class extends y{},t0=class extends ui{},r0=class extends ui{};var pi=class extends y{},s0=class extends pi{},n0=class extends pi{};var fi=class extends y{},o0=class extends fi{},a0=class extends fi{};var di=class extends y{},i0=class extends di{},l0=class extends di{};var mi=class extends y{},c0=class extends mi{},u0=class extends mi{};var _i=class extends y{},p0=class extends _i{},f0=class extends _i{};var hi=class extends y{},d0=class extends hi{},m0=class extends hi{};var gi=class extends y{},_0=class extends gi{},h0=class extends gi{};var g0=class extends Et{};var Wu=class extends y{},w0=class extends Wu{async _call(e){return new kt(await super._call(e))}};var wi=class extends y{},x0=class extends wi{},y0=class extends wi{};var xi=class extends y{},b0=class extends xi{},v0=class extends xi{};var yi=class extends y{},k0=class extends yi{},E0=class extends yi{};var bi=class extends y{},A0=class extends bi{},T0=class extends bi{};var Vu=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},vi=class extends Vu{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,...p}){if(!a){let 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 R("float32",[],[0,_])}({inputs_embeds:a}=await fe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await Ct(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var ki=class extends y{},M0=class extends ki{},S0=class extends ki{async _call(e){return new G(await super._call(e))}};var Ei=class extends y{},O0=class extends Ei{},I0=class extends Ei{async _call(e){return new he(await super._call(e))}};var Ai=class extends y{},C0=class extends Ai{},P0=class extends Ai{};var Ti=class extends y{},L0=class extends Ti{},z0=class extends Ti{};var Mi=class extends y{},N0=class extends Mi{},R0=class extends Mi{};var Si=class extends y{},$0=class extends Si{},B0=class extends Si{};var Oi=class extends y{},D0=class extends Oi{},U0=class extends Oi{};var qs=class extends Ds{},Ii=class extends Ta{};var F0=class extends qs{},G0=class extends Ii{};var Gn=class extends qs{},Ci=class extends Gn{};var j0=class extends Gn{},q0=class extends Ci{};var Pi=class extends y{},W0=class extends Pi{},V0=class extends Pi{async _call(e){return new G(await super._call(e))}};var Li=class extends y{},H0=class extends Li{},X0=class extends Li{async _call(e){return new Hu(await super._call(e))}},Hu=class extends dr{};var ss=class extends y{},K0=class extends ss{},Y0=class extends ss{async _call(e){return new ge(await super._call(e))}},Q0=class extends ss{async _call(e){return new G(await super._call(e))}},J0=class extends ss{async _call(e){return new he(await super._call(e))}},Z0=class extends ss{async _call(e){return new Te(await super._call(e))}};var ns=class extends y{},eb=class extends ns{},tb=class extends ns{async _call(e){return new ge(await super._call(e))}},rb=class extends ns{async _call(e){return new G(await super._call(e))}},sb=class extends ns{async _call(e){return new he(await super._call(e))}},nb=class extends ns{async _call(e){return new Te(await super._call(e))}};var zi=class extends y{},ob=class extends zi{},ab=class extends zi{async _call(e){return new Xu(await super._call(e))}},Xu=class extends dr{};var Ku=class extends Re{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},Yu=class extends y{},ib=class extends Yu{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??=tt(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 Ku(await super._call(e))}};var Qu=class extends Re{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},Ju=class extends y{},Ni=class extends Ju{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??=tt(a.slice(0,-1)),e.input_boxes??=He([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=He([a[0],a[1],0],-1n),e.input_points=He([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=Ke(e,n.inputNames);return await fe(n,o)}async _call(e){return new Qu(await super._call(e))}},lb=class extends Ni{},cb=class extends Ni{};var jn=class extends y{},ub=class extends jn{},pb=class extends jn{},fb=class extends jn{};var qn=class extends y{},db=class extends qn{},mb=class extends qn{},_b=class extends qn{};var Ri=class extends y{},hb=class extends Ri{},$i=class extends Ri{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},gb=class extends fr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Bi=class extends y{},wb=class extends Bi{},xb=class extends Bi{};var Wn=class extends y{main_input_name="input_values";forward_params=["input_values"]},yb=class extends Wn{async encode(e){return await fe(this.sessions.encoder_model,e)}async decode(e){return await fe(this.sessions.decoder_model,e)}},Di=class extends Wn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Ui=class extends Wn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Fi=class extends y{},bb=class extends Fi{},vb=class extends Fi{};var Vn=class extends y{},kb=class extends Vn{},Eb=class extends Vn{},Ab=class extends Vn{async generate_speech(e,r,{threshold:s=.5,minlenratio:n=0,maxlenratio:o=20,vocoder:a=null}={}){let i={input_ids:e},{encoder_outputs:l,encoder_attention_mask:c}=await Vt(this,i),p=l.dims[1]/this.config.reduction_factor,f=Math.floor(p*o),m=Math.floor(p*n),_=this.config.num_mel_bins,w=[],x=null,b=null,E=0;for(;;){++E;let M=uh(!!b),P;b?P=b.output_sequence_out:P=new R("float32",new Float32Array(_),[1,1,_]);let O={use_cache_branch:M,output_sequence:P,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(O,x),b=await fe(this.sessions.decoder_model_merged,O),x=this.getPastKeyValues(b,x);let{prob:k,spectrum:W}=b;if(w.push(W),E>=m&&(Array.from(k.data).filter(X=>X>=s).length>0||E>=f))break}let A=ke(w),{waveform:S}=await fe(a.sessions.model,{spectrogram:A});return{spectrogram:A,waveform:S}}},Tb=class extends y{main_input_name="spectrogram"};var Ws=class extends y{},Mb=class extends Ws{},Sb=class extends Ws{async _call(e){return new ge(await super._call(e))}},Ob=class extends Ws{async _call(e){return new G(await super._call(e))}},Ib=class extends Ws{async _call(e){return new Te(await super._call(e))}};var Gi=class extends y{},Cb=class extends Gi{},Pb=class extends Gi{};var ji=class extends y{},Lb=class extends ji{},zb=class extends ji{};var Zu=class extends y{},Nb=class extends Zu{};var ep=class extends y{},qi=class extends ep{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:c}=this.config,{last_hidden_state:p,durations:f}=await 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,U=>Math.ceil(U/_)),b=Math.max(...x),E=e.dims[0],A=new BigInt64Array(E*b);for(let U=0;U<E;++U)A.fill(1n,U*b,U*b+x[U]);let S=new R("int64",A,[E,b]),M=c*i,P=M*b,O=V2([E,M,b]),k=O.data;for(let U=0;U<E;++U)if(x[U]!==b)for(let H=0;H<M;++H)k.fill(0,U*P+H*b+x[U],U*P+(H+1)*b);let W=He([E],n);for(let U=0;U<n;++U){let H=He([E],U);({denoised_latents:O}=await fe(this.sessions.latent_denoiser,{style:s,noisy_latents:O,latent_mask:S,encoder_outputs:p,attention_mask:r,timestep:H,num_inference_steps:W}))}let{waveform:X}=await fe(this.sessions.voice_decoder,{latents:O});return{waveform:X,durations:m}}};var Hn=class extends y{},Rb=class extends Hn{},$b=class extends Hn{async _call(e){return new G(await super._call(e))}},Bb=class extends Hn{};var Wi=class extends y{},Db=class extends Wi{},Ub=class extends Wi{};var Vi=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},Fb=class extends Vi{},Gb=class extends Vi{};var Hi=class extends y{},jb=class extends Hi{},qb=class extends Hi{async _call(e){return new tp(await super._call(e))}},tp=class extends Ln{};var rp=class extends y{},Wb=class extends rp{};var Xn=class extends y{},Vb=class extends Xn{},Hb=class extends Xn{async _call(e){return new kt(await super._call(e))}},Xb=class extends Xn{async _call(e){return new G(await super._call(e))}};var Vs=class extends y{},Kb=class extends Vs{},Yb=class extends Vs{async _call(e){return new kt(await super._call(e))}},Qb=class extends Vs{async _call(e){return new G(await super._call(e))}},Jb=class extends Vs{async _call(e){return new he(await super._call(e))}};var Xi=class extends y{},Zb=class extends Xi{},e1=class extends Xi{};var t1=class extends y{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]};var Ki=class extends y{},r1=class extends Ki{},s1=class extends Ki{async _call(e){return new G(await super._call(e))}};var sp=class extends y{},n1=class extends sp{};var Yi=class extends y{},o1=class extends Yi{},a1=class extends Yi{async _call(e){return new G(await super._call(e))}};var np=class extends y{},i1=class extends np{async _call(e){return new Yc(await super._call(e))}};var op=class extends y{},l1=class extends op{};var ap=class extends Re{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}},ip=class extends y{},c1=class extends ip{async _call(e){return new ap(await super._call(e))}};var u1=class extends Us{};var ET=2,MN=1,p1=new WeakMap;function SN(t,e){let{text_config:r,audio_config:s}=t.config,n=t.sessions.audio_encoder,{num_mel_bins:o,hidden_size:a}=s,i=o+a,l=new Uo,c=n?.config?.kv_cache_dtype??"float32",p=c==="float16"?vr.float16:vr.float32,f=Cs(s,{batch_size:1});for(let w in f){let x=f[w].reduce((b,E)=>b*E,1);l[w]=new R(c,new p(x),f[w])}let m=new R(c,new p(i*ET),[1,i,ET]),_=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 ON(t,e){let r=e.dims[2],s=Math.floor((MN+r-3)/2)+1,n=new R("int64",BigInt64Array.from({length:s},(p,f)=>BigInt(t.enc_past_seq_len+f)),[1,s]),o=t.enc_past_seq_len+s,a=tt([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 p in c)if(p.startsWith("present.")){let f=p.replace("present","past_key_values"),m=t.enc_kv_cache[f];m?.location==="gpu-buffer"&&m.dispose(),t.enc_kv_cache[f]=c[p]}return t.enc_past_seq_len=o,i}async function IN(t,e){for(;t.audio_embed_total_tokens<e&&!t.stream_exhausted;){let r=await t.chunks_iter.next();if(r.done){t.stream_exhausted=!0;break}let s=await ON(t,r.value);t.audio_embed_queue.push({data:s.data,tokens:s.dims[1]}),t.audio_embed_total_tokens+=s.dims[1]}}function CN(t,e,r){if(t.audio_embed_queue.length===0)return;let s=e.data,n=0,o=r;for(;o>0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let p=0;p<l*t.text_hidden_size;++p)s[n*t.text_hidden_size+p]+=a.data[c+p];n+=l,o-=l,t.audio_queue_offset+=l,t.audio_queue_offset>=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var f1=class extends Hr{constructor(e){super(),this._s=e}_call(e){let r=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>r)}},lp=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},Qi=class extends lp{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=p1.get(this);o&&await IN(o,o.audio_consumed+n);let{inputs_embeds:a}=await fe(this.sessions.embed_tokens,{input_ids:e});o&&CN(o,a,n);let i={inputs_embeds:a,...s};this.addPastKeyValues(i,r);let l=this.sessions.decoder_model_merged,c=Ke(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=SN(this,e);p1.set(this,n);let o=new Tn;o.push(new f1(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),p1.delete(this)}}};var Kn=class extends y{},d1=class extends Kn{},m1=class extends Kn{async _call(e){return new kt(await super._call(e))}},_1=class extends Kn{async _call(e){return new G(await super._call(e))}};var cp=class extends Re{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},os=class extends y{},h1=class extends os{},g1=class extends os{async _call(e){return new kt(await super._call(e))}},w1=class extends os{async _call(e){return new G(await super._call(e))}},x1=class extends os{async _call(e){return new cp(await super._call(e))}},y1=class extends os{async _call(e){return new he(await super._call(e))}};var up=class extends y{},b1=class extends up{};var pp=class extends An{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 Ji=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"]},v1=class extends Ji{},fp=class extends Ji{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,pp)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(Z.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${K2(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&&(Z.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 Ps,s.push(new Zc(r,a))),r.begin_suppress_tokens&&(s??=new Ps,s.push(new En(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"&&Z.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}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)),i}_extract_token_timestamps(e,r,s=null,n=.02){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&&Z.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 o=this.config.median_filter_width;o===void 0&&(Z.warn("Model config has no `median_filter_width`, using default value of 7."),o=7);let a=e.cross_attentions,i=Array.from({length:this.config.decoder_layers},(x,b)=>ke(a.map(E=>E[b]),2)),l=It(r.map(([x,b])=>{if(x>=i.length)throw new Error(`Layer index ${x} is out of bounds for cross attentions (length ${i.length}).`);return s?i[x].slice(null,b,null,[0,s]):i[x].slice(null,b)})).transpose(1,0,2,3),[c,p]=Ad(l,-2,0,!0),f=l.clone();for(let x=0;x<f.dims[0];++x){let b=f[x];for(let E=0;E<b.dims[0];++E){let A=b[E],S=c[x][E][0].data,M=p[x][E][0].data;for(let P=0;P<A.dims[0];++P){let O=A[P].data;for(let k=0;k<O.length;++k)O[k]=(O[k]-M[k])/S[k];O.set(HE(O,o))}}}let m=[bc(f,1)],_=e.sequences.dims,w=new R("float32",new Float32Array(_[0]*_[1]),_);for(let x=0;x<_[0];++x){let b=m[x].neg().squeeze_(0),[E,A]=KE(b.tolist()),S=Array.from({length:E.length-1},(O,k)=>E[k+1]-E[k]),M=gt([1],S).map(O=>!!O),P=[];for(let O=0;O<M.length;++O)M[O]&&P.push(A[O]*n);w[x].data.set(P,1)}return w}},k1=class extends fp{};var as=class extends y{},E1=class extends as{},A1=class extends as{async _call(e){return new ge(await super._call(e))}},T1=class extends as{async _call(e){return new G(await super._call(e))}},M1=class extends as{async _call(e){return new he(await super._call(e))}},S1=class extends as{async _call(e){return new Te(await super._call(e))}};var is=class extends y{},O1=class extends is{},I1=class extends is{async _call(e){return new ge(await super._call(e))}},C1=class extends is{async _call(e){return new G(await super._call(e))}},P1=class extends is{async _call(e){return new he(await super._call(e))}},L1=class extends is{async _call(e){return new Te(await super._call(e))}};var Zi=class extends y{},z1=class extends Zi{},N1=class extends Zi{async _call(e){return new dp(await super._call(e))}},dp=class extends Re{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var el=class extends y{},R1=class extends el{},$1=class extends el{};var PN=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"]]),LN=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),zN=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),NN=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"]]),AT=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),TT=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),MT=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),ST=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"]]),OT=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"]]),IT=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),CT=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"]]),RN=new Map([["multi_modality","MultiModalityCausalLM"]]),PT=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"]]),LT=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"]]),zT=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),NT=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"]]),RT=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),$N=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),$T=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"]]),BT=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),DT=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Yn=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),UT=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),FT=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),GT=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),jT=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),qT=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),WT=new Map([["wavlm","WavLMForXVector"]]),VT=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),HT=new Map([["vitmatte","VitMatteForImageMatting"]]),BN=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),XT=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),KT=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),YT=new Map([["sapiens","SapiensForNormalEstimation"]]),QT=new Map([["vitpose","VitPoseForPoseEstimation"]]),JT=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),B1=[[PN,Q.EncoderOnly],[LN,Q.EncoderDecoder],[NN,Q.DecoderOnlyWithoutHead],[zN,Q.AutoEncoder],[ST,Q.EncoderOnly],[OT,Q.EncoderOnly],[IT,Q.Seq2Seq],[AT,Q.Seq2Seq],[CT,Q.DecoderOnly],[RN,Q.MultiModality],[PT,Q.EncoderOnly],[LT,Q.EncoderOnly],[zT,Q.Vision2Seq],[NT,Q.ImageTextToText],[RT,Q.AudioTextToText],[$T,Q.EncoderOnly],[Yn,Q.EncoderOnly],[FT,Q.EncoderOnly],[UT,Q.EncoderOnly],[HT,Q.EncoderOnly],[BN,Q.EncoderOnly],[XT,Q.EncoderOnly],[KT,Q.EncoderOnly],[YT,Q.EncoderOnly],[QT,Q.EncoderOnly],[BT,Q.EncoderOnly],[DT,Q.EncoderOnly],[GT,Q.MaskGeneration],[jT,Q.EncoderOnly],[qT,Q.EncoderOnly],[TT,Q.Seq2Seq],[MT,Q.EncoderOnly],[WT,Q.EncoderOnly],[VT,Q.EncoderOnly],[JT,Q.EncoderOnly]];for(let[t,e]of B1)for(let r of t.values()){rr.set(r,e);let s=tl[r];Ns.set(s,r),du.set(r,s)}var DN=[["MusicgenForConditionalGeneration",ii,Q.Musicgen],["Phi3VForCausalLM",vi,Q.Phi3V],["CLIPTextModelWithProjection",Zo,Q.EncoderOnly],["SiglipTextModel",$i,Q.EncoderOnly],["JinaCLIPTextModel",Fa,Q.EncoderOnly],["ClapTextModelWithProjection",Qo,Q.EncoderOnly],["ClapAudioModelWithProjection",Jo,Q.EncoderOnly],["DacEncoderModel",la,Q.EncoderOnly],["DacDecoderModel",ca,Q.EncoderOnly],["MimiEncoderModel",Ka,Q.EncoderOnly],["MimiDecoderModel",Ya,Q.EncoderOnly],["SnacEncoderModel",Di,Q.EncoderOnly],["SnacDecoderModel",Ui,Q.EncoderOnly],["Gemma3nForConditionalGeneration",zn,Q.ImageAudioTextToText],["SupertonicForConditionalGeneration",qi,Q.Supertonic],["ChatterboxModel",Yo,Q.Chatterbox],["VoxtralRealtimeForConditionalGeneration",Qi,Q.VoxtralRealtime]];for(let[t,e,r]of DN)rr.set(t,r),Ns.set(e,t),du.set(t,e);var ZT=new Map([["modnet",Yn],["birefnet",Yn],["isnet",Yn],["ben",Yn]]);for(let[t,e]of ZT.entries())e.set(t,"PreTrainedModel"),rr.set(t,Q.EncoderOnly),du.set(t,y);var eM=new Set(ZT.keys());rr.set("PreTrainedModel",Q.EncoderOnly);Ns.set(y,"PreTrainedModel");var Le={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:ST,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:OT,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:TT,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:MT,MODEL_FOR_MASKED_LM_MAPPING_NAMES:PT,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:LT,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:$T,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Yn,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:UT,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:FT,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:BT,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:DT,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:GT,MODEL_FOR_CTC_MAPPING_NAMES:jT,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:qT,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:WT,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:VT,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:$N,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:HT,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:XT,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:KT,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:YT,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:QT,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:JT,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:NT,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:RT,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:IT,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:AT,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:CT,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:zT};yT(Le);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:p=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:p,use_external_data_format:f,session_options:m};if(_.config=await qt.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 b=x.get(w);if(!b){for(let E of x.values())if(E[0]===w){b=E;break}if(!b)continue}return await tl[b].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return eM.has(w)||Z.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,_);throw Error(`Unsupported model type: ${w}`)}},Er=class extends Ie{static MODEL_CLASS_MAPPINGS=B1.map(e=>e[0]);static BASE_IF_FAIL=!0},rl=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},mp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Qn=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},_p=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},hp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},gp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},wp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},xp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},yp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},bp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},vp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},sl=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},nl=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},ol=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},kp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Ep=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},tM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},Ap=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_CTC_MAPPING_NAMES]},Tp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},rM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},sM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},Mp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},nM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},Sp=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},Op=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},oM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},aM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},Ip=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},iM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},lM=class extends Ie{static MODEL_CLASS_MAPPINGS=[Le.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function Je(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Ye.read(e)))}async function ls(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?km(r,e):r instanceof Float64Array?new Float32Array(r):r))}function al(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 et{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 il=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 R("float32",Ne(c.data),c.dims),l=[];for(let c of n.logits){let p=i(c),f=await tr(p,r),m=f[0].tolist(),w=f[1].tolist().map((x,b)=>({label:a?a[x]:`LABEL_${x}`,score:m[b]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var ll=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;c<a.dims[0];++c){let p=n.input_ids[c],f=a[c],m=[];for(let _=0;_<f.dims[0];++_){let w=f[_],x=Ce(w.data)[1],b=i?i[x]:`LABEL_${x}`;if(r.includes(b))continue;let E=this.tokenizer.decode([p[_].item()],{skip_special_tokens:!0});if(E==="")continue;let A=Ne(w.data);m.push({entity:b,score:A[x],index:_,word:E})}l.push(m)}return s?l:l[0]}};var cl=class extends de{async _call(e,r,{top_k:s=1}={}){let n=this.tokenizer(e,{text_pair:r,padding:!0,truncation:!0}),o=Array.isArray(e),{start_logits:a,end_logits:i}=await this.model(n),l=n.input_ids.tolist(),c=n.attention_mask.tolist(),{all_special_ids:p,sep_token_id:f}=this.tokenizer,m=[];for(let _=0;_<a.dims[0];++_){let w=l[_],x=w.findIndex(O=>O==f),b=a[_].tolist(),E=i[_].tolist();for(let O=1;O<b.length;++O)(c[_]==0||O<=x||p.findIndex(k=>k==w[O])!==-1)&&(b[O]=-1/0,E[O]=-1/0);let A=Ne(b).map((O,k)=>[O,k]),S=Ne(E).map((O,k)=>[O,k]);A[0][0]=0,S[0][0]=0;let M=rE(A,S).filter(O=>O[0][1]<=O[1][1]).map(O=>[O[0][1],O[1][1],O[0][0]*O[1][0]]).sort((O,k)=>k[2]-O[2]),P=[];for(let O=0;O<Math.min(M.length,s);++O){let[k,W,X]=M[O],U=w.slice(k,W+1),H=this.tokenizer.decode(U,{skip_special_tokens:!0});P.push({answer:H,score:X})}s===1?m.push(...P):m.push(P)}return o?m:m[0]}};var ul=class extends de{async _call(e,{top_k:r=5}={}){let{mask_token_id:s,mask_token:n}=this.tokenizer,o=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(o),i=[],l=o.input_ids.tolist();for(let c=0;c<l.length;++c){let p=l[c],f=p.findIndex(b=>b==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][f],_=await tr(new R("float32",Ne(m.data),m.dims),r),w=_[0].tolist(),x=_[1].tolist();i.push(x.map((b,E)=>{let A=p.slice();return A[f]=b,{score:w[E],token:Number(b),token_str:this.tokenizer.decode([b]),sequence:this.tokenizer.decode(A,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Ar=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 pl=class extends Ar{_key="summary_text"};var fl=class extends Ar{_key="translation_text"};function cM(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var dl=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(cM(e))e=[e];else if(Array.isArray(e)&&e.every(cM))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}),p=await this.model.generate({...c,...r}),f=this.tokenizer.batch_decode(p,{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<f.length;++w){let x=Math.floor(w/p.dims[0]*e.length);m&&(f[w]=f[w].slice(m[x])),_[x].push({generated_text:n?[...e[x],{role:"assistant",content:f[w]}]:f[w]})}return!s&&_.length===1?_[0]:_}};var ml=class extends de{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([r,s])=>[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(Z.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&&(Z.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let p=[];for(let _ of a){let w=this.tokenizer(c,{text_pair:_,padding:!0,truncation:!0}),x=await this.model(w);i?p.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):p.push(x.logits.data[this.entailment_id])}let m=(i?p.map(_=>Ne(_)[1]):Ne(p)).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 _l=class extends de{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await ls(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),p=(await this.model(l)).logits[0],f=await tr(new R("float32",Ne(p.data),p.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,b)=>({label:o?o[x]:`LABEL_${x}`,score:m[b]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var hl=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(p=>s.replace("{}",p)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await ls(e,i),c=[];for(let p of l){let f=await this.processor(p),m=await this.model({...a,...f}),_=Ne(m.logits_per_audio.data);c.push([..._].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var gl=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);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&Z.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&Z.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 ls(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=!1);let l=!Array.isArray(e),c=l?[e]:e,p=this.processor.feature_extractor.config,f=p.chunk_length/this.model.config.max_source_positions,m=p.hop_length,_=p.sampling_rate,w=await ls(c,_),x=[];for(let b of w){let E=[];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,P=_*a,O=M-2*P,k=0;for(;;){let W=k+M,X=b.subarray(k,W),U=await this.processor(X),H=k===0,j=W>=b.length;if(E.push({stride:[X.length,H?0:P,j?0:P],input_features:U.input_features,is_last:j}),j)break;k+=O}}else E=[{stride:[b.length,0,0],input_features:(await this.processor(b)).input_features,is_last:!0}];for(let M of E){i.num_frames=Math.floor(M.stride[0]/m);let P=await this.model.generate({inputs:M.input_features,...i});s==="word"?(M.tokens=P.sequences.tolist()[0],M.token_timestamps=P.token_timestamps.tolist()[0].map(O=>gs(O,2))):M.tokens=P[0].tolist(),M.stride=M.stride.map(O=>O/_)}let[A,S]=this.tokenizer._decode_asr(E,{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 ls(n,o),i=[];for(let l of a){let c=await this.processor(l),p=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:p,...r,...c}),m=this.processor.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}};var wl=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 R("float32",e,[e.length]);else if(!(e instanceof R))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,c=[];for(let p=0;p<a;++p){let f=l?Math.min(Math.ceil(l[p]),i):i,m=p*i;c.push(new Io(o.slice(m,m+f),s))}return Array.isArray(e)?c:c[0]}async _call(e,r){return this.processor?this._call_text_to_spectrogram(e,r):this.model.config.model_type==="supertonic"?this._call_supertonic(e,r):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:r,num_inference_steps:s,speed:n}){if(!r)throw new Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:o,style_dim:a}=this.model.config,i=this.tokenizer(e,{padding:!0,truncation:!0}),l=i.input_ids.dims[0];r=await this._prepare_speaker_embeddings(r,l),r=r.view(l,-1,a);let{waveform:c,durations:p}=await this.model.generate_speech({...i,style:r,num_inference_steps:s,speed:n});return this._postprocess_waveform(e,c,o,p)}async _call_text_to_waveform(e){let r=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(r),n=this.model.config.sampling_rate;return this._postprocess_waveform(e,s,n)}async _call_text_to_spectrogram(e,{speaker_embeddings:r}){this.vocoder||(Z.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await Er.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:s}=this.tokenizer(e,{padding:!0,truncation:!0}),n=s.dims[0];r=await this._prepare_speaker_embeddings(r,n),r=r.view(n,-1);let{waveform:o}=await this.model.generate_speech(s,r,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,o,a)}};var xl=class extends de{async _call(e,r={}){let s=Array.isArray(e),n=await Je(e),{pixel_values:o}=await this.processor(n),a=[];for(let i of o){i.dims=[1,...i.dims];let l=await this.model.generate({inputs:i,...r}),c=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}).map(p=>({generated_text:p.trim()}));a.push(c)}return s?a:a[0]}};var yl=class extends de{async _call(e,{top_k:r=5}={}){let s=await Je(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 R("float32",Ne(l.data),l.dims),r),p=c[0].tolist(),m=c[1].tolist().map((_,w)=>({label:a?a[_]:`LABEL_${_}`,score:p[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var uM={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},Hs=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 Je(e),p=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=uM[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(uM))if(S in this.processor.image_processor){x=this.processor.image_processor[S].bind(this.processor.image_processor),i=A;break}}let b=this.model.config.id2label,E=[];if(i)if(i==="panoptic"||i==="instance"){let A=x(w,r,s,n,o,a??p)[0],S=A.segmentation;for(let M of A.segments_info){let P=new Uint8ClampedArray(S.data.length);for(let k=0;k<S.data.length;++k)S.data[k]===M.id&&(P[k]=255);let O=new Ye(P,S.dims[1],S.dims[0],1);E.push({score:M.score,label:b[M.label_id],mask:O})}}else if(i==="semantic"){let{segmentation:A,labels:S}=x(w,a??p)[0];for(let M of S){let P=new Uint8ClampedArray(A.data.length);for(let k=0;k<A.data.length;++k)A.data[k]===M&&(P[k]=255);let O=new Ye(P,A.dims[1],A.dims[0],1);E.push({score:null,label:b[M],mask:O})}}else throw Error(`Subtask ${i} not supported.`);else{let S=w[_[0]];for(let M=0;M<p.length;++M){let P=p[M],O=S[M];O.data.some(W=>W<-1e-5||W>1+1e-5)&&O.sigmoid_();let k=await Ye.fromTensor(O.mul_(255).to("uint8")).resize(P[1],P[0]);E.push({label:null,score:null,mask:k})}}return E}};var bl=class extends Hs{async _call(e,r={}){let s=await Je(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 vl=class extends de{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await Je(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}),p=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Ne(m.data),f=[];for(let m of c.logits_per_image){let w=[...p(m)].map((x,b)=>({score:x,label:r[b]}));w.sort((x,b)=>b.score-x.score),f.push(w)}return n?f:f[0]}};var kl=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 Je(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}),p=this.processor.image_processor.post_process_object_detection(c,r,a),{id2label:f}=this.model.config,m=p.map(_=>_.boxes.map((w,x)=>({score:_.scores[x],label:f[_.classes[x]],box:al(w,!s)})));return n?m:m[0]}};var El=class extends de{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await Je(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=await this.processor(i),p=[];for(let f=0;f<i.length;++f){let m=i[f],_=o?null:[[m.height,m.width]],w=c.pixel_values[f].unsqueeze_(0),x=await this.model({...l,pixel_values:w}),b;if("post_process_grounded_object_detection"in this.processor){let E=this.processor.post_process_grounded_object_detection(x,l.input_ids,{box_threshold:s,text_threshold:s,target_sizes:_})[0];b=E.boxes.map((A,S)=>({score:E.scores[S],label:E.labels[S],box:al(A,!o)}))}else{let E=this.processor.image_processor.post_process_object_detection(x,s,_,!0)[0];b=E.boxes.map((A,S)=>({score:E.scores[S],label:r[E.classes[S]],box:al(A,!o)}))}b.sort((E,A)=>A.score-E.score),n!==null&&(b=b.slice(0,n)),p.push(b)}return a?p:p[0]}};var Al=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 Je(e))[0],{pixel_values:o}=await this.processor(n),a=`<s_docvqa><s_question>${r}</s_question><s_answer>`,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}),p=this.tokenizer.batch_decode(l)[0].match(/<s_answer>(.*?)<\/s_answer>/),f=null;return p&&p.length>=2&&(f=p[1].trim()),[{answer:f}]}};var Tl=class extends de{async _call(e){let r=await Je(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(Ye.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var Ml=class extends de{async _call(e){let r=await Je(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a<r.length;++a){let i=n[a],[l,c]=i.dims.slice(-2),[p,f]=r[a].size,m=(await vt(i.view(1,1,l,c),{size:[f,p],mode:"bilinear"})).view(f,p),_=m.min().item(),w=m.max().item(),x=m.sub(_).div_(w-_).mul_(255).to("uint8").unsqueeze(0),b=Ye.fromTensor(x);o.push({predicted_depth:m,depth:b})}return Array.isArray(e)?o:o[0]}};var Sl=class extends de{async _call(e,{pooling:r="none",normalize:s=!1,quantize:n=!1,precision:o="binary"}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(a),l=i.last_hidden_state??i.logits??i.token_embeddings;switch(r){case"none":break;case"mean":l=W2(l,a.attention_mask);break;case"first_token":case"cls":l=l.slice(null,0);break;case"last_token":case"eos":l=l.slice(null,-1);break;default:throw Error(`Pooling method '${r}' not supported.`)}return s&&(l=l.normalize(2,-1)),n&&(l=H2(l,o)),l}};var Ol=class extends de{async _call(e,{pool:r=null}={}){let s=await Je(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),a;if(r){if(!("pooler_output"in o))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");a=o.pooler_output}else a=o.last_hidden_state??o.logits??o.image_embeds;return a}};var Jn=Object.freeze({"text-classification":{pipeline:il,model:rl,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:ll,model:mp,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:cl,model:yp,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:ul,model:xp,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:pl,model:Qn,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:fl,model:Qn,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:Ar,model:Qn,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:dl,model:wp,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:ml,model:rl,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:_l,model:Tp,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:hl,model:Er,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:gl,model:[_p,Ap],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:wl,model:[gp,hp],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:xl,model:bp,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:yl,model:vp,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Hs,model:[sl,nl,ol],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:bl,model:[sl,nl,ol],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:vl,model:Er,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:kl,model:kp,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:El,model:Ep,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:Al,model:Mp,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Tl,model:Sp,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ml,model:Op,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:Sl,model:Er,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:Ol,model:[Ip,Er],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),Cp=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});function Pp(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(zs))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)";Z.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${qr}`)}return Q.EncoderOnly}function D1(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return qt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=JSON.stringify([t,r,s,n]);return Jl(o,()=>qt.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n}))}async function Lp(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await D1(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,p=r??a.dtype,f=Pp(e),m=(x,b=null)=>{b=b??x;let E=gc(c,x),A=wc(p,x,E),S=jr[A]??"",M=`${b}${S}.onnx`,P=l?`${l}/${M}`:M;o.push(P);let O=sh(i,M,x);for(let k of nh(M,O)){let W=l?`${l}/${k}`:k;o.push(W)}},{sessions:_,optional_configs:w}=fu(f,e,{model_file_name:n});for(let[x,b]of Object.entries(_))m(x,b);if(w)for(let x of Object.values(w))o.push(x);return o}async function zp(t){if(!t)throw new Error("modelId is required");return(await Ft(t,kr,{})).exists?[kr]:[]}async function Tr(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null,include_tokenizer:o=!0,include_processor:a=!0}={}){let i=await Lp(t,{config:e,dtype:r,device:s,model_file_name:n});if(o){let l=await dn(t);i.push(...l)}if(a){let l=await zp(t);i.push(...l)}return i}async function Mr(t,e,r={}){t=Cp[t]??t;let s=Jn[t];if(!s)throw new Error(`Unsupported pipeline task: ${t}. Must be one of [${Object.keys(Jn).join(", ")}]`);let{type:n}=s;return Tr(e,{...r,include_tokenizer:n!=="audio"&&n!=="image",include_processor:n!=="text"})}async function gle(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:p=null,model_file_name:f=null,session_options:m={}}={}){t=Cp[t]??t;let _=Jn[t.split("_",1)[0]];if(!_)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(Jn)}]`);e||(e=_.default.model,Z.info(`No model specified. Using default model: "${e}".`),!l&&_.default.dtype&&(l=_.default.dtype));let w=await Mr(t,e,{device:i,dtype:l}),x={};r&&(await Promise.all(w.map(async H=>Ft(e,H)))).forEach((H,j)=>{H.exists&&(x[w[j]]={loaded:0,total:H.size??0})});let b={progress_callback:r?U=>{if(U.status==="progress"){x[U.file]={loaded:U.loaded,total:U.total};let H=Object.values(x).reduce(($,C)=>$+C.loaded,0),j=Object.values(x).reduce(($,C)=>$+C.total,0),K=j>0?H/j*100:0;r({status:"progress_total",name:U.name,progress:K,loaded:H,total:j,files:structuredClone(x)})}r(U)}:void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:p,model_file_name:f,session_options:m},E=w.includes("tokenizer.json"),A=w.includes("preprocessor_config.json"),S=_.model,M;if(Array.isArray(S)){let U=s??await qt.from_pretrained(e,b),{model_type:H}=U,j=S.find(K=>K.supports(H));if(!j)throw Error(`Unsupported model type "${H}" for task "${t}". None of the candidate model classes support this type.`);M=j.from_pretrained(e,{...b,config:U})}else M=S.from_pretrained(e,b);let[P,O,k]=await Promise.all([E?se.from_pretrained(e,b):null,A?Kc.from_pretrained(e,b):null,M]),W={task:t,model:k};P&&(W.tokenizer=P),O&&(W.processor=O),yr(r,{status:"ready",task:t,model:e});let X=_.pipeline;return new X(W)}var UN=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,U1=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},pM=ie.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),F1=class extends U1{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??pM,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(`
|
|
30
|
+
`)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&UN(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===pM&&ie.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
|
|
31
|
+
`)}},fM=class extends F1{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:c=!0,decode_kwargs:p={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,callback_function:s,token_callback_function:n,decode_kwargs:p}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var Il=class{constructor(e,r){this.image=e,this.timestamp=r}},Np=class{constructor(e,r){e.length>0&&e[0]instanceof Ye&&(e=e.map((s,n)=>new Il(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 FN(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<a;++f)l.push(e===1?o/2:f*i);let c=document.createElement("canvas");c.width=n.videoWidth,c.height=n.videoHeight;let p=c.getContext("2d",{willReadFrequently:!0});for(let f of l){n.currentTime=f,await new Promise(x=>{n.onseeked=x}),p.drawImage(n,0,0,c.width,c.height);let m=p.getImageData(0,0,c.width,c.height),_=new Ye(m.data,c.width,c.height,4),w=new Il(_,f);s.push(w)}return n.remove(),new Np(s,o)}async function Rp(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}=zr(t,o,r,s),l=await Nr(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function dM(t,e,r={}){let s=await Zt(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=zr(t,e,r,s);return!!await Nr(s,n,o)}async function mM(t,e={}){if(!t)throw new Error("modelId is required");if(!await dM(t,"config.json",e))return!1;let r=await Tr(t,e);return(await Rp(t,r,e)).allCached}async function _M(t,e={}){if(!t)throw new Error("modelId is required");let r=await Tr(t,e);return await Rp(t,r,e)}async function hM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await dM(e,"config.json",r))return!1;let s=await Mr(t,e,r);return(await Rp(e,s,r)).allCached}async function gM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Mr(t,e,r);return await Rp(e,s,r)}async function wM(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}=zr(t,o,r,s),c=!!await Nr(s,a,i),p=!1;if(c){let f=await s.delete(i),m=!f&&i!==a?await s.delete(a):!1;p=f||m}return{file:o,deleted:p,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function xM(t,e={}){if(!t)throw new Error("modelId is required");let r=await Tr(t,e);return await wM(t,r,e)}async function yM(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Mr(t,e,r);return await wM(e,s,r)}var GN=Object.keys(jr);async function bM(t,{config:e=null,model_file_name:r=null,revision:s="main",cache_dir:n=null,local_files_only:o=!1}={}){e=await D1(t,{config:e,cache_dir:n,local_files_only:o,revision:s});let a="onnx",i=Pp(e),{sessions:l}=fu(i,e,{model_file_name:r}),c=Object.values(l),p={revision:s,cache_dir:n,local_files_only:o};return(await Promise.all(GN.map(async m=>{let _=jr[m]??"",w=await Promise.all(c.map(async x=>{let b=`${a}/${x}${_}.onnx`;return(await Ft(t,b,p)).exists}));return{dtype:m,available:w.every(Boolean)}}))).filter(m=>m.available).map(m=>m.dtype)}var G1=class{static async get_files(e,r={}){return Tr(e,r)}static async get_pipeline_files(e,r,s={}){return Mr(e,r,s)}static async get_model_files(e,r={}){return Lp(e,r)}static async get_tokenizer_files(e){return dn(e)}static async get_processor_files(e){return zp(e)}static async get_available_dtypes(e,r={}){return bM(e,r)}static async is_cached(e,r={}){return mM(e,r)}static async is_cached_files(e,r={}){return _M(e,r)}static async is_pipeline_cached(e,r,s={}){return hM(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return gM(e,r,s)}static async get_file_metadata(e,r,s={}){return Ft(e,r,s)}static async clear_cache(e,r={}){return xM(e,r)}static async clear_pipeline_cache(e,r,s={}){return yM(e,r,s)}};export{Em as ASTFeatureExtractor,kh as ASTForAudioClassification,vh as ASTModel,Wo as ASTPreTrainedModel,xh as AfmoeForCausalLM,wh as AfmoeModel,jo as AfmoePreTrainedModel,_h as AlbertForMaskedLM,mh as AlbertForQuestionAnswering,dh as AlbertForSequenceClassification,fh as AlbertModel,Rs as AlbertPreTrainedModel,Cd as AlbertTokenizer,gh as ApertusForCausalLM,hh as ApertusModel,Go as ApertusPreTrainedModel,bh as ArceeForCausalLM,yh as ArceeModel,qo as ArceePreTrainedModel,_l as AudioClassificationPipeline,qt as AutoConfig,Xe as AutoFeatureExtractor,Ae as AutoImageProcessor,Er as AutoModel,Tp as AutoModelForAudioClassification,sM as AutoModelForAudioFrameClassification,lM as AutoModelForAudioTextToText,Ap as AutoModelForCTC,wp as AutoModelForCausalLM,Op as AutoModelForDepthEstimation,Mp as AutoModelForDocumentQuestionAnswering,vp as AutoModelForImageClassification,Ip as AutoModelForImageFeatureExtraction,nM as AutoModelForImageMatting,sl as AutoModelForImageSegmentation,iM as AutoModelForImageTextToText,Sp as AutoModelForImageToImage,tM as AutoModelForMaskGeneration,xp as AutoModelForMaskedLM,oM as AutoModelForNormalEstimation,kp as AutoModelForObjectDetection,aM as AutoModelForPoseEstimation,yp as AutoModelForQuestionAnswering,nl as AutoModelForSemanticSegmentation,Qn as AutoModelForSeq2SeqLM,rl as AutoModelForSequenceClassification,_p as AutoModelForSpeechSeq2Seq,hp as AutoModelForTextToSpectrogram,gp as AutoModelForTextToWaveform,mp as AutoModelForTokenClassification,ol as AutoModelForUniversalSegmentation,bp as AutoModelForVision2Seq,rM as AutoModelForXVector,Ep as AutoModelForZeroShotObjectDetection,Kc as AutoProcessor,se as AutoTokenizer,gl as AutomaticSpeechRecognitionPipeline,bl as BackgroundRemovalPipeline,Ah as BartForConditionalGeneration,Th as BartForSequenceClassification,Eh as BartModel,On as BartPretrainedModel,Pd as BartTokenizer,U1 as BaseStreamer,Um as BeitFeatureExtractor,Sh as BeitForImageClassification,Mh as BeitModel,Vo as BeitPreTrainedModel,Ih as BertForMaskedLM,Lh as BertForQuestionAnswering,Ch as BertForSequenceClassification,Ph as BertForTokenClassification,Oh as BertModel,Xr as BertPreTrainedModel,Ld as BertTokenizer,Fm as BitImageProcessor,Nh as BlenderbotForConditionalGeneration,zh as BlenderbotModel,Ho as BlenderbotPreTrainedModel,$h as BlenderbotSmallForConditionalGeneration,Rh as BlenderbotSmallModel,Xo as BlenderbotSmallPreTrainedModel,zd as BlenderbotSmallTokenizer,Nd as BlenderbotTokenizer,Dh as BloomForCausalLM,Bh as BloomModel,Ko as BloomPreTrainedModel,Rd as BloomTokenizer,Vh as CHMv2ForDepthEstimation,jm as CHMv2ImageProcessor,gu as CHMv2PreTrainedModel,qm as CLIPFeatureExtractor,Oc as CLIPImageProcessor,Xh as CLIPModel,fr as CLIPPreTrainedModel,Zh as CLIPSegForImageSegmentation,Jh as CLIPSegModel,ea as CLIPSegPreTrainedModel,Kh as CLIPTextModel,Zo as CLIPTextModelWithProjection,Bd as CLIPTokenizer,Yh as CLIPVisionModel,Qh as CLIPVisionModelWithProjection,Fh as CamembertForMaskedLM,qh as CamembertForQuestionAnswering,Gh as CamembertForSequenceClassification,jh as CamembertForTokenClassification,Uh as CamembertModel,Kr as CamembertPreTrainedModel,$d as CamembertTokenizer,Am as ChatterboxFeatureExtractor,Yo as ChatterboxModel,_u as ChatterboxPreTrainedModel,Bm as ChatterboxProcessor,Gm as ChineseCLIPFeatureExtractor,Wh as ChineseCLIPModel,hu as ChineseCLIPPreTrainedModel,Jo as ClapAudioModelWithProjection,Tm as ClapFeatureExtractor,Hh as ClapModel,In as ClapPreTrainedModel,Qo as ClapTextModelWithProjection,ou as ClassifierFreeGuidanceLogitsProcessor,tg as CodeGenForCausalLM,eg as CodeGenModel,ta as CodeGenPreTrainedModel,Ud as CodeGenTokenizer,Dd as CodeLlamaTokenizer,og as Cohere2ForCausalLM,ng as Cohere2Model,sa as Cohere2PreTrainedModel,sg as CohereForCausalLM,rg as CohereModel,ra as CoherePreTrainedModel,Fd as CohereTokenizer,ig as ConvBertForMaskedLM,ug as ConvBertForQuestionAnswering,lg as ConvBertForSequenceClassification,cg as ConvBertForTokenClassification,ag as ConvBertModel,Yr as ConvBertPreTrainedModel,Gd as ConvBertTokenizer,Wm as ConvNextFeatureExtractor,fg as ConvNextForImageClassification,Ic as ConvNextImageProcessor,pg as ConvNextModel,na as ConvNextPreTrainedModel,mg as ConvNextV2ForImageClassification,dg as ConvNextV2Model,oa as ConvNextV2PreTrainedModel,wg as DFineForObjectDetection,gg as DFineModel,ia as DFinePreTrainedModel,qg as DINOv3ConvNextModel,Eu as DINOv3ConvNextPreTrainedModel,Xm as DINOv3ViTImageProcessor,Wg as DINOv3ViTModel,Au as DINOv3ViTPreTrainedModel,Ym as DPTFeatureExtractor,Zg as DPTForDepthEstimation,Lc as DPTImageProcessor,Jg as DPTModel,ma as DPTPreTrainedModel,ca as DacDecoderModel,xu as DacDecoderOutput,la as DacEncoderModel,wu as DacEncoderOutput,Po as DacFeatureExtractor,xg as DacModel,Cn as DacPreTrainedModel,bg as DebertaForMaskedLM,Eg as DebertaForQuestionAnswering,vg as DebertaForSequenceClassification,kg as DebertaForTokenClassification,yg as DebertaModel,Qr as DebertaPreTrainedModel,qd as DebertaTokenizer,Sg as DebertaV2ForMaskedLM,Cg as DebertaV2ForQuestionAnswering,Og as DebertaV2ForSequenceClassification,Ig as DebertaV2ForTokenClassification,Mg as DebertaV2Model,Jr as DebertaV2PreTrainedModel,jd as DebertaV2Tokenizer,Pg as DecisionTransformerModel,yu as DecisionTransformerPreTrainedModel,Tg as DeepseekV3ForCausalLM,Ag as DeepseekV3Model,ua as DeepseekV3PreTrainedModel,Vm as DeiTFeatureExtractor,zg as DeiTForImageClassification,Cc as DeiTImageProcessor,Lg as DeiTModel,pa as DeiTPreTrainedModel,Ng as DepthAnythingForDepthEstimation,bu as DepthAnythingPreTrainedModel,Ml as DepthEstimationPipeline,Rg as DepthProForDepthEstimation,vu as DepthProPreTrainedModel,Hm as DetrFeatureExtractor,Bg as DetrForObjectDetection,Dg as DetrForSegmentation,Pc as DetrImageProcessor,$g as DetrModel,Ln as DetrObjectDetectionOutput,Pn as DetrPreTrainedModel,ku as DetrSegmentationOutput,Fg as Dinov2ForImageClassification,Ug as Dinov2Model,fa as Dinov2PreTrainedModel,jg as Dinov2WithRegistersForImageClassification,Gg as Dinov2WithRegistersModel,da as Dinov2WithRegistersPreTrainedModel,Yg as DistilBertForMaskedLM,Kg as DistilBertForQuestionAnswering,Hg as DistilBertForSequenceClassification,Xg as DistilBertForTokenClassification,Vg as DistilBertModel,Zr as DistilBertPreTrainedModel,Wd as DistilBertTokenizer,Al as DocumentQuestionAnsweringPipeline,Km as DonutFeatureExtractor,hn as DonutImageProcessor,Qg as DonutSwinModel,Tu as DonutSwinPreTrainedModel,Uo as DynamicCache,lb as EdgeTamModel,tw as EfficientNetForImageClassification,Qm as EfficientNetImageProcessor,ew as EfficientNetModel,_a as EfficientNetPreTrainedModel,sw as ElectraForMaskedLM,aw as ElectraForQuestionAnswering,nw as ElectraForSequenceClassification,ow as ElectraForTokenClassification,rw as ElectraModel,es as ElectraPreTrainedModel,Vd as ElectraTokenizer,Co as EncodecFeatureExtractor,lu as EosTokenCriteria,lw as Ernie4_5ForCausalLM,iw as Ernie4_5Model,ha as Ernie4_5PretrainedModel,uw as EsmForMaskedLM,pw as EsmForSequenceClassification,fw as EsmForTokenClassification,cw as EsmModel,$s as EsmPreTrainedModel,Hd as EsmTokenizer,mw as EuroBertForMaskedLM,_w as EuroBertForSequenceClassification,hw as EuroBertForTokenClassification,dw as EuroBertModel,Bs as EuroBertPreTrainedModel,ww as ExaoneForCausalLM,gw as ExaoneModel,ga as ExaonePreTrainedModel,yw as FalconForCausalLM,vw as FalconH1ForCausalLM,bw as FalconH1Model,xa as FalconH1PreTrainedModel,xw as FalconModel,wa as FalconPreTrainedModel,Xd as FalconTokenizer,Ew as FastViTForImageClassification,kw as FastViTModel,ya as FastViTPreTrainedModel,Sl as FeatureExtractionPipeline,Ee as FeatureExtractor,ul as FillMaskPipeline,Aw as Florence2ForConditionalGeneration,Mu as Florence2PreTrainedModel,I_ as Florence2Processor,Qc as ForcedBOSTokenLogitsProcessor,Jc as ForcedEOSTokenLogitsProcessor,e_ as GLPNFeatureExtractor,Fw as GLPNForDepthEstimation,Uw as GLPNModel,Ma as GLPNPreTrainedModel,Qw as GPT2LMHeadModel,Yw as GPT2Model,Pa as GPT2PreTrainedModel,Qd as GPT2Tokenizer,jw as GPTBigCodeForCausalLM,Gw as GPTBigCodeModel,Sa as GPTBigCodePreTrainedModel,Zw as GPTJForCausalLM,Jw as GPTJModel,La as GPTJPreTrainedModel,Ww as GPTNeoForCausalLM,qw as GPTNeoModel,Oa as GPTNeoPreTrainedModel,Hw as GPTNeoXForCausalLM,Vw as GPTNeoXModel,Ia as GPTNeoXPreTrainedModel,Yd as GPTNeoXTokenizer,Ow as Gemma2ForCausalLM,Sw as Gemma2Model,va as Gemma2PreTrainedModel,Lw as Gemma3ForCausalLM,Iu as Gemma3ForConditionalGeneration,Jm as Gemma3ImageProcessor,Pw as Gemma3Model,Ou as Gemma3PreTrainedModel,C_ as Gemma3Processor,Mm as Gemma3nAudioFeatureExtractor,zw as Gemma3nForCausalLM,zn as Gemma3nForConditionalGeneration,Cu as Gemma3nPreTrainedModel,P_ as Gemma3nProcessor,Mw as GemmaForCausalLM,Tw as GemmaModel,ba as GemmaPreTrainedModel,Kd as GemmaTokenizer,Zm as Glm46VImageProcessor,L_ as Glm46VProcessor,Rw as GlmForCausalLM,Nw as GlmModel,Bw as GlmMoeDsaForCausalLM,$w as GlmMoeDsaModel,Ea as GlmMoeDsaPreTrainedModel,Dw as GlmOcrForConditionalGeneration,ka as GlmPreTrainedModel,Kw as GptOssForCausalLM,Xw as GptOssModel,Ca as GptOssPreTrainedModel,tx as GraniteForCausalLM,ex as GraniteModel,sx as GraniteMoeHybridForCausalLM,rx as GraniteMoeHybridModel,Na as GraniteMoeHybridPreTrainedModel,za as GranitePreTrainedModel,Sm as GraniteSpeechFeatureExtractor,nx as GraniteSpeechForConditionalGeneration,z_ as GraniteSpeechProcessor,ox as GroundingDinoForObjectDetection,t_ as GroundingDinoImageProcessor,zu as GroundingDinoPreTrainedModel,N_ as GroundingDinoProcessor,ax as GroupViTModel,Nu as GroupViTPreTrainedModel,lx as HeliumForCausalLM,ix as HeliumModel,Ra as HeliumPreTrainedModel,Jd as HerbertTokenizer,ux as HieraForImageClassification,cx as HieraModel,$a as HieraPreTrainedModel,gx as HubertForCTC,wx as HubertForSequenceClassification,hx as HubertModel,_x as HubertPreTrainedModel,yx as HunYuanDenseV1ForCausalLM,xx as HunYuanDenseV1Model,Ba as HunYuanDenseV1PreTrainedModel,kx as IJepaForImageClassification,vx as IJepaModel,Da as IJepaPreTrainedModel,bx as Idefics3ForConditionalGeneration,zc as Idefics3ImageProcessor,qc as Idefics3Processor,yl as ImageClassificationPipeline,Ol as ImageFeatureExtractionPipeline,V as ImageFeatureExtractor,V as ImageProcessor,Hs as ImageSegmentationPipeline,Tl as ImageToImagePipeline,xl as ImageToTextPipeline,wT as InterruptableStoppingCriteria,Ax as JAISLMHeadModel,Ex as JAISModel,Ua as JAISPreTrainedModel,s_ as JinaCLIPImageProcessor,Tx as JinaCLIPModel,Rn as JinaCLIPPreTrainedModel,$_ as JinaCLIPProcessor,Fa as JinaCLIPTextModel,Mx as JinaCLIPVisionModel,Ox as Lfm2ForCausalLM,Sx as Lfm2Model,Px as Lfm2MoeForCausalLM,Cx as Lfm2MoeModel,ja as Lfm2MoePreTrainedModel,Ga as Lfm2PreTrainedModel,Lx as Lfm2VlForConditionalGeneration,n_ as Lfm2VlImageProcessor,B_ as Lfm2VlProcessor,Ix as LightOnOcrForConditionalGeneration,k1 as LiteWhisperForConditionalGeneration,Rx as Llama4ForCausalLM,Ru as Llama4PreTrainedModel,Nx as LlamaForCausalLM,zx as LlamaModel,qa as LlamaPreTrainedModel,Zd as LlamaTokenizer,Et as LlavaForConditionalGeneration,Et as LlavaOnevisionForConditionalGeneration,o_ as LlavaOnevisionImageProcessor,Su as LlavaPreTrainedModel,D_ as LlavaProcessor,Cw as LlavaQwen2ForCausalLM,Ot as LogLevel,Wt as LogitsProcessor,Ps as LogitsProcessorList,Do as LogitsWarper,Bx as LongT5ForConditionalGeneration,$x as LongT5Model,Wa as LongT5PreTrainedModel,Ux as M2M100ForConditionalGeneration,Dx as M2M100Model,Va as M2M100PreTrainedModel,em as M2M100Tokenizer,rm as MBart50Tokenizer,Xx as MBartForCausalLM,Vx as MBartForConditionalGeneration,Hx as MBartForSequenceClassification,Wx as MBartModel,Fs as MBartPreTrainedModel,Mo as MBartTokenizer,zy as MPNetForMaskedLM,$y as MPNetForQuestionAnswering,Ny as MPNetForSequenceClassification,Ry as MPNetForTokenClassification,Ly as MPNetModel,ts as MPNetPreTrainedModel,om as MPNetTokenizer,Fy as MT5ForConditionalGeneration,Uy as MT5Model,oi as MT5PreTrainedModel,Gx as MarianMTModel,Fx as MarianModel,Ha as MarianPreTrainedModel,tm as MarianTokenizer,i_ as Mask2FormerImageProcessor,a_ as MaskFormerFeatureExtractor,qx as MaskFormerForInstanceSegmentation,gn as MaskFormerImageProcessor,jx as MaskFormerModel,Xa as MaskFormerPreTrainedModel,iu as MaxLengthCriteria,Kx as Metric3DForDepthEstimation,$u as Metric3DPreTrainedModel,Yx as Metric3Dv2ForDepthEstimation,Bu as Metric3Dv2PreTrainedModel,Qx as MgpstrForSceneTextRecognition,Du as MgpstrModelOutput,Uu as MgpstrPreTrainedModel,U_ as MgpstrProcessor,sm as MgpstrTokenizer,Ya as MimiDecoderModel,Gu as MimiDecoderOutput,Ka as MimiEncoderModel,Fu as MimiEncoderOutput,Jx as MimiModel,$n as MimiPreTrainedModel,ru as MinLengthLogitsProcessor,su as MinNewTokensLengthLogitsProcessor,ry as Mistral4ForCausalLM,ty as Mistral4Model,Ja as Mistral4PreTrainedModel,ey as MistralForCausalLM,Zx as MistralModel,Qa as MistralPreTrainedModel,ny as MobileBertForMaskedLM,ay as MobileBertForQuestionAnswering,oy as MobileBertForSequenceClassification,sy as MobileBertModel,Gs as MobileBertPreTrainedModel,nm as MobileBertTokenizer,ly as MobileLLMForCausalLM,iy as MobileLLMModel,Za as MobileLLMPreTrainedModel,l_ as MobileNetV1FeatureExtractor,uy as MobileNetV1ForImageClassification,py as MobileNetV1ForSemanticSegmentation,Nc as MobileNetV1ImageProcessor,cy as MobileNetV1Model,Bn as MobileNetV1PreTrainedModel,c_ as MobileNetV2FeatureExtractor,dy as MobileNetV2ForImageClassification,my as MobileNetV2ForSemanticSegmentation,Rc as MobileNetV2ImageProcessor,fy as MobileNetV2Model,Dn as MobileNetV2PreTrainedModel,u_ as MobileNetV3FeatureExtractor,hy as MobileNetV3ForImageClassification,gy as MobileNetV3ForSemanticSegmentation,$c as MobileNetV3ImageProcessor,_y as MobileNetV3Model,Un as MobileNetV3PreTrainedModel,p_ as MobileNetV4FeatureExtractor,xy as MobileNetV4ForImageClassification,yy as MobileNetV4ForSemanticSegmentation,Bc as MobileNetV4ImageProcessor,wy as MobileNetV4Model,Fn as MobileNetV4PreTrainedModel,f_ as MobileViTFeatureExtractor,vy as MobileViTForImageClassification,Dc as MobileViTImageProcessor,by as MobileViTModel,ei as MobileViTPreTrainedModel,Ey as MobileViTV2ForImageClassification,ky as MobileViTV2Model,ti as MobileViTV2PreTrainedModel,G1 as ModelRegistry,Iy as ModernBertDecoderForCausalLM,Oy as ModernBertDecoderModel,ri as ModernBertDecoderPreTrainedModel,Ty as ModernBertForMaskedLM,My as ModernBertForSequenceClassification,Sy as ModernBertForTokenClassification,Ay as ModernBertModel,js as ModernBertPreTrainedModel,Iw as Moondream1ForConditionalGeneration,Om as MoonshineFeatureExtractor,Py as MoonshineForConditionalGeneration,Cy as MoonshineModel,si as MoonshinePreTrainedModel,F_ as MoonshineProcessor,Dy as MptForCausalLM,By as MptModel,ni as MptPreTrainedModel,Gy as MultiModalityCausalLM,ju as MultiModalityPreTrainedModel,qy as MusicgenForCausalLM,ii as MusicgenForConditionalGeneration,jy as MusicgenModel,ai as MusicgenPreTrainedModel,Vy as NanoChatForCausalLM,Wy as NanoChatModel,li as NanoChatPreTrainedModel,Xy as NemotronHForCausalLM,Hy as NemotronHModel,ci as NemotronHPreTrainedModel,Yy as NeoBertForMaskedLM,Zy as NeoBertForQuestionAnswering,Qy as NeoBertForSequenceClassification,Jy as NeoBertForTokenClassification,Ky as NeoBertModel,rs as NeoBertPreTrainedModel,am as NllbTokenizer,nu as NoBadWordsLogitsProcessor,eu as NoRepeatNGramLogitsProcessor,e0 as NomicBertModel,qu as NomicBertPreTrainedModel,d_ as NougatImageProcessor,im as NougatTokenizer,f0 as OPTForCausalLM,p0 as OPTModel,_i as OPTPreTrainedModel,kl as ObjectDetectionPipeline,n0 as Olmo2ForCausalLM,s0 as Olmo2Model,pi as Olmo2PreTrainedModel,a0 as Olmo3ForCausalLM,o0 as Olmo3Model,fi as Olmo3PreTrainedModel,r0 as OlmoForCausalLM,l0 as OlmoHybridForCausalLM,i0 as OlmoHybridModel,di as OlmoHybridPreTrainedModel,t0 as OlmoModel,ui as OlmoPreTrainedModel,u0 as OpenELMForCausalLM,c0 as OpenELMModel,mi as OpenELMPreTrainedModel,m_ as OwlViTFeatureExtractor,h0 as OwlViTForObjectDetection,wn as OwlViTImageProcessor,_0 as OwlViTModel,gi as OwlViTPreTrainedModel,G_ as OwlViTProcessor,m0 as Owlv2ForObjectDetection,__ as Owlv2ImageProcessor,d0 as Owlv2Model,hi as Owlv2PreTrainedModel,g0 as PaliGemmaForConditionalGeneration,j_ as PaliGemmaProcessor,Im as ParakeetFeatureExtractor,w0 as ParakeetForCTC,Wu as ParakeetPreTrainedModel,y0 as PatchTSMixerForPrediction,x0 as PatchTSMixerModel,wi as PatchTSMixerPreTrainedModel,v0 as PatchTSTForPrediction,b0 as PatchTSTModel,xi as PatchTSTPreTrainedModel,T0 as Phi3ForCausalLM,A0 as Phi3Model,bi as Phi3PreTrainedModel,vi as Phi3VForCausalLM,w_ as Phi3VImageProcessor,Vu as Phi3VPreTrainedModel,q_ as Phi3VProcessor,E0 as PhiForCausalLM,k0 as PhiModel,yi as PhiPreTrainedModel,x_ as PixtralImageProcessor,W_ as PixtralProcessor,y as PreTrainedModel,q as PreTrainedTokenizer,kn as PretrainedConfig,re as Processor,S0 as PvtForImageClassification,y_ as PvtImageProcessor,M0 as PvtModel,ki as PvtPreTrainedModel,Lo as PyAnnoteFeatureExtractor,I0 as PyAnnoteForAudioFrameClassification,O0 as PyAnnoteModel,Ei as PyAnnotePreTrainedModel,V_ as PyAnnoteProcessor,cl as QuestionAnsweringPipeline,P0 as Qwen2ForCausalLM,C0 as Qwen2Model,z0 as Qwen2MoeForCausalLM,L0 as Qwen2MoeModel,Ti as Qwen2MoePreTrainedModel,Ai as Qwen2PreTrainedModel,lm as Qwen2Tokenizer,Aa as Qwen2VLForCausalLM,Nn as Qwen2VLForConditionalGeneration,No as Qwen2VLImageProcessor,Pu as Qwen2VLPreTrainedModel,Is as Qwen2VLProcessor,Ta as Qwen2_5_VLForCausalLM,Ds as Qwen2_5_VLForConditionalGeneration,$o as Qwen2_5_VLProcessor,R0 as Qwen3ForCausalLM,N0 as Qwen3Model,B0 as Qwen3MoeForCausalLM,$0 as Qwen3MoeModel,Si as Qwen3MoePreTrainedModel,U0 as Qwen3NextForCausalLM,D0 as Qwen3NextModel,Oi as Qwen3NextPreTrainedModel,Mi as Qwen3PreTrainedModel,Ii as Qwen3VLForCausalLM,qs as Qwen3VLForConditionalGeneration,G0 as Qwen3VLMoeForCausalLM,F0 as Qwen3VLMoeForConditionalGeneration,H_ as Qwen3VLProcessor,Ci as Qwen3_5ForCausalLM,Gn as Qwen3_5ForConditionalGeneration,q0 as Qwen3_5MoeForCausalLM,j0 as Qwen3_5MoeForConditionalGeneration,X0 as RFDetrForObjectDetection,H0 as RFDetrModel,Hu as RFDetrObjectDetectionOutput,Li as RFDetrPreTrainedModel,hg as RTDetrForObjectDetection,b_ as RTDetrImageProcessor,_g as RTDetrModel,dr as RTDetrObjectDetectionOutput,aa as RTDetrPreTrainedModel,ab as RTDetrV2ForObjectDetection,ob as RTDetrV2Model,Xu as RTDetrV2ObjectDetectionOutput,zi as RTDetrV2PreTrainedModel,Io as RawAudio,Ye as RawImage,Np as RawVideo,Il as RawVideoFrame,tu as RepetitionPenaltyLogitsProcessor,V0 as ResNetForImageClassification,W0 as ResNetModel,Pi as ResNetPreTrainedModel,tb as RoFormerForMaskedLM,nb as RoFormerForQuestionAnswering,rb as RoFormerForSequenceClassification,sb as RoFormerForTokenClassification,eb as RoFormerModel,ns as RoFormerPreTrainedModel,um as RoFormerTokenizer,Y0 as RobertaForMaskedLM,Z0 as RobertaForQuestionAnswering,Q0 as RobertaForSequenceClassification,J0 as RobertaForTokenClassification,K0 as RobertaModel,ss as RobertaPreTrainedModel,cm as RobertaTokenizer,Ro as Sam2ImageProcessor,Qu as Sam2ImageSegmentationOutput,Ni as Sam2Model,Ju as Sam2PreTrainedModel,Wc as Sam2Processor,X_ as Sam2VideoProcessor,Ro as Sam3ImageProcessor,cb as Sam3TrackerModel,Ro as SamImageProcessor,Ku as SamImageSegmentationOutput,ib as SamModel,Yu as SamPreTrainedModel,Bo as SamProcessor,v_ as SapiensFeatureExtractor,pb as SapiensForDepthEstimation,fb as SapiensForNormalEstimation,ub as SapiensForSemanticSegmentation,Uc as SapiensImageProcessor,jn as SapiensPreTrainedModel,Cm as SeamlessM4TFeatureExtractor,k_ as SegformerFeatureExtractor,mb as SegformerForImageClassification,_b as SegformerForSemanticSegmentation,Fc as SegformerImageProcessor,db as SegformerModel,qn as SegformerPreTrainedModel,E_ as SiglipImageProcessor,hb as SiglipModel,Ri as SiglipPreTrainedModel,$i as SiglipTextModel,pm as SiglipTokenizer,gb as SiglipVisionModel,xb as SmolLM3ForCausalLM,wb as SmolLM3Model,Bi as SmolLM3PreTrainedModel,zc as SmolVLMImageProcessor,qc as SmolVLMProcessor,Ui as SnacDecoderModel,Di as SnacEncoderModel,Pm as SnacFeatureExtractor,yb as SnacModel,Wn as SnacPreTrainedModel,vb as SolarOpenForCausalLM,bb as SolarOpenModel,Fi as SolarOpenPreTrainedModel,Lm as SpeechT5FeatureExtractor,Eb as SpeechT5ForSpeechToText,Ab as SpeechT5ForTextToSpeech,Tb as SpeechT5HifiGan,kb as SpeechT5Model,Vn as SpeechT5PreTrainedModel,K_ as SpeechT5Processor,fm as SpeechT5Tokenizer,Sb as SqueezeBertForMaskedLM,Ib as SqueezeBertForQuestionAnswering,Ob as SqueezeBertForSequenceClassification,Mb as SqueezeBertModel,Ws as SqueezeBertPreTrainedModel,dm as SqueezeBertTokenizer,Pb as StableLmForCausalLM,Cb as StableLmModel,Gi as StableLmPreTrainedModel,zb as Starcoder2ForCausalLM,Lb as Starcoder2Model,ji as Starcoder2PreTrainedModel,Hr as StoppingCriteria,Tn as StoppingCriteriaList,Nb as StyleTextToSpeech2Model,Zu as StyleTextToSpeech2PreTrainedModel,pl as SummarizationPipeline,qi as SupertonicForConditionalGeneration,ep as SupertonicPreTrainedModel,En as SuppressTokensAtBeginLogitsProcessor,Ub as Swin2SRForImageSuperResolution,A_ as Swin2SRImageProcessor,Db as Swin2SRModel,Wi as Swin2SRPreTrainedModel,$b as SwinForImageClassification,Bb as SwinForSemanticSegmentation,Rb as SwinModel,Hn as SwinPreTrainedModel,Gb as T5ForConditionalGeneration,Fb as T5Model,Vi as T5PreTrainedModel,mm as T5Tokenizer,qb as TableTransformerForObjectDetection,jb as TableTransformerModel,tp as TableTransformerObjectDetectionOutput,Hi as TableTransformerPreTrainedModel,au as TemperatureLogitsWarper,R as Tensor,Ar as Text2TextGenerationPipeline,il as TextClassificationPipeline,dl as TextGenerationPipeline,F1 as TextStreamer,wl as TextToAudioPipeline,ll as TokenClassificationPipeline,q as TokenizersBackend,gT as TopKLogitsWarper,hT as TopPLogitsWarper,Wb as TrOCRForCausalLM,rp as TrOCRPreTrainedModel,fl as TranslationPipeline,Us as UltravoxModel,Lu as UltravoxPreTrainedModel,Y_ as UltravoxProcessor,Hb as UniSpeechForCTC,Xb as UniSpeechForSequenceClassification,Vb as UniSpeechModel,Xn as UniSpeechPreTrainedModel,Jb as UniSpeechSatForAudioFrameClassification,Yb as UniSpeechSatForCTC,Qb as UniSpeechSatForSequenceClassification,Kb as UniSpeechSatModel,Vs as UniSpeechSatPreTrainedModel,R_ as VLChatProcessor,r_ as VLMImageProcessor,e1 as VaultGemmaForCausalLM,Zb as VaultGemmaModel,Xi as VaultGemmaPreTrainedModel,T_ as ViTFeatureExtractor,s1 as ViTForImageClassification,Gc as ViTImageProcessor,n1 as ViTMAEModel,sp as ViTMAEPreTrainedModel,a1 as ViTMSNForImageClassification,o1 as ViTMSNModel,Yi as ViTMSNPreTrainedModel,r1 as ViTModel,Ki as ViTPreTrainedModel,t1 as VisionEncoderDecoderModel,i1 as VitMatteForImageMatting,M_ as VitMatteImageProcessor,np as VitMattePreTrainedModel,l1 as VitPoseForPoseEstimation,S_ as VitPoseImageProcessor,op as VitPosePreTrainedModel,c1 as VitsModel,ap as VitsModelOutput,ip as VitsPreTrainedModel,hm as VitsTokenizer,u1 as VoxtralForConditionalGeneration,Q_ as VoxtralProcessor,Rm as VoxtralRealtimeFeatureExtractor,Qi as VoxtralRealtimeForConditionalGeneration,lp as VoxtralRealtimePreTrainedModel,Z_ as VoxtralRealtimeProcessor,m1 as Wav2Vec2BertForCTC,_1 as Wav2Vec2BertForSequenceClassification,d1 as Wav2Vec2BertModel,Kn as Wav2Vec2BertPreTrainedModel,gm as Wav2Vec2CTCTokenizer,zm as Wav2Vec2FeatureExtractor,mx as Wav2Vec2ForAudioFrameClassification,fx as Wav2Vec2ForCTC,dx as Wav2Vec2ForSequenceClassification,px as Wav2Vec2Model,sr as Wav2Vec2PreTrainedModel,eh as Wav2Vec2Processor,th as Wav2Vec2ProcessorWithLM,y1 as WavLMForAudioFrameClassification,g1 as WavLMForCTC,w1 as WavLMForSequenceClassification,x1 as WavLMForXVector,h1 as WavLMModel,os as WavLMPreTrainedModel,Nm as WeSpeakerFeatureExtractor,b1 as WeSpeakerResNetModel,up as WeSpeakerResNetPreTrainedModel,$m as WhisperFeatureExtractor,fp as WhisperForConditionalGeneration,v1 as WhisperModel,Ji as WhisperPreTrainedModel,rh as WhisperProcessor,fM as WhisperTextStreamer,Zc as WhisperTimeStampLogitsProcessor,wm as WhisperTokenizer,S1 as XLMForQuestionAnswering,T1 as XLMForSequenceClassification,M1 as XLMForTokenClassification,E1 as XLMModel,as as XLMPreTrainedModel,I1 as XLMRobertaForMaskedLM,L1 as XLMRobertaForQuestionAnswering,C1 as XLMRobertaForSequenceClassification,P1 as XLMRobertaForTokenClassification,O1 as XLMRobertaModel,is as XLMRobertaPreTrainedModel,xm as XLMRobertaTokenizer,ym as XLMTokenizer,A1 as XLMWithLMHeadModel,cp as XVectorOutput,O_ as YolosFeatureExtractor,N1 as YolosForObjectDetection,jc as YolosImageProcessor,z1 as YolosModel,dp as YolosObjectDetectionOutput,Zi as YolosPreTrainedModel,$1 as YoutuForCausalLM,R1 as YoutuModel,el as YoutuPreTrainedModel,hl as ZeroShotAudioClassificationPipeline,ml as ZeroShotClassificationPipeline,vl as ZeroShotImageClassificationPipeline,El as ZeroShotObjectDetectionPipeline,ke as cat,XL as cos_sim,WE as dot,me as env,He as full,To as full_like,Ed as interpolate,vt as interpolate_4d,mB as layer_norm,Qz as load_image,FN as load_video,Mf as log_softmax,q2 as matmul,bc as mean,W2 as mean_pooling,tt as ones,vc as ones_like,Iz as permute,gle as pipeline,H2 as quantize_embeddings,_B as rand,V2 as randn,hs as random,km as read_audio,dB as rfft,yc as slice,Ne as softmax,It as stack,Ad as std_mean,tr as topk,Md as zeros,Sd as zeros_like};
|