@huggingface/transformers 4.0.0-next.2 → 4.0.0-next.4
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 +4 -3
- package/dist/ort-wasm-simd-threaded.jsep.mjs +23 -23
- package/dist/transformers.js +49 -18
- package/dist/transformers.min.js +20 -20
- package/dist/transformers.node.cjs +43 -9
- package/dist/transformers.node.min.cjs +18 -18
- package/dist/transformers.node.min.mjs +18 -18
- package/dist/transformers.node.mjs +40 -9
- package/dist/transformers.web.js +33 -2
- package/dist/transformers.web.min.js +17 -17
- package/package.json +2 -2
- package/src/configs.js +1 -0
- package/src/env.js +1 -1
- package/src/generation/parameters.js +1 -1
- package/src/generation/streamers.js +21 -0
- package/src/models/cohere2/modeling_cohere2.js +5 -0
- package/src/models/modeling_utils.js +1 -1
- package/src/models/models.js +1 -0
- package/src/models/registry.js +2 -0
- package/src/pipelines/automatic-speech-recognition.js +1 -1
- package/src/pipelines/document-question-answering.js +1 -1
- package/src/pipelines/image-to-text.js +2 -2
- package/src/pipelines/summarization.js +1 -1
- package/src/pipelines/text-generation.js +1 -1
- package/src/pipelines/text2text-generation.js +1 -1
- package/src/pipelines/translation.js +1 -1
- package/src/transformers.js +2 -0
- package/types/configs.d.ts.map +1 -1
- package/types/generation/parameters.d.ts +1 -1
- package/types/generation/parameters.d.ts.map +1 -1
- package/types/generation/streamers.d.ts +1 -0
- package/types/generation/streamers.d.ts.map +1 -1
- package/types/models/cohere2/modeling_cohere2.d.ts +8 -0
- package/types/models/cohere2/modeling_cohere2.d.ts.map +1 -0
- package/types/models/modeling_utils.d.ts +2 -2
- package/types/models/modeling_utils.d.ts.map +1 -1
- package/types/models/models.d.ts +1 -0
- package/types/models/registry.d.ts.map +1 -1
- package/types/pipelines/automatic-speech-recognition.d.ts +2 -2
- package/types/pipelines/automatic-speech-recognition.d.ts.map +1 -1
- package/types/pipelines/document-question-answering.d.ts +2 -2
- package/types/pipelines/document-question-answering.d.ts.map +1 -1
- package/types/pipelines/image-to-text.d.ts +4 -4
- package/types/pipelines/image-to-text.d.ts.map +1 -1
- package/types/pipelines/summarization.d.ts +2 -2
- package/types/pipelines/summarization.d.ts.map +1 -1
- package/types/pipelines/text-generation.d.ts +2 -2
- package/types/pipelines/text-generation.d.ts.map +1 -1
- package/types/pipelines/text2text-generation.d.ts +3 -3
- package/types/pipelines/text2text-generation.d.ts.map +1 -1
- package/types/pipelines/translation.d.ts +2 -2
- package/types/pipelines/translation.d.ts.map +1 -1
- package/types/transformers.d.ts +2 -0
- package/types/transformers.d.ts.map +1 -1
package/dist/transformers.min.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
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}},WS=GS,qS=class extends wr{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}},VS=qS,HS=class extends wr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>bv(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},XS=HS,YS=class extends wr{normalize(t){let e=Bi(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},KS=YS,QS=class extends wr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Ui=QS,JS=class extends Ui{constructor(){super(...arguments),this.form="NFC"}},ZS=JS,eO=class extends Ui{constructor(){super(...arguments),this.form="NFD"}},tO=eO,rO=class extends Ui{constructor(){super(...arguments),this.form="NFKC"}},sO=rO,nO=class extends Ui{constructor(){super(...arguments),this.form="NFKD"}},oO=nO,aO=class extends wr{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}},iO=aO,lO=class extends wr{normalize(t){return yv(t)}},cO=lO,uO=class extends wr{normalize(t){return t.toLowerCase()}},pO=uO,fO=class extends wr{normalize(t){return t=this.config.prepend+t,t}},dO=fO;function mO(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new WS(t);case"Precompiled":return new VS(t);case"Sequence":return new XS(t);case"Replace":return new KS(t);case"NFC":return new ZS(t);case"NFD":return new tO(t);case"NFKC":return new sO(t);case"NFKD":return new oO(t);case"Strip":return new iO(t);case"StripAccents":return new cO(t);case"Lowercase":return new pO(t);case"Prepend":return new dO(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var bv=mO,hO=class extends zn{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=hO,_O=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=xv,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(""))}},wO=_O,gO=class extends Yt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},xO=gO,yO=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]}},bO=yO,vO=class extends Yt{constructor(t){super(),this.config=t,this.pattern=Bi(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):US(t,this.pattern)}},kO=vO,EO=class extends Yt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${$i}]+|[${$i}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},AO=EO,TO=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)||[]}},MO=TO,SO=class extends Yt{constructor(){super(),this.pattern=new RegExp(`[^\\s${$i}]+|[${$i}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},OO=SO,IO=class extends Yt{constructor(t){super(),this.config=t,this.pattern=Bi(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},CO=IO,PO=class extends Yt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>vv(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},LO=PO,NO=class extends Yt{pre_tokenize_text(t){return DS(t)}},zO=NO,RO=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}},$O=RO;function BO(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new OO;case"Sequence":return new LO(t);case"Whitespace":return new xO;case"WhitespaceSplit":return new zO;case"Metaspace":return new bO(t);case"ByteLevel":return new wO(t);case"Split":return new kO(t);case"Punctuation":return new AO(t);case"Digits":return new MO(t);case"Replace":return new CO(t);case"FixedLength":return new $O(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var vv=BO,UO=class extends zn{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=NS(e,this.tokens_to_ids,this.unk_token_id)),e}},Di=UO,DO=class extends Di{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=bp(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}},hv=DO,_v=class kv{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new kv(!1,new Map)}},FO=class{constructor(){this.root=_v.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=_v.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)}}},jO=FO,xp=class Ev{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 Ev(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},GO=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 xp(this.bos_token_id??0,0,0,0,0),n=new xp(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 xp(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)}},WO=GO;function qO(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 VO=class extends Di{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=qO(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new jO,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=$S(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 WO(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}},wv=VO,HO=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}},XO=HO,YO=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()}},KO=YO,QO=class extends Di{constructor(t){super(t),this.tokens_to_ids=bp(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 KO(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 XO((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):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},gv=QO,JO=class extends Di{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=bp(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}},ZO=JO;function eI(t,e){switch(t.type){case"WordPiece":return new hv(t);case"Unigram":return new wv(t,e.eos_token);case"BPE":return new gv(t);default:if(t.vocab)return Array.isArray(t.vocab)?new wv(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new gv(t):new hv(t):new ZO(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 tI=eI,rI=class extends zn{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Rn=rI,sI=class extends Rn{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}}},nI=sI,oI=class extends Rn{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},aI=oI,iI=class extends Rn{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}}},lI=iI,cI=class extends Rn{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}}},uI=cI,pI=class extends Rn{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>Av(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}},fI=pI;function dI(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new nI(t);case"ByteLevel":return new aI(t);case"BertProcessing":return new lI(t);case"RobertaProcessing":return new uI(t);case"Sequence":return new fI(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var Av=dI,mI=class extends zn{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=mI,hI=class extends Bt{constructor(t){super(t),this.byte_decoder=CS,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}},_I=hI,wI=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=yp(e)),e})}},gI=wI,xI=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}},yI=xI,bI=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?"":" "))}},vI=bI,kI=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=yp(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},EI=kI,AI=class extends Bt{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Tv(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},TI=AI,MI=class extends Bt{decode_chain(t){let e=Bi(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},SI=MI,OI=class extends Bt{decode_chain(t){return[t.join("")]}},II=OI,CI=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)})}},PI=CI,LI=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}},NI=LI;function zI(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new _I(t);case"WordPiece":return new gI(t);case"Metaspace":return new yI(t);case"BPEDecoder":return new vI(t);case"CTC":return new EI(t);case"Sequence":return new TI(t);case"Replace":return new SI(t);case"Fuse":return new II(t);case"Strip":return new PI(t);case"ByteFallback":return new NI(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Tv=zI,RI=class{constructor(t,e){let r=mv(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=mv(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=bv(this.tokenizer.normalizer),this.pre_tokenizer=vv(this.tokenizer.pre_tokenizer),this.model=tI(this.tokenizer.model,this.config),this.post_processor=Av(this.tokenizer.post_processor),this.decoder=Tv(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 OS(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 fv(n),this.splitter_normalized=new fv(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||!RS(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=yp(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=BS(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}},Mv=RI;var R=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 Sv(t){return/\w/.test(t)}function $n(t){return/[0-9]/.test(t)}function Ov(t){return/\s/.test(t)}var $I=[["{%",R.OpenStatement],["%}",R.CloseStatement],["{{",R.OpenExpression],["}}",R.CloseExpression],["(",R.OpenParen],[")",R.CloseParen],["{",R.OpenCurlyBracket],["}",R.CloseCurlyBracket],["[",R.OpenSquareBracket],["]",R.CloseSquareBracket],[",",R.Comma],[".",R.Dot],[":",R.Colon],["|",R.Pipe],["<=",R.ComparisonBinaryOperator],[">=",R.ComparisonBinaryOperator],["==",R.ComparisonBinaryOperator],["!=",R.ComparisonBinaryOperator],["<",R.ComparisonBinaryOperator],[">",R.ComparisonBinaryOperator],["+",R.AdditiveBinaryOperator],["-",R.AdditiveBinaryOperator],["~",R.AdditiveBinaryOperator],["*",R.MultiplicativeBinaryOperator],["/",R.MultiplicativeBinaryOperator],["%",R.MultiplicativeBinaryOperator],["=",R.Equals]],BI=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 DI(t,e={}){let r=[],s=UI(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=BI.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===R.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n<s.length&&Ov(s[n]);)++n};e:for(;n<s.length;){let c=r.at(-1)?.type;if(c===void 0||c===R.CloseStatement||c===R.CloseExpression||c===R.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,R.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 h=m.endsWith("-");h&&(m=m.slice(0,-1)),d&&i(),r.push(new Ut(m,R.Comment)),n+=2,h&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Ut("{%",R.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Ut("{{",R.OpenExpression)),o=0,n+=3;continue}if(a(Ov),s.slice(n,n+3)==="-%}"){r.push(new Ut("%}",R.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Ut("}}",R.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let d=r.at(-1)?.type;if(d===R.Text||d===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(d){case R.Identifier:case R.NumericLiteral:case R.StringLiteral:case R.CloseParen:case R.CloseSquareBracket:break;default:{++n;let m=a($n);r.push(new Ut(`${p}${m}`,m.length>0?R.NumericLiteral:R.UnaryOperator));continue}}}for(let[d,m]of $I){if(d==="}}"&&o>0)continue;if(s.slice(n,n+d.length)===d){r.push(new Ut(d,m)),m===R.OpenExpression?o=0:m===R.OpenCurlyBracket?++o:m===R.CloseCurlyBracket&&--o,n+=d.length;continue e}}if(p==="'"||p==='"'){++n;let d=a(m=>m!==p);r.push(new Ut(d,R.StringLiteral)),++n;continue}if($n(p)){let d=a($n);if(s[n]==="."&&$n(s[n+1])){++n;let m=a($n);d=`${d}.${m}`}r.push(new Ut(d,R.NumericLiteral));continue}if(Sv(p)){let d=a(Sv);r.push(new Ut(d,R.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Qt=class{type="Statement"},FI=class extends Qt{constructor(t){super(),this.body=t}type="Program"},jI=class extends Qt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},GI=class extends Qt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},WI=class extends Qt{type="Break"},qI=class extends Qt{type="Continue"},VI=class extends Qt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},HI=class extends Qt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},XI=class extends Qt{constructor(t){super(),this.value=t}type="Comment"},It=class extends Qt{type="Expression"},YI=class extends It{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},Iv=class extends It{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Rs=class extends It{constructor(t){super(),this.value=t}type="Identifier"},$s=class extends It{constructor(t){super(),this.value=t}type="Literal"},KI=class extends $s{type="IntegerLiteral"},QI=class extends $s{type="FloatLiteral"},Cv=class extends $s{type="StringLiteral"},JI=class extends $s{type="ArrayLiteral"},Pv=class extends $s{type="TupleLiteral"},ZI=class extends $s{type="ObjectLiteral"},Bn=class extends It{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},eC=class extends It{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},tC=class extends Qt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},rC=class extends It{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},sC=class extends It{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},nC=class extends It{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},oC=class extends It{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},aC=class extends It{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},iC=class extends It{constructor(t){super(),this.argument=t}type="SpreadExpression"},lC=class extends Qt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},cC=class extends It{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function uC(t){let e=new FI([]),r=0;function s(O,N){let $=t[r++];if(!$||$.type!==O)throw new Error(`Parser Error: ${N}. ${$.type} !== ${O}.`);return $}function n(O){if(!l(O))throw new SyntaxError(`Expected ${O}`);++r}function o(){switch(t[r].type){case R.Comment:return new XI(t[r++].value);case R.Text:return c();case R.OpenStatement:return p();case R.OpenExpression:return d();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...O){return r+O.length<=t.length&&O.every((N,$)=>N===t[r+$].type)}function i(...O){return t[r]?.type===R.OpenStatement&&t[r+1]?.type===R.Identifier&&O.includes(t[r+1]?.value)}function l(...O){return r+O.length<=t.length&&O.every((N,$)=>t[r+$].type==="Identifier"&&N===t[r+$].value)}function c(){return new Cv(s(R.Text,"Expected text token").value)}function p(){if(s(R.OpenStatement,"Expected opening statement token"),t[r].type!==R.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let O=t[r].value,N;switch(O){case"set":++r,N=m();break;case"if":++r,N=h(),s(R.OpenStatement,"Expected {% token"),n("endif"),s(R.CloseStatement,"Expected %} token");break;case"macro":++r,N=g(),s(R.OpenStatement,"Expected {% token"),n("endmacro"),s(R.CloseStatement,"Expected %} token");break;case"for":++r,N=k(),s(R.OpenStatement,"Expected {% token"),n("endfor"),s(R.CloseStatement,"Expected %} token");break;case"call":{++r;let $=null;a(R.OpenParen)&&($=V());let te=ie();if(te.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let ue=V();s(R.CloseStatement,"Expected closing statement token");let Ue=[];for(;!i("endcall");)Ue.push(o());s(R.OpenStatement,"Expected '{%'"),n("endcall"),s(R.CloseStatement,"Expected closing statement token");let Ce=new Iv(te,ue);N=new lC(Ce,$,Ue);break}case"break":++r,s(R.CloseStatement,"Expected closing statement token"),N=new WI;break;case"continue":++r,s(R.CloseStatement,"Expected closing statement token"),N=new qI;break;case"filter":{++r;let $=ie();$ instanceof Rs&&a(R.OpenParen)&&($=X($)),s(R.CloseStatement,"Expected closing statement token");let te=[];for(;!i("endfilter");)te.push(o());s(R.OpenStatement,"Expected '{%'"),n("endfilter"),s(R.CloseStatement,"Expected '%}'"),N=new tC($,te);break}default:throw new SyntaxError(`Unknown statement type: ${O}`)}return N}function d(){s(R.OpenExpression,"Expected opening expression token");let O=E();return s(R.CloseExpression,"Expected closing expression token"),O}function m(){let O=x(),N=null,$=[];if(a(R.Equals))++r,N=x();else{for(s(R.CloseStatement,"Expected %} token");!i("endset");)$.push(o());s(R.OpenStatement,"Expected {% token"),n("endset")}return s(R.CloseStatement,"Expected closing statement token"),new VI(O,N,$)}function h(){let O=E();s(R.CloseStatement,"Expected closing statement token");let N=[],$=[];for(;!i("elif","else","endif");)N.push(o());if(i("elif")){++r,++r;let te=h();$.push(te)}else if(i("else"))for(++r,++r,s(R.CloseStatement,"Expected closing statement token");!i("endif");)$.push(o());return new jI(O,N,$)}function g(){let O=ie();if(O.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let N=V();s(R.CloseStatement,"Expected closing statement token");let $=[];for(;!i("endmacro");)$.push(o());return new HI(O,N,$)}function x(O=!1){let N=O?ie:E,$=[N()],te=a(R.Comma);for(;te&&(++r,$.push(N()),!!a(R.Comma)););return te?new Pv($):$[0]}function k(){let O=x(!0);if(!(O instanceof Rs||O instanceof Pv))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${O.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let N=E();s(R.CloseStatement,"Expected closing statement token");let $=[];for(;!i("endfor","else");)$.push(o());let te=[];if(i("else"))for(++r,++r,s(R.CloseStatement,"Expected closing statement token");!i("endfor");)te.push(o());return new GI(O,N,$,te)}function E(){return A()}function A(){let O=S();if(l("if")){++r;let N=S();if(l("else")){++r;let $=A();return new cC(N,O,$)}else return new rC(O,N)}return O}function S(){let O=M();for(;l("or");){let N=t[r];++r;let $=M();O=new Bn(N,O,$)}return O}function M(){let O=L();for(;l("and");){let N=t[r];++r;let $=L();O=new Bn(N,O,$)}return O}function L(){let O;for(;l("not");){let N=t[r];++r;let $=L();O=new nC(N,$)}return O??C()}function C(){let O=v();for(;;){let N;if(l("not","in"))N=new Ut("not in",R.Identifier),r+=2;else if(l("in"))N=t[r++];else if(a(R.ComparisonBinaryOperator))N=t[r++];else break;let $=v();O=new Bn(N,O,$)}return O}function v(){let O=U();for(;a(R.AdditiveBinaryOperator);){let N=t[r];++r;let $=U();O=new Bn(N,O,$)}return O}function G(){let O=K(ie());return a(R.OpenParen)?X(O):O}function X(O){let N=new Iv(O,V());return N=K(N),a(R.OpenParen)&&(N=X(N)),N}function V(){s(R.OpenParen,"Expected opening parenthesis for arguments list");let O=Q();return s(R.CloseParen,"Expected closing parenthesis for arguments list"),O}function Q(){let O=[];for(;!a(R.CloseParen);){let N;if(t[r].type===R.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let $=E();N=new iC($)}else if(N=E(),a(R.Equals)){if(++r,!(N instanceof Rs))throw new SyntaxError("Expected identifier for keyword argument");let $=E();N=new aC(N,$)}O.push(N),a(R.Comma)&&++r}return O}function Y(){let O=[],N=!1;for(;!a(R.CloseSquareBracket);)a(R.Colon)?(O.push(void 0),++r,N=!0):(O.push(E()),a(R.Colon)&&(++r,N=!0));if(O.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(O.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new oC(...O)}return O[0]}function K(O){for(;a(R.Dot)||a(R.OpenSquareBracket);){let N=t[r];++r;let $,te=N.type===R.OpenSquareBracket;if(te)$=Y(),s(R.CloseSquareBracket,"Expected closing square bracket");else if($=ie(),$.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");O=new YI(O,$,te)}return O}function U(){let O=P();for(;a(R.MultiplicativeBinaryOperator);){let N=t[r++],$=P();O=new Bn(N,O,$)}return O}function P(){let O=se();for(;l("is");){++r;let N=l("not");N&&++r;let $=ie();if(!($ instanceof Rs))throw new SyntaxError("Expected identifier for the test");O=new sC(O,N,$)}return O}function se(){let O=G();for(;a(R.Pipe);){++r;let N=ie();if(!(N instanceof Rs))throw new SyntaxError("Expected identifier for the filter");a(R.OpenParen)&&(N=X(N)),O=new eC(O,N)}return O}function ie(){let O=t[r++];switch(O.type){case R.NumericLiteral:{let N=O.value;return N.includes(".")?new QI(Number(N)):new KI(Number(N))}case R.StringLiteral:{let N=O.value;for(;a(R.StringLiteral);)N+=t[r++].value;return new Cv(N)}case R.Identifier:return new Rs(O.value);case R.OpenParen:{let N=x();return s(R.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),N}case R.OpenSquareBracket:{let N=[];for(;!a(R.CloseSquareBracket);)N.push(E()),a(R.Comma)&&++r;return++r,new JI(N)}case R.OpenCurlyBracket:{let N=new Map;for(;!a(R.CloseCurlyBracket);){let $=E();s(R.Colon,"Expected colon between key and value in object literal");let te=E();N.set($,te),a(R.Comma)&&++r}return++r,new ZI(N)}default:throw new SyntaxError(`Unexpected token: ${O.type}`)}}for(;r<t.length;)e.body.push(o());return e}function pC(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 Lv(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 fC(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function dC(t){return mC(new Date,t)}function mC(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 hC(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _C(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(hC(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var Nv=class extends Error{},zv=class extends Error{},ar=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new le(!!this.value)}toString(){return String(this.value)}},fe=class extends ar{type="IntegerValue"},Ye=class extends ar{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Z=class extends ar{type="StringValue";builtins=new Map([["upper",new je(()=>new Z(this.value.toUpperCase()))],["lower",new je(()=>new Z(this.value.toLowerCase()))],["strip",new je(()=>new Z(this.value.trim()))],["title",new je(()=>new Z(fC(this.value)))],["capitalize",new je(()=>new Z(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new fe(this.value.length)],["rstrip",new je(()=>new Z(this.value.trimEnd()))],["lstrip",new je(()=>new Z(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 Z)return new le(this.value.startsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof Z))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new le(!0)}return new le(!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 Z)return new le(this.value.endsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof Z))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new le(!0)}return new le(!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 Z||e instanceof We))throw new Error("sep argument must be a string or null");let r=t[1]??new fe(-1);if(!(r instanceof fe))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 ve(s.map(n=>new Z(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 Z&&r instanceof Z))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 fe||s instanceof We))throw new Error("replace() count argument must be a number or null");return new Z(_C(this.value,e.value,r.value,s.value))})]])},le=class extends ar{type="BooleanValue"},wC=/[\x7f-\uffff]/g;function Rv(t){return t.replace(wC,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function ss(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=Rv(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",d=`
|
|
5
|
-
`+p.repeat(r),m=
|
|
1
|
+
var gS=Object.defineProperty;var es=(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 ts=(t,e)=>{for(var r in e)gS(t,r,{get:e[r],enumerable:!0})};var xS={},Tt=xS;var yS={},Ht=yS;var bS={},iv=bS;var vS="4.0.0-next.4",cv=typeof process<"u",uv=cv&&process?.release?.name==="node",Nn=!mv(Tt),pv=!mv(Ht),kS=typeof globalThis.Deno<"u",$L=typeof globalThis.Bun<"u",dv=typeof window<"u"&&typeof window.document<"u",fv=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),gp=typeof self<"u"&&"caches"in self,ES=uv||typeof navigator<"u"&&"gpu"in navigator,AS=typeof navigator<"u"&&"ml"in navigator,TS=()=>{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},MS=TS(),be=Object.freeze({IS_BROWSER_ENV:dv,IS_WEBWORKER_ENV:fv,IS_WEB_CACHE_AVAILABLE:gp,IS_WEBGPU_AVAILABLE:ES,IS_WEBNN_AVAILABLE:AS,IS_SAFARI:MS,IS_PROCESS_AVAILABLE:cv,IS_NODE_ENV:uv,IS_FS_AVAILABLE:Nn,IS_PATH_AVAILABLE:pv}),xp=Nn&&pv,$i="./";if(xp){let t=Object(import.meta).url;t?$i=Ht.dirname(Ht.dirname(iv.fileURLToPath(t))):typeof __dirname<"u"&&($i=Ht.dirname(__dirname))}var SS=xp?Ht.join($i,"/.cache/"):null,lv="/models/",OS=xp?Ht.join($i,lv):lv,De={version:vS,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(dv||fv),localModelPath:OS,useFS:Nn,useBrowserCache:gp&&!kS,useFSCache:Nn,cacheDir:SS,useCustomCache:!1,customCache:null,useWasmCache:gp||Nn,cacheKey:"transformers-cache"};function mv(t){return Object.keys(t).length===0}var IS=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}},hv=IS,CS=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}},PS=CS,vv=(()=>{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]]))})(),LS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),NS=LS(vv),_v=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",zS=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}]+"],[` ?[^(\\s|[${_v}])]+`,` ?[^\\s${_v}]+`]]),Bi="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",bp=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"),Ui=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[s,n]of zS)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=RS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},RS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$S=(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},BS=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,US=t=>Number.isInteger(t)||typeof t=="bigint",DS=t=>{let e=0;for(let r of t)++e;return e},FS=t=>kv(t.toLowerCase()),Xt=(...t)=>Array.prototype.concat.apply([],t),vp=t=>new Map(Object.entries(t)),jS=(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},kv=t=>t.replace(/\p{M}/gu,""),wv=(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},GS=t=>t.match(/\S+/g)||[],WS=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},zn=WS,qS=class extends zn{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},wr=qS,VS=class extends wr{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r],n=s.charCodeAt(0);BS(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}},HS=VS,XS=class extends wr{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}},YS=XS,KS=class extends wr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>Ev(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},QS=KS,JS=class extends wr{normalize(t){let e=Ui(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},ZS=JS,eO=class extends wr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Di=eO,tO=class extends Di{constructor(){super(...arguments),this.form="NFC"}},rO=tO,sO=class extends Di{constructor(){super(...arguments),this.form="NFD"}},nO=sO,oO=class extends Di{constructor(){super(...arguments),this.form="NFKC"}},aO=oO,iO=class extends Di{constructor(){super(...arguments),this.form="NFKD"}},lO=iO,cO=class extends wr{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}},uO=cO,pO=class extends wr{normalize(t){return kv(t)}},dO=pO,fO=class extends wr{normalize(t){return t.toLowerCase()}},mO=fO,hO=class extends wr{normalize(t){return t=this.config.prepend+t,t}},_O=hO;function wO(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new HS(t);case"Precompiled":return new YS(t);case"Sequence":return new QS(t);case"Replace":return new ZS(t);case"NFC":return new rO(t);case"NFD":return new nO(t);case"NFKC":return new aO(t);case"NFKD":return new lO(t);case"Strip":return new uO(t);case"StripAccents":return new dO(t);case"Lowercase":return new mO(t);case"Prepend":return new _O(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var Ev=wO,gO=class extends zn{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=gO,xO=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=vv,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(""))}},yO=xO,bO=class extends Yt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},vO=bO,kO=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]}},EO=kO,AO=class extends Yt{constructor(t){super(),this.config=t,this.pattern=Ui(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):jS(t,this.pattern)}},TO=AO,MO=class extends Yt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Bi}]+|[${Bi}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},SO=MO,OO=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)||[]}},IO=OO,CO=class extends Yt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Bi}]+|[${Bi}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},PO=CO,LO=class extends Yt{constructor(t){super(),this.config=t,this.pattern=Ui(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},NO=LO,zO=class extends Yt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>Av(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},RO=zO,$O=class extends Yt{pre_tokenize_text(t){return GS(t)}},BO=$O,UO=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}},DO=UO;function FO(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new PO;case"Sequence":return new RO(t);case"Whitespace":return new vO;case"WhitespaceSplit":return new BO;case"Metaspace":return new EO(t);case"ByteLevel":return new yO(t);case"Split":return new TO(t);case"Punctuation":return new SO(t);case"Digits":return new IO(t);case"Replace":return new NO(t);case"FixedLength":return new DO(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var Av=FO,jO=class extends zn{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=$S(e,this.tokens_to_ids,this.unk_token_id)),e}},Fi=jO,GO=class extends Fi{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=vp(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}},gv=GO,xv=class Tv{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new Tv(!1,new Map)}},WO=class{constructor(){this.root=xv.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=xv.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)}}},qO=WO,yp=class Mv{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 Mv(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},VO=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 yp(this.bos_token_id??0,0,0,0,0),n=new yp(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 yp(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)}},HO=VO;function XO(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 YO=class extends Fi{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=XO(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new qO,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=DS(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 HO(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}},yv=YO,KO=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}},QO=KO,JO=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()}},ZO=JO,eI=class extends Fi{constructor(t){super(t),this.tokens_to_ids=vp(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 ZO(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 QO((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):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},bv=eI,tI=class extends Fi{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=vp(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}},rI=tI;function sI(t,e){switch(t.type){case"WordPiece":return new gv(t);case"Unigram":return new yv(t,e.eos_token);case"BPE":return new bv(t);default:if(t.vocab)return Array.isArray(t.vocab)?new yv(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new bv(t):new gv(t):new rI(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 nI=sI,oI=class extends zn{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Rn=oI,aI=class extends Rn{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}}},iI=aI,lI=class extends Rn{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},cI=lI,uI=class extends Rn{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}}},pI=uI,dI=class extends Rn{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}}},fI=dI,mI=class extends Rn{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>Sv(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}},hI=mI;function _I(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new iI(t);case"ByteLevel":return new cI(t);case"BertProcessing":return new pI(t);case"RobertaProcessing":return new fI(t);case"Sequence":return new hI(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var Sv=_I,wI=class extends zn{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=wI,gI=class extends Bt{constructor(t){super(t),this.byte_decoder=NS,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}},xI=gI,yI=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=bp(e)),e})}},bI=yI,vI=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}},kI=vI,EI=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?"":" "))}},AI=EI,TI=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=bp(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},MI=TI,SI=class extends Bt{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>Ov(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},OI=SI,II=class extends Bt{decode_chain(t){let e=Ui(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},CI=II,PI=class extends Bt{decode_chain(t){return[t.join("")]}},LI=PI,NI=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)})}},zI=NI,RI=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}},$I=RI;function BI(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new xI(t);case"WordPiece":return new bI(t);case"Metaspace":return new kI(t);case"BPEDecoder":return new AI(t);case"CTC":return new MI(t);case"Sequence":return new OI(t);case"Replace":return new CI(t);case"Fuse":return new LI(t);case"Strip":return new zI(t);case"ByteFallback":return new $I(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var Ov=BI,UI=class{constructor(t,e){let r=wv(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=wv(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=Ev(this.tokenizer.normalizer),this.pre_tokenizer=Av(this.tokenizer.pre_tokenizer),this.model=nI(this.tokenizer.model,this.config),this.post_processor=Sv(this.tokenizer.post_processor),this.decoder=Ov(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 PS(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 hv(n),this.splitter_normalized=new hv(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||!US(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=bp(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=FS(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}},Iv=UI;var R=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 Cv(t){return/\w/.test(t)}function $n(t){return/[0-9]/.test(t)}function Pv(t){return/\s/.test(t)}var DI=[["{%",R.OpenStatement],["%}",R.CloseStatement],["{{",R.OpenExpression],["}}",R.CloseExpression],["(",R.OpenParen],[")",R.CloseParen],["{",R.OpenCurlyBracket],["}",R.CloseCurlyBracket],["[",R.OpenSquareBracket],["]",R.CloseSquareBracket],[",",R.Comma],[".",R.Dot],[":",R.Colon],["|",R.Pipe],["<=",R.ComparisonBinaryOperator],[">=",R.ComparisonBinaryOperator],["==",R.ComparisonBinaryOperator],["!=",R.ComparisonBinaryOperator],["<",R.ComparisonBinaryOperator],[">",R.ComparisonBinaryOperator],["+",R.AdditiveBinaryOperator],["-",R.AdditiveBinaryOperator],["~",R.AdditiveBinaryOperator],["*",R.MultiplicativeBinaryOperator],["/",R.MultiplicativeBinaryOperator],["%",R.MultiplicativeBinaryOperator],["=",R.Equals]],FI=new Map([["n",`
|
|
3
|
+
`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function jI(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 GI(t,e={}){let r=[],s=jI(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=FI.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===R.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n<s.length&&Pv(s[n]);)++n};e:for(;n<s.length;){let c=r.at(-1)?.type;if(c===void 0||c===R.CloseStatement||c===R.CloseExpression||c===R.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,R.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 h=m.endsWith("-");h&&(m=m.slice(0,-1)),f&&i(),r.push(new Ut(m,R.Comment)),n+=2,h&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Ut("{%",R.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Ut("{{",R.OpenExpression)),o=0,n+=3;continue}if(a(Pv),s.slice(n,n+3)==="-%}"){r.push(new Ut("%}",R.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Ut("}}",R.CloseExpression)),n+=3,l();continue}let p=s[n];if(p==="-"||p==="+"){let f=r.at(-1)?.type;if(f===R.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${p}`);switch(f){case R.Identifier:case R.NumericLiteral:case R.StringLiteral:case R.CloseParen:case R.CloseSquareBracket:break;default:{++n;let m=a($n);r.push(new Ut(`${p}${m}`,m.length>0?R.NumericLiteral:R.UnaryOperator));continue}}}for(let[f,m]of DI){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Ut(f,m)),m===R.OpenExpression?o=0:m===R.OpenCurlyBracket?++o:m===R.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(p==="'"||p==='"'){++n;let f=a(m=>m!==p);r.push(new Ut(f,R.StringLiteral)),++n;continue}if($n(p)){let f=a($n);if(s[n]==="."&&$n(s[n+1])){++n;let m=a($n);f=`${f}.${m}`}r.push(new Ut(f,R.NumericLiteral));continue}if(Cv(p)){let f=a(Cv);r.push(new Ut(f,R.Identifier));continue}throw new SyntaxError(`Unexpected character: ${p}`)}return r}var Qt=class{type="Statement"},WI=class extends Qt{constructor(t){super(),this.body=t}type="Program"},qI=class extends Qt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},VI=class extends Qt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},HI=class extends Qt{type="Break"},XI=class extends Qt{type="Continue"},YI=class extends Qt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},KI=class extends Qt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},QI=class extends Qt{constructor(t){super(),this.value=t}type="Comment"},It=class extends Qt{type="Expression"},JI=class extends It{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},Lv=class extends It{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Rs=class extends It{constructor(t){super(),this.value=t}type="Identifier"},$s=class extends It{constructor(t){super(),this.value=t}type="Literal"},ZI=class extends $s{type="IntegerLiteral"},eC=class extends $s{type="FloatLiteral"},Nv=class extends $s{type="StringLiteral"},tC=class extends $s{type="ArrayLiteral"},zv=class extends $s{type="TupleLiteral"},rC=class extends $s{type="ObjectLiteral"},Bn=class extends It{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},sC=class extends It{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},nC=class extends Qt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},oC=class extends It{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},aC=class extends It{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},iC=class extends It{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},lC=class extends It{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},cC=class extends It{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},uC=class extends It{constructor(t){super(),this.argument=t}type="SpreadExpression"},pC=class extends Qt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},dC=class extends It{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function fC(t){let e=new WI([]),r=0;function s(O,N){let $=t[r++];if(!$||$.type!==O)throw new Error(`Parser Error: ${N}. ${$.type} !== ${O}.`);return $}function n(O){if(!l(O))throw new SyntaxError(`Expected ${O}`);++r}function o(){switch(t[r].type){case R.Comment:return new QI(t[r++].value);case R.Text:return c();case R.OpenStatement:return p();case R.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...O){return r+O.length<=t.length&&O.every((N,$)=>N===t[r+$].type)}function i(...O){return t[r]?.type===R.OpenStatement&&t[r+1]?.type===R.Identifier&&O.includes(t[r+1]?.value)}function l(...O){return r+O.length<=t.length&&O.every((N,$)=>t[r+$].type==="Identifier"&&N===t[r+$].value)}function c(){return new Nv(s(R.Text,"Expected text token").value)}function p(){if(s(R.OpenStatement,"Expected opening statement token"),t[r].type!==R.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let O=t[r].value,N;switch(O){case"set":++r,N=m();break;case"if":++r,N=h(),s(R.OpenStatement,"Expected {% token"),n("endif"),s(R.CloseStatement,"Expected %} token");break;case"macro":++r,N=g(),s(R.OpenStatement,"Expected {% token"),n("endmacro"),s(R.CloseStatement,"Expected %} token");break;case"for":++r,N=k(),s(R.OpenStatement,"Expected {% token"),n("endfor"),s(R.CloseStatement,"Expected %} token");break;case"call":{++r;let $=null;a(R.OpenParen)&&($=V());let te=ie();if(te.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let ue=V();s(R.CloseStatement,"Expected closing statement token");let Ue=[];for(;!i("endcall");)Ue.push(o());s(R.OpenStatement,"Expected '{%'"),n("endcall"),s(R.CloseStatement,"Expected closing statement token");let Ce=new Lv(te,ue);N=new pC(Ce,$,Ue);break}case"break":++r,s(R.CloseStatement,"Expected closing statement token"),N=new HI;break;case"continue":++r,s(R.CloseStatement,"Expected closing statement token"),N=new XI;break;case"filter":{++r;let $=ie();$ instanceof Rs&&a(R.OpenParen)&&($=X($)),s(R.CloseStatement,"Expected closing statement token");let te=[];for(;!i("endfilter");)te.push(o());s(R.OpenStatement,"Expected '{%'"),n("endfilter"),s(R.CloseStatement,"Expected '%}'"),N=new nC($,te);break}default:throw new SyntaxError(`Unknown statement type: ${O}`)}return N}function f(){s(R.OpenExpression,"Expected opening expression token");let O=E();return s(R.CloseExpression,"Expected closing expression token"),O}function m(){let O=x(),N=null,$=[];if(a(R.Equals))++r,N=x();else{for(s(R.CloseStatement,"Expected %} token");!i("endset");)$.push(o());s(R.OpenStatement,"Expected {% token"),n("endset")}return s(R.CloseStatement,"Expected closing statement token"),new YI(O,N,$)}function h(){let O=E();s(R.CloseStatement,"Expected closing statement token");let N=[],$=[];for(;!i("elif","else","endif");)N.push(o());if(i("elif")){++r,++r;let te=h();$.push(te)}else if(i("else"))for(++r,++r,s(R.CloseStatement,"Expected closing statement token");!i("endif");)$.push(o());return new qI(O,N,$)}function g(){let O=ie();if(O.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let N=V();s(R.CloseStatement,"Expected closing statement token");let $=[];for(;!i("endmacro");)$.push(o());return new KI(O,N,$)}function x(O=!1){let N=O?ie:E,$=[N()],te=a(R.Comma);for(;te&&(++r,$.push(N()),!!a(R.Comma)););return te?new zv($):$[0]}function k(){let O=x(!0);if(!(O instanceof Rs||O instanceof zv))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${O.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let N=E();s(R.CloseStatement,"Expected closing statement token");let $=[];for(;!i("endfor","else");)$.push(o());let te=[];if(i("else"))for(++r,++r,s(R.CloseStatement,"Expected closing statement token");!i("endfor");)te.push(o());return new VI(O,N,$,te)}function E(){return A()}function A(){let O=S();if(l("if")){++r;let N=S();if(l("else")){++r;let $=A();return new dC(N,O,$)}else return new oC(O,N)}return O}function S(){let O=M();for(;l("or");){let N=t[r];++r;let $=M();O=new Bn(N,O,$)}return O}function M(){let O=L();for(;l("and");){let N=t[r];++r;let $=L();O=new Bn(N,O,$)}return O}function L(){let O;for(;l("not");){let N=t[r];++r;let $=L();O=new iC(N,$)}return O??C()}function C(){let O=v();for(;;){let N;if(l("not","in"))N=new Ut("not in",R.Identifier),r+=2;else if(l("in"))N=t[r++];else if(a(R.ComparisonBinaryOperator))N=t[r++];else break;let $=v();O=new Bn(N,O,$)}return O}function v(){let O=U();for(;a(R.AdditiveBinaryOperator);){let N=t[r];++r;let $=U();O=new Bn(N,O,$)}return O}function G(){let O=K(ie());return a(R.OpenParen)?X(O):O}function X(O){let N=new Lv(O,V());return N=K(N),a(R.OpenParen)&&(N=X(N)),N}function V(){s(R.OpenParen,"Expected opening parenthesis for arguments list");let O=Q();return s(R.CloseParen,"Expected closing parenthesis for arguments list"),O}function Q(){let O=[];for(;!a(R.CloseParen);){let N;if(t[r].type===R.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let $=E();N=new uC($)}else if(N=E(),a(R.Equals)){if(++r,!(N instanceof Rs))throw new SyntaxError("Expected identifier for keyword argument");let $=E();N=new cC(N,$)}O.push(N),a(R.Comma)&&++r}return O}function Y(){let O=[],N=!1;for(;!a(R.CloseSquareBracket);)a(R.Colon)?(O.push(void 0),++r,N=!0):(O.push(E()),a(R.Colon)&&(++r,N=!0));if(O.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(N){if(O.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new lC(...O)}return O[0]}function K(O){for(;a(R.Dot)||a(R.OpenSquareBracket);){let N=t[r];++r;let $,te=N.type===R.OpenSquareBracket;if(te)$=Y(),s(R.CloseSquareBracket,"Expected closing square bracket");else if($=ie(),$.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");O=new JI(O,$,te)}return O}function U(){let O=P();for(;a(R.MultiplicativeBinaryOperator);){let N=t[r++],$=P();O=new Bn(N,O,$)}return O}function P(){let O=se();for(;l("is");){++r;let N=l("not");N&&++r;let $=ie();if(!($ instanceof Rs))throw new SyntaxError("Expected identifier for the test");O=new aC(O,N,$)}return O}function se(){let O=G();for(;a(R.Pipe);){++r;let N=ie();if(!(N instanceof Rs))throw new SyntaxError("Expected identifier for the filter");a(R.OpenParen)&&(N=X(N)),O=new sC(O,N)}return O}function ie(){let O=t[r++];switch(O.type){case R.NumericLiteral:{let N=O.value;return N.includes(".")?new eC(Number(N)):new ZI(Number(N))}case R.StringLiteral:{let N=O.value;for(;a(R.StringLiteral);)N+=t[r++].value;return new Nv(N)}case R.Identifier:return new Rs(O.value);case R.OpenParen:{let N=x();return s(R.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),N}case R.OpenSquareBracket:{let N=[];for(;!a(R.CloseSquareBracket);)N.push(E()),a(R.Comma)&&++r;return++r,new tC(N)}case R.OpenCurlyBracket:{let N=new Map;for(;!a(R.CloseCurlyBracket);){let $=E();s(R.Colon,"Expected colon between key and value in object literal");let te=E();N.set($,te),a(R.Comma)&&++r}return++r,new rC(N)}default:throw new SyntaxError(`Unexpected token: ${O.type}`)}}for(;r<t.length;)e.body.push(o());return e}function mC(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 Rv(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 hC(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function _C(t){return wC(new Date,t)}function wC(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 gC(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xC(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(gC(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var $v=class extends Error{},Bv=class extends Error{},ar=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new le(!!this.value)}toString(){return String(this.value)}},de=class extends ar{type="IntegerValue"},Ye=class extends ar{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Z=class extends ar{type="StringValue";builtins=new Map([["upper",new je(()=>new Z(this.value.toUpperCase()))],["lower",new je(()=>new Z(this.value.toLowerCase()))],["strip",new je(()=>new Z(this.value.trim()))],["title",new je(()=>new Z(hC(this.value)))],["capitalize",new je(()=>new Z(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new de(this.value.length)],["rstrip",new je(()=>new Z(this.value.trimEnd()))],["lstrip",new je(()=>new Z(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 Z)return new le(this.value.startsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof Z))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new le(!0)}return new le(!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 Z)return new le(this.value.endsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof Z))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new le(!0)}return new le(!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 Z||e instanceof We))throw new Error("sep argument must be a string or null");let r=t[1]??new de(-1);if(!(r instanceof de))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 ve(s.map(n=>new Z(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 Z&&r instanceof Z))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 de||s instanceof We))throw new Error("replace() count argument must be a number or null");return new Z(xC(this.value,e.value,r.value,s.value))})]])},le=class extends ar{type="BooleanValue"},yC=/[\x7f-\uffff]/g;function Uv(t){return t.replace(yC,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function ss(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=Uv(p)),p}case"ArrayValue":case"ObjectValue":{let p=n?" ".repeat(n):"",f=`
|
|
5
|
+
`+p.repeat(r),m=f+p;if(t.type==="ArrayValue"){let h=t.value.map(g=>ss(g,e,r+1,s));return n?`[${m}${h.join(`${l}${m}`)}${f}]`:`[${h.join(l)}]`}else{let h=Array.from(t.value.entries());i&&(h=h.sort(([x],[k])=>x.localeCompare(k)));let g=h.map(([x,k])=>{let E=JSON.stringify(x);o&&(E=Uv(E));let A=`${E}${c}${ss(k,e,r+1,s)}`;return n?`${m}${A}`:A});return n?`{${g.join(l)}${f}}`:`{${g.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var _t=class extends ar{type="ObjectValue";__bool__(){return new le(this.value.size>0)}builtins=new Map([["get",new je(([t,e])=>{if(!(t instanceof Z))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 Un?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new le(!1);if(!(s instanceof le))throw new Error("case_sensitive must be a boolean");let n=r.at(1)??e.get("by")??new Z("key");if(!(n instanceof Z))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 le(!1);if(!(o instanceof le))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new ve([new Z(i),l])).sort((i,l)=>{let c=n.value==="key"?0:1,p=i.value[c],f=l.value[c],m=kp(p,f,s.value);return o.value?-m:m});return new ve(a)})]]);items(){return new ve(Array.from(this.value.entries()).map(([t,e])=>new ve([new Z(t),e])))}keys(){return new ve(Array.from(this.value.keys()).map(t=>new Z(t)))}values(){return new ve(Array.from(this.value.values()))}toString(){return ss(this,{},0,!1)}},Un=class extends _t{type="KeywordArgumentsValue"},ve=class extends ar{type="ArrayValue";builtins=new Map([["length",new de(this.value.length)]]);__bool__(){return new le(this.value.length>0)}toString(){return ss(this,{},0,!1)}},Dv=class extends ve{type="TupleValue"},je=class extends ar{type="FunctionValue"},We=class extends ar{type="NullValue"},Fe=class extends ar{type="UndefinedValue"},rs=class{constructor(t){this.parent=t}variables=new Map([["namespace",new je(t=>{if(t.length===0)return new _t(new Map);if(t.length!==1||!(t[0]instanceof _t))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 de))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof de))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 de||t instanceof Ye],["integer",t=>t instanceof de],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t.type==="ObjectValue"],["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,ji(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 Fe}catch{return new Fe}}};function bC(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",mC),t.set("strftime_now",_C),t.set("True",!0),t.set("False",!1),t.set("None",null)}function Fv(t,e){let r=e.split("."),s=t;for(let n of r)if(s instanceof _t)s=s.value.get(n)??new Fe;else if(s instanceof ve){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&o<s.value.length)s=s.value[o];else return new Fe}else return new Fe;return s}function kp(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 Fe&&e instanceof Fe)return 0;if(t instanceof Fe||e instanceof Fe)throw new Error(`Cannot compare ${t.type} with ${e.type}`);let s=o=>o instanceof de||o instanceof Ye||o instanceof le,n=o=>o instanceof le?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 vC=class{global;constructor(t){this.global=t??new rs}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 le(r.value==s.value);case"!=":return new le(r.value!=s.value)}if(r instanceof Fe||s instanceof Fe){if(s instanceof Fe&&["in","not in"].includes(t.operator.value))return new le(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 Z(r.value.toString()+s.value.toString());if((r instanceof de||r instanceof Ye)&&(s instanceof de||s instanceof Ye)){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 Ye||s instanceof Ye?new Ye(a):new de(a)}case"/":return new Ye(n/o);case"%":{let a=n%o;return r instanceof Ye||s instanceof Ye?new Ye(a):new de(a)}case"<":return new le(n<o);case">":return new le(n>o);case">=":return new le(n>=o);case"<=":return new le(n<=o)}}else if(r instanceof ve&&s instanceof ve){if(t.operator.value==="+")return new ve(r.value.concat(s.value))}else if(s instanceof ve){let n=s.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new le(n);case"not in":return new le(!n)}}}if((r instanceof Z||s instanceof Z)&&t.operator.value==="+")return new Z(r.value.toString()+s.value.toString());if(r instanceof Z&&s instanceof Z)switch(t.operator.value){case"in":return new le(s.value.includes(r.value));case"not in":return new le(!s.value.includes(r.value))}if(r instanceof Z&&s instanceof _t)switch(t.operator.value){case"in":return new le(s.value.has(r.value));case"not in":return new le(!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 ve))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==="tojson")return new Z(ss(t,{}));if(t instanceof ve)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 de(t.value.length);case"reverse":return new ve(t.value.slice().reverse());case"sort":return new ve(t.value.slice().sort((n,o)=>kp(n,o,!1)));case"join":return new Z(t.value.map(n=>n.value).join(""));case"string":return new Z(ss(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 ve(o)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(t instanceof Z)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 de)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new Z(t.value.trim());case"indent":return new Z(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
|
|
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 Un(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof _t){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 Un(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 le(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new Fe}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new le(!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 Z(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 Un(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 ve||t instanceof Z))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
|
|
10
|
-
`,yC="{%- ",bC=" -%}";function vC(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 kC(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Kt(t.body,0,r).replace(/\n$/,"")}function pt(...t){return yC+t.join(" ")+bC}function Kt(t,e,r){return t.map(s=>EC(s,e,r)).join(nt)}function EC(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Kt(t.body,e,r);case"If":return AC(t,e,r);case"For":return TC(t,e,r);case"Set":return MC(t,e,r);case"Macro":return SC(t,e,r);case"Break":return s+pt("break");case"Continue":return s+pt("continue");case"CallStatement":return OC(t,e,r);case"FilterStatement":return IC(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function AC(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+pt("if",ke(n[0].test))+nt+Kt(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=nt+s+pt("elif",ke(n[i].test))+nt+Kt(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=nt+s+pt("else")+nt+Kt(o.alternate,e+1,r)),a+=nt+s+pt("endif"),a}function TC(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+pt("for",ke(t.loopvar),"in",n)+nt+Kt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=nt+s+pt("else")+nt+Kt(t.defaultBlock,e+1,r)),o+=nt+s+pt("endfor"),o}function MC(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+pt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+nt+Kt(t.body,e+1,r)+nt+s+pt("endset")}function SC(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+pt("macro",`${t.name.value}(${n})`)+nt+Kt(t.body,e+1,r)+nt+s+pt("endmacro")}function OC(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+pt(`call${n}`,o)+nt;return a+=Kt(t.body,e+1,r)+nt,a+=s+pt("endcall"),a}function IC(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+pt("filter",n)+nt;return o+=Kt(t.body,e+1,r)+nt,o+=s+pt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=vC(r),n=ke(r.left,s),o=ke(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"?" ":"")+ke(r.argument,1/0)}case"CallExpression":{let r=t,s=r.args.map(ke).join(", ");return`${ke(r.callee)}(${s})`}case"MemberExpression":{let r=t,s=ke(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ke(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{let r=t,s=ke(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ke(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{let r=t;return`${ke(r.lhs)} if ${ke(r.test)}`}case"TestExpression":{let r=t;return`${ke(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=t.value.map(ke),s=t.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([s,n])=>`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var Uv=class{parsed;constructor(t){let e=DI(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=uC(e)}render(t){let e=new rs;if(gC(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new xC(e).run(this.parsed).value}format(t){return kC(this.parsed,t?.indent||" ")}};var Je=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function gr(t,e){t&&t(e)}function Dv(t){return Number.isInteger(t)||typeof t=="bigint"}function kp(t){return t==null||t===-1}function Ep(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function ft(...t){return Array.prototype.concat.apply([],t)}function Fv(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function Bs(t,e){return Math.abs((t+e)%(2*e)-e)}function ot(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function jv(t,e){let r=0;for(let s of t)s===e&&++r;return r}var CC={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"},ns=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Tt.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Tt.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=Tt.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",CC[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 Tt.promises.readFile(this.filePath)).buffer}async blob(){let e=await Tt.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Tt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Us=class{constructor(e){this.path=e}async match(e){let r=Ht.join(this.path,e),s=new ns(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Ht.join(this.path,e);try{let o=r.headers.get("Content-Length"),a=parseInt(o??"0"),i=0;await Tt.promises.mkdir(Ht.dirname(n),{recursive:!0});let l=Tt.createWriteStream(n),c=r.body.getReader();for(;;){let{done:p,value:d}=await c.read();if(p)break;await new Promise((h,g)=>{l.write(d,x=>{if(x){g(x);return}h()})}),i+=d.length;let m=a?i/a*100:0;s?.({progress:m,loaded:i,total:a})}l.close()}catch(o){try{await Tt.promises.unlink(n)}catch{}throw o}}};var Gv={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"},ji=100,Wv=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Dn(...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 Ds(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 qv(t){return!(!Wv.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function Vv(t,e,r){if(!r)return null;let s=Gv[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function Hv(t,e){let r=t.headers.get("Content-Length");r===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let s=parseInt(r??"0"),n=new Uint8Array(s),o=0,a=t.body.getReader();async function i(){let{done:l,value:c}=await a.read();if(l)return;let p=o+c.length;if(p>s){s=p;let m=new Uint8Array(s);m.set(n),n=m}n.set(c,o),o=p;let d=o/s*100;return e({progress:d,loaded:o,total:s}),i()}return await i(),n}async function Gi(t=null){let e=null;if(De.useCustomCache){if(!De.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!De.customCache.match||!De.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=De.customCache}if(!e&&De.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(De.cacheKey)}catch(r){console.warn("An error occurred while opening the browser cache:",r)}}if(!e&&De.useFSCache){if(!be.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Us(t??De.cacheDir)}return e}async function Xv(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}async function Fs(t){if(De.useFS&&!Ds(t,["http:","https:","blob:"]))return new ns(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t);if(typeof process<"u"&&process?.release?.name==="node"){let e=!!process.env?.TESTING_REMOTELY,r=De.version,s=new Headers;if(s.set("User-Agent",`transformers.js/${r}; is_ci/${e};`),Ds(t,["http:","https:"],["huggingface.co","hf.co"])){let o=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;o&&s.set("Authorization",`Bearer ${o}`)}return fetch(t,{headers:s})}else return fetch(t)}function PC(t,e,r={},s=null){let n=r.revision??"main",o=Dn(t,e),a=qv(t),i=a?Dn(De.localModelPath,o):o,l=Dn(De.remoteHost,De.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof Us?n==="main"?o:Dn(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function LC(t,e,r){if(t)return await Xv(t,e,r)}async function NC(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o)typeof n!="string"&&await r.put(s,new Response(o,{headers:n.headers})).catch(i=>{console.warn(`Unable to add response to browser cache: ${i}.`)});else{let i=a.progress_callback?l=>gr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function zC(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=PC(t,e,s,o),d,m=!1,h;h=await LC(o,i,c);let g=h!==void 0;if(!g){if(De.allowLocalModels)if(Ds(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(!De.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{h=await Fs(i),d=i}catch(A){console.warn(`Unable to load from local path "${i}": "${A}"`)}if(h===void 0||typeof h!="string"&&h.status===404){if(s.local_files_only||!De.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(h=await Fs(l),h.status!==200)return Vv(h.status,l,r);d=c}m=o&&typeof Response<"u"&&h instanceof Response&&h.status===200}gr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(be.IS_NODE_ENV&&n)){let E;typeof h!="string"&&(s.progress_callback?g&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(E=new Uint8Array(await h.arrayBuffer()),gr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:E.length,total:E.length})):E=await Hv(h,A=>{gr(s.progress_callback,{status:"progress",name:t,file:e,...A})}):E=new Uint8Array(await h.arrayBuffer())),x=E}if(m&&d&&typeof h!="string"&&await NC(t,e,o,d,h,x,s),gr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!be.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(h instanceof ns)return h.filePath;let k=await o?.match(d);if(k instanceof ns)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 Fn(t,e,r=!0,s={},n=!1){if(!De.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(!De.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}gr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await Gi(s?.cache_dir);return await zC(t,e,r,s,n,o)}async function Ap(t,e,r=!0,s={}){let n=await Fn(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function at(t,e,r=!0,s={}){let n=await Ap(t,e,r,s);return n===null?{}:JSON.parse(n)}function Kv(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 h=0;h<n;++h)for(let g=0;g<o;++g){let x=h*o+g,k=(g+.5)/l-.5,E=(h+.5)/c-.5,A=Math.floor(k),S=Math.floor(E),M=Math.min(A+1,s-1),L=Math.min(S+1,r-1);A=Math.max(A,0),S=Math.max(S,0);let C=k-A,v=E-S,G=(1-C)*(1-v),X=C*(1-v),V=(1-C)*v,Q=C*v,Y=S*s,K=L*s,U=Y+A,P=Y+M,se=K+A,ie=K+M;for(let O=0;O<e;++O){let N=O*d;p[O*m+x]=G*t[N+U]+X*t[N+P]+V*t[N+se]+Q*t[N+ie]}}return p}function Qv(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 Pe(t){let e=Me(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 Mp(t){let e=Me(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 Jv(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function RC(t,e){let r=Jv(t,e),s=Yv(t),n=Yv(e);return r/(s*n)}function Yv(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function jn(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 Me(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 Zv(t){return t>0&&(t&t-1)===0}var Wi=class{constructor(e){if(this.size=e|0,this.size<=1||!Zv(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 h=l+m-1;for(let g=l,x=0;g<h;g+=2,x+=a){let k=g,E=k+m,A=E+m,S=A+m,M=e[k],L=e[k+1],C=e[E],v=e[E+1],G=e[A],X=e[A+1],V=e[S],Q=e[S+1],Y=d[x],K=s*d[x+1],U=C*Y-v*K,P=C*K+v*Y,se=d[2*x],ie=s*d[2*x+1],O=G*se-X*ie,N=G*ie+X*se,$=d[3*x],te=s*d[3*x+1],ue=V*$-Q*te,Ue=V*te+Q*$,Ce=M+O,kt=L+N,Qe=M-O,Ze=L-N,rt=U+ue,Te=P+Ue,xe=s*(U-ue),Ge=s*(P-Ue);e[k]=Ce+rt,e[k+1]=kt+Te,e[E]=Qe+Ge,e[E+1]=Ze-xe,e[A]=Ce-rt,e[A+1]=kt-Te,e[S]=Qe-Ge,e[S+1]=Ze+xe}}}}_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],h=e[n+i],g=e[n+i+1],x=e[n+l],k=e[n+l+1],E=c+h,A=p+g,S=c-h,M=p-g,L=d+x,C=m+k,v=a*(d-x),G=a*(m-k);r[s]=E+L,r[s+1]=A+C,r[s+2]=S+G,r[s+3]=M-v,r[s+4]=E-L,r[s+5]=A-C,r[s+6]=S-G,r[s+7]=M+v}_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 h=p[c];this._singleRealTransform2(r,e,l,h>>>1,a>>>1)}else for(l=0,c=0;l<n;l+=i,++c){let h=p[c];this._singleRealTransform4(r,e,l,h>>>1,a>>>1,s)}let d=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let h=i>>>1,g=h>>>1,x=g>>>1;for(l=0;l<n;l+=i)for(let k=0,E=0;k<=x;k+=2,E+=a){let A=l+k,S=A+g,M=S+g,L=M+g,C=e[A],v=e[A+1],G=e[S],X=e[S+1],V=e[M],Q=e[M+1],Y=e[L],K=e[L+1],U=C,P=v,se=d[E],ie=s*d[E+1],O=G*se-X*ie,N=G*ie+X*se,$=d[2*E],te=s*d[2*E+1],ue=V*$-Q*te,Ue=V*te+Q*$,Ce=d[3*E],kt=s*d[3*E+1],Qe=Y*Ce-K*kt,Ze=Y*kt+K*Ce,rt=U+ue,Te=P+Ue,xe=U-ue,Ge=P-Ue,Et=O+Qe,we=N+Ze,Ne=s*(O-Qe),br=s*(N-Ze);if(e[A]=rt+Et,e[A+1]=Te+we,e[S]=xe+br,e[S+1]=Ge-Ne,k===0){e[M]=rt-Et,e[M+1]=Te-we;continue}if(k===x)continue;let Yr=l+g-k,At=l+h-k;e[Yr]=xe-s*br,e[Yr+1]=-Ge-s*Ne,e[At]=rt-s*Et,e[At+1]=-Te+s*we}}let m=n>>>1;for(let h=2;h<m;h+=2)e[n-h]=e[h],e[n-h+1]=-e[h+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],h=c+d,g=c-d,x=p+m,k=a*(p-m);r[s]=h+x,r[s+1]=0,r[s+2]=g,r[s+3]=-k,r[s+4]=h-x,r[s+5]=0,r[s+6]=g,r[s+7]=k}},Tp=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,h=d*Math.atan2(c,l),g=2*p;o[g]=m*Math.cos(h),o[g+1]=m*Math.sin(h),a[g]=o[g],a[g+1]=-o[g+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new Wi(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,h=d>>1,g=r[h];n[d]=g*c[d],n[m]=g*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],h=i[d+p+1],g=c[d],x=c[d+1];e[d]=m*g-h*x,e[d+1]=m*x+h*g}}transform(e,r){this._transform(e,r,!1)}realTransform(e,r){this._transform(e,r,!0)}},qi=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Zv(e),this.isPowerOfTwo?(this.fft=new Wi(e),this.outputBufferSize=2*e):(this.fft=new Tp(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function ek(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 os(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function tk(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function rk(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],h=n[d-1][p],g=n[d][p-1],x,k;m<h&&m<g?(x=m,k=0):h<m&&h<g?(x=h,k=1):(x=g,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 sk=(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 h=113;for(;(m&1024)===0;)m<<=1,--h;m&=-1025,c=p|h<<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 Sp={};ts(Sp,{Readable:()=>UC,createReadStream:()=>jC,createWriteStream:()=>FC,default:()=>BC,pipeline:()=>DC});var Vi=()=>{},$C={},BC=$C,UC={fromWeb:Vi},DC=Vi,FC=Vi,jC=Vi;var xf={};ts(xf,{InferenceSession:()=>sf,TRACE:()=>tl,TRACE_EVENT_BEGIN:()=>Sr,TRACE_EVENT_END:()=>Or,TRACE_FUNC_BEGIN:()=>ps,TRACE_FUNC_END:()=>fs,Tensor:()=>Jt,default:()=>wP,env:()=>qe,registerBackend:()=>us});var tf=Object.defineProperty,GC=Object.getOwnPropertyDescriptor,WC=Object.getOwnPropertyNames,qC=Object.prototype.hasOwnProperty,VC=(t=>typeof es<"u"?es:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof es<"u"?es:e)[r]}):t)(function(t){if(typeof es<"u")return es.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ye=(t,e)=>()=>(t&&(e=t(t=0)),e),Kn=(t,e)=>{for(var r in e)tf(t,r,{get:e[r],enumerable:!0})},HC=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of WC(e))!qC.call(t,n)&&n!==r&&tf(t,n,{get:()=>e[n],enumerable:!(s=GC(e,n))||s.enumerable});return t},el=t=>HC(tf({},"__esModule",{value:!0}),t),Gn,Er,us,nk,Ck,Pk=ye(()=>{"use strict";Gn=new Map,Er=[],us=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Gn.get(t);if(s===void 0)Gn.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=Er.indexOf(t);n!==-1&&Er.splice(n,1);for(let o=0;o<Er.length;o++)if(Gn.get(Er[o]).priority<=r){Er.splice(o,0,t);return}Er.push(t)}return}throw new TypeError("not a valid backend")},nk=async t=>{let e=Gn.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}}},Ck=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Er:r,n,o=[],a=new Set;for(let l of s){let c=await nk(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)})]}}),XC=ye(()=>{"use strict";Pk()}),Lk,YC=ye(()=>{"use strict";Lk="1.24.0-dev.20251116-b39e144322"}),Op,ct,Nk=ye(()=>{"use strict";YC(),Op="warning",ct={wasm:{},webgl:{},webgpu:{},versions:{common:Lk},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}`);Op=t}},get logLevel(){return Op}},Object.defineProperty(ct,"logLevel",{enumerable:!0})}),qe,KC=ye(()=>{"use strict";Nk(),qe=ct}),zk,Rk,QC=ye(()=>{"use strict";zk=(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,h=p*2,g=-1;a==="RGBA"?(d=0,m=p,h=p*2,g=p*3):a==="RGB"?(d=0,m=p,h=p*2):a==="RBG"&&(d=0,h=p,m=p*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let E=(t.data[d++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[h++]-c[2])*l[2],M=g===-1?255:(t.data[g++]-c[3])*l[3];s.fillStyle="rgba("+E+","+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")},Rk=(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,h=0,g=1,x=2,k=3,E=0,A=d,S=d*2,M=-1;i==="RGBA"?(E=0,A=d,S=d*2,M=d*3):i==="RGB"?(E=0,A=d,S=d*2):i==="RBG"&&(E=0,S=d,A=d*2),s=r.createImageData(n,o);for(let L=0;L<o*n;h+=m,g+=m,x+=m,k+=m,L++)s.data[h]=(t.data[E++]-p[0])*c[0],s.data[g]=(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}}),Hi,$k,Bk,Uk,Dk,Fk,JC=ye(()=>{"use strict";rf(),Hi=(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,h=1,g=2,x=3,k=0,E=c,A=c*2,S=-1;i==="RGB"&&(d=3,m=0,h=1,g=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,k=c*2);for(let M=0;M<c;M++,m+=d,g+=d,h+=d,x+=d)p[k++]=(t[m]+a[0])/o[0],p[E++]=(t[h]+a[1])/o[1],p[A++]=(t[g]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new Lt("float32",p,[1,4,r,s]):new Lt("float32",p,[1,3,r,s])},$k=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,h=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,h=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=h}else i.tensorFormat="RGBA",i.height=m,i.width=h;d.drawImage(t,0,0),a=d.getImageData(0,0,h,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 h=c(m);if(h!=null)h.putImageData(t,0,0),a=h.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,h=t.width;return d.drawImage(t,0,0,h,m),a=d.getImageData(0,0,h,m).data,i.height=m,i.width=h,Hi(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{let m=l(),h=c(m);if(!t||!h)return d();let g=new Image;g.crossOrigin="Anonymous",g.src=t,g.onload=()=>{m.width=g.width,m.height=g.height,h.drawImage(g,0,0,m.width,m.height);let x=h.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,p(Hi(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Hi(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Bk=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Lt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},Uk=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Lt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},Dk=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Lt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},Fk=(t,e,r)=>new Lt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ls,Xn,Ip,jk,ZC=ye(()=>{"use strict";ls=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Xn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ip=!1,jk=()=>{if(!Ip){Ip=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(ls.set("int64",BigInt64Array),Xn.set(BigInt64Array,"int64")),e&&(ls.set("uint64",BigUint64Array),Xn.set(BigUint64Array,"uint64")),s?(ls.set("float16",r),Xn.set(r,"float16")):ls.set("float16",Uint16Array)}}}),Gk,Wk,eP=ye(()=>{"use strict";rf(),Gk=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},Wk=(t,e)=>{switch(t.location){case"cpu":return new Lt(t.type,t.data,e);case"cpu-pinned":return new Lt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Lt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Lt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Lt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Lt,rf=ye(()=>{"use strict";QC(),JC(),ZC(),eP(),Lt=class{constructor(t,e,r){jk();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=ls.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=ls.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=Xn.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=Gk(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 $k(t,e)}static fromTexture(t,e){return Bk(t,e)}static fromGpuBuffer(t,e){return Uk(t,e)}static fromMLTensor(t,e){return Dk(t,e)}static fromPinnedBuffer(t,e,r){return Fk(t,e,r)}toDataURL(t){return zk(this,t)}toImageData(t){return Rk(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 Wk(this,t)}}}),Jt,qk=ye(()=>{"use strict";rf(),Jt=Lt}),tl,Cp,ps,fs,Sr,Or,Vk=ye(()=>{"use strict";Nk(),tl=(t,e)=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeStamp(`${t}::ORT::${e}`)},Cp=(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}`),tl("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},ps=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Cp("BEGIN",t)},fs=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Cp("END",t)},Sr=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.time(`ORT::${t}`)},Or=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeEnd(`ORT::${t}`)}}),Hk,tP=ye(()=>{"use strict";Pk(),qk(),Vk(),Hk=class Xk{constructor(e){this.handler=e}async run(e,r,s){ps(),Sr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Jt||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 Jt)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 Jt)&&(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 Jt?l[c]=p:l[c]=new Jt(p.type,p.data,p.dims)}return Or("InferenceSession.run"),fs(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ps(),Sr("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 Ck(a),c=await i.createInferenceSessionHandler(o,l);return Or("InferenceSession.create"),fs(),new Xk(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}}}),sf,rP=ye(()=>{"use strict";tP(),sf=Hk}),sP=ye(()=>{"use strict"}),nP=ye(()=>{"use strict"}),oP=ye(()=>{"use strict"}),aP=ye(()=>{"use strict"}),Yk={};Kn(Yk,{InferenceSession:()=>sf,TRACE:()=>tl,TRACE_EVENT_BEGIN:()=>Sr,TRACE_EVENT_END:()=>Or,TRACE_FUNC_BEGIN:()=>ps,TRACE_FUNC_END:()=>fs,Tensor:()=>Jt,env:()=>qe,registerBackend:()=>us});var ds=ye(()=>{"use strict";XC(),KC(),rP(),qk(),sP(),nP(),Vk(),oP(),aP()}),nf=ye(()=>{"use strict"}),Kk={};Kn(Kk,{default:()=>Qk});var Pp,Lp,Qk,iP=ye(()=>{"use strict";fE(),ms(),of(),Pp="ort-wasm-proxy-worker",Lp=globalThis.self?.name===Pp,Lp&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":af(r.wasm).then(()=>{ff(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=nl(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;mf(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":hf(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":wf(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),Qk=Lp?null:t=>new Worker(t??Ct,{type:"module",name:Pp})}),Jk={};Kn(Jk,{default:()=>Zk});async function ok(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.Zc||(e.Zc=new Map)).set(u,f)},e.unmountExternalData=()=>{delete e.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Me:!0}).buffer.constructor;let o=()=>{let u=f=>(..._)=>{let w=sr;return _=f(..._),sr!=w?new Promise((b,T)=>{Zu={resolve:b,reject:T}}):_};(()=>{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(C(u))return new Promise((_,w)=>{var b=new XMLHttpRequest;b.open("GET",u,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?_(b.response):w(b.status)},b.onerror=w,b.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,h,g,x,k,E=console.log.bind(console),A=console.error.bind(console),S=E,M=A,L=!1,C=u=>u.startsWith("file://");function v(){vr.buffer!=V.buffer&&ue()}if(n){let u=function(f){try{var _=f.data,w=_.Uc;if(w==="load"){let b=[];self.onmessage=T=>b.push(T),k=()=>{postMessage({Uc:"loaded"});for(let T of b)u(T);self.onmessage=u};for(let T of _.ne)e[T]&&!e[T].proxy||(e[T]=(...I)=>{postMessage({Uc:"callHandler",me:T,args:I})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));vr=_.we,ue(),m=_.xe,Qe(),zi()}else if(w==="run"){(function(b){var T=(v(),P)[b+52>>>2>>>0];b=(v(),P)[b+56>>>2>>>0],d1(T,T-b),oe(T)})(_.Sc),pp(_.Sc,0,0,1,0,0),J0(),Ku(_.Sc),X||(Yb(),X=!0);try{d2(_.te,_.ad)}catch(b){if(b!="unwind")throw b}}else _.target!=="setimmediate"&&(w==="checkMailbox"?X&&Ai():w&&(M(`worker: received unknown command ${w}`),M(_)))}catch(b){throw l1(),b}};var G=u,X=!1;self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=u}var V,Q,Y,K,U,P,se,ie,O,N,$,te=!1;function ue(){var u=vr.buffer;e.HEAP8=V=new Int8Array(u),Y=new Int16Array(u),e.HEAPU8=Q=new Uint8Array(u),K=new Uint16Array(u),e.HEAP32=U=new Int32Array(u),e.HEAPU32=P=new Uint32Array(u),se=new Float32Array(u),ie=new Float64Array(u),O=new BigInt64Array(u),N=new BigUint64Array(u)}function Ue(){te=!0,n?k():_r.dc()}function Ce(u){throw M(u="Aborted("+u+")"),L=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function kt(){return{a:{sa:OM,g:m2,K:h2,f:_2,n:w2,h:g2,wa:x2,b:y2,ea:b2,Ja:nb,o:v2,fa:lb,Za:cb,$b:ub,bc:pb,_a:fb,Xa:db,Qa:mb,Wa:hb,qa:_b,ac:wb,Zb:gb,Ya:xb,_b:yb,db:k2,Fa:A2,Ub:T2,Sb:S2,Ea:I2,P:C2,J:P2,Tb:L2,ma:D2,Vb:F2,Ta:j2,Xb:W2,Ka:q2,Pb:V2,Ha:H2,Sa:Ku,ab:X2,W:J2,r:sT,c:Xu,tb:nT,y:oT,N:aT,D:iT,m:lT,s:Sb,ub:cT,I:uT,V:pT,j:fT,u:dT,q:mT,k:hT,Na:_T,Oa:wT,Pa:gT,La:Pb,Ma:Lb,Rb:Nb,fb:yT,cb:kT,$:ET,sb:AT,na:TT,bb:bT,Y:MT,$a:ST,Yb:OT,G:xT,ib:IT,_:CT,ra:Ii,Wb:LT,hb:PT,gb:NT,pb:FT,F:jT,va:GT,ua:WT,rb:qT,Z:VT,w:HT,ob:XT,nb:YT,mb:KT,qb:QT,lb:JT,kb:ZT,jb:eM,Ua:jb,Va:Gb,Ia:At,ga:Wb,pa:qb,Ra:Vb,oa:Hb,Eb:fS,za:oS,Fb:pS,Aa:nS,H:YM,e:LM,t:CM,x:IM,B:GM,Ib:tS,L:VM,v:zM,Ba:rS,ca:aS,ja:eS,Gb:uS,Hb:cS,Da:KM,Ca:ZM,Kb:QM,O:HM,da:sS,d:NM,A:RM,l:PM,Db:dS,p:BM,z:jM,C:$M,E:UM,M:WM,Lb:XM,U:iS,ka:qM,ba:lS,Mb:FM,Nb:DM,R:JM,i:rM,a:vr,eb:br,Jb:sM,la:nM,Q:oM,ta:aM,Ob:iM,S:lM,Ab:cM,Bb:uM,xa:pM,ha:fM,T:dM,Ga:mM,ya:hM,aa:_M,yb:wM,cc:gM,X:xM,Cb:yM,vb:bM,wb:kM,xb:EM,ia:AM,zb:TM,Qb:MM}}}async function Qe(){function u(w,b){var T=_r=w.exports;w={};for(let[I,z]of Object.entries(T))typeof z=="function"?(T=Y2(z),w[I]=T):w[I]=z;return _r=w,_r=(function(){var I=_r,z=W=>de=>W(de)>>>0,D=W=>()=>W()>>>0;return(I=Object.assign({},I)).ec=z(I.ec),I.Hc=D(I.Hc),I.Jc=z(I.Jc),I.vd=(W=>(de,me)=>W(de,me)>>>0)(I.vd),I.Ad=z(I.Ad),I.Bd=D(I.Bd),I.Fd=z(I.Fd),I})(),K0.push(_r.md),Xb=(w=_r).ec,Yb=w.fc,e._OrtInit=w.gc,e._OrtGetLastError=w.hc,e._OrtCreateSessionOptions=w.ic,e._OrtAppendExecutionProvider=w.jc,e._OrtAddFreeDimensionOverride=w.kc,e._OrtAddSessionConfigEntry=w.lc,e._OrtReleaseSessionOptions=w.mc,e._OrtCreateSession=w.nc,e._OrtReleaseSession=w.oc,e._OrtGetInputOutputCount=w.pc,e._OrtGetInputOutputMetadata=w.qc,e._OrtFree=w.rc,e._OrtCreateTensor=w.sc,e._OrtGetTensorData=w.tc,e._OrtReleaseTensor=w.uc,e._OrtCreateRunOptions=w.vc,e._OrtAddRunConfigEntry=w.wc,e._OrtReleaseRunOptions=w.xc,e._OrtCreateBinding=w.yc,e._OrtBindInput=w.zc,e._OrtBindOutput=w.Ac,e._OrtClearBoundOutputs=w.Bc,e._OrtReleaseBinding=w.Cc,e._OrtRunWithBinding=w.Dc,e._OrtRun=w.Ec,e._OrtEndProfiling=w.Fc,op=e._OrtGetWebGpuDevice=w.Gc,Li=w.Hc,Rt=e._free=w.Ic,zs=e._malloc=w.Jc,Kb=e._wgpuBufferRelease=w.Kc,Qb=e._wgpuCreateInstance=w.Lc,Jb=w.Mc,Zb=w.Nc,e1=w.Oc,t1=w.Pc,r1=w.Qc,s1=w.Tc,n1=w.bd,o1=w.cd,a1=w.dd,ap=w.fd,ip=w.gd,lp=w.hd,cp=w.id,Pn=w.jd,up=w.kd,i1=w.ld,pp=w.od,l1=w.pd,c1=w.qd,u1=w.rd,fp=w.sd,p1=w.td,f1=w.ud,dp=w.vd,he=w.wd,Ln=w.xd,d1=w.yd,oe=w.zd,Ni=w.Ad,ae=w.Bd,m1=w.Cd,mp=w.Dd,h1=w.Ed,_1=w.Fd,w1=w.Gd,hp=w.Hd,g1=w.Id,x1=w.Jd,y1=w.Kd,b1=w.Ld,v1=w.Md,k1=w.Nd,E1=w.Od,A1=w.Pd,T1=w.Qd,M1=w.Rd,S1=w.Sd,O1=w.Td,I1=w.Ud,C1=w.Vd,P1=w.Wd,L1=w.Yd,N1=w.Zd,z1=w._d,R1=w.$d,$1=w.be,B1=w.ce,U1=w.de,D1=w.ee,F1=w.fe,j1=w.ge,G1=w.qe,W1=w.ve,q1=w.ye,V1=w.ze,H1=w.Ae,X1=w.Be,Y1=w.Ce,K1=w.De,Q1=w.Ee,J1=w.Fe,Z1=w.Ge,ev=w.ef,tv=w.ff,rv=w.gf,sv=w.hf,m=b,_r}var f,_=kt();return e.instantiateWasm?new Promise(w=>{e.instantiateWasm(_,(b,T)=>{w(u(b,T))})}):n?u(new WebAssembly.Instance(m,kt()),m):($??=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(w){var b=$;if(!d&&!C(b))try{var T=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,w)}catch(I){M(`wasm streaming compile failed: ${I}`),M("falling back to ArrayBuffer instantiation")}return(async function(I,z){try{var D=await(async function(W){if(!d)try{var de=await a(W);return new Uint8Array(de)}catch{}if(W==$&&d)W=new Uint8Array(d);else{if(!i)throw"both async and sync fetching of the wasm failed";W=i(W)}return W})(I);return await WebAssembly.instantiate(D,z)}catch(W){M(`failed to asynchronously prepare wasm: ${W}`),Ce(W)}})(b,w)})(_),u(f.instance,f.module))}class Ze{name="ExitStatus";constructor(f){this.message=`Program terminated with exit(${f})`,this.status=f}}var rt=u=>{u.terminate(),u.onmessage=()=>{}},Te=[],xe=0,Ge=null,Et=u=>{et.length==0&&(eb(),Z0(et[0]));var f=et.pop();if(!f)return 6;In.push(f),Kr[u.Sc]=f,f.Sc=u.Sc;var _={Uc:"run",te:u.se,ad:u.ad,Sc:u.Sc};return f.postMessage(_,u.he),0},we=0,Ne=(u,f,..._)=>{var w,b=16*_.length,T=ae(),I=Ni(b),z=I>>>3;for(w of _)typeof w=="bigint"?((v(),O)[z++>>>0]=1n,(v(),O)[z++>>>0]=w):((v(),O)[z++>>>0]=0n,(v(),ie)[z++>>>0]=w);return u=c1(u,0,b,I,f),oe(T),u};function br(u){if(n)return Ne(0,1,u);if(h=u,!(0<we)){for(var f of In)rt(f);for(f of et)rt(f);et=[],In=[],Kr={},L=!0}l(0,new Ze(u))}function Yr(u){if(n)return Ne(1,0,u);At(u)}var At=u=>{if(h=u,n)throw Yr(u),"unwind";br(u)},et=[],In=[],K0=[],Kr={},Q0=u=>{var f=u.Sc;delete Kr[f],et.push(u),In.splice(In.indexOf(u),1),u.Sc=0,u1(f)};function J0(){K0.forEach(u=>u())}var Z0=u=>new Promise(f=>{u.onmessage=b=>{var T=b.data;if(b=T.Uc,T.$c&&T.$c!=Li()){var I=Kr[T.$c];I?I.postMessage(T,T.he):M(`Internal error! Worker sent a message "${b}" to target pthread ${T.$c}, but that thread no longer exists!`)}else b==="checkMailbox"?Ai():b==="spawnThread"?Et(T):b==="cleanupThread"?Ei(()=>{Q0(Kr[T.ue])}):b==="loaded"?(u.loaded=!0,f(u)):T.target==="setimmediate"?u.postMessage(T):b==="uncaughtException"?u.onerror(T.error):b==="callHandler"?e[T.me](...T.args):b&&M(`worker sent an unknown command ${b}`)},u.onerror=b=>{throw M(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var _,w=[];for(_ of[])e.propertyIsEnumerable(_)&&w.push(_);u.postMessage({Uc:"load",ne:w,we:vr,xe:m})});function eb(){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"});et.push(u)}var vr,d2=(u,f)=>{we=0,u=hp(u,f),0<we?h=u:fp(u)},vi=[],ki=0,xt=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function m2(u){var f=new Wu(u>>>=0);return(v(),V)[f.Vc+12>>>0]==0&&(tb(f,!0),ki--),rb(f,!1),vi.push(f),_1(u)}var Is=0,h2=()=>{he(0,0);var u=vi.pop();m1(u.nd),Is=0};function tb(u,f){f=f?1:0,(v(),V)[u.Vc+12>>>0]=f}function rb(u,f){f=f?1:0,(v(),V)[u.Vc+13>>>0]=f}class Wu{constructor(f){this.nd=f,this.Vc=f-24}}var qu=u=>{var f=Is;if(!f)return Ln(0),0;var _=new Wu(f);(v(),P)[_.Vc+16>>>2>>>0]=f;var w=(v(),P)[_.Vc+4>>>2>>>0];if(!w)return Ln(0),f;for(var b of u){if(b===0||b===w)break;if(h1(b,w,_.Vc+16))return Ln(b),f}return Ln(w),f};function _2(){return qu([])}function w2(u){return qu([u>>>0])}function g2(u,f,_,w){return qu([u>>>0,f>>>0,_>>>0,w>>>0])}var x2=()=>{var u=vi.pop();u||Ce("no exception to throw");var f=u.nd;throw(v(),V)[u.Vc+13>>>0]==0&&(vi.push(u),rb(u,!0),tb(u,!1),ki++),mp(f),Is=f};function y2(u,f,_){var w=new Wu(u>>>=0);throw f>>>=0,_>>>=0,(v(),P)[w.Vc+16>>>2>>>0]=0,(v(),P)[w.Vc+4>>>2>>>0]=f,(v(),P)[w.Vc+8>>>2>>>0]=_,mp(u),ki++,Is=u}var b2=()=>ki;function sb(u,f,_,w){return n?Ne(2,1,u,f,_,w):nb(u,f,_,w)}function nb(u,f,_,w){if(u>>>=0,f>>>=0,_>>>=0,w>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?sb(u,f,_,w):(u={se:_,Sc:u,ad:w,he:b},n?(u.Uc="spawnThread",postMessage(u,b),0):Et(u))}function v2(u){throw Is||=u>>>0,Is}var ob=globalThis.TextDecoder&&new TextDecoder,ab=(u,f,_,w)=>{if(_=f+_,w)return _;for(;u[f]&&!(f>=_);)++f;return f},ib=(u,f=0,_,w)=>{if(16<(_=ab(u,f>>>=0,_,w))-f&&u.buffer&&ob)return ob.decode(u.buffer instanceof ArrayBuffer?u.subarray(f,_):u.slice(f,_));for(w="";f<_;){var b=u[f++];if(128&b){var T=63&u[f++];if((224&b)==192)w+=String.fromCharCode((31&b)<<6|T);else{var I=63&u[f++];65536>(b=(240&b)==224?(15&b)<<12|T<<6|I:(7&b)<<18|T<<12|I<<6|63&u[f++])?w+=String.fromCharCode(b):(b-=65536,w+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else w+=String.fromCharCode(b)}return w},Cs=(u,f,_)=>(u>>>=0)?ib((v(),Q),u,f,_):"";function lb(u,f,_){return n?Ne(3,1,u,f,_):0}function cb(u,f){if(n)return Ne(4,1,u,f)}function ub(u,f){if(n)return Ne(5,1,u,f)}function pb(u,f,_){if(n)return Ne(6,1,u,f,_)}function fb(u,f,_){return n?Ne(7,1,u,f,_):0}function db(u,f){if(n)return Ne(8,1,u,f)}function mb(u,f,_){if(n)return Ne(9,1,u,f,_)}function hb(u,f,_,w){if(n)return Ne(10,1,u,f,_,w)}function _b(u,f,_,w){if(n)return Ne(11,1,u,f,_,w)}function wb(u,f,_,w){if(n)return Ne(12,1,u,f,_,w)}function gb(u){if(n)return Ne(13,1,u)}function xb(u,f){if(n)return Ne(14,1,u,f)}function yb(u,f,_){if(n)return Ne(15,1,u,f,_)}var k2=()=>Ce(""),rr=u=>{u>>>=0;for(var f="";;){var _=(v(),Q)[u++>>>0];if(!_)return f;f+=String.fromCharCode(_)}},Vu={},Hu={},E2={},Ps=class extends Error{constructor(u){super(u),this.name="BindingError"}};function fr(u,f,_={}){return(function(w,b,T={}){var I=b.name;if(!w)throw new Ps(`type "${I}" must have a positive integer typeid pointer`);if(Hu.hasOwnProperty(w)){if(T.oe)return;throw new Ps(`Cannot register type '${I}' twice`)}Hu[w]=b,delete E2[w],Vu.hasOwnProperty(w)&&(b=Vu[w],delete Vu[w],b.forEach(z=>z()))})(u,f,_)}var bb=(u,f,_)=>{switch(f){case 1:return _?w=>(v(),V)[w>>>0]:w=>(v(),Q)[w>>>0];case 2:return _?w=>(v(),Y)[w>>>1>>>0]:w=>(v(),K)[w>>>1>>>0];case 4:return _?w=>(v(),U)[w>>>2>>>0]:w=>(v(),P)[w>>>2>>>0];case 8:return _?w=>(v(),O)[w>>>3>>>0]:w=>(v(),N)[w>>>3>>>0];default:throw new TypeError(`invalid integer width (${f}): ${u}`)}};function A2(u,f,_,w,b){u>>>=0,_>>>=0,f=rr(f>>>0);let T=I=>I;if(w=w===0n){let I=8*_;T=z=>BigInt.asUintN(I,z),b=T(b)}fr(u,{name:f,Rc:T,Xc:(I,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Wc:bb(f,_,!w),Yc:null})}function T2(u,f,_,w){fr(u>>>=0,{name:f=rr(f>>>0),Rc:function(b){return!!b},Xc:function(b,T){return T?_:w},Wc:function(b){return this.Rc((v(),Q)[b>>>0])},Yc:null})}var vb=[],Qr=[0,1,,1,null,1,!0,1,!1,1];function Xu(u){9<(u>>>=0)&&--Qr[u+1]==0&&(Qr[u]=void 0,vb.push(u))}var zt=u=>{if(!u)throw new Ps(`Cannot use deleted val. handle = ${u}`);return Qr[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=vb.pop()||Qr.length;return Qr[f]=u,Qr[f+1]=1,f}};function Yu(u){return this.Rc((v(),P)[u>>>2>>>0])}var M2={name:"emscripten::val",Rc:u=>{var f=zt(u);return Xu(u),f},Xc:(u,f)=>Vt(f),Wc:Yu,Yc:null};function S2(u){return fr(u>>>0,M2)}var O2=(u,f)=>{switch(f){case 4:return function(_){return this.Rc((v(),se)[_>>>2>>>0])};case 8:return function(_){return this.Rc((v(),ie)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${u}`)}};function I2(u,f,_){_>>>=0,fr(u>>>=0,{name:f=rr(f>>>0),Rc:w=>w,Xc:(w,b)=>b,Wc:O2(f,_),Yc:null})}function C2(u,f,_,w,b){u>>>=0,_>>>=0,f=rr(f>>>0);let T=z=>z;if(w===0){var I=32-8*_;T=z=>z<<I>>>I,b=T(b)}fr(u,{name:f,Rc:T,Xc:(z,D)=>D,Wc:bb(f,_,w!==0),Yc:null})}function P2(u,f,_){function w(T){var I=(v(),P)[T>>>2>>>0];return T=(v(),P)[T+4>>>2>>>0],new b((v(),V).buffer,T,I)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];fr(u>>>=0,{name:_=rr(_>>>0),Rc:w,Wc:w},{oe:!0})}var dr=(u,f,_)=>{var w=(v(),Q);if(f>>>=0,0<_){var b=f;_=f+_-1;for(var T=0;T<u.length;++T){var I=u.codePointAt(T);if(127>=I){if(f>=_)break;w[f++>>>0]=I}else if(2047>=I){if(f+1>=_)break;w[f++>>>0]=192|I>>6,w[f++>>>0]=128|63&I}else if(65535>=I){if(f+2>=_)break;w[f++>>>0]=224|I>>12,w[f++>>>0]=128|I>>6&63,w[f++>>>0]=128|63&I}else{if(f+3>=_)break;w[f++>>>0]=240|I>>18,w[f++>>>0]=128|I>>12&63,w[f++>>>0]=128|I>>6&63,w[f++>>>0]=128|63&I,T++}}w[f>>>0]=0,u=f-b}else u=0;return u},mr=u=>{for(var f=0,_=0;_<u.length;++_){var w=u.charCodeAt(_);127>=w?f++:2047>=w?f+=2:55296<=w&&57343>=w?(f+=4,++_):f+=3}return f};function L2(u,f){fr(u>>>=0,{name:f=rr(f>>>0),Rc(_){var w=(v(),P)[_>>>2>>>0];return w=Cs(_+4,w,!0),Rt(_),w},Xc(_,w){w instanceof ArrayBuffer&&(w=new Uint8Array(w));var b=typeof w=="string";if(!(b||ArrayBuffer.isView(w)&&w.BYTES_PER_ELEMENT==1))throw new Ps("Cannot pass non-string to std::string");var T=b?mr(w):w.length,I=zs(4+T+1),z=I+4;return(v(),P)[I>>>2>>>0]=T,b?dr(w,z,T+1):(v(),Q).set(w,z>>>0),_!==null&&_.push(Rt,I),I},Wc:Yu,Yc(_){Rt(_)}})}var kb=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,N2=(u,f,_)=>{if(u>>>=1,16<(f=ab((v(),K),u,f/2,_))-u&&kb)return kb.decode((v(),K).slice(u,f));for(_="";u<f;++u){var w=(v(),K)[u>>>0];_+=String.fromCharCode(w)}return _},z2=(u,f,_)=>{if(_??=2147483647,2>_)return 0;var w=f;_=(_-=2)<2*u.length?_/2:u.length;for(var b=0;b<_;++b){var T=u.charCodeAt(b);(v(),Y)[f>>>1>>>0]=T,f+=2}return(v(),Y)[f>>>1>>>0]=0,f-w},R2=u=>2*u.length,$2=(u,f,_)=>{var w="";u>>>=2;for(var b=0;!(b>=f/4);b++){var T=(v(),P)[u+b>>>0];if(!T&&!_)break;w+=String.fromCodePoint(T)}return w},B2=(u,f,_)=>{if(f>>>=0,_??=2147483647,4>_)return 0;var w=f;_=w+_-4;for(var b=0;b<u.length;++b){var T=u.codePointAt(b);if(65535<T&&b++,(v(),U)[f>>>2>>>0]=T,(f+=4)+4>_)break}return(v(),U)[f>>>2>>>0]=0,f-w},U2=u=>{for(var f=0,_=0;_<u.length;++_)65535<u.codePointAt(_)&&_++,f+=4;return f};function D2(u,f,_){if(u>>>=0,f>>>=0,_=rr(_>>>=0),f===2)var w=N2,b=z2,T=R2;else w=$2,b=B2,T=U2;fr(u,{name:_,Rc:I=>{var z=(v(),P)[I>>>2>>>0];return z=w(I+4,z*f,!0),Rt(I),z},Xc:(I,z)=>{if(typeof z!="string")throw new Ps(`Cannot pass non-string to C++ string type ${_}`);var D=T(z),W=zs(4+D+f);return(v(),P)[W>>>2>>>0]=D/f,b(z,W+4,D+f),I!==null&&I.push(Rt,W),W},Wc:Yu,Yc(I){Rt(I)}})}function F2(u,f){fr(u>>>=0,{pe:!0,name:f=rr(f>>>0),Rc:()=>{},Xc:()=>{}})}function j2(u){pp(u>>>0,!s,1,!r,131072,!1),J0()}var Ei=u=>{if(!L)try{if(u(),!(0<we))try{n?Li()&&fp(h):At(h)}catch(f){f instanceof Ze||f=="unwind"||l(0,f)}}catch(f){f instanceof Ze||f=="unwind"||l(0,f)}},G2=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ku(u){u>>>=0,G2||(Atomics.waitAsync((v(),U),u>>>2,u).value.then(Ai),u+=128,Atomics.store((v(),U),u>>>2,1))}var Ai=()=>Ei(()=>{var u=Li();u&&(Ku(u),f1())});function W2(u,f){(u>>>=0)==f>>>0?setTimeout(Ai):n?postMessage({$c:u,Uc:"checkMailbox"}):(u=Kr[u])&&u.postMessage({Uc:"checkMailbox"})}var Qu=[];function q2(u,f,_,w,b){for(f>>>=0,b>>>=0,Qu.length=0,_=b>>>3,w=b+w>>>3;_<w;){var T;T=(v(),O)[_++>>>0]?(v(),O)[_++>>>0]:(v(),ie)[_++>>>0],Qu.push(T)}return(f?_p[f]:SM[u])(...Qu)}var V2=()=>{we=0};function H2(u){u>>>=0,n?postMessage({Uc:"cleanupThread",ue:u}):Q0(Kr[u])}function X2(u){}var Ti=u=>{try{u()}catch(f){Ce(f)}};function Y2(u){var f=(..._)=>{Mi.push(u);try{return u(..._)}finally{L||(Mi.pop(),sr&&kr===1&&Mi.length===0&&(kr=0,we+=1,Ti(tv),typeof Fibers<"u"&&Fibers.Oe()))}};return Tb.set(u,f),f}var kr=0,sr=null,Eb=0,Mi=[],Ju=new Map,Ab=new Map,Tb=new Map,K2=0,Zu=null,Q2=[],Mb=u=>(function(f){if(!L){if(kr===0){var _=!1,w=!1;f((b=0)=>{if(!L&&(Eb=b,_=!0,w)){kr=2,Ti(()=>rv(sr)),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.resume(),b=!1;try{var T=(function(){var D=(v(),U)[sr+8>>>2>>>0];return D=Ab.get(D),D=Tb.get(D),--we,D()})()}catch(D){T=D,b=!0}var I=!1;if(!sr){var z=Zu;z&&(Zu=null,(b?z.reject:z.resolve)(T),I=!0)}if(b&&!I)throw T}}),w=!0,_||(kr=1,sr=(function(){var b=zs(65548),T=b+12;if((v(),P)[b>>>2>>>0]=T,(v(),P)[b+4>>>2>>>0]=T+65536,T=Mi[0],!Ju.has(T)){var I=K2++;Ju.set(T,I),Ab.set(I,T)}return T=Ju.get(T),(v(),U)[b+8>>>2>>>0]=T,b})(),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.pause(),Ti(()=>ev(sr)))}else kr===2?(kr=0,Ti(sv),Rt(sr),sr=null,Q2.forEach(Ei)):Ce(`invalid state: ${kr}`);return Eb}})(f=>{u().then(f)});function J2(u){return u>>>=0,Mb(async()=>{var f=await zt(u);return Vt(f)})}var ep=[],Z2=u=>{var f=ep.length;return ep.push(u),f},eT=(u,f)=>{for(var _=Array(u),w=0;w<u;++w){var b=w,T=(v(),P)[f+4*w>>>2>>>0],I=Hu[T];if(I===void 0)throw u=`parameter ${w}`,T=Xb(T),f=rr(T),Rt(T),new Ps(`${u} has unknown type ${f}`);_[b]=I}return _},tT=(u,f,_)=>{var w=[];return u=u(w,_),w.length&&((v(),P)[f>>>2>>>0]=Vt(w)),u},rT={},Si=u=>{var f=rT[u];return f===void 0?rr(u):f};function sT(u,f,_){var[w,...b]=eT(u,f>>>0);f=w.Xc.bind(w);var T=b.map(D=>D.Wc.bind(D));u--;var I={toValue:zt};switch(u=T.map((D,W)=>{var de=`argFromPtr${W}`;return I[de]=D,`${de}(args${W?"+"+8*W:""})`}),_){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:I.getStringOrSymbol=Si,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${u})`,w.pe||(I.toReturnWire=f,I.emval_returnValue=tT,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 de(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ye(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof de||t instanceof Ye)switch(s.value){case"abs":return t instanceof de?new de(Math.abs(t.value)):new Ye(Math.abs(t.value));case"int":return new de(Math.floor(t.value));case"float":return new Ye(t.value);default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof _t)switch(s.value){case"items":return new ve(Array.from(t.value.entries()).map(([n,o])=>new ve([new Z(n),o])));case"length":return new de(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 le)switch(s.value){case"bool":return new le(t.value);case"int":return new de(t.value?1:0);case"float":return new Ye(t.value?1:0);case"string":return new Z(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 de||a instanceof We))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new le(!1);if(!(i instanceof le))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new le(!1);if(!(l instanceof le))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new We,p=null;if(c instanceof ve||c instanceof Dv){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.value;if(!(f instanceof Z)||!(m instanceof Z))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 Z(ss(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:p}))}else if(n==="join"){let o;if(t instanceof Z)o=Array.from(t.value);else if(t instanceof ve)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 Z("");if(!(l instanceof Z))throw new Error("separator must be a string");return new Z(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 de(0):new Ye(0));if(t instanceof Z){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new de(l):new Ye(l)}else{if(t instanceof de||t instanceof Ye)return t;if(t instanceof le)return n==="int"?new de(t.value?1:0):new Ye(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 Z(""),l=o[1]??a.get("boolean")??new le(!1);if(!(l instanceof le))throw new Error("`default` filter flag must be a boolean");return t instanceof Fe||l.value&&!t.__bool__().value?i:t}if(t instanceof ve){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new le(!1);if(!(i instanceof le))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new le(!1);if(!(l instanceof le))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new We;if(!(c instanceof Z||c instanceof de||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 de?String(c.value):c.value;return Fv(f,m)};return new ve(t.value.slice().sort((f,m)=>{let h=p(f),g=p(m),x=kp(h,g,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof _t)))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),h=m?c(m,l):!1;return o?h:!h});return new ve(p)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof Z))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!(c instanceof _t))throw new Error("items in map must be an object");let p=Fv(c,a.value);return p instanceof Fe?i??new Fe:p});return new ve(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 Z){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new de(4);if(!(i instanceof de))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new le(!1),c=o.at(2)??a.get("blank")??new le(!1),p=t.value.split(`
|
|
8
|
+
`),f=" ".repeat(i.value),m=p.map((h,g)=>!l.value&&g===0||!c.value&&h.length===0?h:f+h);return new Z(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 Un(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof _t){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 Un(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 le(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new Fe}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new le(!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 Z(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 Un(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 ve||t instanceof Z))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 de||s instanceof Fe))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof de||n instanceof Fe))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof de||o instanceof Fe))throw new Error("Slice step must be numeric or undefined");return t instanceof ve?new ve(Rv(t.value,s.value,n.value,o.value)):new Z(Rv(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 Z(t.property.value);let n;if(r instanceof _t){if(!(s instanceof Z))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 ve||r instanceof Z)if(s instanceof de)n=r.value.at(s.value),r instanceof Z&&(n=new Z(r.value.at(s.value)));else if(s instanceof Z)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 Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof ar?n:new Fe}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 ve))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 _t))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 rs(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 ve||n instanceof _t))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof _t&&(n=n.keys());let o=[],a=[];for(let c=0;c<n.value.length;++c){let p=new rs(r),f=n.value[c],m;if(t.loopvar.type==="Identifier")m=h=>h.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let h=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let g=f;if(h.value.length!==g.value.length)throw new Error(`Too ${h.value.length>g.value.length?"few":"many"} items to unpack`);m=x=>{for(let k=0;k<h.value.length;++k){if(h.value[k].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${h.value[k].type}`);x.setVariable(h.value[k].value,g.value[k])}}}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 de(c+1)],["index0",new de(c)],["revindex",new de(o.length-c)],["revindex0",new de(o.length-c-1)],["first",new le(c===0)],["last",new le(c===o.length-1)],["length",new de(o.length)],["previtem",c>0?o[c-1]:new Fe],["nextitem",c<o.length-1?o[c+1]:new Fe]]);r.setVariable("loop",new _t(p)),a[c](r);try{let f=this.evaluateBlock(t.body,r);i+=f.value}catch(f){if(f instanceof Bv)continue;if(f instanceof $v)break;throw f}l=!1}if(l){let c=this.evaluateBlock(t.defaultBlock,r);i+=c.value}return new Z(i)}evaluateMacro(t,e){return e.setVariable(t.name.value,new je((r,s)=>{let n=new rs(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 rs(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 Fe)}return this.evaluateBlock(t.body,c)}),[s,n]=this.evaluateArguments(t.call.args,e);s.push(new Un(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 rs(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 Fe;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 $v;case"Continue":throw new Bv;case"IntegerLiteral":return new de(t.value);case"FloatLiteral":return new Ye(t.value);case"StringLiteral":return new Z(t.value);case"ArrayLiteral":return new ve(t.value.map(r=>this.evaluate(r,e)));case"TupleLiteral":return new Dv(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 Z))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new _t(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 ji(t){switch(typeof t){case"number":return Number.isInteger(t)?new de(t):new Ye(t);case"string":return new Z(t);case"boolean":return new le(t);case"undefined":return new Fe;case"object":return t===null?new We:Array.isArray(t)?new ve(t.map(ji)):new _t(new Map(Object.entries(t).map(([e,r])=>[e,ji(r)])));case"function":return new je((e,r)=>{let s=t(...e.map(n=>n.value))??null;return ji(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var nt=`
|
|
10
|
+
`,kC="{%- ",EC=" -%}";function AC(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 TC(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Kt(t.body,0,r).replace(/\n$/,"")}function pt(...t){return kC+t.join(" ")+EC}function Kt(t,e,r){return t.map(s=>MC(s,e,r)).join(nt)}function MC(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Kt(t.body,e,r);case"If":return SC(t,e,r);case"For":return OC(t,e,r);case"Set":return IC(t,e,r);case"Macro":return CC(t,e,r);case"Break":return s+pt("break");case"Continue":return s+pt("continue");case"CallStatement":return PC(t,e,r);case"FilterStatement":return LC(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function SC(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+pt("if",ke(n[0].test))+nt+Kt(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=nt+s+pt("elif",ke(n[i].test))+nt+Kt(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=nt+s+pt("else")+nt+Kt(o.alternate,e+1,r)),a+=nt+s+pt("endif"),a}function OC(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+pt("for",ke(t.loopvar),"in",n)+nt+Kt(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=nt+s+pt("else")+nt+Kt(t.defaultBlock,e+1,r)),o+=nt+s+pt("endfor"),o}function IC(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+pt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+nt+Kt(t.body,e+1,r)+nt+s+pt("endset")}function CC(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+pt("macro",`${t.name.value}(${n})`)+nt+Kt(t.body,e+1,r)+nt+s+pt("endmacro")}function PC(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+pt(`call${n}`,o)+nt;return a+=Kt(t.body,e+1,r)+nt,a+=s+pt("endcall"),a}function LC(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+pt("filter",n)+nt;return o+=Kt(t.body,e+1,r)+nt,o+=s+pt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=AC(r),n=ke(r.left,s),o=ke(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"?" ":"")+ke(r.argument,1/0)}case"CallExpression":{let r=t,s=r.args.map(ke).join(", ");return`${ke(r.callee)}(${s})`}case"MemberExpression":{let r=t,s=ke(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ke(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{let r=t,s=ke(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ke(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{let r=t;return`${ke(r.lhs)} if ${ke(r.test)}`}case"TestExpression":{let r=t;return`${ke(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=t.value.map(ke),s=t.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([s,n])=>`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var jv=class{parsed;constructor(t){let e=GI(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=fC(e)}render(t){let e=new rs;if(bC(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new vC(e).run(this.parsed).value}format(t){return TC(this.parsed,t?.indent||" ")}};var Je=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function gr(t,e){t&&t(e)}function Gv(t){return Number.isInteger(t)||typeof t=="bigint"}function Ep(t){return t==null||t===-1}function Ap(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function dt(...t){return Array.prototype.concat.apply([],t)}function Wv(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function Bs(t,e){return Math.abs((t+e)%(2*e)-e)}function ot(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function qv(t,e){let r=0;for(let s of t)s===e&&++r;return r}var NC={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"},ns=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=Tt.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=Tt.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=Tt.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",NC[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 Tt.promises.readFile(this.filePath)).buffer}async blob(){let e=await Tt.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await Tt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Us=class{constructor(e){this.path=e}async match(e){let r=Ht.join(this.path,e),s=new ns(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Ht.join(this.path,e);try{let o=r.headers.get("Content-Length"),a=parseInt(o??"0"),i=0;await Tt.promises.mkdir(Ht.dirname(n),{recursive:!0});let l=Tt.createWriteStream(n),c=r.body.getReader();for(;;){let{done:p,value:f}=await c.read();if(p)break;await new Promise((h,g)=>{l.write(f,x=>{if(x){g(x);return}h()})}),i+=f.length;let m=a?i/a*100:0;s?.({progress:m,loaded:i,total:a})}l.close()}catch(o){try{await Tt.promises.unlink(n)}catch{}throw o}}};var Vv={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"},Gi=100,Hv=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Dn(...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 Ds(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 Xv(t){return!(!Hv.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function Yv(t,e,r){if(!r)return null;let s=Vv[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function Kv(t,e){let r=t.headers.get("Content-Length");r===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let s=parseInt(r??"0"),n=new Uint8Array(s),o=0,a=t.body.getReader();async function i(){let{done:l,value:c}=await a.read();if(l)return;let p=o+c.length;if(p>s){s=p;let m=new Uint8Array(s);m.set(n),n=m}n.set(c,o),o=p;let f=o/s*100;return e({progress:f,loaded:o,total:s}),i()}return await i(),n}async function Wi(t=null){let e=null;if(De.useCustomCache){if(!De.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!De.customCache.match||!De.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=De.customCache}if(!e&&De.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(De.cacheKey)}catch(r){console.warn("An error occurred while opening the browser cache:",r)}}if(!e&&De.useFSCache){if(!be.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Us(t??De.cacheDir)}return e}async function Qv(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}async function Fs(t){if(De.useFS&&!Ds(t,["http:","https:","blob:"]))return new ns(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t);if(typeof process<"u"&&process?.release?.name==="node"){let e=!!process.env?.TESTING_REMOTELY,r=De.version,s=new Headers;if(s.set("User-Agent",`transformers.js/${r}; is_ci/${e};`),Ds(t,["http:","https:"],["huggingface.co","hf.co"])){let o=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;o&&s.set("Authorization",`Bearer ${o}`)}return fetch(t,{headers:s})}else return fetch(t)}function zC(t,e,r={},s=null){let n=r.revision??"main",o=Dn(t,e),a=Xv(t),i=a?Dn(De.localModelPath,o):o,l=Dn(De.remoteHost,De.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof Us?n==="main"?o:Dn(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function RC(t,e,r){if(t)return await Qv(t,e,r)}async function $C(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o)typeof n!="string"&&await r.put(s,new Response(o,{headers:n.headers})).catch(i=>{console.warn(`Unable to add response to browser cache: ${i}.`)});else{let i=a.progress_callback?l=>gr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function BC(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:p}=zC(t,e,s,o),f,m=!1,h;h=await RC(o,i,c);let g=h!==void 0;if(!g){if(De.allowLocalModels)if(Ds(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(!De.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{h=await Fs(i),f=i}catch(A){console.warn(`Unable to load from local path "${i}": "${A}"`)}if(h===void 0||typeof h!="string"&&h.status===404){if(s.local_files_only||!De.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(h=await Fs(l),h.status!==200)return Yv(h.status,l,r);f=c}m=o&&typeof Response<"u"&&h instanceof Response&&h.status===200}gr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(be.IS_NODE_ENV&&n)){let E;typeof h!="string"&&(s.progress_callback?g&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(E=new Uint8Array(await h.arrayBuffer()),gr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:E.length,total:E.length})):E=await Kv(h,A=>{gr(s.progress_callback,{status:"progress",name:t,file:e,...A})}):E=new Uint8Array(await h.arrayBuffer())),x=E}if(m&&f&&typeof h!="string"&&await $C(t,e,o,f,h,x,s),gr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!be.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(h instanceof ns)return h.filePath;let k=await o?.match(f);if(k instanceof ns)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 Fn(t,e,r=!0,s={},n=!1){if(!De.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(!De.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}gr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await Wi(s?.cache_dir);return await BC(t,e,r,s,n,o)}async function Tp(t,e,r=!0,s={}){let n=await Fn(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function at(t,e,r=!0,s={}){let n=await Tp(t,e,r,s);return n===null?{}:JSON.parse(n)}function Zv(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 h=0;h<n;++h)for(let g=0;g<o;++g){let x=h*o+g,k=(g+.5)/l-.5,E=(h+.5)/c-.5,A=Math.floor(k),S=Math.floor(E),M=Math.min(A+1,s-1),L=Math.min(S+1,r-1);A=Math.max(A,0),S=Math.max(S,0);let C=k-A,v=E-S,G=(1-C)*(1-v),X=C*(1-v),V=(1-C)*v,Q=C*v,Y=S*s,K=L*s,U=Y+A,P=Y+M,se=K+A,ie=K+M;for(let O=0;O<e;++O){let N=O*f;p[O*m+x]=G*t[N+U]+X*t[N+P]+V*t[N+se]+Q*t[N+ie]}}return p}function ek(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 Pe(t){let e=Me(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 Sp(t){let e=Me(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 tk(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function UC(t,e){let r=tk(t,e),s=Jv(t),n=Jv(e);return r/(s*n)}function Jv(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function jn(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 Me(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 rk(t){return t>0&&(t&t-1)===0}var qi=class{constructor(e){if(this.size=e|0,this.size<=1||!rk(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 h=l+m-1;for(let g=l,x=0;g<h;g+=2,x+=a){let k=g,E=k+m,A=E+m,S=A+m,M=e[k],L=e[k+1],C=e[E],v=e[E+1],G=e[A],X=e[A+1],V=e[S],Q=e[S+1],Y=f[x],K=s*f[x+1],U=C*Y-v*K,P=C*K+v*Y,se=f[2*x],ie=s*f[2*x+1],O=G*se-X*ie,N=G*ie+X*se,$=f[3*x],te=s*f[3*x+1],ue=V*$-Q*te,Ue=V*te+Q*$,Ce=M+O,kt=L+N,Qe=M-O,Ze=L-N,rt=U+ue,Te=P+Ue,xe=s*(U-ue),Ge=s*(P-Ue);e[k]=Ce+rt,e[k+1]=kt+Te,e[E]=Qe+Ge,e[E+1]=Ze-xe,e[A]=Ce-rt,e[A+1]=kt-Te,e[S]=Qe-Ge,e[S+1]=Ze+xe}}}}_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],h=e[n+i],g=e[n+i+1],x=e[n+l],k=e[n+l+1],E=c+h,A=p+g,S=c-h,M=p-g,L=f+x,C=m+k,v=a*(f-x),G=a*(m-k);r[s]=E+L,r[s+1]=A+C,r[s+2]=S+G,r[s+3]=M-v,r[s+4]=E-L,r[s+5]=A-C,r[s+6]=S-G,r[s+7]=M+v}_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 h=p[c];this._singleRealTransform2(r,e,l,h>>>1,a>>>1)}else for(l=0,c=0;l<n;l+=i,++c){let h=p[c];this._singleRealTransform4(r,e,l,h>>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let h=i>>>1,g=h>>>1,x=g>>>1;for(l=0;l<n;l+=i)for(let k=0,E=0;k<=x;k+=2,E+=a){let A=l+k,S=A+g,M=S+g,L=M+g,C=e[A],v=e[A+1],G=e[S],X=e[S+1],V=e[M],Q=e[M+1],Y=e[L],K=e[L+1],U=C,P=v,se=f[E],ie=s*f[E+1],O=G*se-X*ie,N=G*ie+X*se,$=f[2*E],te=s*f[2*E+1],ue=V*$-Q*te,Ue=V*te+Q*$,Ce=f[3*E],kt=s*f[3*E+1],Qe=Y*Ce-K*kt,Ze=Y*kt+K*Ce,rt=U+ue,Te=P+Ue,xe=U-ue,Ge=P-Ue,Et=O+Qe,we=N+Ze,Ne=s*(O-Qe),br=s*(N-Ze);if(e[A]=rt+Et,e[A+1]=Te+we,e[S]=xe+br,e[S+1]=Ge-Ne,k===0){e[M]=rt-Et,e[M+1]=Te-we;continue}if(k===x)continue;let Yr=l+g-k,At=l+h-k;e[Yr]=xe-s*br,e[Yr+1]=-Ge-s*Ne,e[At]=rt-s*Et,e[At+1]=-Te+s*we}}let m=n>>>1;for(let h=2;h<m;h+=2)e[n-h]=e[h],e[n-h+1]=-e[h+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],h=c+f,g=c-f,x=p+m,k=a*(p-m);r[s]=h+x,r[s+1]=0,r[s+2]=g,r[s+3]=-k,r[s+4]=h-x,r[s+5]=0,r[s+6]=g,r[s+7]=k}},Mp=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,h=f*Math.atan2(c,l),g=2*p;o[g]=m*Math.cos(h),o[g+1]=m*Math.sin(h),a[g]=o[g],a[g+1]=-o[g+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new qi(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,h=f>>1,g=r[h];n[f]=g*c[f],n[m]=g*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],h=i[f+p+1],g=c[f],x=c[f+1];e[f]=m*g-h*x,e[f+1]=m*x+h*g}}transform(e,r){this._transform(e,r,!1)}realTransform(e,r){this._transform(e,r,!0)}},Vi=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=rk(e),this.isPowerOfTwo?(this.fft=new qi(e),this.outputBufferSize=2*e):(this.fft=new Mp(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function sk(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 os(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function nk(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function ok(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],h=n[f-1][p],g=n[f][p-1],x,k;m<h&&m<g?(x=m,k=0):h<m&&h<g?(x=h,k=1):(x=g,k=2),n[f][p]=t[f-1][p-1]+x,o[f][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 ak=(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 h=113;for(;(m&1024)===0;)m<<=1,--h;m&=-1025,c=p|h<<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 Op={};ts(Op,{Readable:()=>jC,createReadStream:()=>qC,createWriteStream:()=>WC,default:()=>FC,pipeline:()=>GC});var Hi=()=>{},DC={},FC=DC,jC={fromWeb:Hi},GC=Hi,WC=Hi,qC=Hi;var xd={};ts(xd,{InferenceSession:()=>nd,TRACE:()=>rl,TRACE_EVENT_BEGIN:()=>Sr,TRACE_EVENT_END:()=>Or,TRACE_FUNC_BEGIN:()=>ps,TRACE_FUNC_END:()=>ds,Tensor:()=>Jt,default:()=>yP,env:()=>qe,registerBackend:()=>us});var rd=Object.defineProperty,VC=Object.getOwnPropertyDescriptor,HC=Object.getOwnPropertyNames,XC=Object.prototype.hasOwnProperty,YC=(t=>typeof es<"u"?es:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof es<"u"?es:e)[r]}):t)(function(t){if(typeof es<"u")return es.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ye=(t,e)=>()=>(t&&(e=t(t=0)),e),Kn=(t,e)=>{for(var r in e)rd(t,r,{get:e[r],enumerable:!0})},KC=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of HC(e))!XC.call(t,n)&&n!==r&&rd(t,n,{get:()=>e[n],enumerable:!(s=VC(e,n))||s.enumerable});return t},tl=t=>KC(rd({},"__esModule",{value:!0}),t),Gn,Er,us,ik,Nk,zk=ye(()=>{"use strict";Gn=new Map,Er=[],us=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Gn.get(t);if(s===void 0)Gn.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=Er.indexOf(t);n!==-1&&Er.splice(n,1);for(let o=0;o<Er.length;o++)if(Gn.get(Er[o]).priority<=r){Er.splice(o,0,t);return}Er.push(t)}return}throw new TypeError("not a valid backend")},ik=async t=>{let e=Gn.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}}},Nk=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Er:r,n,o=[],a=new Set;for(let l of s){let c=await ik(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)})]}}),QC=ye(()=>{"use strict";zk()}),Rk,JC=ye(()=>{"use strict";Rk="1.24.0-dev.20251116-b39e144322"}),Ip,ct,$k=ye(()=>{"use strict";JC(),Ip="warning",ct={wasm:{},webgl:{},webgpu:{},versions:{common:Rk},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}`);Ip=t}},get logLevel(){return Ip}},Object.defineProperty(ct,"logLevel",{enumerable:!0})}),qe,ZC=ye(()=>{"use strict";$k(),qe=ct}),Bk,Uk,eP=ye(()=>{"use strict";Bk=(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,h=p*2,g=-1;a==="RGBA"?(f=0,m=p,h=p*2,g=p*3):a==="RGB"?(f=0,m=p,h=p*2):a==="RBG"&&(f=0,h=p,m=p*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let E=(t.data[f++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[h++]-c[2])*l[2],M=g===-1?255:(t.data[g++]-c[3])*l[3];s.fillStyle="rgba("+E+","+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")},Uk=(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,h=0,g=1,x=2,k=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 L=0;L<o*n;h+=m,g+=m,x+=m,k+=m,L++)s.data[h]=(t.data[E++]-p[0])*c[0],s.data[g]=(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}}),Xi,Dk,Fk,jk,Gk,Wk,tP=ye(()=>{"use strict";sd(),Xi=(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,h=1,g=2,x=3,k=0,E=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,h=1,g=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,k=c*2);for(let M=0;M<c;M++,m+=f,g+=f,h+=f,x+=f)p[k++]=(t[m]+a[0])/o[0],p[E++]=(t[h]+a[1])/o[1],p[A++]=(t[g]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new Lt("float32",p,[1,4,r,s]):new Lt("float32",p,[1,3,r,s])},Dk=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,h=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,h=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=h}else i.tensorFormat="RGBA",i.height=m,i.width=h;f.drawImage(t,0,0),a=f.getImageData(0,0,h,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 h=c(m);if(h!=null)h.putImageData(t,0,0),a=h.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,h=t.width;return f.drawImage(t,0,0,h,m),a=f.getImageData(0,0,h,m).data,i.height=m,i.width=h,Xi(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let m=l(),h=c(m);if(!t||!h)return f();let g=new Image;g.crossOrigin="Anonymous",g.src=t,g.onload=()=>{m.width=g.width,m.height=g.height,h.drawImage(g,0,0,m.width,m.height);let x=h.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,p(Xi(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Xi(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Fk=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Lt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},jk=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Lt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},Gk=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Lt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},Wk=(t,e,r)=>new Lt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),ls,Xn,Cp,qk,rP=ye(()=>{"use strict";ls=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Xn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Cp=!1,qk=()=>{if(!Cp){Cp=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(ls.set("int64",BigInt64Array),Xn.set(BigInt64Array,"int64")),e&&(ls.set("uint64",BigUint64Array),Xn.set(BigUint64Array,"uint64")),s?(ls.set("float16",r),Xn.set(r,"float16")):ls.set("float16",Uint16Array)}}}),Vk,Hk,sP=ye(()=>{"use strict";sd(),Vk=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},Hk=(t,e)=>{switch(t.location){case"cpu":return new Lt(t.type,t.data,e);case"cpu-pinned":return new Lt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Lt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Lt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Lt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Lt,sd=ye(()=>{"use strict";eP(),tP(),rP(),sP(),Lt=class{constructor(t,e,r){qk();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=ls.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=ls.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=Xn.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=Vk(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 Dk(t,e)}static fromTexture(t,e){return Fk(t,e)}static fromGpuBuffer(t,e){return jk(t,e)}static fromMLTensor(t,e){return Gk(t,e)}static fromPinnedBuffer(t,e,r){return Wk(t,e,r)}toDataURL(t){return Bk(this,t)}toImageData(t){return Uk(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 Hk(this,t)}}}),Jt,Xk=ye(()=>{"use strict";sd(),Jt=Lt}),rl,Pp,ps,ds,Sr,Or,Yk=ye(()=>{"use strict";$k(),rl=(t,e)=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeStamp(`${t}::ORT::${e}`)},Pp=(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}`),rl("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},ps=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Pp("BEGIN",t)},ds=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Pp("END",t)},Sr=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.time(`ORT::${t}`)},Or=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeEnd(`ORT::${t}`)}}),Kk,nP=ye(()=>{"use strict";zk(),Xk(),Yk(),Kk=class Qk{constructor(e){this.handler=e}async run(e,r,s){ps(),Sr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Jt||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 Jt)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 Jt)&&(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 Jt?l[c]=p:l[c]=new Jt(p.type,p.data,p.dims)}return Or("InferenceSession.run"),ds(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ps(),Sr("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 Nk(a),c=await i.createInferenceSessionHandler(o,l);return Or("InferenceSession.create"),ds(),new Qk(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}}}),nd,oP=ye(()=>{"use strict";nP(),nd=Kk}),aP=ye(()=>{"use strict"}),iP=ye(()=>{"use strict"}),lP=ye(()=>{"use strict"}),cP=ye(()=>{"use strict"}),Jk={};Kn(Jk,{InferenceSession:()=>nd,TRACE:()=>rl,TRACE_EVENT_BEGIN:()=>Sr,TRACE_EVENT_END:()=>Or,TRACE_FUNC_BEGIN:()=>ps,TRACE_FUNC_END:()=>ds,Tensor:()=>Jt,env:()=>qe,registerBackend:()=>us});var fs=ye(()=>{"use strict";QC(),ZC(),oP(),Xk(),aP(),iP(),Yk(),lP(),cP()}),od=ye(()=>{"use strict"}),Zk={};Kn(Zk,{default:()=>eE});var Lp,Np,eE,uP=ye(()=>{"use strict";hE(),ms(),ad(),Lp="ort-wasm-proxy-worker",Np=globalThis.self?.name===Lp,Np&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":id(r.wasm).then(()=>{dd(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=ol(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;md(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":hd(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":wd(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),eE=Np?null:t=>new Worker(t??Ct,{type:"module",name:Lp})}),tE={};Kn(tE,{default:()=>rE});async function lk(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.Zc||(e.Zc=new Map)).set(u,d)},e.unmountExternalData=()=>{delete e.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Me:!0}).buffer.constructor;let o=()=>{let u=d=>(..._)=>{let w=sr;return _=d(..._),sr!=w?new Promise((b,T)=>{ep={resolve:b,reject:T}}):_};(()=>{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(C(u))return new Promise((_,w)=>{var b=new XMLHttpRequest;b.open("GET",u,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?_(b.response):w(b.status)},b.onerror=w,b.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,h,g,x,k,E=console.log.bind(console),A=console.error.bind(console),S=E,M=A,L=!1,C=u=>u.startsWith("file://");function v(){vr.buffer!=V.buffer&&ue()}if(n){let u=function(d){try{var _=d.data,w=_.Uc;if(w==="load"){let b=[];self.onmessage=T=>b.push(T),k=()=>{postMessage({Uc:"loaded"});for(let T of b)u(T);self.onmessage=u};for(let T of _.ne)e[T]&&!e[T].proxy||(e[T]=(...I)=>{postMessage({Uc:"callHandler",me:T,args:I})},T=="print"&&(S=e[T]),T=="printErr"&&(M=e[T]));vr=_.we,ue(),m=_.xe,Qe(),Ri()}else if(w==="run"){(function(b){var T=(v(),P)[b+52>>>2>>>0];b=(v(),P)[b+56>>>2>>>0],_1(T,T-b),oe(T)})(_.Sc),dp(_.Sc,0,0,1,0,0),tb(),Qu(_.Sc),X||(Jb(),X=!0);try{_2(_.te,_.ad)}catch(b){if(b!="unwind")throw b}}else _.target!=="setimmediate"&&(w==="checkMailbox"?X&&Ti():w&&(M(`worker: received unknown command ${w}`),M(_)))}catch(b){throw p1(),b}};var G=u,X=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=u}var V,Q,Y,K,U,P,se,ie,O,N,$,te=!1;function ue(){var u=vr.buffer;e.HEAP8=V=new Int8Array(u),Y=new Int16Array(u),e.HEAPU8=Q=new Uint8Array(u),K=new Uint16Array(u),e.HEAP32=U=new Int32Array(u),e.HEAPU32=P=new Uint32Array(u),se=new Float32Array(u),ie=new Float64Array(u),O=new BigInt64Array(u),N=new BigUint64Array(u)}function Ue(){te=!0,n?k():_r.dc()}function Ce(u){throw M(u="Aborted("+u+")"),L=!0,u=new WebAssembly.RuntimeError(u+". Build with -sASSERTIONS for more info."),x?.(u),u}function kt(){return{a:{sa:PM,g:w2,K:g2,f:x2,n:y2,h:b2,wa:v2,b:k2,ea:E2,Ja:ib,o:A2,fa:pb,Za:db,$b:fb,bc:mb,_a:hb,Xa:_b,Qa:wb,Wa:gb,qa:xb,ac:yb,Zb:bb,Ya:vb,_b:kb,db:T2,Fa:S2,Ub:O2,Sb:C2,Ea:L2,P:N2,J:z2,Tb:R2,ma:G2,Vb:W2,Ta:q2,Xb:H2,Ka:X2,Pb:Y2,Ha:K2,Sa:Qu,ab:Q2,W:tT,r:aT,c:Yu,tb:iT,y:lT,N:cT,D:uT,m:pT,s:Cb,ub:dT,I:fT,V:mT,j:hT,u:_T,q:wT,k:gT,Na:xT,Oa:yT,Pa:bT,La:zb,Ma:Rb,Rb:$b,fb:kT,cb:TT,$:MT,sb:ST,na:OT,bb:ET,Y:IT,$a:CT,Yb:PT,G:vT,ib:LT,_:NT,ra:Ci,Wb:RT,hb:zT,gb:$T,pb:WT,F:qT,va:VT,ua:HT,rb:XT,Z:YT,w:KT,ob:QT,nb:JT,mb:ZT,qb:eM,lb:tM,kb:rM,jb:sM,Ua:qb,Va:Vb,Ia:At,ga:Hb,pa:Xb,Ra:Yb,oa:Kb,Eb:hS,za:lS,Fb:mS,Aa:iS,H:JM,e:RM,t:NM,x:LM,B:VM,Ib:nS,L:YM,v:BM,Ba:oS,ca:cS,ja:sS,Gb:fS,Hb:dS,Da:ZM,Ca:rS,Kb:eS,O:KM,da:aS,d:$M,A:UM,l:zM,Db:_S,p:FM,z:qM,C:DM,E:jM,M:HM,Lb:QM,U:uS,ka:XM,ba:pS,Mb:WM,Nb:GM,R:tS,i:oM,a:vr,eb:br,Jb:aM,la:iM,Q:lM,ta:cM,Ob:uM,S:pM,Ab:dM,Bb:fM,xa:mM,ha:hM,T:_M,Ga:wM,ya:gM,aa:xM,yb:yM,cc:bM,X:vM,Cb:kM,vb:EM,wb:TM,xb:MM,ia:SM,zb:OM,Qb:IM}}}async function Qe(){function u(w,b){var T=_r=w.exports;w={};for(let[I,z]of Object.entries(T))typeof z=="function"?(T=J2(z),w[I]=T):w[I]=z;return _r=w,_r=(function(){var I=_r,z=W=>fe=>W(fe)>>>0,D=W=>()=>W()>>>0;return(I=Object.assign({},I)).ec=z(I.ec),I.Hc=D(I.Hc),I.Jc=z(I.Jc),I.vd=(W=>(fe,me)=>W(fe,me)>>>0)(I.vd),I.Ad=z(I.Ad),I.Bd=D(I.Bd),I.Fd=z(I.Fd),I})(),Z0.push(_r.md),Qb=(w=_r).ec,Jb=w.fc,e._OrtInit=w.gc,e._OrtGetLastError=w.hc,e._OrtCreateSessionOptions=w.ic,e._OrtAppendExecutionProvider=w.jc,e._OrtAddFreeDimensionOverride=w.kc,e._OrtAddSessionConfigEntry=w.lc,e._OrtReleaseSessionOptions=w.mc,e._OrtCreateSession=w.nc,e._OrtReleaseSession=w.oc,e._OrtGetInputOutputCount=w.pc,e._OrtGetInputOutputMetadata=w.qc,e._OrtFree=w.rc,e._OrtCreateTensor=w.sc,e._OrtGetTensorData=w.tc,e._OrtReleaseTensor=w.uc,e._OrtCreateRunOptions=w.vc,e._OrtAddRunConfigEntry=w.wc,e._OrtReleaseRunOptions=w.xc,e._OrtCreateBinding=w.yc,e._OrtBindInput=w.zc,e._OrtBindOutput=w.Ac,e._OrtClearBoundOutputs=w.Bc,e._OrtReleaseBinding=w.Cc,e._OrtRunWithBinding=w.Dc,e._OrtRun=w.Ec,e._OrtEndProfiling=w.Fc,ap=e._OrtGetWebGpuDevice=w.Gc,Ni=w.Hc,Rt=e._free=w.Ic,zs=e._malloc=w.Jc,Zb=e._wgpuBufferRelease=w.Kc,e1=e._wgpuCreateInstance=w.Lc,t1=w.Mc,r1=w.Nc,s1=w.Oc,n1=w.Pc,o1=w.Qc,a1=w.Tc,i1=w.bd,l1=w.cd,c1=w.dd,ip=w.fd,lp=w.gd,cp=w.hd,up=w.id,Pn=w.jd,pp=w.kd,u1=w.ld,dp=w.od,p1=w.pd,d1=w.qd,f1=w.rd,fp=w.sd,m1=w.td,h1=w.ud,mp=w.vd,he=w.wd,Ln=w.xd,_1=w.yd,oe=w.zd,zi=w.Ad,ae=w.Bd,w1=w.Cd,hp=w.Dd,g1=w.Ed,x1=w.Fd,y1=w.Gd,_p=w.Hd,b1=w.Id,v1=w.Jd,k1=w.Kd,E1=w.Ld,A1=w.Md,T1=w.Nd,M1=w.Od,S1=w.Pd,O1=w.Qd,I1=w.Rd,C1=w.Sd,P1=w.Td,L1=w.Ud,N1=w.Vd,z1=w.Wd,R1=w.Yd,$1=w.Zd,B1=w._d,U1=w.$d,D1=w.be,F1=w.ce,j1=w.de,G1=w.ee,W1=w.fe,q1=w.ge,V1=w.qe,H1=w.ve,X1=w.ye,Y1=w.ze,K1=w.Ae,Q1=w.Be,J1=w.Ce,Z1=w.De,ev=w.Ee,tv=w.Fe,rv=w.Ge,sv=w.ef,nv=w.ff,ov=w.gf,av=w.hf,m=b,_r}var d,_=kt();return e.instantiateWasm?new Promise(w=>{e.instantiateWasm(_,(b,T)=>{w(u(b,T))})}):n?u(new WebAssembly.Instance(m,kt()),m):($??=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(w){var b=$;if(!f&&!C(b))try{var T=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,w)}catch(I){M(`wasm streaming compile failed: ${I}`),M("falling back to ArrayBuffer instantiation")}return(async function(I,z){try{var D=await(async function(W){if(!f)try{var fe=await a(W);return new Uint8Array(fe)}catch{}if(W==$&&f)W=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";W=i(W)}return W})(I);return await WebAssembly.instantiate(D,z)}catch(W){M(`failed to asynchronously prepare wasm: ${W}`),Ce(W)}})(b,w)})(_),u(d.instance,d.module))}class Ze{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var rt=u=>{u.terminate(),u.onmessage=()=>{}},Te=[],xe=0,Ge=null,Et=u=>{et.length==0&&(sb(),rb(et[0]));var d=et.pop();if(!d)return 6;In.push(d),Kr[u.Sc]=d,d.Sc=u.Sc;var _={Uc:"run",te:u.se,ad:u.ad,Sc:u.Sc};return d.postMessage(_,u.he),0},we=0,Ne=(u,d,..._)=>{var w,b=16*_.length,T=ae(),I=zi(b),z=I>>>3;for(w of _)typeof w=="bigint"?((v(),O)[z++>>>0]=1n,(v(),O)[z++>>>0]=w):((v(),O)[z++>>>0]=0n,(v(),ie)[z++>>>0]=w);return u=d1(u,0,b,I,d),oe(T),u};function br(u){if(n)return Ne(0,1,u);if(h=u,!(0<we)){for(var d of In)rt(d);for(d of et)rt(d);et=[],In=[],Kr={},L=!0}l(0,new Ze(u))}function Yr(u){if(n)return Ne(1,0,u);At(u)}var At=u=>{if(h=u,n)throw Yr(u),"unwind";br(u)},et=[],In=[],Z0=[],Kr={},eb=u=>{var d=u.Sc;delete Kr[d],et.push(u),In.splice(In.indexOf(u),1),u.Sc=0,f1(d)};function tb(){Z0.forEach(u=>u())}var rb=u=>new Promise(d=>{u.onmessage=b=>{var T=b.data;if(b=T.Uc,T.$c&&T.$c!=Ni()){var I=Kr[T.$c];I?I.postMessage(T,T.he):M(`Internal error! Worker sent a message "${b}" to target pthread ${T.$c}, but that thread no longer exists!`)}else b==="checkMailbox"?Ti():b==="spawnThread"?Et(T):b==="cleanupThread"?Ai(()=>{eb(Kr[T.ue])}):b==="loaded"?(u.loaded=!0,d(u)):T.target==="setimmediate"?u.postMessage(T):b==="uncaughtException"?u.onerror(T.error):b==="callHandler"?e[T.me](...T.args):b&&M(`worker sent an unknown command ${b}`)},u.onerror=b=>{throw M(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var _,w=[];for(_ of[])e.propertyIsEnumerable(_)&&w.push(_);u.postMessage({Uc:"load",ne:w,we:vr,xe:m})});function sb(){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"});et.push(u)}var vr,_2=(u,d)=>{we=0,u=_p(u,d),0<we?h=u:fp(u)},ki=[],Ei=0,xt=u=>-9007199254740992>u||9007199254740992<u?NaN:Number(u);function w2(u){var d=new qu(u>>>=0);return(v(),V)[d.Vc+12>>>0]==0&&(nb(d,!0),Ei--),ob(d,!1),ki.push(d),x1(u)}var Is=0,g2=()=>{he(0,0);var u=ki.pop();w1(u.nd),Is=0};function nb(u,d){d=d?1:0,(v(),V)[u.Vc+12>>>0]=d}function ob(u,d){d=d?1:0,(v(),V)[u.Vc+13>>>0]=d}class qu{constructor(d){this.nd=d,this.Vc=d-24}}var Vu=u=>{var d=Is;if(!d)return Ln(0),0;var _=new qu(d);(v(),P)[_.Vc+16>>>2>>>0]=d;var w=(v(),P)[_.Vc+4>>>2>>>0];if(!w)return Ln(0),d;for(var b of u){if(b===0||b===w)break;if(g1(b,w,_.Vc+16))return Ln(b),d}return Ln(w),d};function x2(){return Vu([])}function y2(u){return Vu([u>>>0])}function b2(u,d,_,w){return Vu([u>>>0,d>>>0,_>>>0,w>>>0])}var v2=()=>{var u=ki.pop();u||Ce("no exception to throw");var d=u.nd;throw(v(),V)[u.Vc+13>>>0]==0&&(ki.push(u),ob(u,!0),nb(u,!1),Ei++),hp(d),Is=d};function k2(u,d,_){var w=new qu(u>>>=0);throw d>>>=0,_>>>=0,(v(),P)[w.Vc+16>>>2>>>0]=0,(v(),P)[w.Vc+4>>>2>>>0]=d,(v(),P)[w.Vc+8>>>2>>>0]=_,hp(u),Ei++,Is=u}var E2=()=>Ei;function ab(u,d,_,w){return n?Ne(2,1,u,d,_,w):ib(u,d,_,w)}function ib(u,d,_,w){if(u>>>=0,d>>>=0,_>>>=0,w>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?ab(u,d,_,w):(u={se:_,Sc:u,ad:w,he:b},n?(u.Uc="spawnThread",postMessage(u,b),0):Et(u))}function A2(u){throw Is||=u>>>0,Is}var lb=globalThis.TextDecoder&&new TextDecoder,cb=(u,d,_,w)=>{if(_=d+_,w)return _;for(;u[d]&&!(d>=_);)++d;return d},ub=(u,d=0,_,w)=>{if(16<(_=cb(u,d>>>=0,_,w))-d&&u.buffer&&lb)return lb.decode(u.buffer instanceof ArrayBuffer?u.subarray(d,_):u.slice(d,_));for(w="";d<_;){var b=u[d++];if(128&b){var T=63&u[d++];if((224&b)==192)w+=String.fromCharCode((31&b)<<6|T);else{var I=63&u[d++];65536>(b=(240&b)==224?(15&b)<<12|T<<6|I:(7&b)<<18|T<<12|I<<6|63&u[d++])?w+=String.fromCharCode(b):(b-=65536,w+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else w+=String.fromCharCode(b)}return w},Cs=(u,d,_)=>(u>>>=0)?ub((v(),Q),u,d,_):"";function pb(u,d,_){return n?Ne(3,1,u,d,_):0}function db(u,d){if(n)return Ne(4,1,u,d)}function fb(u,d){if(n)return Ne(5,1,u,d)}function mb(u,d,_){if(n)return Ne(6,1,u,d,_)}function hb(u,d,_){return n?Ne(7,1,u,d,_):0}function _b(u,d){if(n)return Ne(8,1,u,d)}function wb(u,d,_){if(n)return Ne(9,1,u,d,_)}function gb(u,d,_,w){if(n)return Ne(10,1,u,d,_,w)}function xb(u,d,_,w){if(n)return Ne(11,1,u,d,_,w)}function yb(u,d,_,w){if(n)return Ne(12,1,u,d,_,w)}function bb(u){if(n)return Ne(13,1,u)}function vb(u,d){if(n)return Ne(14,1,u,d)}function kb(u,d,_){if(n)return Ne(15,1,u,d,_)}var T2=()=>Ce(""),rr=u=>{u>>>=0;for(var d="";;){var _=(v(),Q)[u++>>>0];if(!_)return d;d+=String.fromCharCode(_)}},Hu={},Xu={},M2={},Ps=class extends Error{constructor(u){super(u),this.name="BindingError"}};function dr(u,d,_={}){return(function(w,b,T={}){var I=b.name;if(!w)throw new Ps(`type "${I}" must have a positive integer typeid pointer`);if(Xu.hasOwnProperty(w)){if(T.oe)return;throw new Ps(`Cannot register type '${I}' twice`)}Xu[w]=b,delete M2[w],Hu.hasOwnProperty(w)&&(b=Hu[w],delete Hu[w],b.forEach(z=>z()))})(u,d,_)}var Eb=(u,d,_)=>{switch(d){case 1:return _?w=>(v(),V)[w>>>0]:w=>(v(),Q)[w>>>0];case 2:return _?w=>(v(),Y)[w>>>1>>>0]:w=>(v(),K)[w>>>1>>>0];case 4:return _?w=>(v(),U)[w>>>2>>>0]:w=>(v(),P)[w>>>2>>>0];case 8:return _?w=>(v(),O)[w>>>3>>>0]:w=>(v(),N)[w>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${u}`)}};function S2(u,d,_,w,b){u>>>=0,_>>>=0,d=rr(d>>>0);let T=I=>I;if(w=w===0n){let I=8*_;T=z=>BigInt.asUintN(I,z),b=T(b)}dr(u,{name:d,Rc:T,Xc:(I,z)=>(typeof z=="number"&&(z=BigInt(z)),z),Wc:Eb(d,_,!w),Yc:null})}function O2(u,d,_,w){dr(u>>>=0,{name:d=rr(d>>>0),Rc:function(b){return!!b},Xc:function(b,T){return T?_:w},Wc:function(b){return this.Rc((v(),Q)[b>>>0])},Yc:null})}var Ab=[],Qr=[0,1,,1,null,1,!0,1,!1,1];function Yu(u){9<(u>>>=0)&&--Qr[u+1]==0&&(Qr[u]=void 0,Ab.push(u))}var zt=u=>{if(!u)throw new Ps(`Cannot use deleted val. handle = ${u}`);return Qr[u]},Vt=u=>{switch(u){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=Ab.pop()||Qr.length;return Qr[d]=u,Qr[d+1]=1,d}};function Ku(u){return this.Rc((v(),P)[u>>>2>>>0])}var I2={name:"emscripten::val",Rc:u=>{var d=zt(u);return Yu(u),d},Xc:(u,d)=>Vt(d),Wc:Ku,Yc:null};function C2(u){return dr(u>>>0,I2)}var P2=(u,d)=>{switch(d){case 4:return function(_){return this.Rc((v(),se)[_>>>2>>>0])};case 8:return function(_){return this.Rc((v(),ie)[_>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${u}`)}};function L2(u,d,_){_>>>=0,dr(u>>>=0,{name:d=rr(d>>>0),Rc:w=>w,Xc:(w,b)=>b,Wc:P2(d,_),Yc:null})}function N2(u,d,_,w,b){u>>>=0,_>>>=0,d=rr(d>>>0);let T=z=>z;if(w===0){var I=32-8*_;T=z=>z<<I>>>I,b=T(b)}dr(u,{name:d,Rc:T,Xc:(z,D)=>D,Wc:Eb(d,_,w!==0),Yc:null})}function z2(u,d,_){function w(T){var I=(v(),P)[T>>>2>>>0];return T=(v(),P)[T+4>>>2>>>0],new b((v(),V).buffer,T,I)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];dr(u>>>=0,{name:_=rr(_>>>0),Rc:w,Wc:w},{oe:!0})}var fr=(u,d,_)=>{var w=(v(),Q);if(d>>>=0,0<_){var b=d;_=d+_-1;for(var T=0;T<u.length;++T){var I=u.codePointAt(T);if(127>=I){if(d>=_)break;w[d++>>>0]=I}else if(2047>=I){if(d+1>=_)break;w[d++>>>0]=192|I>>6,w[d++>>>0]=128|63&I}else if(65535>=I){if(d+2>=_)break;w[d++>>>0]=224|I>>12,w[d++>>>0]=128|I>>6&63,w[d++>>>0]=128|63&I}else{if(d+3>=_)break;w[d++>>>0]=240|I>>18,w[d++>>>0]=128|I>>12&63,w[d++>>>0]=128|I>>6&63,w[d++>>>0]=128|63&I,T++}}w[d>>>0]=0,u=d-b}else u=0;return u},mr=u=>{for(var d=0,_=0;_<u.length;++_){var w=u.charCodeAt(_);127>=w?d++:2047>=w?d+=2:55296<=w&&57343>=w?(d+=4,++_):d+=3}return d};function R2(u,d){dr(u>>>=0,{name:d=rr(d>>>0),Rc(_){var w=(v(),P)[_>>>2>>>0];return w=Cs(_+4,w,!0),Rt(_),w},Xc(_,w){w instanceof ArrayBuffer&&(w=new Uint8Array(w));var b=typeof w=="string";if(!(b||ArrayBuffer.isView(w)&&w.BYTES_PER_ELEMENT==1))throw new Ps("Cannot pass non-string to std::string");var T=b?mr(w):w.length,I=zs(4+T+1),z=I+4;return(v(),P)[I>>>2>>>0]=T,b?fr(w,z,T+1):(v(),Q).set(w,z>>>0),_!==null&&_.push(Rt,I),I},Wc:Ku,Yc(_){Rt(_)}})}var Tb=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,$2=(u,d,_)=>{if(u>>>=1,16<(d=cb((v(),K),u,d/2,_))-u&&Tb)return Tb.decode((v(),K).slice(u,d));for(_="";u<d;++u){var w=(v(),K)[u>>>0];_+=String.fromCharCode(w)}return _},B2=(u,d,_)=>{if(_??=2147483647,2>_)return 0;var w=d;_=(_-=2)<2*u.length?_/2:u.length;for(var b=0;b<_;++b){var T=u.charCodeAt(b);(v(),Y)[d>>>1>>>0]=T,d+=2}return(v(),Y)[d>>>1>>>0]=0,d-w},U2=u=>2*u.length,D2=(u,d,_)=>{var w="";u>>>=2;for(var b=0;!(b>=d/4);b++){var T=(v(),P)[u+b>>>0];if(!T&&!_)break;w+=String.fromCodePoint(T)}return w},F2=(u,d,_)=>{if(d>>>=0,_??=2147483647,4>_)return 0;var w=d;_=w+_-4;for(var b=0;b<u.length;++b){var T=u.codePointAt(b);if(65535<T&&b++,(v(),U)[d>>>2>>>0]=T,(d+=4)+4>_)break}return(v(),U)[d>>>2>>>0]=0,d-w},j2=u=>{for(var d=0,_=0;_<u.length;++_)65535<u.codePointAt(_)&&_++,d+=4;return d};function G2(u,d,_){if(u>>>=0,d>>>=0,_=rr(_>>>=0),d===2)var w=$2,b=B2,T=U2;else w=D2,b=F2,T=j2;dr(u,{name:_,Rc:I=>{var z=(v(),P)[I>>>2>>>0];return z=w(I+4,z*d,!0),Rt(I),z},Xc:(I,z)=>{if(typeof z!="string")throw new Ps(`Cannot pass non-string to C++ string type ${_}`);var D=T(z),W=zs(4+D+d);return(v(),P)[W>>>2>>>0]=D/d,b(z,W+4,D+d),I!==null&&I.push(Rt,W),W},Wc:Ku,Yc(I){Rt(I)}})}function W2(u,d){dr(u>>>=0,{pe:!0,name:d=rr(d>>>0),Rc:()=>{},Xc:()=>{}})}function q2(u){dp(u>>>0,!s,1,!r,131072,!1),tb()}var Ai=u=>{if(!L)try{if(u(),!(0<we))try{n?Ni()&&fp(h):At(h)}catch(d){d instanceof Ze||d=="unwind"||l(0,d)}}catch(d){d instanceof Ze||d=="unwind"||l(0,d)}},V2=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Qu(u){u>>>=0,V2||(Atomics.waitAsync((v(),U),u>>>2,u).value.then(Ti),u+=128,Atomics.store((v(),U),u>>>2,1))}var Ti=()=>Ai(()=>{var u=Ni();u&&(Qu(u),h1())});function H2(u,d){(u>>>=0)==d>>>0?setTimeout(Ti):n?postMessage({$c:u,Uc:"checkMailbox"}):(u=Kr[u])&&u.postMessage({Uc:"checkMailbox"})}var Ju=[];function X2(u,d,_,w,b){for(d>>>=0,b>>>=0,Ju.length=0,_=b>>>3,w=b+w>>>3;_<w;){var T;T=(v(),O)[_++>>>0]?(v(),O)[_++>>>0]:(v(),ie)[_++>>>0],Ju.push(T)}return(d?wp[d]:CM[u])(...Ju)}var Y2=()=>{we=0};function K2(u){u>>>=0,n?postMessage({Uc:"cleanupThread",ue:u}):eb(Kr[u])}function Q2(u){}var Mi=u=>{try{u()}catch(d){Ce(d)}};function J2(u){var d=(..._)=>{Si.push(u);try{return u(..._)}finally{L||(Si.pop(),sr&&kr===1&&Si.length===0&&(kr=0,we+=1,Mi(nv),typeof Fibers<"u"&&Fibers.Oe()))}};return Ob.set(u,d),d}var kr=0,sr=null,Mb=0,Si=[],Zu=new Map,Sb=new Map,Ob=new Map,Z2=0,ep=null,eT=[],Ib=u=>(function(d){if(!L){if(kr===0){var _=!1,w=!1;d((b=0)=>{if(!L&&(Mb=b,_=!0,w)){kr=2,Mi(()=>ov(sr)),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.resume(),b=!1;try{var T=(function(){var D=(v(),U)[sr+8>>>2>>>0];return D=Sb.get(D),D=Ob.get(D),--we,D()})()}catch(D){T=D,b=!0}var I=!1;if(!sr){var z=ep;z&&(ep=null,(b?z.reject:z.resolve)(T),I=!0)}if(b&&!I)throw T}}),w=!0,_||(kr=1,sr=(function(){var b=zs(65548),T=b+12;if((v(),P)[b>>>2>>>0]=T,(v(),P)[b+4>>>2>>>0]=T+65536,T=Si[0],!Zu.has(T)){var I=Z2++;Zu.set(T,I),Sb.set(I,T)}return T=Zu.get(T),(v(),U)[b+8>>>2>>>0]=T,b})(),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.pause(),Mi(()=>sv(sr)))}else kr===2?(kr=0,Mi(av),Rt(sr),sr=null,eT.forEach(Ai)):Ce(`invalid state: ${kr}`);return Mb}})(d=>{u().then(d)});function tT(u){return u>>>=0,Ib(async()=>{var d=await zt(u);return Vt(d)})}var tp=[],rT=u=>{var d=tp.length;return tp.push(u),d},sT=(u,d)=>{for(var _=Array(u),w=0;w<u;++w){var b=w,T=(v(),P)[d+4*w>>>2>>>0],I=Xu[T];if(I===void 0)throw u=`parameter ${w}`,T=Qb(T),d=rr(T),Rt(T),new Ps(`${u} has unknown type ${d}`);_[b]=I}return _},nT=(u,d,_)=>{var w=[];return u=u(w,_),w.length&&((v(),P)[d>>>2>>>0]=Vt(w)),u},oT={},Oi=u=>{var d=oT[u];return d===void 0?rr(u):d};function aT(u,d,_){var[w,...b]=sT(u,d>>>0);d=w.Xc.bind(w);var T=b.map(D=>D.Wc.bind(D));u--;var I={toValue:zt};switch(u=T.map((D,W)=>{var fe=`argFromPtr${W}`;return I[fe]=D,`${fe}(args${W?"+"+8*W:""})`}),_){case 0:var z="toValue(handle)";break;case 2:z="new (toValue(handle))";break;case 3:z="";break;case 1:I.getStringOrSymbol=Oi,z="toValue(handle)[getStringOrSymbol(methodName)]"}return z+=`(${u})`,w.pe||(I.toReturnWire=d,I.emval_returnValue=nT,z=`return emval_returnValue(toReturnWire, destructorsRef, ${z})`),z=`return function (handle, methodName, destructorsRef, args) {
|
|
11
11
|
${z}
|
|
12
|
-
}`,_=new Function(Object.keys(I),z)(...Object.values(I)),z=`methodCaller<(${b.map(D=>D.name)}) => ${w.name}>`,
|
|
13
|
-
`);return u[0]=="Error"&&u.shift()
|
|
14
|
-
`))[0]=="Error"&&w.shift(),$b(w);for(var b=3;w[b]&&Oi(w[b])!=u;)++b;for(u=0;u<_&&w[u+b];++u)(v(),U)[f+4*u>>>2>>>0]=Oi(w[u+b]);return u}var nr=u=>{var f=mr(u)+1,_=Ni(f);return dr(u,_,f),_},rp=[],yt=(u,f)=>{rp[u>>>=0]=f},or=[],Ci=[],Ls=(u,f)=>{Ci[u]=new Promise(_=>f.finally(()=>_(u)))},re=u=>{if(u)return rp[u>>>0]},Pi=(u,f,_)=>{(v(),P)[u>>>2>>>0]=f,(v(),P)[u+4>>>2>>>0]=_},Bb=u=>{var f=(v(),P)[u>>>2>>>0];return u=(v(),P)[u+4>>>2>>>0],Cs(f,u)},hr=u=>{var f=(v(),P)[u>>>2>>>0];return u=(v(),P)[u+4>>>2>>>0],f?Cs(f,u):u===0?"":void 0},zT=u=>{var f=hr(u+4),_=(_=(v(),P)[u+12>>>2>>>0])?re(_):"auto";if(u+=16){var w=re((v(),P)[u+4>>>2>>>0]),b=(v(),P)[u+16>>>2>>>0],T=(v(),P)[u+20>>>2>>>0];if(b){for(var I={},z=0;z<b;++z){var D=T+24*z;I[Bb(D+4)]=(v(),ie)[D+16>>>3>>>0]}b=I}else b=void 0;u={module:w,constants:b,entryPoint:hr(u+8)}}else u=void 0;return{label:f,layout:_,compute:u}},Ub=(u,f)=>{function _(b,T){b=u[b],(v(),U)[f+T>>>2>>>0]=b}function w(b,T){b=u[b],(v(),O)[f+T>>>3>>>0]=BigInt(b)}_("maxTextureDimension1D",4),_("maxTextureDimension2D",8),_("maxTextureDimension3D",12),_("maxTextureArrayLayers",16),_("maxBindGroups",20),_("maxBindGroupsPlusVertexBuffers",24),_("maxBindingsPerBindGroup",28),_("maxDynamicUniformBuffersPerPipelineLayout",32),_("maxDynamicStorageBuffersPerPipelineLayout",36),_("maxSampledTexturesPerShaderStage",40),_("maxSamplersPerShaderStage",44),_("maxStorageBuffersPerShaderStage",48),_("maxStorageTexturesPerShaderStage",52),_("maxUniformBuffersPerShaderStage",56),_("minUniformBufferOffsetAlignment",80),_("minStorageBufferOffsetAlignment",84),w("maxUniformBufferBindingSize",64),w("maxStorageBufferBindingSize",72),_("maxVertexBuffers",88),w("maxBufferSize",96),_("maxVertexAttributes",104),_("maxVertexBufferArrayStride",108),_("maxInterStageShaderVariables",112),_("maxColorAttachments",116),_("maxColorAttachmentBytesPerSample",120),_("maxComputeWorkgroupStorageSize",124),_("maxComputeInvocationsPerWorkgroup",128),_("maxComputeWorkgroupSizeX",132),_("maxComputeWorkgroupSizeY",136),_("maxComputeWorkgroupSizeZ",140),_("maxComputeWorkgroupsPerDimension",144),u.Le!==void 0&&_("maxImmediateSize",148)},RT=[,"validation","out-of-memory","internal"],$T=[,"compatibility","core"],Db={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",327692:"chromium-experimental-unorm16-texture-formats",327693:"chromium-experimental-snorm16-texture-formats",327732:"chromium-experimental-multi-draw-indirect"},BT=[,"low-power","high-performance"],UT=[,"occlusion","timestamp"],DT={undefined:1,unknown:1,destroyed:2};function FT(u,f,_,w,b,T){f=xt(f),_=xt(_),w>>>=0,b>>>=0,T>>>=0;var I=re(u>>>0);if(u={},T){var z=(v(),P)[T+12>>>2>>>0];if(z){var D=(v(),P)[T+16>>>2>>>0];u.requiredFeatures=Array.from((v(),P).subarray(D>>>2>>>0,D+4*z>>>2>>>0),ee=>Db[ee])}var W=(v(),P)[T+20>>>2>>>0];if(W){let ee=function($t,st,Zr=!1){st=W+st,(st=(v(),P)[st>>>2>>>0])==4294967295||Zr&&st==0||($e[$t]=st)},lt=function($t,st){st=W+st;var Zr=(v(),P)[st>>>2>>>0],mS=(v(),P)[st+4>>>2>>>0];Zr==4294967295&&mS==4294967295||($e[$t]=4294967296*(v(),P)[st+4>>>2>>>0]+(v(),P)[st>>>2>>>0])};var de=ee,me=lt,$e={};ee("maxTextureDimension1D",4),ee("maxTextureDimension2D",8),ee("maxTextureDimension3D",12),ee("maxTextureArrayLayers",16),ee("maxBindGroups",20),ee("maxBindGroupsPlusVertexBuffers",24),ee("maxDynamicUniformBuffersPerPipelineLayout",32),ee("maxDynamicStorageBuffersPerPipelineLayout",36),ee("maxSampledTexturesPerShaderStage",40),ee("maxSamplersPerShaderStage",44),ee("maxStorageBuffersPerShaderStage",48),ee("maxStorageTexturesPerShaderStage",52),ee("maxUniformBuffersPerShaderStage",56),ee("minUniformBufferOffsetAlignment",80),ee("minStorageBufferOffsetAlignment",84),lt("maxUniformBufferBindingSize",64),lt("maxStorageBufferBindingSize",72),ee("maxVertexBuffers",88),lt("maxBufferSize",96),ee("maxVertexAttributes",104),ee("maxVertexBufferArrayStride",108),ee("maxInterStageShaderVariables",112),ee("maxColorAttachments",116),ee("maxColorAttachmentBytesPerSample",120),ee("maxComputeWorkgroupStorageSize",124),ee("maxComputeInvocationsPerWorkgroup",128),ee("maxComputeWorkgroupSizeX",132),ee("maxComputeWorkgroupSizeY",136),ee("maxComputeWorkgroupSizeZ",140),ee("maxComputeWorkgroupsPerDimension",144),ee("maxImmediateSize",148,!0),u.requiredLimits=$e}(z=(v(),P)[T+24>>>2>>>0])&&(z={label:hr(z+4)},u.defaultQueue=z),u.label=hr(T+4)}we+=1,Ls(f,I.requestDevice(u).then(ee=>{--we,yt(b,ee.queue),yt(w,ee),_&&(we+=1,Ls(_,ee.lost.then(lt=>{--we,ee.onuncapturederror=()=>{};var $t=ae(),st=nr(lt.message);ip(_,DT[lt.reason],st),oe($t)}))),ee.onuncapturederror=lt=>{var $t=5;lt.error instanceof GPUValidationError?$t=2:lt.error instanceof GPUOutOfMemoryError?$t=3:lt.error instanceof GPUInternalError&&($t=4);var st=ae();lt=nr(lt.error.message),i1(w,$t,lt),oe(st)},"adapterInfo"in ee||(ee.adapterInfo=I.info),up(f,1,w,0)},ee=>{--we;var lt=ae();ee=nr(ee.message),up(f,3,w,ee),_&&ip(_,4,ee),oe(lt)}))}function jT(u){var f=re(u>>>=0),_=or[u];if(_){for(var w=0;w<_.length;++w)_[w]();delete or[u]}f.destroy()}var Ns=()=>{var u="getMappedRange size=0 no longer means WGPU_WHOLE_MAP_SIZE";Ns.ed||(Ns.ed={}),Ns.ed[u]||(Ns.ed[u]=1,M(u))};function GT(u,f,_){f>>>=0,_>>>=0;var w=re(u>>>=0);_===0&&Ns(),_==4294967295&&(_=void 0);try{var b=w.getMappedRange(f,_)}catch{return 0}var T=dp(16,b.byteLength);return(v(),Q).set(new Uint8Array(b),T>>>0),or[u].push(()=>Rt(T)),T}function WT(u,f,_){f>>>=0,_>>>=0;var w=re(u>>>=0);_===0&&Ns(),_==4294967295&&(_=void 0);try{var b=w.getMappedRange(f,_)}catch{return 0}var T=dp(16,b.byteLength);return(v(),Q).fill(0,T,b.byteLength),or[u].push(()=>{new Uint8Array(b).set((v(),Q).subarray(T>>>0,T+b.byteLength>>>0)),Rt(T)}),T}function qT(u,f,_,w,b){u>>>=0,f=xt(f),_=xt(_),b>>>=0;var T=re(u);or[u]=[],b==4294967295&&(b=void 0),we+=1,Ls(f,T.mapAsync(_,w>>>0,b).then(()=>{--we,lp(f,1,0)},I=>{--we,ae();var z=nr(I.message);lp(f,I.name==="AbortError"?4:I.name==="OperationError"?3:0,z),delete or[u]}))}function VT(u){var f=re(u>>>=0),_=or[u];if(_){for(var w=0;w<_.length;++w)_[w]();delete or[u],f.unmap()}}function HT(u){delete rp[u>>>0]}function XT(u,f,_){u>>>=0,f>>>=0,_>>>=0;var w=!!(v(),P)[f+32>>>2>>>0];f={label:hr(f+4),usage:(v(),P)[f+16>>>2>>>0],size:4294967296*(v(),P)[f+28>>>2>>>0]+(v(),P)[f+24>>>2>>>0],mappedAtCreation:w},u=re(u);try{var b=u.createBuffer(f)}catch{return!1}return yt(_,b),w&&(or[_]=[]),!0}function YT(u,f,_,w){u>>>=0,f=xt(f),w>>>=0,_=zT(_>>>0),u=re(u),we+=1,Ls(f,u.createComputePipelineAsync(_).then(b=>{--we,yt(w,b),ap(f,1,w,0)},b=>{--we;var T=ae(),I=nr(b.message);ap(f,b.reason==="validation"?3:b.reason==="internal"?4:0,w,I),oe(T)}))}function KT(u,f,_){u>>>=0,f>>>=0,_>>>=0;var w=(v(),P)[f>>>2>>>0],b=(v(),P)[w+4>>>2>>>0];f={label:hr(f+4),code:""},b===2&&(f.code=Bb(w+8)),yt(_,re(u).createShaderModule(f))}var QT=u=>{(u=re(u)).onuncapturederror=null,u.destroy()};function JT(u,f){f=xt(f),u=re(u>>>0),we+=1,Ls(f,u.popErrorScope().then(_=>{--we;var w=5;_?_ instanceof GPUValidationError?w=2:_ instanceof GPUOutOfMemoryError?w=3:_ instanceof GPUInternalError&&(w=4):w=1;var b=ae();_=_?nr(_.message):0,cp(f,1,w,_),oe(b)},_=>{--we;var w=ae();_=nr(_.message),cp(f,1,5,_),oe(w)}))}function ZT(u,f,_,w){if(f=xt(f),w>>>=0,_>>>=0){var b=(v(),P)[_+4>>>2>>>0];b={featureLevel:$T[b],powerPreference:BT[(v(),P)[_+8>>>2>>>0]],forceFallbackAdapter:!!(v(),P)[_+12>>>2>>>0]},(_=(v(),P)[_>>>2>>>0])!==0&&(v(),b.Qe=!!(v(),P)[_+8>>>2>>>0])}"gpu"in navigator?(we+=1,Ls(f,navigator.gpu.requestAdapter(b).then(T=>{if(--we,T)yt(w,T),Pn(f,1,w,0);else{T=ae();var I=nr("WebGPU not available on this browser (requestAdapter returned null)");Pn(f,3,w,I),oe(T)}},T=>{--we;var I=ae();T=nr(T.message),Pn(f,4,w,T),oe(I)}))):(_=ae(),b=nr("WebGPU not available on this browser (navigator.gpu is not available)"),Pn(f,3,w,b),oe(_))}function eM(u,f,_){return u>>>=0,f>>>=0,_>>>=0,Mb(async()=>{var w=[];if(_){var b=(v(),U)[_>>>2>>>0];w.length=f+1,w[f]=new Promise(z=>setTimeout(z,b,0))}else w.length=f;for(var T=0;T<f;++T){var I=4294967296*(v(),P)[u+8*T+4>>>2>>>0]+(v(),P)[u+8*T>>>2>>>0];if(!(I in Ci))return I;w[T]=Ci[I]}return w=await Promise.race(w),delete Ci[w],w})}var sp,np={},Fb=()=>{if(!sp){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 np)np[u]===void 0?delete f[u]:f[u]=np[u];var _=[];for(u in f)_.push(`${u}=${f[u]}`);sp=_}return sp};function jb(u,f){if(n)return Ne(19,1,u,f);u>>>=0,f>>>=0;var _,w=0,b=0;for(_ of Fb()){var T=f+w;(v(),P)[u+b>>>2>>>0]=T,w+=dr(_,T,1/0)+1,b+=4}return 0}function Gb(u,f){if(n)return Ne(20,1,u,f);u>>>=0,f>>>=0;var _=Fb();for(var w of((v(),P)[u>>>2>>>0]=_.length,u=0,_))u+=mr(w)+1;return(v(),P)[f>>>2>>>0]=u,0}function Wb(u){return n?Ne(21,1,u):52}function qb(u,f,_,w){return n?Ne(22,1,u,f,_,w):52}function Vb(u,f,_,w){return n?Ne(23,1,u,f,_,w):70}var tM=[null,[],[]];function Hb(u,f,_,w){if(n)return Ne(24,1,u,f,_,w);f>>>=0,_>>>=0,w>>>=0;for(var b=0,T=0;T<_;T++){var I=(v(),P)[f>>>2>>>0],z=(v(),P)[f+4>>>2>>>0];f+=8;for(var D=0;D<z;D++){var W=u,de=(v(),Q)[I+D>>>0],me=tM[W];de===0||de===10?((W===1?S:M)(ib(me)),me.length=0):me.push(de)}b+=z}return(v(),P)[w>>>2>>>0]=b,0}function rM(u){return u>>>0}function sM(u,f){return Ub(re(u>>>0).limits,f>>>0),1}function nM(u,f){return re(u>>>0).features.has(Db[f])}function oM(u){return BigInt(re(u>>>0).size)}function aM(u){return BigInt(re(u>>>0).usage)}function iM(u,f){if(u>>>=0,f>>>=0){var _=hr(f+4);_={label:_,timestampWrites:f=(f=(v(),P)[f+12>>>2>>>0])!==0?{querySet:re((v(),P)[f+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),P)[f+8>>>2>>>0],endOfPassWriteIndex:(v(),P)[f+12>>>2>>>0]}:void 0}}return u=re(u),f=r1(0),yt(f,u.beginComputePass(_)),f}function lM(u,f,_,w,b,T){_=xt(_),b=xt(b),T=xt(T),re(u>>>0).copyBufferToBuffer(re(f>>>0),_,re(w>>>0),b,T)}function cM(u){u=re(u>>>0);var f=e1(0);return yt(f,u.finish()),f}function uM(u,f,_,w,b,T){T=xt(T),re(u>>>0).resolveQuerySet(re(f>>>0),_,w,re(b>>>0),T)}function pM(u,f,_,w){re(u>>>0).dispatchWorkgroups(f,_,w)}function fM(u,f,_){_=xt(_),re(u>>>0).dispatchWorkgroupsIndirect(re(f>>>0),_)}function dM(u){re(u>>>0).end()}function mM(u,f,_,w,b){w>>>=0,b>>>=0,u=re(u>>>0),_=re(_>>>0),w==0?u.setBindGroup(f,_):u.setBindGroup(f,_,(v(),P),b>>>2,w)}function hM(u,f){re(u>>>0).setPipeline(re(f>>>0))}function _M(u,f,_){re(u>>>0).Pe(re(f>>>0),_)}function wM(u,f){u=re(u>>>0);var _=Zb(0);return yt(_,u.getBindGroupLayout(f)),_}function gM(u,f){u>>>=0;var _=hr(4+(f>>>=0)),w=re((v(),P)[f+12>>>2>>>0]),b=(v(),P)[f+16>>>2>>>0];f=(v(),P)[f+20>>>2>>>0];for(var T=[],I=0;I<b;++I){var z=T,D=z.push,W=f+40*I,de=(v(),P)[W+8>>>2>>>0],me=(v(),P)[W+32>>>2>>>0],$e=(v(),P)[W+36>>>2>>>0],ee=(v(),P)[W+4>>>2>>>0];de?(me=W+24,(me=(v(),P)[me>>>2>>>0]+4294967296*(v(),U)[me+4>>>2>>>0])==-1&&(me=void 0),W={binding:ee,resource:{buffer:re(de),offset:4294967296*(v(),P)[W+4+16>>>2>>>0]+(v(),P)[W+16>>>2>>>0],size:me}}):W=me?{binding:ee,resource:re(me)}:{binding:ee,resource:re($e)},D.call(z,W)}return _={label:_,layout:w,entries:T},u=re(u),w=Jb(0),yt(w,u.createBindGroup(_)),w}function xM(u,f){var _;return u>>>=0,(f>>>=0)&&(_={label:hr(f+4)}),u=re(u),f=t1(0),yt(f,u.createCommandEncoder(_)),f}function yM(u,f){u>>>=0,f>>>=0,f={type:UT[(v(),P)[f+12>>>2>>>0]],count:(v(),P)[f+16>>>2>>>0]},u=re(u);var _=s1(0);return yt(_,u.createQuerySet(f)),_}function bM(u,f){u=re(u>>>0).adapterInfo,f>>>=0,(v(),U)[f+52>>>2>>>0]=u.subgroupMinSize,(v(),U)[f+56>>>2>>>0]=u.subgroupMaxSize;var _=Rb(u.vendor+u.architecture+u.device+u.description),w=mr(u.vendor);return Pi(f+4,_,w),_+=w,w=mr(u.architecture),Pi(f+12,_,w),_+=w,w=mr(u.device),Pi(f+20,_,w),Pi(f+28,_+w,mr(u.description)),(v(),U)[f+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(v(),U)[f+40>>>2>>>0]=u,(v(),U)[f+44>>>2>>>0]=0,(v(),U)[f+48>>>2>>>0]=0,1}var vM={"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,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-snorm16-texture-formats":327693,"chromium-experimental-multi-draw-indirect":327732};function kM(u,f){f>>>=0,u=re(u>>>0);var _=zs(4*u.features.size),w=0,b=0;u.features.forEach(T=>{0<=(T=vM[T])&&((v(),U)[_+w>>>2>>>0]=T,w+=4,b++)}),(v(),P)[f+4>>>2>>>0]=_,(v(),P)[f>>>2>>>0]=b}function EM(u,f){return Ub(re(u>>>0).limits,f>>>0),1}function AM(u,f){re(u>>>0).pushErrorScope(RT[f])}function TM(u,f,_){f>>>=0,_>>>=0,u=re(u>>>0),f=Array.from((v(),U).subarray(_>>>2>>>0,_+4*f>>>2>>>0),w=>re(w)),u.submit(f)}function MM(u,f,_,w,b){_=xt(_),w>>>=0,b>>>=0,u=re(u>>>0),f=re(f>>>0),w=(v(),Q).subarray(w>>>0,w+b>>>0),u.writeBuffer(f,_,w,0,b)}n||(function(){for(var u=e.numThreads-1;u--;)eb();Te.push(async()=>{var f=(async function(){if(!n)return Promise.all(et.map(Z0))})();xe++,await f,--xe==0&&Ge&&(f=Ge,Ge=null,f())})})(),n||(vr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ue()),e.wasmBinary&&(d=e.wasmBinary),e.stackSave=()=>ae(),e.stackRestore=u=>oe(u),e.stackAlloc=u=>Ni(u),e.setValue=function(u,f,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(v(),V)[u>>>0]=f;break;case"i16":(v(),Y)[u>>>1>>>0]=f;break;case"i32":(v(),U)[u>>>2>>>0]=f;break;case"i64":(v(),O)[u>>>3>>>0]=BigInt(f);break;case"float":(v(),se)[u>>>2>>>0]=f;break;case"double":(v(),ie)[u>>>3>>>0]=f;break;case"*":(v(),P)[u>>>2>>>0]=f;break;default:Ce(`invalid type for setValue: ${_}`)}},e.getValue=function(u,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return(v(),V)[u>>>0];case"i16":return(v(),Y)[u>>>1>>>0];case"i32":return(v(),U)[u>>>2>>>0];case"i64":return(v(),O)[u>>>3>>>0];case"float":return(v(),se)[u>>>2>>>0];case"double":return(v(),ie)[u>>>3>>>0];case"*":return(v(),P)[u>>>2>>>0];default:Ce(`invalid type for getValue: ${f}`)}},e.UTF8ToString=Cs,e.stringToUTF8=dr,e.lengthBytesUTF8=mr;var Xb,Yb,op,Li,Rt,zs,Kb,Qb,Jb,Zb,e1,t1,r1,s1,n1,o1,a1,ap,ip,lp,cp,Pn,up,i1,pp,l1,c1,u1,fp,p1,f1,dp,he,Ln,d1,oe,Ni,ae,m1,mp,h1,_1,w1,hp,g1,x1,y1,b1,v1,k1,E1,A1,T1,M1,S1,O1,I1,C1,P1,L1,N1,z1,R1,$1,B1,U1,D1,F1,j1,G1,W1,q1,V1,H1,X1,Y1,K1,Q1,J1,Z1,ev,tv,rv,sv,_r,SM=[br,Yr,sb,lb,cb,ub,pb,fb,db,mb,hb,_b,wb,gb,xb,yb,Pb,Lb,Nb,jb,Gb,Wb,qb,Vb,Hb],_p={1116828:(u,f,_,w,b)=>{if(e===void 0||!e.Zc)return 1;if((u=Cs(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Zc.get(u)))return 2;if(f=Number(f>>>0),_=Number(_>>>0),w=Number(w>>>0),f+_>u.byteLength)return 3;try{let T=u.subarray(f,f+_);switch(b){case 0:(v(),Q).set(T,w>>>0);break;case 1:e.ie?e.ie(w,T):e.Ke(w,T);break;default:return 4}return 0}catch{return 4}},1117652:(u,f,_)=>{e.ke(u,(v(),Q).subarray(f>>>0,f+_>>>0))},1117716:()=>e.Ie(),1117758:u=>{e.je(u)},1117795:()=>typeof wasmOffsetConverter<"u"};function OM(){return typeof wasmOffsetConverter<"u"}function IM(u,f,_,w){var b=ae();try{return A1(u,f,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function CM(u,f,_){var w=ae();try{return v1(u,f,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function PM(u,f,_){var w=ae();try{w1(u,f,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function LM(u,f){var _=ae();try{return hp(u,f)}catch(w){if(oe(_),w!==w+0)throw w;he(1,0)}}function NM(u){var f=ae();try{g1(u)}catch(_){if(oe(f),_!==_+0)throw _;he(1,0)}}function zM(u,f,_,w,b,T,I){var z=ae();try{return b1(u,f,_,w,b,T,I)}catch(D){if(oe(z),D!==D+0)throw D;he(1,0)}}function RM(u,f){var _=ae();try{T1(u,f)}catch(w){if(oe(_),w!==w+0)throw w;he(1,0)}}function $M(u,f,_,w,b,T){var I=ae();try{x1(u,f,_,w,b,T)}catch(z){if(oe(I),z!==z+0)throw z;he(1,0)}}function BM(u,f,_,w){var b=ae();try{E1(u,f,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function UM(u,f,_,w,b,T,I){var z=ae();try{S1(u,f,_,w,b,T,I)}catch(D){if(oe(z),D!==D+0)throw D;he(1,0)}}function DM(u,f,_,w,b,T,I){var z=ae();try{O1(u,f,_,w,b,T,I)}catch(D){if(oe(z),D!==D+0)throw D;he(1,0)}}function FM(u,f,_,w,b,T,I,z){var D=ae();try{U1(u,f,_,w,b,T,I,z)}catch(W){if(oe(D),W!==W+0)throw W;he(1,0)}}function jM(u,f,_,w,b){var T=ae();try{y1(u,f,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;he(1,0)}}function GM(u,f,_,w,b){var T=ae();try{return M1(u,f,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;he(1,0)}}function WM(u,f,_,w,b,T,I,z){var D=ae();try{D1(u,f,_,w,b,T,I,z)}catch(W){if(oe(D),W!==W+0)throw W;he(1,0)}}function qM(u,f,_,w,b,T,I,z,D,W,de,me){var $e=ae();try{I1(u,f,_,w,b,T,I,z,D,W,de,me)}catch(ee){if(oe($e),ee!==ee+0)throw ee;he(1,0)}}function VM(u,f,_,w,b,T){var I=ae();try{return $1(u,f,_,w,b,T)}catch(z){if(oe(I),z!==z+0)throw z;he(1,0)}}function HM(u,f,_){var w=ae();try{return N1(u,f,_)}catch(b){if(oe(w),b!==b+0)throw b;return he(1,0),0n}}function XM(u,f,_,w,b,T,I,z,D){var W=ae();try{k1(u,f,_,w,b,T,I,z,D)}catch(de){if(oe(W),de!==de+0)throw de;he(1,0)}}function YM(u){var f=ae();try{return P1(u)}catch(_){if(oe(f),_!==_+0)throw _;he(1,0)}}function KM(u,f,_){var w=ae();try{return F1(u,f,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function QM(u,f){var _=ae();try{return Z1(u,f)}catch(w){if(oe(_),w!==w+0)throw w;return he(1,0),0n}}function JM(u,f,_,w,b){var T=ae();try{j1(u,f,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;he(1,0)}}function ZM(u){var f=ae();try{return C1(u)}catch(_){if(oe(f),_!==_+0)throw _;return he(1,0),0n}}function eS(u,f,_,w,b,T){var I=ae();try{return q1(u,f,_,w,b,T)}catch(z){if(oe(I),z!==z+0)throw z;he(1,0)}}function tS(u,f,_,w,b,T){var I=ae();try{return V1(u,f,_,w,b,T)}catch(z){if(oe(I),z!==z+0)throw z;he(1,0)}}function rS(u,f,_,w,b,T,I,z){var D=ae();try{return B1(u,f,_,w,b,T,I,z)}catch(W){if(oe(D),W!==W+0)throw W;he(1,0)}}function sS(u,f,_,w,b){var T=ae();try{return H1(u,f,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;return he(1,0),0n}}function nS(u,f,_,w){var b=ae();try{return X1(u,f,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function oS(u,f,_,w){var b=ae();try{return Y1(u,f,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function aS(u,f,_,w,b,T,I,z,D,W,de,me){var $e=ae();try{return K1(u,f,_,w,b,T,I,z,D,W,de,me)}catch(ee){if(oe($e),ee!==ee+0)throw ee;he(1,0)}}function iS(u,f,_,w,b,T,I,z,D,W,de){var me=ae();try{G1(u,f,_,w,b,T,I,z,D,W,de)}catch($e){if(oe(me),$e!==$e+0)throw $e;he(1,0)}}function lS(u,f,_,w,b,T,I,z,D,W,de,me,$e,ee,lt,$t){var st=ae();try{W1(u,f,_,w,b,T,I,z,D,W,de,me,$e,ee,lt,$t)}catch(Zr){if(oe(st),Zr!==Zr+0)throw Zr;he(1,0)}}function cS(u,f,_,w){var b=ae();try{return Q1(u,f,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function uS(u,f,_,w,b){var T=ae();try{return J1(u,f,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;he(1,0)}}function pS(u,f,_){var w=ae();try{return L1(u,f,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function fS(u,f,_){var w=ae();try{return z1(u,f,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function dS(u,f,_,w){var b=ae();try{R1(u,f,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function zi(){if(0<xe)Ge=zi;else if(n)g?.(e),Ue();else{for(var u=Te;0<u.length;)u.shift()(e);0<xe?Ge=zi:(e.calledRun=!0,L||(Ue(),g?.(e)))}}return n||(_r=await Qe(),zi()),e.PTR_SIZE=4,e.webgpuInit=u=>{let f=new WeakMap,_,w,b=1;e.webgpuRegisterDevice=z=>{if(w!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var D=f.get(z);if(!D){let W=((de,me=0)=>{var $e=a1(me);return me=o1(me,$e),yt($e,de.queue),yt(me,de),me})(z,D=Qb(0));D=[b++,D,W],f.set(z,D)}return _=z,w=D[0],D}_=void 0,w=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(w!==void 0){var D=w;if(w=void 0,z){let W=op(D);T.set(z,W),D===0&&u(_??re(W))}_=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let I=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,D,W)=>{if(W)return z[I]=[W,NaN],W;if(W=z[I])return W[1]++,W[0];if((D=T.get(D))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return D=((de,me=0)=>(de.mapState!="pending"||Ce(),me=n1(me,de.mapState=="mapped"?3:1),yt(me,de),de.mapState=="mapped"&&(or[me]=[]),me))(z,D),z[I]=[D,1],D},e.webgpuUnregisterBuffer=z=>{let D=z[I];if(!D)throw Error("Buffer is not registered");D[1]--,D[1]===0&&(Kb(D[0]),delete z[I])},e.webgpuGetBuffer=z=>re(z),e.webgpuCreateDownloader=(z,D,W)=>{if((W=T.get(W))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let de=re(W),me=16*Math.ceil(Number(D)/16);return async()=>{let $e=de.createBuffer({size:me,usage:9});try{let ee=de.createCommandEncoder();return ee.copyBufferToBuffer(z,0,$e,0,me),de.queue.submit([ee.finish()]),await $e.mapAsync(GPUMapMode.READ),$e.getMappedRange().slice(0,D)}finally{$e.destroy()}}},e.ie=(z,D)=>{var W=D.buffer;let de=D.byteOffset,me=D.byteLength;if(D=16*Math.ceil(Number(me)/16),z=re(z),!_){var $e=op(w);_=re($e)}let ee=($e=_.createBuffer({mappedAtCreation:!0,size:D,usage:6})).getMappedRange();new Uint8Array(ee).set(new Uint8Array(W,de,me)),$e.unmap(),(W=_.createCommandEncoder()).copyBufferToBuffer($e,0,z,0,D),_.queue.submit([W.finish()]),$e.destroy()}},e.webnnInit=u=>{let f=u[0];[e.Ie,e.je,e.webnnEnsureTensor,e.ke,e.webnnDownloadTensor,e.He,e.webnnEnableTraceEvent]=u.slice(1),e.webnnReleaseTensorId=e.je,e.webnnUploadTensor=e.ke,e.webnnRegisterMLContext=e.He,e.webnnOnRunStart=_=>f.onRunStart(_),e.webnnOnRunEnd=f.onRunEnd.bind(f),e.webnnOnReleaseSession=_=>{f.onReleaseSession(_)},e.webnnCreateMLTensorDownloader=(_,w)=>f.createMLTensorDownloader(_,w),e.webnnRegisterMLTensor=(_,w,b,T)=>f.registerMLTensor(_,w,b,T),e.webnnCreateMLContext=_=>f.createMLContext(_),e.webnnRegisterMLConstant=(_,w,b,T,I,z)=>f.registerMLConstant(_,w,b,T,I,e.Zc,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)},te?e:new Promise((u,f)=>{g=u,x=f})}var Zk,ak,lP=ye(()=>{"use strict";Zk=ok,ak=globalThis.self?.name?.startsWith("em-pthread"),ak&&ok()}),Np,Kp,ik,Ct,eE,Xi,lk,ck,zp,uk,Rp,tE,$p,rE,of=ye(()=>{"use strict";nf(),Np=typeof location>"u"?void 0:location.origin,Kp=import.meta.url>"file:"&&import.meta.url<"file;",ik=()=>{if(Kp){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Np).href}return import.meta.url},Ct=ik(),eE=()=>{if(Ct&&!Ct.startsWith("blob:"))return Ct.substring(0,Ct.lastIndexOf("/")+1)},Xi=(t,e)=>{try{let r=e??Ct;return(r?new URL(t,r):new URL(t)).origin===Np}catch{return!1}},lk=(t,e)=>{let r=e??Ct;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},ck=(t,e)=>`${e??"./"}${t}`,zp=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},uk=async t=>(await import(t)).default,Rp=(iP(),el(Kk)).default,tE=async()=>{if(!Ct)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Xi(Ct))return[void 0,Rp()];let t=await zp(Ct);return[t,Rp(t)]},$p=(lP(),el(Jk)).default,rE=async(t,e,r,s)=>{let n=$p&&!(t||e);if(n)if(Ct)n=Xi(Ct);else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,$p];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??lk(o,e),i=r&&a&&!Xi(a,e),l=i?await zp(a):a??ck(o,e);return[i?l:void 0,await uk(l)]}}}),Bp,Yi,Wn,Up,pk,fk,dk,af,Be,ms=ye(()=>{"use strict";of(),Yi=!1,Wn=!1,Up=!1,pk=()=>{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}},fk=()=>{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}},dk=()=>{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}},af=async t=>{if(Yi)return Promise.resolve();if(Wn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Up)throw new Error("previous call to 'initializeWebAssembly()' failed.");Wn=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!dk())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!fk())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=pk();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 rE(i,o,r>1,!!p||!!c),h=!1,g=[];if(e>0&&g.push(new Promise(x=>{setTimeout(()=>{h=!0,x()},e)})),g.push(new Promise((x,k)=>{let E={numThreads:r};if(p)E.wasmBinary=p;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(d){let A=eE();A&&(E.locateFile=S=>A+S)}m(E).then(A=>{Wn=!1,Yi=!0,Bp=A,x(),d&&URL.revokeObjectURL(d)},A=>{Wn=!1,Up=!0,k(A)})})),await Promise.race(g),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Be=()=>{if(Yi&&Bp)return Bp;throw new Error("WebAssembly is not initialized yet.")}}),Pt,rl,Oe,lf=ye(()=>{"use strict";ms(),Pt=(t,e)=>{let r=Be(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},rl=(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")rl(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}`)})},Oe=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)}}}),sE,cP=ye(()=>{"use strict";ms(),lf(),sE=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=Pt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Oe("Can't create run options."),t?.extra!==void 0&&rl(t.extra,"",new WeakSet,(a,i)=>{let l=Pt(a,s),c=Pt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Oe(`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}}}),mk,hk,_k,Ki,Ar,wk,nE,uP=ye(()=>{"use strict";ms(),lf(),mk=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}`)}},hk=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},_k=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)},Ki=(t,e,r,s)=>{let n=Pt(e,s),o=Pt(r,s);Be()._OrtAddSessionConfigEntry(t,n,o)!==0&&Oe(`Can't set a session config entry: ${e} - ${r}.`)},Ar=(t,e,r,s)=>{let n=Pt(e,s),o=Pt(r,s);t.push([n,o])},wk=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&&Ki(t,"deviceType",d,r)}break;case"webgpu":{o="WebGPU";let d;if(typeof n!="string"){let h=n;if(h.device)if(typeof GPUDevice<"u"&&h.device instanceof GPUDevice)d=h.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:g}=e;if(typeof g=="boolean"&&g&&Ar(a,"enableGraphCapture","1",r),typeof h.preferredLayout=="string"&&Ar(a,"preferredLayout",h.preferredLayout,r),h.forceCpuNodeNames){let x=Array.isArray(h.forceCpuNodeNames)?h.forceCpuNodeNames:[h.forceCpuNodeNames];Ar(a,"forceCpuNodeNames",x.join(`
|
|
15
|
-
`),r)}h.validationMode&&Ar(a,"validationMode",h.validationMode,r)}let m=Be().webgpuRegisterDevice(d);if(m){let[h,g,x]=m;Ar(a,"deviceId",h.toString(),r),Ar(a,"webgpuInstance",g.toString(),r),Ar(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Pt(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 d=0;d<l;d++)Be().setValue(c+d*Be().PTR_SIZE,a[d][0],"*"),Be().setValue(p+d*Be().PTR_SIZE,a[d][1],"*")}await Be()._OrtAppendExecutionProvider(t,i,c,p,l)!==0&&Oe(`Can't append execution provider: ${o}.`)}},nE=async t=>{let e=Be(),r=0,s=[],n=t||{};_k(n);try{let o=mk(n.graphOptimizationLevel??"all"),a=hk(n.executionMode??"sequential"),i=typeof n.logId=="string"?Pt(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"?Pt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&Oe("Can't create session options."),n.executionProviders&&await wk(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Ki(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 h=Pt(d,s);e._OrtAddFreeDimensionOverride(r,h,m)!==0&&Oe(`Can't set a free dimension override: ${d} - ${m}.`)}return n.extra!==void 0&&rl(n.extra,"",new WeakSet,(d,m)=>{Ki(r,d,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Oe("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),cs,Zi,Gs,Yn,sl,cf,uf,Qp,Ws=ye(()=>{"use strict";cs=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}`)}},Zi=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}`)}},Gs=(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},Yn=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}`)}},sl=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}`)}},cf=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",uf=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Qp=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}`)}}}),pf,oE=ye(()=>{"use strict";nf(),pf=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)}}),aE,pP=ye(()=>{"use strict";Ws(),aE=(t,e)=>new(Yn(e))(t)}),gk,xk,yk,bk,iE,vk,wt,lE=ye(()=>{"use strict";Ws(),gk=["V","I","W","E","F"],xk=(t,e)=>{console.log(`[${gk[t]},${new Date().toISOString()}]${e}`)},iE=(t,e)=>{yk=t,bk=e},vk=(t,e)=>{let r=sl(t),s=sl(yk);r>=s&&xk(r,typeof e=="function"?e():e)},wt=(...t)=>{bk&&vk(...t)}}),Dp,Jp,Fp,kk,jp,Ek,Gp,Wp,qp,Ak,cE,fP=ye(()=>{"use strict";Ws(),lE(),Dp=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Jp=(t,e)=>{if(e==="int32")return t;let r=Dp.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(Yn(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'`)}},Fp=(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}`)}},kk=1,jp=()=>kk++,Ek=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Gp=(t,e)=>{let r=Dp.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},Wp=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 Gp(this.dataType,this.tensorShape)}destroy(){wt("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=Fp(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}},qp=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=Ek.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);wt("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!==Gp(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=Jp(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 wt("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?Fp(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()}},Ak=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=jp();return this.tensorTrackersById.set(t,new qp(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){wt("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){wt("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=jp(),a=new Wp({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new qp(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)){wt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let d=this.freeTensors.splice(c,1)[0];return d.sessionId=t,d}wt("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 Wp({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)}},cE=(...t)=>new Ak(...t)}),uE={};Kn(uE,{WebNNBackend:()=>pE});var qn,Tk,pE,dP=ye(()=>{"use strict";Ws(),ms(),pP(),fP(),lE(),qn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Tk=(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])},pE=class{constructor(t){this.tensorManager=cE(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,iE(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){wt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){wt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)wt("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=>Tk(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){wt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=qn.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){wt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=qn.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");wt("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 aE(r,e)}}registerMLTensor(t,e,r,s){let n=qn.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return wt("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=Jp(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 wt("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=qn.get(cs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),Mk,ff,df,Tr,Sk,Vp,nl,mf,hf,Hp,_f,wf,gf,fE=ye(()=>{"use strict";ds(),cP(),uP(),Ws(),ms(),lf(),oE(),Mk=(t,e)=>{Be()._OrtInit(t,e)!==0&&Oe("Can't initialize onnxruntime.")},ff=async t=>{Mk(t.wasm.numThreads,sl(t.logLevel))},df=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(dP(),el(uE)).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])}},Tr=new Map,Sk=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&&Oe("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)}},Vp=(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&&Oe("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)}},nl=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]},mf=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]=nl(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await nE(e),e?.externalData&&n.mountExternalData){let M=[];for(let L of e.externalData){let C=typeof L=="string"?L:L.path;M.push(pf(typeof L=="string"?L:L.data).then(v=>{n.mountExternalData(C,v)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let L=M,C=L?.context,v=L?.gpuDevice,G=L?.deviceType,X=L?.powerPreference;C?n.currentContext=C:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:G,powerPreference:X})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Oe("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[d,m]=Sk(o),h=!!e?.enableGraphCapture,g=[],x=[],k=[],E=[],A=[];for(let M=0;M<d;M++){let[L,C,v]=Vp(o,M);L===0&&Oe("Can't get an input name."),c.push(L);let G=n.UTF8ToString(L);g.push(G),k.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Zi(C),shape:v})}for(let M=0;M<m;M++){let[L,C,v]=Vp(o,M+d);L===0&&Oe("Can't get an output name."),p.push(L);let G=n.UTF8ToString(L);x.push(G),E.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Zi(C),shape:v});{if(h&&e?.preferredOutputLocation===void 0){A.push("gpu-buffer");continue}let X=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[G]??"cpu",V=n.webnnIsGraphOutput;if(X==="cpu"&&V&&V(o,G)){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(h&&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&&Oe("Can't create IO binding."),S={handle:i,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>Qp(M))}),Tr.set(o,[o,c,p,S,h,!1]),[o,g,x,k,E]}catch(d){throw c.forEach(m=>n._OrtFree(m)),p.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Oe("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Oe("Can't release session."),d}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Oe("Can't release session options."),l.forEach(d=>n._free(d)),n.unmountExternalData?.()}},hf=t=>{let e=Be(),r=Tr.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&&Oe("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Oe("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&&Oe("Can't release session."),Tr.delete(t)},Hp=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],d=t[3],m=d,h,g;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 E=t[2].gpuBuffer;g=Gs(cs(c),p);{let A=i.webgpuRegisterBuffer;if(!A)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=A(E,s)}}else if(d==="ml-tensor"){let E=t[2].mlTensor;g=Gs(cs(c),p);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=A(s,E,cs(c),p)}else{let E=t[2];if(Array.isArray(E)){g=l*E.length,h=i._malloc(g),r.push(h);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(h+A*l,Pt(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 L=cs(c);g=Gs(L,p),m="ml-tensor";let C=i.webnnCreateTemporaryTensor,v=i.webnnUploadTensor;if(!C||!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let G=await C(s,L,p);v(G,new Uint8Array(E.buffer,E.byteOffset,E.byteLength)),h=G}else g=E.byteLength,h=i._malloc(g),r.push(h),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,g),h)}else g=E.byteLength,h=i._malloc(g),r.push(h),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,g),h)}}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 E=i._OrtCreateTensor(cs(c),h,g,k,p.length,Qp(m));E===0&&Oe(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(E)}finally{i.stackRestore(x)}},_f=async(t,e,r,s,n,o)=>{let a=Be(),i=a.PTR_SIZE,l=Tr.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],h=l[4],g=l[5],x=e.length,k=s.length,E=0,A=[],S=[],M=[],L=[],C=[],v=a.stackSave(),G=a.stackAlloc(x*i),X=a.stackAlloc(x*i),V=a.stackAlloc(k*i),Q=a.stackAlloc(k*i);try{[E,A]=sE(o),Sr("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)await Hp(r[P],S,L,t,p[e[P]],e[P],h);for(let P=0;P<k;P++)await Hp(n[P],M,L,t,d[s[P]],x+s[P],h);Or("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)a.setValue(G+P*i,S[P],"*"),a.setValue(X+P*i,p[e[P]],"*");for(let P=0;P<k;P++)a.setValue(V+P*i,M[P],"*"),a.setValue(Q+P*i,d[s[P]],"*");if(m&&!g){let{handle:P,outputPreferredLocations:se,outputPreferredLocationsEncoded:ie}=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}).`);Sr("wasm bindInputsOutputs");for(let O=0;O<x;O++){let N=e[O];await a._OrtBindInput(P,p[N],S[O])!==0&&Oe(`Can't bind input[${O}] for session=${t}.`)}for(let O=0;O<k;O++){let N=s[O];n[O]?.[3]?(C.push(M[O]),a._OrtBindOutput(P,d[N],M[O],0)!==0&&Oe(`Can't bind pre-allocated output[${O}] for session=${t}.`)):a._OrtBindOutput(P,d[N],0,ie[N])!==0&&Oe(`Can't bind output[${O}] to ${se[O]} for session=${t}.`)}Or("wasm bindInputsOutputs"),Tr.set(t,[c,p,d,m,h,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let Y;m?Y=await a._OrtRunWithBinding(c,m.handle,k,V,E):Y=await a._OrtRun(c,X,G,x,Q,k,V,E),Y!==0&&Oe("failed to call OrtRun().");let K=[],U=[];Sr("wasm ProcessOutputTensor");for(let P=0;P<k;P++){let se=Number(a.getValue(V+P*i,"*"));if(se===M[P]||C.includes(M[P])){K.push(n[P]),se!==M[P]&&a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.");continue}let ie=a.stackSave(),O=a.stackAlloc(4*i),N=!1,$,te=0;try{a._OrtGetTensorData(se,O,O+i,O+2*i,O+3*i)!==0&&Oe(`Can't access output tensor data on index ${P}.`);let ue=i===4?"i32":"i64",Ue=Number(a.getValue(O,ue));te=a.getValue(O+i,"*");let Ce=a.getValue(O+i*2,"*"),kt=Number(a.getValue(O+i*3,ue)),Qe=[];for(let Te=0;Te<kt;Te++)Qe.push(Number(a.getValue(Ce+Te*i,ue)));a._OrtFree(Ce)!==0&&Oe("Can't free memory for tensor dims.");let Ze=Qe.reduce((Te,xe)=>Te*xe,1);$=Zi(Ue);let rt=m?.outputPreferredLocations[s[P]];if($==="string"){if(rt==="gpu-buffer"||rt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Te=[];for(let xe=0;xe<Ze;xe++){let Ge=a.getValue(te+xe*i,"*"),Et=a.getValue(te+(xe+1)*i,"*"),we=xe===Ze-1?void 0:Et-Ge;Te.push(a.UTF8ToString(Ge,we))}K.push([$,Qe,Te,"cpu"])}else if(rt==="gpu-buffer"&&Ze>0){let Te=a.webgpuGetBuffer;if(!Te)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=Te(te),Ge=Gs(Ue,Ze);if(Ge===void 0||!cf($))throw new Error(`Unsupported data type: ${$}`);N=!0;{a.webgpuRegisterBuffer(xe,t,te);let Et=a.webgpuCreateDownloader(xe,Ge,t);K.push([$,Qe,{gpuBuffer:xe,download:async()=>{let we=await Et();return new(Yn($))(we)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.")}},"gpu-buffer"])}}else if(rt==="ml-tensor"&&Ze>0){let Te=a.webnnEnsureTensor,xe=a.webnnIsGraphInputOutputTypeSupported;if(!Te||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Gs(Ue,Ze)===void 0||!uf($))throw new Error(`Unsupported data type: ${$}`);if(!xe(t,$,!1))throw new Error(`preferredLocation "ml-tensor" for ${$} output is not supported by current WebNN Context.`);let Ge=await Te(t,te,Ue,Qe,!1);N=!0,K.push([$,Qe,{mlTensor:Ge,download:a.webnnCreateMLTensorDownloader(te,$),dispose:()=>{a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(rt==="ml-tensor-cpu-output"&&Ze>0){let Te=a.webnnCreateMLTensorDownloader(te,$)(),xe=K.length;N=!0,U.push((async()=>{let Ge=[xe,await Te];return a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se),Ge})()),K.push([$,Qe,[],"cpu"])}else{let Te=Yn($),xe=new Te(Ze);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(a.HEAPU8.subarray(te,te+xe.byteLength)),K.push([$,Qe,xe,"cpu"])}}finally{a.stackRestore(ie),$==="string"&&te&&a._free(te),N||a._OrtReleaseTensor(se)}}m&&!h&&(a._OrtClearBoundOutputs(m.handle)!==0&&Oe("Can't clear bound outputs."),Tr.set(t,[c,p,d,m,h,!1]));for(let[P,se]of await Promise.all(U))K[P][2]=se;return Or("wasm ProcessOutputTensor"),K}finally{a.webnnOnRunEnd?.(c),a.stackRestore(v),r.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),n.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),S.forEach(Y=>a._OrtReleaseTensor(Y)),M.forEach(Y=>a._OrtReleaseTensor(Y)),L.forEach(Y=>a._free(Y)),E!==0&&a._OrtReleaseRunOptions(E),A.forEach(Y=>a._free(Y))}},wf=t=>{let e=Be(),r=Tr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Oe("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}}),Mr,Dt,js,Vn,Hn,Qi,Xp,Ji,as,is,Ok,dE,mE,hE,_E,wE,gE,xE,yE=ye(()=>{"use strict";ds(),fE(),ms(),of(),Mr=()=>!!qe.wasm.proxy&&typeof document<"u",js=!1,Vn=!1,Hn=!1,Ji=new Map,as=(t,e)=>{let r=Ji.get(t);r?r.push(e):Ji.set(t,[e])},is=()=>{if(js||!Vn||Hn||!Dt)throw new Error("worker not ready")},Ok=t=>{switch(t.data.type){case"init-wasm":js=!1,t.data.err?(Hn=!0,Xp[1](t.data.err)):(Vn=!0,Xp[0]()),Qi&&(URL.revokeObjectURL(Qi),Qi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Ji.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},dE=async()=>{if(!Vn){if(js)throw new Error("multiple calls to 'initWasm()' detected.");if(Hn)throw new Error("previous call to 'initWasm()' failed.");if(js=!0,Mr())return new Promise((t,e)=>{Dt?.terminate(),tE().then(([r,s])=>{try{Dt=s,Dt.onerror=o=>e(o),Dt.onmessage=Ok,Xp=[t,e];let n={type:"init-wasm",in:qe};!n.in.wasm.wasmPaths&&(r||Kp)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Dt.postMessage(n),Qi=r}catch(n){e(n)}},e)});try{await af(qe.wasm),await ff(qe),Vn=!0}catch(t){throw Hn=!0,t}finally{js=!1}}},mE=async t=>{if(Mr())return is(),new Promise((e,r)=>{as("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:qe}};Dt.postMessage(s)});await df(qe,t)},hE=async t=>Mr()?(is(),new Promise((e,r)=>{as("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Dt.postMessage(s,[t.buffer])})):nl(t),_E=async(t,e)=>{if(Mr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return is(),new Promise((r,s)=>{as("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Dt.postMessage(n,o)})}else return mf(t,e)},wE=async t=>{if(Mr())return is(),new Promise((e,r)=>{as("release",[e,r]);let s={type:"release",in:t};Dt.postMessage(s)});hf(t)},gE=async(t,e,r,s,n,o)=>{if(Mr()){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 is(),new Promise((a,i)=>{as("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Dt.postMessage(c,gf(l))})}else return _f(t,e,r,s,n,o)},xE=async t=>{if(Mr())return is(),new Promise((e,r)=>{as("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Dt.postMessage(s)});wf(t)}}),Yp,Ik,bE,mP=ye(()=>{"use strict";ds(),yE(),Ws(),nf(),oE(),Yp=(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()}`)}},Ik=t=>{switch(t[3]){case"cpu":return new Jt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!cf(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Jt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!uf(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Jt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},bE=class{async fetchModelAndCopyToWasmMemory(t){return hE(await pf(t))}async loadModel(t,e){ps();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await _E(r,e),fs()}async dispose(){return wE(this.sessionId)}async run(t,e,r){ps();let s=[],n=[];Object.entries(t).forEach(d=>{let m=d[0],h=d[1],g=this.inputNames.indexOf(m);if(g===-1)throw new Error(`invalid input '${m}'`);s.push(h),n.push(g)});let o=[],a=[];Object.entries(e).forEach(d=>{let m=d[0],h=d[1],g=this.outputNames.indexOf(m);if(g===-1)throw new Error(`invalid output '${m}'`);o.push(h),a.push(g)});let i=s.map((d,m)=>Yp(d,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((d,m)=>d?Yp(d,()=>`output "${this.outputNames[a[m]]}"`):null),c=await gE(this.sessionId,n,i,a,l,r),p={};for(let d=0;d<c.length;d++)p[this.outputNames[a[d]]]=o[d]??Ik(c[d]);return fs(),p}startProfiling(){}endProfiling(){xE(this.sessionId)}}}),vE={};Kn(vE,{OnnxruntimeWebAssemblyBackend:()=>ef,initializeFlags:()=>Zp,wasmBackend:()=>kE});var Zp,ef,kE,hP=ye(()=>{"use strict";ds(),yE(),mP(),Zp=()=>{(typeof qe.wasm.initTimeout!="number"||qe.wasm.initTimeout<0)&&(qe.wasm.initTimeout=0);let t=qe.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.`),qe.wasm.simd=!1),typeof qe.wasm.proxy!="boolean"&&(qe.wasm.proxy=!1),typeof qe.wasm.trace!="boolean"&&(qe.wasm.trace=!1),typeof qe.wasm.numThreads!="number"||!Number.isInteger(qe.wasm.numThreads)||qe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)qe.wasm.numThreads=1;else{let e=typeof navigator>"u"?VC("node:os").cpus().length:navigator.hardwareConcurrency;qe.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},ef=class{async init(t){Zp(),await dE(),await mE(t)}async createInferenceSessionHandler(t,e){let r=new bE;return await r.loadModel(t,e),r}},kE=new ef});ds();ds();ds();var _P="1.25.0-dev.20260209-a3749f1353",wP=Yk;{let t=(hP(),el(vE)).wasmBackend;us("webgpu",t,5),us("webnn",t,5),us("cpu",t,10),us("wasm",t,10)}Object.defineProperty(qe.versions,"web",{value:_P,enumerable:!0});async function EE(t){let e=t.split("/").pop(),r;try{if(r=await Gi(),r){let n=await r.match(t);if(n)return n}}catch(n){console.warn(`Failed to load ${e} from cache:`,n)}let s=await 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){console.warn(`Failed to cache ${e}:`,n)}return s}async function AE(t){let e=await EE(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return console.warn("Failed to read WASM binary:",r),null}}async function TE(t){let e=await EE(t);if(!e||typeof e=="string")return null;try{let r=await e.text(),s=t.split("/").slice(0,-1).join("/");r=r.replace(/import\.meta\.url/g,`"${s}"`);let n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return console.warn("Failed to read WASM binary:",r),null}}function yf(t){return Ds(t,["blob:"])}function bf(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 ME="1.24.1";var SE="warning",vf={wasm:{},webgl:{},webgpu:{},versions:{common:ME},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}`);SE=t}},get logLevel(){return SE}};Object.defineProperty(vf,"logLevel",{enumerable:!0});var OE=(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,h=p*2,g=-1;a==="RGBA"?(d=0,m=p,h=p*2,g=p*3):a==="RGB"?(d=0,m=p,h=p*2):a==="RBG"&&(d=0,h=p,m=p*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let E=(t.data[d++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[h++]-c[2])*l[2],M=g===-1?255:(t.data[g++]-c[3])*l[3];s.fillStyle="rgba("+E+","+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")},IE=(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,h=0,g=1,x=2,k=3,E=0,A=d,S=d*2,M=-1;i==="RGBA"?(E=0,A=d,S=d*2,M=d*3):i==="RGB"?(E=0,A=d,S=d*2):i==="RBG"&&(E=0,S=d,A=d*2),s=r.createImageData(n,o);for(let L=0;L<o*n;h+=m,g+=m,x+=m,k+=m,L++)s.data[h]=(t.data[E++]-p[0])*c[0],s.data[g]=(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 kf=(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,h=1,g=2,x=3,k=0,E=c,A=c*2,S=-1;i==="RGB"&&(d=3,m=0,h=1,g=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,k=c*2);for(let L=0;L<c;L++,m+=d,g+=d,h+=d,x+=d)p[k++]=(t[m]+a[0])/o[0],p[E++]=(t[h]+a[1])/o[1],p[A++]=(t[g]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new dt("float32",p,[1,4,r,s]):new dt("float32",p,[1,3,r,s])},CE=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,h=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,h=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=h}else i.tensorFormat="RGBA",i.height=m,i.width=h;d.drawImage(t,0,0),a=d.getImageData(0,0,h,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 h=c(m);if(h!=null)h.putImageData(t,0,0),a=h.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,h=t.width;return d.drawImage(t,0,0,h,m),a=d.getImageData(0,0,h,m).data,i.height=m,i.width=h,kf(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{let m=l(),h=c(m);if(!t||!h)return d();let g=new Image;g.crossOrigin="Anonymous",g.src=t,g.onload=()=>{m.width=g.width,m.height=g.height,h.drawImage(g,0,0,m.width,m.height);let x=h.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,p(kf(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return kf(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},PE=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new dt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},LE=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new dt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},NE=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new dt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},zE=(t,e,r)=>new dt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var hs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Qn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),RE=!1,$E=()=>{if(!RE){RE=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(hs.set("int64",BigInt64Array),Qn.set(BigInt64Array,"int64")),e&&(hs.set("uint64",BigUint64Array),Qn.set(BigUint64Array,"uint64")),s?(hs.set("float16",r),Qn.set(r,"float16")):hs.set("float16",Uint16Array)}};var BE=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},UE=(t,e)=>{switch(t.location){case"cpu":return new dt(t.type,t.data,e);case"cpu-pinned":return new dt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new dt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new dt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new dt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var dt=class{constructor(e,r,s){$E();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=hs.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=hs.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=Qn.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=BE(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 CE(e,r)}static fromTexture(e,r){return PE(e,r)}static fromGpuBuffer(e,r){return LE(e,r)}static fromMLTensor(e,r){return NE(e,r)}static fromPinnedBuffer(e,r,s){return zE(e,r,s)}toDataURL(e){return OE(this,e)}toImageData(e){return IE(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 UE(this,e)}};var ol=dt;var gP=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"}}),xP=["verbose","info","warning","error","fatal"],GE=4,Ft=[],Ef,Vs,DE=Symbol.for("onnxruntime");if(DE in globalThis)Vs=globalThis[DE];else if(be.IS_NODE_ENV){switch(Vs=Sp,process.platform){case"win32":Ft.push("dml");break;case"linux":process.arch==="x64"&&Ft.push("cuda");break;case"darwin":Ft.push("coreml");break}Ft.push("webgpu"),Ft.push("cpu"),Ef=["cpu"]}else Vs=xf,be.IS_WEBNN_AVAILABLE&&Ft.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),be.IS_WEBGPU_AVAILABLE&&Ft.push("webgpu"),Ft.push("wasm"),Ef=["wasm"];var yP=Vs.InferenceSession;function WE(t=null){if(!t)return Ef;switch(t){case"auto":return Ft;case"gpu":return Ft.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Ft.includes(t))return[gP[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Ft.join(", ")}.`)}var qE=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV,FE=Promise.resolve(),qs=null;async function bP(){return qs||(De.useWasmCache&&typeof mt?.wasm?.wasmPaths=="object"&&mt?.wasm?.wasmPaths?.wasm&&mt?.wasm?.wasmPaths?.mjs?(qs=(async()=>{let e=mt.wasm.wasmPaths;await Promise.all([e.wasm&&!yf(e.wasm)?(async()=>{try{let r=await AE(bf(e.wasm));r&&(mt.wasm.wasmBinary=r)}catch(r){console.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!yf(e.mjs)?(async()=>{try{let r=await TE(bf(e.mjs));r&&(mt.wasm.wasmPaths.mjs=r)}catch(r){console.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),qs):(qs=Promise.resolve(),qs))}async function al(t,e,r){await bP();let s=()=>yP.create(t,{logSeverityLevel:GE,...e}),n=await(qE?FE=FE.then(s):s());return n.config=r,n}var jE=Promise.resolve();async function il(t,e){let r=()=>t.run(e);return await(qE?jE=jE.then(r):r())}function ll(t){return t instanceof Vs.Tensor}var mt=Vs?.env;mt.logLevel=xP[GE];if(mt?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&mt.versions?.web&&!mt.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${mt.versions.web}/dist/`;mt.wasm.wasmPaths=be.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}mt.wasm.proxy=!1}mt?.webgpu&&(mt.webgpu.powerPreference="high-performance");function Jn(){return mt?.wasm?.proxy}De.backends.onnx=mt;var Ir=async(t,e,r)=>{let s=await al(new Uint8Array(t),e);return(async n=>{let o=Jn(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await il(s,a);return Array.isArray(r)?r.map(l=>new B(i[l])):new B(i[r])})},ir=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Ir([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=Ir([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=Ir([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=Ir([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=Ir([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=Ir([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=Ir([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=Ir([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 VE=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"});var HE=(function(){let t;return async function(){if(t===void 0)if(!be.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),ht=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Af=Object.freeze({[VE.wasm]:ht.q8}),Tf=Object.freeze({[ht.fp32]:"",[ht.fp16]:"_fp16",[ht.int8]:"_int8",[ht.uint8]:"_uint8",[ht.q8]:"_quantized",[ht.q4]:"_q4",[ht.q4f16]:"_q4f16",[ht.bnb4]:"_bnb4"}),Hs=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 B=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 ll(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new ol(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=lr(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 vP(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=lr(d,this.dims[p],p),s.push([d,d+1]);else if(Array.isArray(d)&&d.length===2){let[m,h]=d;if(m=m===null?0:lr(m,this.dims[p],p,!1),h=h===null?this.dims[p]:lr(h,this.dims[p],p,!1),m>h)throw new Error(`Invalid slice: ${d}`);let g=[Math.max(m,0),Math.min(h,this.dims[p])];s.push(g),r.push(g[1]-g[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 h=0;h<m.length;++h)i[h]=m[h]}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,h=p;m>=0;--m){let g=n[m];d+=(h%g+s[m][0])*l[m],h=Math.floor(h/g)}i[p]=a[d]}return new t(this.type,i,r)}permute(...e){return kP(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=(c,p)=>c+p**e;if(r===null){let c=n.reduce(o,0)**(1/e);return new t(this.type,[c],[])}let[a,i,l]=Zn(o,this,r,s);if(e!==1)for(let c=0;c<i.length;++c)i[c]=i[c]**(1/e);return new t(a,i,l)}normalize_(e=2,r=1){r=lr(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 Mf(this.dims)}squeeze(e=null){return new t(this.type,this.data,XE(this.dims,e))}squeeze_(e=null){return this.dims=XE(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,YE(this.dims,e))}unsqueeze_(e){return this.dims=YE(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 pl(this,e,r)}min(e=null,r=!1){if(e===null){let a=jn(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Zn((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=Me(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Zn((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=jn(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=Me(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=Mf(s),c=Mf(n);for(let p=0;p<o;++p){let d=p,m=0;for(let h=0;h<n.length;++h){let g=Math.floor(d/c[h]);d=d%c[h];let x=g%s[h];m+=x*l[h]}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(!Hs.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,sk(this.data),this.dims);return new t(e,Hs[e].from(this.data,r),this.dims)}};function vP(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 kP(t,e){let[r,s]=Qv(t.data,t.dims,e);return new B(t.type,r,s)}function Sf(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=Kv(t.data,[o,a,i],[e,r],s,n);return new B(t.type,l,[o,e,r])}async function jt(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 ir.nearest_interpolate_4d;else if(r==="bilinear")n=await ir.bilinear_interpolate_4d;else if(r==="bicubic")n=await ir.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new B("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function KE(t,e){return await(await ir.matmul)({a:t,b:e})}async function y3(t,e){return await(await ir.rfft)({x:t,a:e})}async function Zt(t,e){let r=await ir.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new B("int64",[BigInt(e)],[1])})}var cl=t=>new B("int64",t,[t.length]);async function ul(t,e,r,s,n){return await(await ir.slice)({x:t,s:cl(e),e:cl(r),a:cl(s),t:cl(n??new Array(s.length).fill(1))})}function QE(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 h=0,g=0,x=p*i,k=d+m;for(let A=0;A<i;++A){let S=Number(s[x+A]);g+=S,h+=r[k+A*l]*S}let E=h/g;o[c++]=E}}return new B(t.type,o,n)}function b3(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]=Of(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 h=0;h<n;++h){let g=m+h;p[g]=(c[g]-l[d])/(i[d]+r)}}return new B(t.type,p,t.dims)}function XE(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 YE(t,e){return e=lr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function lr(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 Ee(t,e=0){e=lr(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,h=p,g=1;m>=0;--m){let x=c[m],k=h%x;m===e&&(k+=a),d+=k*g,g*=r[m],h=Math.floor(h/x)}n[d]=l[p]}a+=c[e]}}return new B(o,n,r)}function Gt(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function Zn(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=lr(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,h=1;d>=0;--d){let g=a[d];if(d!==r){let x=m%g;p+=x*h,h*=i[d]}m=Math.floor(m/g)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function Of(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let h=n.reduce((E,A)=>E+A,0)/n.length,g=Math.sqrt(n.reduce((E,A)=>E+(A-h)**2,0)/(n.length-r)),x=new B(t.type,[h],[]);return[new B(t.type,[g],[]),x]}e=lr(e,o.length);let a=pl(t,e,s),i=a.data,[l,c,p]=Zn((m,h,g,x)=>m+(h-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 B(l,c,p),a]}function pl(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 B(t.type,[l/n.length],[])}e=lr(e,s.length);let[o,a,i]=Zn((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 B(o,a,i)}function Mf(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 If(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new B(r,new s(n).fill(e),t)}function Ve(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 If(t,e,r,s)}function eo(t,e){return Ve(t.dims,e)}function it(t){return If(t,1n,"int64",BigInt64Array)}function fl(t){return it(t.dims)}function Cf(t){return If(t,0n,"int64",BigInt64Array)}function Pf(t){return Cf(t.dims)}function v3(t){let e=t.reduce((r,s)=>r*s,1);return new B("float32",Float32Array.from({length:e},()=>Math.random()),t)}function JE(t){let e=t.reduce((s,n)=>s*n,1),r=new Float32Array(e);for(let s=0;s<e;s+=2){let n=1-Math.random(),o=Math.random(),a=Math.sqrt(-2*Math.log(n)),i=2*Math.PI*o;r[s]=a*Math.cos(i),s+1<e&&(r[s+1]=a*Math.sin(i))}return new B("float32",r,t)}function ZE(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 B(s,a,[t.dims[0],t.dims[1]/8])}async function Lf(t,e){return await Promise.all([at(t,"tokenizer.json",!0,e),at(t,"tokenizer_config.json",!0,e)])}function Nf(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 EP=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function AP(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"?ft(t[n],i):ft(i,t[n])}}function TP(t,e){for(let r of Object.keys(t))t[r].length=e}function _s(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 MP(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var j=class extends Je{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new Mv(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=_s(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=_s(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=_s(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=_s(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=_s(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=_s(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=MP(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 Lf(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,h)=>this._encode_plus(m,{text_pair:r[h],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?(console.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&&(console.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(Me(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&&TP(p[m],a):n&&AP(p[m],a,h=>h==="input_ids"?this.pad_token_id:0,this.padding_side));let d={};if(i){if(!(n&&o)&&p.some(h=>{for(let g of Object.keys(h))if(h[g].length!==p[0][g]?.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 h of Object.keys(p[0]))d[h]=new B("int64",BigInt64Array.from(p.flatMap(g=>g[h]).map(BigInt)),m)}else{for(let m of Object.keys(p[0]))d[m]=p.map(h=>h[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 B&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof B&&(e=Nf(e)),!Array.isArray(e)||e.length===0||!Dv(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={},...h}={}){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 g=this._compiled_template_cache.get(n);g===void 0&&(g=new Uv(n),this._compiled_template_cache.set(n,g));let x=Object.create(null);for(let E of EP){let A=_s(this.config,E);A&&(x[E]=A)}let k=g.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,...h});if(a){let E=this._call(k,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:p,...m});return d?E:E.input_ids}return k}};function Xs(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 Ad={};ts(Ad,{AlbertTokenizer:()=>zf,AutoTokenizer:()=>J,BartTokenizer:()=>Rf,BertTokenizer:()=>$f,BlenderbotSmallTokenizer:()=>Bf,BlenderbotTokenizer:()=>Uf,BloomTokenizer:()=>Df,CLIPTokenizer:()=>jf,CamembertTokenizer:()=>Ff,CodeGenTokenizer:()=>Wf,CodeLlamaTokenizer:()=>Gf,CohereTokenizer:()=>qf,ConvBertTokenizer:()=>Vf,DebertaTokenizer:()=>Xf,DebertaV2Tokenizer:()=>Hf,DistilBertTokenizer:()=>Yf,ElectraTokenizer:()=>Kf,EsmTokenizer:()=>Qf,FalconTokenizer:()=>Jf,GPT2Tokenizer:()=>td,GPTNeoXTokenizer:()=>ed,GemmaTokenizer:()=>Zf,HerbertTokenizer:()=>rd,LlamaTokenizer:()=>sd,M2M100Tokenizer:()=>nd,MBart50Tokenizer:()=>ad,MBartTokenizer:()=>to,MPNetTokenizer:()=>cd,MarianTokenizer:()=>od,MgpstrTokenizer:()=>id,MobileBertTokenizer:()=>ld,NllbTokenizer:()=>ud,NougatTokenizer:()=>pd,PreTrainedTokenizer:()=>j,Qwen2Tokenizer:()=>fd,RoFormerTokenizer:()=>md,RobertaTokenizer:()=>dd,SiglipTokenizer:()=>hd,SpeechT5Tokenizer:()=>_d,SqueezeBertTokenizer:()=>wd,T5Tokenizer:()=>gd,TokenizersBackend:()=>j,VitsTokenizer:()=>yd,Wav2Vec2CTCTokenizer:()=>bd,WhisperTokenizer:()=>vd,XLMRobertaTokenizer:()=>kd,XLMTokenizer:()=>Ed});var zf=class extends j{return_token_type_ids=!0};var Rf=class extends j{};var $f=class extends j{return_token_type_ids=!0};var Bf=class extends j{};var Uf=class extends j{};var Df=class extends j{};var Ff=class extends j{};var jf=class extends j{};var Gf=class extends j{};var Wf=class extends j{};var qf=class extends j{};var Vf=class extends j{return_token_type_ids=!0};var Hf=class extends j{return_token_type_ids=!0};var Xf=class extends j{return_token_type_ids=!0};var Yf=class extends j{};var Kf=class extends j{return_token_type_ids=!0};var Qf=class extends j{};var Jf=class extends j{};var Zf=class extends j{};var ed=class extends j{};var td=class extends j{};var rd=class extends j{return_token_type_ids=!0};var sd=class extends j{padding_side="left"};var nd=class extends j{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 Xs(this,e,r,s)}};var od=class extends j{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)),console.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)||console.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),ft([n],super._encode_text(o))}}};var to=class extends j{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 Xs(this,e,r,s)}};var ad=class extends to{};var id=class extends j{};var ld=class extends j{return_token_type_ids=!0};var cd=class extends j{};var ud=class extends j{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 Xs(this,e,r,s)}};var pd=class extends j{};var fd=class extends j{};var dd=class extends j{};var md=class extends j{return_token_type_ids=!0};var hd=class extends j{};var _d=class extends j{};var wd=class extends j{return_token_type_ids=!0};var gd=class extends j{};var xd=class extends Bt{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},yd=class extends j{constructor(e,r){super(e,r),this._tokenizer.decoder=new xd({type:"VitsDecoder"})}};var bd=class extends j{};var eA=[["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"]],ro=new Map(eA),SP=new Map([...eA.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 tA(t){t=t.toLowerCase();let e=SP.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),ro.has(t))e=t;else{let n=t.length===2?ro.keys():ro.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var OP="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",rA=new RegExp(`^[${OP}]+$`,"gu"),vd=class extends j{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,g=m+1500,x=[],k=[],E=!1,A=null,S=new Set(this.all_special_ids);for(let C of e){let v=C.tokens,G=i?C.token_timestamps:null,X=null,V=m;if("stride"in C){let[K,U,P]=C.stride;if(d-=U,A=K-P,U&&(V=U/n+m),P)for(let se=v.length-1;se>=0;--se){let ie=Number(v[se]);if(ie>=m){if(X!==null&&(ie-m)*n<A)break;X=ie}}}let Q=[],Y=[];for(let K=0;K<v.length;++K){let U=Number(v[K]);if(S.has(U)){let P=this.decode([U]),se=ro.get(P.slice(2,-2));if(se!==void 0){if(a!==null&&se!==a&&!r){x.push(Q);let ie=this.findLongestCommonSequence(x)[0],O=this.decode(ie);p.text=O,c.push(p),x=[],Q=[],p=l()}a=p.language=se}}else if(U>=m&&U<=g){let P=(U-m)*n+d,se=os(P,2);if(X!==null&&U>=X)E=!0;else if(E||x.length>0&&U<V)E=!1;else if(p.timestamp[0]===null)p.timestamp[0]=se;else if(se!==p.timestamp[0]){p.timestamp[1]=se,x.push(Q),i&&k.push(Y);let[ie,O]=this.findLongestCommonSequence(x,k),N=this.decode(ie);p.text=N,i&&(p.words=this.collateWordTimestamps(ie,O,a)),c.push(p),x=[],Q=[],k=[],Y=[],p=l()}}else if(Q.push(U),i){let P=os(G[K]+d,2),se;if(K+1<G.length){se=os(G[K+1]+d,2);let ie=this.decode([U]);rA.test(ie)&&(se=os(Math.min(P+n,se),2))}else se=null;Y.push([P,se])}}if("stride"in C){let[K,U,P]=C.stride;d+=K-P}Q.length>0?(x.push(Q),i&&k.push(Y)):x.every(K=>K.length===0)&&(p=l(),x=[],Q=[],k=[],Y=[])}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[C,v]=this.findLongestCommonSequence(x,k),G=this.decode(C);p.text=G,i&&(p.words=this.collateWordTimestamps(C,v,a)),c.push(p)}let M=Object.create(null),L=c.map(C=>C.text).join("");if(r||s){for(let C=0;C<c.length;++C){let v=c[C];r||delete v.timestamp,s||delete v.language}if(i){let C=[];for(let v of c)for(let G of v.words)C.push(G);M={chunks:C}}else M={chunks:c}}return[L,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],h=p.length;for(let M=1;M<n+h;++M){let L=Math.max(0,n-M),C=Math.min(n,n+h-M),v=s.slice(L,C),G=Math.max(0,M-n),X=Math.min(h,M),V=p.slice(G,X);if(v.length!==V.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let Q;a?Q=v.filter((U,P)=>U===V[P]&&l[L+P]<=r[c][G+P]).length:Q=v.filter((U,P)=>U===V[P]).length;let Y=M/1e4,K=Q/M+Y;Q>1&&K>d&&(d=K,m=[L,C,G,X])}let[g,x,k,E]=m,A=Math.floor((x+g)/2),S=Math.floor((E+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 B&&(e=Nf(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|>"),h=c.startsWith(" "),g=c.trim(),x=rA.test(g);if(m||h||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]=ft(i[c],i[p]),l[p]=ft(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]=ft(i[c],i[p]),l[c]=ft(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 kd=class extends j{};var Ed=class extends j{return_token_type_ids=!0;constructor(e,r){super(e,r),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var J=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 Lf(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=Ad[c];return p||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=j),new p(i,l)}};var Ys="https://github.com/huggingface/transformers.js/issues/new/choose";var so="preprocessor_config.json",Ks=so,sA="processor_config.json",nA="chat_template.jinja";var ne=class extends Je{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?at(e,sA,!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?Ap(e,nA,!0,r):null]);return new this(s,n,o)}};var $l={};ts($l,{ChatterboxProcessor:()=>Dd,Florence2Processor:()=>Im,Gemma3nProcessor:()=>Cm,GroundingDinoProcessor:()=>Pm,Idefics3Processor:()=>Nl,JinaCLIPProcessor:()=>Nm,LlavaProcessor:()=>zm,MgpstrProcessor:()=>Rm,MoonshineProcessor:()=>$m,OwlViTProcessor:()=>Bm,PaliGemmaProcessor:()=>Um,Phi3VProcessor:()=>Dm,PixtralProcessor:()=>Fm,Processor:()=>ne,PyAnnoteProcessor:()=>jm,Qwen2VLProcessor:()=>Gm,Sam2Processor:()=>zl,Sam2VideoProcessor:()=>Wm,SamProcessor:()=>uo,SmolVLMProcessor:()=>Nl,SpeechT5Processor:()=>qm,UltravoxProcessor:()=>Vm,VLChatProcessor:()=>Lm,VoxtralProcessor:()=>Hm,Wav2Vec2Processor:()=>Xm,Wav2Vec2ProcessorWithLM:()=>Ym,WhisperProcessor:()=>Km});var ze=class extends Je{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await at(e,so,!0,r);return new this(s)}};function He(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 lo={};ts(lo,{ASTFeatureExtractor:()=>Sd,ChatterboxFeatureExtractor:()=>Od,ClapFeatureExtractor:()=>Id,DacFeatureExtractor:()=>ao,EncodecFeatureExtractor:()=>oo,FeatureExtractor:()=>ze,Gemma3nAudioFeatureExtractor:()=>Cd,MoonshineFeatureExtractor:()=>Pd,ParakeetFeatureExtractor:()=>Ld,PyAnnoteFeatureExtractor:()=>io,SeamlessM4TFeatureExtractor:()=>Nd,SnacFeatureExtractor:()=>zd,SpeechT5FeatureExtractor:()=>Rd,Wav2Vec2FeatureExtractor:()=>$d,WeSpeakerFeatureExtractor:()=>Bd,WhisperFeatureExtractor:()=>Ud});var IP=()=>{};var oA={fromWeb:IP};var CP=()=>{};var aA=CP;async function dl(t,e){if(be.IS_BROWSER_ENV){if(be.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(be.IS_FS_AVAILABLE){let r=e.stream(),s=oA.fromWeb(r),n=Tt.createWriteStream(t);await aA(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function Md(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 Fs(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&console.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 cA(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 iA(t){return cA(t,.5)}function PP(t){return cA(t,.54)}var LP={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 Td(t,e="htk"){let r=LP[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 NP={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 zP(t,e="htk"){let r=NP[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 RP(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 lA(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+s*o)}function bt(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=Td(r,a),c=Td(s,a),p=lA(l,c,e+2),d=zP(p,a),m;if(i){let g=n/((t-1)*2);m=Td(Float64Array.from({length:t},(x,k)=>k*g),a),d=p}else m=lA(0,Math.floor(n/2),t);let h=RP(m,d);if(o!==null&&o==="slaney")for(let g=0;g<e;++g){let x=h[g],k=2/(d[g+2]-d[g]);for(let E=0;E<t;++E)x[E]*=k}return h}function $P(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[Bs(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[Bs(n-o,n)];return s}function uA(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=Me(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function BP(t,e=1,r=1e-5,s=null){return uA(t,20,e,r,s)}function UP(t,e=1,r=1e-10,s=null){return uA(t,10,e,r,s)}async function Mt(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:h=null,reference:g=1,min_value:x=1e-10,db_range:k=null,remove_dc_offset:E=null,min_num_frames:A=null,max_num_frames:S=null,do_pad:M=!0,transpose:L=!1,mel_offset:C=0}={}){let v=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(v!==r)throw new Error(`Length of the window (${v}) 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 N=Math.floor((n-1)/2)+1;t=$P(t,N,N);break}case"constant":{let N=Math.floor(n/2),$=new t.constructor(t.length+2*N);$.set(t,N),t=$;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let G=Math.floor(1+Math.floor((t.length-r)/s));A!==null&&G<A&&(G=A);let X=l?Math.floor(n/2)+1:n,V=G,Q=G;S!==null&&(S>G?M&&(Q=S):Q=V=S);let Y=new qi(n),K=new Float64Array(n),U=new Float64Array(Y.outputBufferSize),P=new Float32Array(X*Q);for(let N=0;N<V;++N){let $=N*s,te=Math.min(t.length-$,r);te!==r&&K.fill(0,0,r);for(let ue=0;ue<te;++ue)K[ue]=t[$+ue];if(E){let ue=0;for(let Ce=0;Ce<te;++Ce)ue+=K[Ce];let Ue=ue/te;for(let Ce=0;Ce<te;++Ce)K[Ce]-=Ue}if(c!==null){for(let ue=te-1;ue>=1;--ue)K[ue]-=c*K[ue-1];K[0]*=1-c}for(let ue=0;ue<e.length;++ue)K[ue]*=e[ue];Y.realTransform(U,K);for(let ue=0;ue<X;++ue){let Ue=ue<<1;P[ue*Q+N]=U[Ue]**2+U[Ue+1]**2}}if(o!==null&&o!==2){let N=o/2;for(let $=0;$<P.length;++$)P[$]**=N}let se=d.length,ie=await KE(new B("float32",d.flat(),[se,X]),new B("float32",P,[X,Q]));L&&(ie=ie.transpose(1,0));let O=ie.data;for(let N=0;N<O.length;++N)O[N]=C+Math.max(m,O[N]);if(o!==null&&h!==null){let N=Math.min(O.length,V*se);switch(h){case"log":for(let $=0;$<N;++$)O[$]=Math.log(O[$]);break;case"log10":for(let $=0;$<N;++$)O[$]=Math.log10(O[$]);break;case"dB":if(o===1)BP(O,g,x,k);else if(o===2)UP(O,g,x,k);else throw new Error(`Cannot use log_mel option '${h}' with power ${o}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${h}'`)}}return ie}function St(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=iA(o);break;case"hamming":a=PP(o);break;case"povey":a=iA(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 DP(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return ml(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),ml(n,8,"WAVE"),ml(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),ml(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function ml(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]),DP(e,this.sampling_rate)}async save(e){return dl(e,this.toBlob())}};var Sd=class extends ze{constructor(e){super(e);let r=this.config.sampling_rate,s=bt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=St(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return Mt(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){He(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 oo=class extends ze{async _call(e){He(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 B("float32",e,s)}}};var Od=class extends ze{async _call(e){He(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new B("float32",e,r)}}};var Id=class extends ze{constructor(e){super(e),this.mel_filters=bt(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=bt(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=St(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(Math.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 Mt(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 He(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 ao=class extends oo{};var Cd=class extends ze{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=bt(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=St(i,"hann")}async _extract_fbank_features(e,r){return Mt(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(He(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=Ve([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Pd=class extends ze{async _call(e){He(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new B("float32",e,r)}}};var FP=1e-5,Ld=class extends ze{constructor(e){super(e),this.config.mel_filters??=bt(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=St(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 Mt(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){He(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 h=0;h<a;++h){let g=n[m+h];i[h]+=g,l[h]+=g*g}}let c=s>1?s-1:1;for(let d=0;d<a;++d){let m=i[d]/s,h=(l[d]-s*m*m)/c,x=1/(Math.sqrt(h)+FP);for(let k=0;k<s;++k){let E=k*a+d;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 B("int64",p,[1,o])}}};var io=class extends ze{async _call(e){He(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new B("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=Pe(o[l]),[p,d]=Me(c),[m,h]=[l,l+1];d!==i?(i=d,a.push({id:d,start:m,end:h,score:p})):(a.at(-1).end=h,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 Nd=class extends ze{constructor(e){super(e);let r=this.config.sampling_rate,s=bt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=St(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),Mt(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}={}){He(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[g,x]=a.dims,k=a.data;for(let E=0;E<x;++E){let A=0;for(let C=0;C<g;++C)A+=k[C*x+E];let S=A/g,M=0;for(let C=0;C<g;++C)M+=(k[C*x+E]-S)**2;M/=g-1;let L=Math.sqrt(M+1e-7);for(let C=0;C<g;++C){let v=C*x+E;k[v]=(k[v]-S)/L}}}let i;if(r){let[g,x]=a.dims,k=a.data,E=g%s;if(E>0){let A=new Float32Array(x*(g+E));A.set(k),A.fill(this.config.padding_value,k.length);let S=g+E;a=new B(a.type,A,[S,x]),o&&(i=new B("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,g))}}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),h={input_features:m};if(o){let g=m.dims[1],x=new BigInt64Array(g);if(i){let k=i.data;for(let E=1,A=0;E<l;E+=p,++A)x[A]=k[E]}else x.fill(1n);h.attention_mask=new B("int64",x,[1,g])}return h}};var zd=class extends ao{};var Rd=class extends ze{};var $d=class extends ze{_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){He(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 B("float32",r,s),attention_mask:new B("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Bd=class extends ze{constructor(e){super(e);let r=this.config.sampling_rate,s=bt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=St(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),Mt(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){He(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 h=0;h<i;++h)n[m+h]-=s[p+h]}}}return{input_features:r}}};var Ud=class extends ze{constructor(e){super(e),this.config.mel_filters??=bt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=St(this.config.n_fft,"hann")}async _extract_fbank_features(e){let r=await Mt(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)}),s=r.data,n=Me(s)[0];for(let o=0;o<s.length;++o)s[o]=(Math.max(s[o],n-8)+4)/4;return r}async _call(e,{max_length:r=null}={}){He(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&console.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 tt=class{static async from_pretrained(e,r={}){let s=await at(e,so,!0,r),n=s.feature_extractor_type,o=lo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Ys}.`);return new o(s)}};var Dd=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var jP={},hl=jP;var ws,pA,Cr,er=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV;if(er)ws=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},Cr=self.createImageBitmap,pA=self.ImageData;else if(hl)Cr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Xe(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 GP={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},WP=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Xe=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(!er)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 Fs(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(er){let r=await Cr(e),s=ws(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=hl(await e.arrayBuffer());return await Cr(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=GP[s]??s,o=kp(e),a=kp(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),er){let i=this.channels,l=this.toCanvas(),c=ws(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")&&(console.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 Cr(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(er){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,c=ws(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 Cr(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(er){let i=this.channels,l=this.toCanvas(),c=ws(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 Cr(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(er){let o=this.channels,a=this.toCanvas(),i=ws(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 Cr(o)}}async toBlob(e="image/png",r=1){if(!er)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 B("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(!er)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=ws(e.width,e.height),s=new pA(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(er){if(be.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=WP.get(r)??"image/png",n=await this.toBlob(s);return dl(e,n)}else if(be.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(er)throw new Error("toSharp() is only supported in server-side environments.");return hl(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},qP=Xe.read.bind(Xe);function fA(t,e,r=0,s=null){let n=t/e,o=tk(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function Fd([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function jd([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Pr(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:[]},h=n[p],g=o[p];for(let x=0;x<i;++x){let k=h[x],E=[],A;if(s){A=k.sigmoid().data;for(let S=0;S<A.length;++S)A[S]>e&&E.push(S)}else{let S=Me(k.data)[1];if(S===l-1||(A=Pe(k.data),A[S]<e))continue;E.push(S)}for(let S of E){let M=g[x].data;M=jd(M),d!==null&&(M=M.map((L,C)=>L*d[(C+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(A[S])}}c.push(m)}return c}function _l(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=Sf(i,a,"bilinear",!1));let[l,c]=a??i.dims.slice(-2),p=new B("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 E=0;E<k.length;++E)k[E]>d[E]&&(d[E]=k[E],m[E]=x)}let h=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let k=m[x];h[k]=k}let g=h.filter(x=>x!==void 0);n.push({segmentation:p,labels:g})}return n}function VP(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=Me(l.data)[1];if(p===s)continue;let m=Pe(l.data)[p];m>r&&(n.push(c),o.push(m),a.push(p))}return[n,o,a]}function HP(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 XP(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new B("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=Sf(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],E=t[x].data;for(let A=0;A<E.length;++A)E[A]*=k,E[A]>m[A]&&(d[A]=x,m[A]=E[A])}let h=0,g=c.data;for(let x=0;x<r.length;++x){let k=r[x],[E,A]=HP(d,t,x,s,n);if(E){++h;for(let S of A)g[S]=h;p.push({id:h,label_id:k,score:e[x]})}}return[c,p]}function YP(t,e,r=28,s=3136,n=784*1280){if(t<r||e<r)throw new Error(`height:${t} or width:${e} must be larger than factor:${r}`);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 o=Math.round(t/r)*r,a=Math.round(e/r)*r;if(o*a>n){let i=Math.sqrt(t*e/n);o=Math.floor(t/i/r)*r,a=Math.floor(e/i/r)*r}else if(o*a<s){let i=Math.sqrt(s/(t*e));o=Math.ceil(t*i/r)*r,a=Math.ceil(e*i/r)*r}return[o,a]}function wl(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(console.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 h=0;h<c;++h){let g=o!==null?o[h]:null,x=a[h],k=l[h],[E,A,S]=VP(x,k,e,d);if(S.length===0){let[C,v]=g??k.dims.slice(-2),G=new B("int32",new Int32Array(C*v).fill(-1),[C,v]);m.push({segmentation:G,segments_info:[]});continue}let[M,L]=XP(E,A,S,r,s,n,g);m.push({segmentation:M,segments_info:L})}return m}function gl(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var q=class extends Je{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&&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=jn(s.data)[0],a=Me(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 h=0;h<s.height;++h){let g=h*s.width;for(let x=0;x<s.width;++x)(m[g+x]-n)/a<i&&(l=Math.min(l,x),c=Math.min(c,h),p=Math.max(p,x),d=Math.max(d,h))}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[h,g]=o?[Math.floor((p-l)/2),Math.floor((d-i)/2)]:[0,0];for(let x=0;x<i;++x){let k=(x+g)*p,E=x*l;for(let A=0;A<l;++A){let S=(k+A+h)*c,M=(E+A)*c;for(let L=0;L<c;++L)m[S+L]=e[M+L]}}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 E=0;E<d;++E){let A=E*p,S=Bs(E,x)*l;for(let M=0;M<p;++M){if(E<i&&M<l)continue;let L=(A+M)*c,C=(S+Bs(M,k))*c;for(let v=0;v<c;++v)m[L+v]=e[C+v]}}}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]=Fd([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=fA(c*n,this.config.ensure_multiple_of),i=fA(p*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return Fd([s,n],this.size_divisibility);if(this.min_pixels!==void 0&&this.max_pixels!==void 0){let i=this.config.patch_size*this.config.merge_size;return YP(n,s,i,this.min_pixels,this.max_pixels)}else 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 h,g;Number.isInteger(this.crop_size)?(h=this.crop_size,g=this.crop_size):(h=this.crop_size.width,g=this.crop_size.height),e=await e.center_crop(h,g)}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 h=this.image_mean;Array.isArray(this.image_mean)||(h=new Array(e.channels).fill(h));let g=this.image_std;if(Array.isArray(this.image_std)||(g=new Array(e.channels).fill(g)),h.length!==e.channels||g.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${h.length}) and \`image_std\` (${g.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]-h[k])/g[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[h,g]=Fd([d[1],d[0]],this.size_divisibility);[p,d]=this.pad_image(p,d,{width:h,height:g})}}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 h=0;h<p.length;h+=3){let g=p[h];p[h]=p[h+2],p[h+2]=g}}let m=new B("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:Gt(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 at(e,Ks,!0,r);return new this(s)}};var tn={};ts(tn,{BeitFeatureExtractor:()=>Gd,BitImageProcessor:()=>Wd,CLIPFeatureExtractor:()=>Vd,CLIPImageProcessor:()=>xl,ChineseCLIPFeatureExtractor:()=>qd,ConvNextFeatureExtractor:()=>Hd,ConvNextImageProcessor:()=>yl,DINOv3ViTImageProcessor:()=>Kd,DPTFeatureExtractor:()=>Jd,DPTImageProcessor:()=>kl,DeiTFeatureExtractor:()=>Xd,DeiTImageProcessor:()=>bl,DetrFeatureExtractor:()=>Yd,DetrImageProcessor:()=>vl,DonutFeatureExtractor:()=>Qd,DonutImageProcessor:()=>Qs,EfficientNetImageProcessor:()=>Zd,GLPNFeatureExtractor:()=>em,GroundingDinoImageProcessor:()=>tm,Idefics3ImageProcessor:()=>El,ImageFeatureExtractor:()=>q,ImageProcessor:()=>q,JinaCLIPImageProcessor:()=>sm,LlavaOnevisionImageProcessor:()=>nm,Mask2FormerImageProcessor:()=>am,MaskFormerFeatureExtractor:()=>om,MaskFormerImageProcessor:()=>Js,MobileNetV1FeatureExtractor:()=>im,MobileNetV1ImageProcessor:()=>Al,MobileNetV2FeatureExtractor:()=>lm,MobileNetV2ImageProcessor:()=>Tl,MobileNetV3FeatureExtractor:()=>cm,MobileNetV3ImageProcessor:()=>Ml,MobileNetV4FeatureExtractor:()=>um,MobileNetV4ImageProcessor:()=>Sl,MobileViTFeatureExtractor:()=>pm,MobileViTImageProcessor:()=>Ol,NougatImageProcessor:()=>fm,OwlViTFeatureExtractor:()=>dm,OwlViTImageProcessor:()=>Zs,Owlv2ImageProcessor:()=>mm,Phi3VImageProcessor:()=>wm,PixtralImageProcessor:()=>gm,PvtImageProcessor:()=>xm,Qwen2VLImageProcessor:()=>ym,RTDetrImageProcessor:()=>bm,Sam2ImageProcessor:()=>co,Sam3ImageProcessor:()=>co,SamImageProcessor:()=>co,SapiensFeatureExtractor:()=>vm,SapiensImageProcessor:()=>Il,SegformerFeatureExtractor:()=>km,SegformerImageProcessor:()=>Cl,SiglipImageProcessor:()=>Em,SmolVLMImageProcessor:()=>El,Swin2SRImageProcessor:()=>Am,VLMImageProcessor:()=>rm,ViTFeatureExtractor:()=>Tm,ViTImageProcessor:()=>Pl,VitMatteImageProcessor:()=>Mm,VitPoseImageProcessor:()=>Sm,YolosFeatureExtractor:()=>Om,YolosImageProcessor:()=>Ll});var Gd=class extends q{};var Wd=class extends q{};var qd=class extends q{};var xl=class extends q{},Vd=class extends xl{};var yl=class extends q{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}},Hd=class extends yl{};var bl=class extends q{},Xd=class extends bl{};var vl=class extends q{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ve(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Pr(...e)}post_process_panoptic_segmentation(...e){return wl(...e)}post_process_instance_segmentation(...e){return gl(...e)}},Yd=class extends vl{};var Kd=class extends q{};var Qs=class extends q{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})}},Qd=class extends Qs{};var kl=class extends q{},Jd=class extends kl{};var Zd=class extends q{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 em=class extends q{};var tm=class extends q{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=it([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var El=class extends q{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(L=>this.preprocess(L)));l.push(...A.map(L=>L.original_size)),c.push(...A.map(L=>L.reshaped_input_size)),A.forEach(L=>L.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let L=new Array(A.length),C=new Array(A.length);M=await Promise.all(A.map(async(v,G)=>{let X=this.get_resize_for_vision_encoder(v.pixel_values,S),V=await jt(v.pixel_values,{size:[X.height,X.width]}),{frames:Q,num_splits_h:Y,num_splits_w:K}=await this.split_image(V,this.max_image_size);return L[G]=Y,C[G]=K,Ee(Q,0)})),a.push(L),i.push(C)}else{let L=[S,S];M=await Promise.all(A.map(C=>jt(C.pixel_values,{size:L}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(Ee(M,0))}let p=o.length,[d,m,h,g]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=Ve([p,d,h,g],!0);else{let E=Math.max(...o.map(M=>M.dims.at(0)));k=Ve([p,E,h,g],!0);let A=k.data,S=E*h*g;for(let M=0;M<p;++M){let L=o[M].dims[0];if(L<E){o[M]=Ee([o[M],Ve([E-L,m,h,g],0)],0);let C=M*S+L*h*g,v=(M+1)*S;A.fill(!1,C,v)}}x=Gt(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 g=0;g<l;++g)for(let x=0;x<c;++x){let k,E,A,S;g===l-1?(E=a-p,S=a):(E=g*p,S=(g+1)*p),x===c-1?(k=i-d,A=i):(k=x*d,A=(x+1)*d);let C=await ul(e,[E,k],[S,A],[2,3]);o.push(C)}let m=s,h=n;(a!==m||i!==h)&&(e=await jt(e,{size:[m,h]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:c}}};var rm=class extends q{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 sm=class extends q{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})}};var nm=class extends q{};var Js=class extends q{post_process_panoptic_segmentation(...e){return wl(...e)}post_process_instance_segmentation(...e){return gl(...e)}},om=class extends Js{};var am=class extends Js{};var Al=class extends q{},im=class extends Al{};var Tl=class extends q{},lm=class extends Tl{};var Ml=class extends q{},cm=class extends Ml{};var Sl=class extends q{},um=class extends Sl{};var Ol=class extends q{},pm=class extends Ol{};var fm=class extends Qs{};var Zs=class extends q{post_process_object_detection(...e){return Pr(...e)}},dm=class extends Zs{};var mm=class extends Zs{};var Nt=336,KP=[2,3],{ceil:hm,floor:en,sqrt:_m}=Math,wm=class extends q{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 en((en(r/Nt)*en(e/Nt)+1)*s+1+(en(r/Nt)+1)*_m(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=Nt*hm(o/Nt),l=Nt*hm(a/Nt),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||_m(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[h,g]=m.dims.slice(-2),x=await jt(m,{size:[Nt,Nt],mode:"bicubic"});if(r>0){let k=[],E=_m(r),A=en(g/E),S=en(h/E);for(let L=0;L<E;++L)for(let C=0;C<E;++C){let v,G,X,V;L===E-1?(G=h-S,V=h):(G=L*S,V=(L+1)*S),C===E-1?(v=g-A,X=g):(v=C*A,X=(C+1)*A);let K=await ul(m,[G,v],[V,X],KP);k.push(K)}let M=await jt(Ee(k,0),{size:[Nt,Nt],mode:"bicubic"});i.push(Ee([x,M],0))}else i.push(x)}let l=Gt(i,0),c=a.map(m=>m.map(h=>Nt*hm(h/Nt))),p=new B("int64",c.flat(),[s,2]),d=c.map(([m,h])=>this.calc_num_image_tokens_from_image_size(h,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:d}}};var gm=class extends q{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,h=Math.floor((l-1)/d)+1;return[m*d,h*d]}};var xm=class extends q{};var ym=class extends q{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=Ee(Array.from({length:i},()=>a),0));let p=a.dims[0]/i,d=a.dims[1],m=Math.floor(a.dims[2]/c),h=Math.floor(a.dims[3]/c),g=a.view(p,i,d,Math.floor(m/l),l,c,Math.floor(h/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*m*h,d*i*c*c),x=new B("int64",[p,m,h],[1,3]);return{pixel_values:g,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var bm=class extends q{post_process_object_detection(...e){return Pr(...e)}};var co=class extends q{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Ep(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 h=0;h<e[a][m].length;++h)for(let g=0;g<e[a][m][h].length;++g)e[a][m][h][g]*=d[g%2]}return new B("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=Ep(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 B("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 jt(e[c],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,d[0]],[0,d[1]]),m=await jt(m,{mode:"bilinear",size:p}),o){let h=m.data,g=new Uint8Array(h.length);for(let x=0;x<h.length;++x)h[x]>n&&(g[x]=1);m=new B("bool",g,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 Il=class extends q{post_process_semantic_segmentation(...e){return _l(...e)}},vm=class extends Il{};var Cl=class extends q{post_process_semantic_segmentation(...e){return _l(...e)}},km=class extends Cl{};var Em=class extends q{};var Am=class extends q{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 Pl=class extends q{},Tm=class extends Pl{};var Mm=class extends q{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:Gt(s.map((a,i)=>Ee([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 Sm=class extends q{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],h=[];for(let g=0;g<m.length;++g){let x=m[g],k=[],E=[],A=[],S=x.at(-2)/l,M=x.at(-1)/i;for(let L=0;L<d.length;++L){let[C,v]=[0,0],G=0,X=-1/0,V=d[L];for(let Y=0;Y<V.length;++Y){let K=V[Y];for(let U=0;U<K.length;++U){let P=K[U];G+=P,X=Math.max(X,P),C+=(U+.5)*P,v+=Y*P}}if(s!=null&&X<s)continue;let Q=[S*C/G,M*v/G];k.push(Q),A.push(L),E.push(X)}h.push({bbox:x,scores:E,labels:A,keypoints:k})}c.push(h)}return c}};var Ll=class extends q{post_process_object_detection(...e){return Pr(...e)}},Om=class extends Ll{};var Re=class{static async from_pretrained(e,r={}){let s=await at(e,Ks,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=tn[n?.replace(/Fast$/,"")];return o||(n!==void 0&&console.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Ys}.`),o=q),new o(s)}};var Im=class extends ne{static tokenizer_class=J;static image_processor_class=Re;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((h,g)=>(Number(h)+.5)/this.size_per_bin*s[g%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 Cm=class extends ne{static image_processor_class=Re;static feature_extractor_class=tt;static tokenizer_class=J;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
|
+
}`,_=new Function(Object.keys(I),z)(...Object.values(I)),z=`methodCaller<(${b.map(D=>D.name)}) => ${w.name}>`,rT(Object.defineProperty(_,"name",{value:z}))}function iT(u,d){return d>>>=0,(u=zt(u>>>0))==zt(d)}function lT(u){return(u>>>=0)?(u=Oi(u),Vt(globalThis[u])):Vt(globalThis)}function cT(u){return u=Oi(u>>>0),Vt(e[u])}function uT(u,d){return d>>>=0,u=zt(u>>>0),d=zt(d),Vt(u[d])}function pT(u){9<(u>>>=0)&&(Qr[u+1]+=1)}function Cb(u,d,_,w,b){return tp[u>>>0](d>>>0,_>>>0,w>>>0,b>>>0)}function dT(u,d,_,w,b){return Cb(u>>>0,d>>>0,_>>>0,w>>>0,b>>>0)}function fT(){return Vt([])}function mT(u){u=zt(u>>>0);for(var d=Array(u.length),_=0;_<u.length;_++)d[_]=u[_];return Vt(d)}function hT(u){return Vt(Oi(u>>>0))}function _T(){return Vt({})}function wT(u){for(var d=zt(u>>>=0);d.length;){var _=d.pop();d.pop()(_)}Yu(u)}function gT(u,d,_){d>>>=0,_>>>=0,u=zt(u>>>0),d=zt(d),_=zt(_),u[d]=_}function xT(u,d){u=xt(u),d>>>=0,u=new Date(1e3*u),(v(),U)[d>>>2>>>0]=u.getUTCSeconds(),(v(),U)[d+4>>>2>>>0]=u.getUTCMinutes(),(v(),U)[d+8>>>2>>>0]=u.getUTCHours(),(v(),U)[d+12>>>2>>>0]=u.getUTCDate(),(v(),U)[d+16>>>2>>>0]=u.getUTCMonth(),(v(),U)[d+20>>>2>>>0]=u.getUTCFullYear()-1900,(v(),U)[d+24>>>2>>>0]=u.getUTCDay(),u=(u.getTime()-Date.UTC(u.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),U)[d+28>>>2>>>0]=u}var Pb=u=>u%4==0&&(u%100!=0||u%400==0),Lb=[0,31,60,91,121,152,182,213,244,274,305,335],Nb=[0,31,59,90,120,151,181,212,243,273,304,334];function yT(u,d){u=xt(u),d>>>=0,u=new Date(1e3*u),(v(),U)[d>>>2>>>0]=u.getSeconds(),(v(),U)[d+4>>>2>>>0]=u.getMinutes(),(v(),U)[d+8>>>2>>>0]=u.getHours(),(v(),U)[d+12>>>2>>>0]=u.getDate(),(v(),U)[d+16>>>2>>>0]=u.getMonth(),(v(),U)[d+20>>>2>>>0]=u.getFullYear()-1900,(v(),U)[d+24>>>2>>>0]=u.getDay();var _=(Pb(u.getFullYear())?Lb:Nb)[u.getMonth()]+u.getDate()-1|0;(v(),U)[d+28>>>2>>>0]=_,(v(),U)[d+36>>>2>>>0]=-60*u.getTimezoneOffset(),_=new Date(u.getFullYear(),6,1).getTimezoneOffset();var w=new Date(u.getFullYear(),0,1).getTimezoneOffset();u=0|(_!=w&&u.getTimezoneOffset()==Math.min(w,_)),(v(),U)[d+32>>>2>>>0]=u}function bT(u){u>>>=0;var d=new Date((v(),U)[u+20>>>2>>>0]+1900,(v(),U)[u+16>>>2>>>0],(v(),U)[u+12>>>2>>>0],(v(),U)[u+8>>>2>>>0],(v(),U)[u+4>>>2>>>0],(v(),U)[u>>>2>>>0],0),_=(v(),U)[u+32>>>2>>>0],w=d.getTimezoneOffset(),b=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),I=Math.min(T,b);return 0>_?(v(),U)[u+32>>>2>>>0]=+(b!=T&&I==w):0<_!=(I==w)&&(b=Math.max(T,b),d.setTime(d.getTime()+6e4*((0<_?I:b)-w))),(v(),U)[u+24>>>2>>>0]=d.getDay(),_=(Pb(d.getFullYear())?Lb:Nb)[d.getMonth()]+d.getDate()-1|0,(v(),U)[u+28>>>2>>>0]=_,(v(),U)[u>>>2>>>0]=d.getSeconds(),(v(),U)[u+4>>>2>>>0]=d.getMinutes(),(v(),U)[u+8>>>2>>>0]=d.getHours(),(v(),U)[u+12>>>2>>>0]=d.getDate(),(v(),U)[u+16>>>2>>>0]=d.getMonth(),(v(),U)[u+20>>>2>>>0]=d.getYear(),u=d.getTime(),BigInt(isNaN(u)?-1:u/1e3)}function zb(u,d,_,w,b,T,I){return n?Ne(16,1,u,d,_,w,b,T,I):-52}function Rb(u,d,_,w,b,T){if(n)return Ne(17,1,u,d,_,w,b,T)}var Cn={},vT=()=>performance.timeOrigin+performance.now();function $b(u,d){if(n)return Ne(18,1,u,d);if(Cn[u]&&(clearTimeout(Cn[u].id),delete Cn[u]),!d)return 0;var _=setTimeout(()=>{delete Cn[u],Ai(()=>m1(u,performance.timeOrigin+performance.now()))},d);return Cn[u]={id:_,Ne:d},0}function kT(u,d,_,w){u>>>=0,d>>>=0,_>>>=0,w>>>=0;var b=new Date().getFullYear(),T=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var I=Math.max(T,b);(v(),P)[u>>>2>>>0]=60*I,(v(),U)[d>>>2>>>0]=+(T!=b),u=(d=z=>{var D=Math.abs(z);return`UTC${0<=z?"-":"+"}${String(Math.floor(D/60)).padStart(2,"0")}${String(D%60).padStart(2,"0")}`})(T),d=d(b),b<T?(fr(u,_,17),fr(d,w,17)):(fr(u,w,17),fr(d,_,17))}var ET=()=>Date.now(),AT=1;function TT(u,d,_){if(_>>>=0,!(0<=u&&3>=u))return 28;if(u===0)u=Date.now();else{if(!AT)return 52;u=performance.timeOrigin+performance.now()}return u=Math.round(1e6*u),(v(),O)[_>>>3>>>0]=BigInt(u),0}var rp=[],Bb=(u,d)=>{rp.length=0;for(var _;_=(v(),Q)[u++>>>0];){var w=_!=105;d+=(w&=_!=112)&&d%8?4:0,rp.push(_==112?(v(),P)[d>>>2>>>0]:_==106?(v(),O)[d>>>3>>>0]:_==105?(v(),U)[d>>>2>>>0]:(v(),ie)[d>>>3>>>0]),d+=w?8:4}return rp};function MT(u,d,_){return u>>>=0,d=Bb(d>>>0,_>>>0),wp[u](...d)}function ST(u,d,_){return u>>>=0,d=Bb(d>>>0,_>>>0),wp[u](...d)}var OT=()=>{};function IT(u,d){return M(Cs(u>>>0,d>>>0))}var CT=()=>{throw we+=1,"unwind"};function PT(){return 4294901760}var LT=()=>1,NT=()=>navigator.hardwareConcurrency,Jr={},Ub=u=>{var d=mr(u)+1,_=zs(d);return _&&fr(u,_,d),_},Ii=u=>{var d;return(d=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(u))?+d[1]:(d=/:(\d+):\d+(?:\)|$)/.exec(u))?2147483648|+d[1]:0},Db=u=>{for(var d of u)(u=Ii(d))&&(Jr[u]=d)};function zT(){var u=Error().stack.toString().split(`
|
|
13
|
+
`);return u[0]=="Error"&&u.shift(),Db(u),Jr.Xd=Ii(u[3]),Jr.re=u,Jr.Xd}function Ci(u){if(!(u=Jr[u>>>0]))return 0;var d;if(d=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(u))u=d[1];else if(d=/^\s+at (.*) \(.*\)$/.exec(u))u=d[1];else{if(!(d=/^(.+?)@/.exec(u)))return 0;u=d[1]}return Rt(Ci.ae??0),Ci.ae=Ub(u),Ci.ae}function RT(u){u>>>=0;var d=(v(),Q).length;if(u<=d||4294901760<u)return!1;for(var _=1;4>=_;_*=2){var w=d*(1+.2/_);w=Math.min(w,u+100663296);e:{w=(Math.min(4294901760,65536*Math.ceil(Math.max(u,w)/65536))-vr.buffer.byteLength+65535)/65536|0;try{vr.grow(w),ue();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}function $T(u,d,_){if(u>>>=0,d>>>=0,Jr.Xd==u)var w=Jr.re;else(w=Error().stack.toString().split(`
|
|
14
|
+
`))[0]=="Error"&&w.shift(),Db(w);for(var b=3;w[b]&&Ii(w[b])!=u;)++b;for(u=0;u<_&&w[u+b];++u)(v(),U)[d+4*u>>>2>>>0]=Ii(w[u+b]);return u}var nr=u=>{var d=mr(u)+1,_=zi(d);return fr(u,_,d),_},sp=[],yt=(u,d)=>{sp[u>>>=0]=d},or=[],Pi=[],Ls=(u,d)=>{Pi[u]=new Promise(_=>d.finally(()=>_(u)))},re=u=>{if(u)return sp[u>>>0]},Li=(u,d,_)=>{(v(),P)[u>>>2>>>0]=d,(v(),P)[u+4>>>2>>>0]=_},Fb=u=>{var d=(v(),P)[u>>>2>>>0];return u=(v(),P)[u+4>>>2>>>0],Cs(d,u)},hr=u=>{var d=(v(),P)[u>>>2>>>0];return u=(v(),P)[u+4>>>2>>>0],d?Cs(d,u):u===0?"":void 0},BT=u=>{var d=hr(u+4),_=(_=(v(),P)[u+12>>>2>>>0])?re(_):"auto";if(u+=16){var w=re((v(),P)[u+4>>>2>>>0]),b=(v(),P)[u+16>>>2>>>0],T=(v(),P)[u+20>>>2>>>0];if(b){for(var I={},z=0;z<b;++z){var D=T+24*z;I[Fb(D+4)]=(v(),ie)[D+16>>>3>>>0]}b=I}else b=void 0;u={module:w,constants:b,entryPoint:hr(u+8)}}else u=void 0;return{label:d,layout:_,compute:u}},jb=(u,d)=>{function _(b,T){b=u[b],(v(),U)[d+T>>>2>>>0]=b}function w(b,T){b=u[b],(v(),O)[d+T>>>3>>>0]=BigInt(b)}_("maxTextureDimension1D",4),_("maxTextureDimension2D",8),_("maxTextureDimension3D",12),_("maxTextureArrayLayers",16),_("maxBindGroups",20),_("maxBindGroupsPlusVertexBuffers",24),_("maxBindingsPerBindGroup",28),_("maxDynamicUniformBuffersPerPipelineLayout",32),_("maxDynamicStorageBuffersPerPipelineLayout",36),_("maxSampledTexturesPerShaderStage",40),_("maxSamplersPerShaderStage",44),_("maxStorageBuffersPerShaderStage",48),_("maxStorageTexturesPerShaderStage",52),_("maxUniformBuffersPerShaderStage",56),_("minUniformBufferOffsetAlignment",80),_("minStorageBufferOffsetAlignment",84),w("maxUniformBufferBindingSize",64),w("maxStorageBufferBindingSize",72),_("maxVertexBuffers",88),w("maxBufferSize",96),_("maxVertexAttributes",104),_("maxVertexBufferArrayStride",108),_("maxInterStageShaderVariables",112),_("maxColorAttachments",116),_("maxColorAttachmentBytesPerSample",120),_("maxComputeWorkgroupStorageSize",124),_("maxComputeInvocationsPerWorkgroup",128),_("maxComputeWorkgroupSizeX",132),_("maxComputeWorkgroupSizeY",136),_("maxComputeWorkgroupSizeZ",140),_("maxComputeWorkgroupsPerDimension",144),u.Le!==void 0&&_("maxImmediateSize",148)},UT=[,"validation","out-of-memory","internal"],DT=[,"compatibility","core"],Gb={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",327692:"chromium-experimental-unorm16-texture-formats",327693:"chromium-experimental-snorm16-texture-formats",327732:"chromium-experimental-multi-draw-indirect"},FT=[,"low-power","high-performance"],jT=[,"occlusion","timestamp"],GT={undefined:1,unknown:1,destroyed:2};function WT(u,d,_,w,b,T){d=xt(d),_=xt(_),w>>>=0,b>>>=0,T>>>=0;var I=re(u>>>0);if(u={},T){var z=(v(),P)[T+12>>>2>>>0];if(z){var D=(v(),P)[T+16>>>2>>>0];u.requiredFeatures=Array.from((v(),P).subarray(D>>>2>>>0,D+4*z>>>2>>>0),ee=>Gb[ee])}var W=(v(),P)[T+20>>>2>>>0];if(W){let ee=function($t,st,Zr=!1){st=W+st,(st=(v(),P)[st>>>2>>>0])==4294967295||Zr&&st==0||($e[$t]=st)},lt=function($t,st){st=W+st;var Zr=(v(),P)[st>>>2>>>0],wS=(v(),P)[st+4>>>2>>>0];Zr==4294967295&&wS==4294967295||($e[$t]=4294967296*(v(),P)[st+4>>>2>>>0]+(v(),P)[st>>>2>>>0])};var fe=ee,me=lt,$e={};ee("maxTextureDimension1D",4),ee("maxTextureDimension2D",8),ee("maxTextureDimension3D",12),ee("maxTextureArrayLayers",16),ee("maxBindGroups",20),ee("maxBindGroupsPlusVertexBuffers",24),ee("maxDynamicUniformBuffersPerPipelineLayout",32),ee("maxDynamicStorageBuffersPerPipelineLayout",36),ee("maxSampledTexturesPerShaderStage",40),ee("maxSamplersPerShaderStage",44),ee("maxStorageBuffersPerShaderStage",48),ee("maxStorageTexturesPerShaderStage",52),ee("maxUniformBuffersPerShaderStage",56),ee("minUniformBufferOffsetAlignment",80),ee("minStorageBufferOffsetAlignment",84),lt("maxUniformBufferBindingSize",64),lt("maxStorageBufferBindingSize",72),ee("maxVertexBuffers",88),lt("maxBufferSize",96),ee("maxVertexAttributes",104),ee("maxVertexBufferArrayStride",108),ee("maxInterStageShaderVariables",112),ee("maxColorAttachments",116),ee("maxColorAttachmentBytesPerSample",120),ee("maxComputeWorkgroupStorageSize",124),ee("maxComputeInvocationsPerWorkgroup",128),ee("maxComputeWorkgroupSizeX",132),ee("maxComputeWorkgroupSizeY",136),ee("maxComputeWorkgroupSizeZ",140),ee("maxComputeWorkgroupsPerDimension",144),ee("maxImmediateSize",148,!0),u.requiredLimits=$e}(z=(v(),P)[T+24>>>2>>>0])&&(z={label:hr(z+4)},u.defaultQueue=z),u.label=hr(T+4)}we+=1,Ls(d,I.requestDevice(u).then(ee=>{--we,yt(b,ee.queue),yt(w,ee),_&&(we+=1,Ls(_,ee.lost.then(lt=>{--we,ee.onuncapturederror=()=>{};var $t=ae(),st=nr(lt.message);lp(_,GT[lt.reason],st),oe($t)}))),ee.onuncapturederror=lt=>{var $t=5;lt.error instanceof GPUValidationError?$t=2:lt.error instanceof GPUOutOfMemoryError?$t=3:lt.error instanceof GPUInternalError&&($t=4);var st=ae();lt=nr(lt.error.message),u1(w,$t,lt),oe(st)},"adapterInfo"in ee||(ee.adapterInfo=I.info),pp(d,1,w,0)},ee=>{--we;var lt=ae();ee=nr(ee.message),pp(d,3,w,ee),_&&lp(_,4,ee),oe(lt)}))}function qT(u){var d=re(u>>>=0),_=or[u];if(_){for(var w=0;w<_.length;++w)_[w]();delete or[u]}d.destroy()}var Ns=()=>{var u="getMappedRange size=0 no longer means WGPU_WHOLE_MAP_SIZE";Ns.ed||(Ns.ed={}),Ns.ed[u]||(Ns.ed[u]=1,M(u))};function VT(u,d,_){d>>>=0,_>>>=0;var w=re(u>>>=0);_===0&&Ns(),_==4294967295&&(_=void 0);try{var b=w.getMappedRange(d,_)}catch{return 0}var T=mp(16,b.byteLength);return(v(),Q).set(new Uint8Array(b),T>>>0),or[u].push(()=>Rt(T)),T}function HT(u,d,_){d>>>=0,_>>>=0;var w=re(u>>>=0);_===0&&Ns(),_==4294967295&&(_=void 0);try{var b=w.getMappedRange(d,_)}catch{return 0}var T=mp(16,b.byteLength);return(v(),Q).fill(0,T,b.byteLength),or[u].push(()=>{new Uint8Array(b).set((v(),Q).subarray(T>>>0,T+b.byteLength>>>0)),Rt(T)}),T}function XT(u,d,_,w,b){u>>>=0,d=xt(d),_=xt(_),b>>>=0;var T=re(u);or[u]=[],b==4294967295&&(b=void 0),we+=1,Ls(d,T.mapAsync(_,w>>>0,b).then(()=>{--we,cp(d,1,0)},I=>{--we,ae();var z=nr(I.message);cp(d,I.name==="AbortError"?4:I.name==="OperationError"?3:0,z),delete or[u]}))}function YT(u){var d=re(u>>>=0),_=or[u];if(_){for(var w=0;w<_.length;++w)_[w]();delete or[u],d.unmap()}}function KT(u){delete sp[u>>>0]}function QT(u,d,_){u>>>=0,d>>>=0,_>>>=0;var w=!!(v(),P)[d+32>>>2>>>0];d={label:hr(d+4),usage:(v(),P)[d+16>>>2>>>0],size:4294967296*(v(),P)[d+28>>>2>>>0]+(v(),P)[d+24>>>2>>>0],mappedAtCreation:w},u=re(u);try{var b=u.createBuffer(d)}catch{return!1}return yt(_,b),w&&(or[_]=[]),!0}function JT(u,d,_,w){u>>>=0,d=xt(d),w>>>=0,_=BT(_>>>0),u=re(u),we+=1,Ls(d,u.createComputePipelineAsync(_).then(b=>{--we,yt(w,b),ip(d,1,w,0)},b=>{--we;var T=ae(),I=nr(b.message);ip(d,b.reason==="validation"?3:b.reason==="internal"?4:0,w,I),oe(T)}))}function ZT(u,d,_){u>>>=0,d>>>=0,_>>>=0;var w=(v(),P)[d>>>2>>>0],b=(v(),P)[w+4>>>2>>>0];d={label:hr(d+4),code:""},b===2&&(d.code=Fb(w+8)),yt(_,re(u).createShaderModule(d))}var eM=u=>{(u=re(u)).onuncapturederror=null,u.destroy()};function tM(u,d){d=xt(d),u=re(u>>>0),we+=1,Ls(d,u.popErrorScope().then(_=>{--we;var w=5;_?_ instanceof GPUValidationError?w=2:_ instanceof GPUOutOfMemoryError?w=3:_ instanceof GPUInternalError&&(w=4):w=1;var b=ae();_=_?nr(_.message):0,up(d,1,w,_),oe(b)},_=>{--we;var w=ae();_=nr(_.message),up(d,1,5,_),oe(w)}))}function rM(u,d,_,w){if(d=xt(d),w>>>=0,_>>>=0){var b=(v(),P)[_+4>>>2>>>0];b={featureLevel:DT[b],powerPreference:FT[(v(),P)[_+8>>>2>>>0]],forceFallbackAdapter:!!(v(),P)[_+12>>>2>>>0]},(_=(v(),P)[_>>>2>>>0])!==0&&(v(),b.Qe=!!(v(),P)[_+8>>>2>>>0])}"gpu"in navigator?(we+=1,Ls(d,navigator.gpu.requestAdapter(b).then(T=>{if(--we,T)yt(w,T),Pn(d,1,w,0);else{T=ae();var I=nr("WebGPU not available on this browser (requestAdapter returned null)");Pn(d,3,w,I),oe(T)}},T=>{--we;var I=ae();T=nr(T.message),Pn(d,4,w,T),oe(I)}))):(_=ae(),b=nr("WebGPU not available on this browser (navigator.gpu is not available)"),Pn(d,3,w,b),oe(_))}function sM(u,d,_){return u>>>=0,d>>>=0,_>>>=0,Ib(async()=>{var w=[];if(_){var b=(v(),U)[_>>>2>>>0];w.length=d+1,w[d]=new Promise(z=>setTimeout(z,b,0))}else w.length=d;for(var T=0;T<d;++T){var I=4294967296*(v(),P)[u+8*T+4>>>2>>>0]+(v(),P)[u+8*T>>>2>>>0];if(!(I in Pi))return I;w[T]=Pi[I]}return w=await Promise.race(w),delete Pi[w],w})}var np,op={},Wb=()=>{if(!np){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 op)op[u]===void 0?delete d[u]:d[u]=op[u];var _=[];for(u in d)_.push(`${u}=${d[u]}`);np=_}return np};function qb(u,d){if(n)return Ne(19,1,u,d);u>>>=0,d>>>=0;var _,w=0,b=0;for(_ of Wb()){var T=d+w;(v(),P)[u+b>>>2>>>0]=T,w+=fr(_,T,1/0)+1,b+=4}return 0}function Vb(u,d){if(n)return Ne(20,1,u,d);u>>>=0,d>>>=0;var _=Wb();for(var w of((v(),P)[u>>>2>>>0]=_.length,u=0,_))u+=mr(w)+1;return(v(),P)[d>>>2>>>0]=u,0}function Hb(u){return n?Ne(21,1,u):52}function Xb(u,d,_,w){return n?Ne(22,1,u,d,_,w):52}function Yb(u,d,_,w){return n?Ne(23,1,u,d,_,w):70}var nM=[null,[],[]];function Kb(u,d,_,w){if(n)return Ne(24,1,u,d,_,w);d>>>=0,_>>>=0,w>>>=0;for(var b=0,T=0;T<_;T++){var I=(v(),P)[d>>>2>>>0],z=(v(),P)[d+4>>>2>>>0];d+=8;for(var D=0;D<z;D++){var W=u,fe=(v(),Q)[I+D>>>0],me=nM[W];fe===0||fe===10?((W===1?S:M)(ub(me)),me.length=0):me.push(fe)}b+=z}return(v(),P)[w>>>2>>>0]=b,0}function oM(u){return u>>>0}function aM(u,d){return jb(re(u>>>0).limits,d>>>0),1}function iM(u,d){return re(u>>>0).features.has(Gb[d])}function lM(u){return BigInt(re(u>>>0).size)}function cM(u){return BigInt(re(u>>>0).usage)}function uM(u,d){if(u>>>=0,d>>>=0){var _=hr(d+4);_={label:_,timestampWrites:d=(d=(v(),P)[d+12>>>2>>>0])!==0?{querySet:re((v(),P)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),P)[d+8>>>2>>>0],endOfPassWriteIndex:(v(),P)[d+12>>>2>>>0]}:void 0}}return u=re(u),d=o1(0),yt(d,u.beginComputePass(_)),d}function pM(u,d,_,w,b,T){_=xt(_),b=xt(b),T=xt(T),re(u>>>0).copyBufferToBuffer(re(d>>>0),_,re(w>>>0),b,T)}function dM(u){u=re(u>>>0);var d=s1(0);return yt(d,u.finish()),d}function fM(u,d,_,w,b,T){T=xt(T),re(u>>>0).resolveQuerySet(re(d>>>0),_,w,re(b>>>0),T)}function mM(u,d,_,w){re(u>>>0).dispatchWorkgroups(d,_,w)}function hM(u,d,_){_=xt(_),re(u>>>0).dispatchWorkgroupsIndirect(re(d>>>0),_)}function _M(u){re(u>>>0).end()}function wM(u,d,_,w,b){w>>>=0,b>>>=0,u=re(u>>>0),_=re(_>>>0),w==0?u.setBindGroup(d,_):u.setBindGroup(d,_,(v(),P),b>>>2,w)}function gM(u,d){re(u>>>0).setPipeline(re(d>>>0))}function xM(u,d,_){re(u>>>0).Pe(re(d>>>0),_)}function yM(u,d){u=re(u>>>0);var _=r1(0);return yt(_,u.getBindGroupLayout(d)),_}function bM(u,d){u>>>=0;var _=hr(4+(d>>>=0)),w=re((v(),P)[d+12>>>2>>>0]),b=(v(),P)[d+16>>>2>>>0];d=(v(),P)[d+20>>>2>>>0];for(var T=[],I=0;I<b;++I){var z=T,D=z.push,W=d+40*I,fe=(v(),P)[W+8>>>2>>>0],me=(v(),P)[W+32>>>2>>>0],$e=(v(),P)[W+36>>>2>>>0],ee=(v(),P)[W+4>>>2>>>0];fe?(me=W+24,(me=(v(),P)[me>>>2>>>0]+4294967296*(v(),U)[me+4>>>2>>>0])==-1&&(me=void 0),W={binding:ee,resource:{buffer:re(fe),offset:4294967296*(v(),P)[W+4+16>>>2>>>0]+(v(),P)[W+16>>>2>>>0],size:me}}):W=me?{binding:ee,resource:re(me)}:{binding:ee,resource:re($e)},D.call(z,W)}return _={label:_,layout:w,entries:T},u=re(u),w=t1(0),yt(w,u.createBindGroup(_)),w}function vM(u,d){var _;return u>>>=0,(d>>>=0)&&(_={label:hr(d+4)}),u=re(u),d=n1(0),yt(d,u.createCommandEncoder(_)),d}function kM(u,d){u>>>=0,d>>>=0,d={type:jT[(v(),P)[d+12>>>2>>>0]],count:(v(),P)[d+16>>>2>>>0]},u=re(u);var _=a1(0);return yt(_,u.createQuerySet(d)),_}function EM(u,d){u=re(u>>>0).adapterInfo,d>>>=0,(v(),U)[d+52>>>2>>>0]=u.subgroupMinSize,(v(),U)[d+56>>>2>>>0]=u.subgroupMaxSize;var _=Ub(u.vendor+u.architecture+u.device+u.description),w=mr(u.vendor);return Li(d+4,_,w),_+=w,w=mr(u.architecture),Li(d+12,_,w),_+=w,w=mr(u.device),Li(d+20,_,w),Li(d+28,_+w,mr(u.description)),(v(),U)[d+36>>>2>>>0]=2,u=u.isFallbackAdapter?3:4,(v(),U)[d+40>>>2>>>0]=u,(v(),U)[d+44>>>2>>>0]=0,(v(),U)[d+48>>>2>>>0]=0,1}var AM={"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,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-snorm16-texture-formats":327693,"chromium-experimental-multi-draw-indirect":327732};function TM(u,d){d>>>=0,u=re(u>>>0);var _=zs(4*u.features.size),w=0,b=0;u.features.forEach(T=>{0<=(T=AM[T])&&((v(),U)[_+w>>>2>>>0]=T,w+=4,b++)}),(v(),P)[d+4>>>2>>>0]=_,(v(),P)[d>>>2>>>0]=b}function MM(u,d){return jb(re(u>>>0).limits,d>>>0),1}function SM(u,d){re(u>>>0).pushErrorScope(UT[d])}function OM(u,d,_){d>>>=0,_>>>=0,u=re(u>>>0),d=Array.from((v(),U).subarray(_>>>2>>>0,_+4*d>>>2>>>0),w=>re(w)),u.submit(d)}function IM(u,d,_,w,b){_=xt(_),w>>>=0,b>>>=0,u=re(u>>>0),d=re(d>>>0),w=(v(),Q).subarray(w>>>0,w+b>>>0),u.writeBuffer(d,_,w,0,b)}n||(function(){for(var u=e.numThreads-1;u--;)sb();Te.push(async()=>{var d=(async function(){if(!n)return Promise.all(et.map(rb))})();xe++,await d,--xe==0&&Ge&&(d=Ge,Ge=null,d())})})(),n||(vr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ue()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ae(),e.stackRestore=u=>oe(u),e.stackAlloc=u=>zi(u),e.setValue=function(u,d,_="i8"){switch(_.endsWith("*")&&(_="*"),_){case"i1":case"i8":(v(),V)[u>>>0]=d;break;case"i16":(v(),Y)[u>>>1>>>0]=d;break;case"i32":(v(),U)[u>>>2>>>0]=d;break;case"i64":(v(),O)[u>>>3>>>0]=BigInt(d);break;case"float":(v(),se)[u>>>2>>>0]=d;break;case"double":(v(),ie)[u>>>3>>>0]=d;break;case"*":(v(),P)[u>>>2>>>0]=d;break;default:Ce(`invalid type for setValue: ${_}`)}},e.getValue=function(u,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(v(),V)[u>>>0];case"i16":return(v(),Y)[u>>>1>>>0];case"i32":return(v(),U)[u>>>2>>>0];case"i64":return(v(),O)[u>>>3>>>0];case"float":return(v(),se)[u>>>2>>>0];case"double":return(v(),ie)[u>>>3>>>0];case"*":return(v(),P)[u>>>2>>>0];default:Ce(`invalid type for getValue: ${d}`)}},e.UTF8ToString=Cs,e.stringToUTF8=fr,e.lengthBytesUTF8=mr;var Qb,Jb,ap,Ni,Rt,zs,Zb,e1,t1,r1,s1,n1,o1,a1,i1,l1,c1,ip,lp,cp,up,Pn,pp,u1,dp,p1,d1,f1,fp,m1,h1,mp,he,Ln,_1,oe,zi,ae,w1,hp,g1,x1,y1,_p,b1,v1,k1,E1,A1,T1,M1,S1,O1,I1,C1,P1,L1,N1,z1,R1,$1,B1,U1,D1,F1,j1,G1,W1,q1,V1,H1,X1,Y1,K1,Q1,J1,Z1,ev,tv,rv,sv,nv,ov,av,_r,CM=[br,Yr,ab,pb,db,fb,mb,hb,_b,wb,gb,xb,yb,bb,vb,kb,zb,Rb,$b,qb,Vb,Hb,Xb,Yb,Kb],wp={1117404:(u,d,_,w,b)=>{if(e===void 0||!e.Zc)return 1;if((u=Cs(Number(u>>>0))).startsWith("./")&&(u=u.substring(2)),!(u=e.Zc.get(u)))return 2;if(d=Number(d>>>0),_=Number(_>>>0),w=Number(w>>>0),d+_>u.byteLength)return 3;try{let T=u.subarray(d,d+_);switch(b){case 0:(v(),Q).set(T,w>>>0);break;case 1:e.ie?e.ie(w,T):e.Ke(w,T);break;default:return 4}return 0}catch{return 4}},1118228:(u,d,_)=>{e.ke(u,(v(),Q).subarray(d>>>0,d+_>>>0))},1118292:()=>e.Ie(),1118334:u=>{e.je(u)},1118371:()=>typeof wasmOffsetConverter<"u"};function PM(){return typeof wasmOffsetConverter<"u"}function LM(u,d,_,w){var b=ae();try{return S1(u,d,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function NM(u,d,_){var w=ae();try{return A1(u,d,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function zM(u,d,_){var w=ae();try{y1(u,d,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function RM(u,d){var _=ae();try{return _p(u,d)}catch(w){if(oe(_),w!==w+0)throw w;he(1,0)}}function $M(u){var d=ae();try{b1(u)}catch(_){if(oe(d),_!==_+0)throw _;he(1,0)}}function BM(u,d,_,w,b,T,I){var z=ae();try{return E1(u,d,_,w,b,T,I)}catch(D){if(oe(z),D!==D+0)throw D;he(1,0)}}function UM(u,d){var _=ae();try{O1(u,d)}catch(w){if(oe(_),w!==w+0)throw w;he(1,0)}}function DM(u,d,_,w,b,T){var I=ae();try{v1(u,d,_,w,b,T)}catch(z){if(oe(I),z!==z+0)throw z;he(1,0)}}function FM(u,d,_,w){var b=ae();try{M1(u,d,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function jM(u,d,_,w,b,T,I){var z=ae();try{C1(u,d,_,w,b,T,I)}catch(D){if(oe(z),D!==D+0)throw D;he(1,0)}}function GM(u,d,_,w,b,T,I){var z=ae();try{P1(u,d,_,w,b,T,I)}catch(D){if(oe(z),D!==D+0)throw D;he(1,0)}}function WM(u,d,_,w,b,T,I,z){var D=ae();try{j1(u,d,_,w,b,T,I,z)}catch(W){if(oe(D),W!==W+0)throw W;he(1,0)}}function qM(u,d,_,w,b){var T=ae();try{k1(u,d,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;he(1,0)}}function VM(u,d,_,w,b){var T=ae();try{return I1(u,d,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;he(1,0)}}function HM(u,d,_,w,b,T,I,z){var D=ae();try{G1(u,d,_,w,b,T,I,z)}catch(W){if(oe(D),W!==W+0)throw W;he(1,0)}}function XM(u,d,_,w,b,T,I,z,D,W,fe,me){var $e=ae();try{L1(u,d,_,w,b,T,I,z,D,W,fe,me)}catch(ee){if(oe($e),ee!==ee+0)throw ee;he(1,0)}}function YM(u,d,_,w,b,T){var I=ae();try{return D1(u,d,_,w,b,T)}catch(z){if(oe(I),z!==z+0)throw z;he(1,0)}}function KM(u,d,_){var w=ae();try{return $1(u,d,_)}catch(b){if(oe(w),b!==b+0)throw b;return he(1,0),0n}}function QM(u,d,_,w,b,T,I,z,D){var W=ae();try{T1(u,d,_,w,b,T,I,z,D)}catch(fe){if(oe(W),fe!==fe+0)throw fe;he(1,0)}}function JM(u){var d=ae();try{return z1(u)}catch(_){if(oe(d),_!==_+0)throw _;he(1,0)}}function ZM(u,d,_){var w=ae();try{return W1(u,d,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function eS(u,d){var _=ae();try{return rv(u,d)}catch(w){if(oe(_),w!==w+0)throw w;return he(1,0),0n}}function tS(u,d,_,w,b){var T=ae();try{q1(u,d,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;he(1,0)}}function rS(u){var d=ae();try{return N1(u)}catch(_){if(oe(d),_!==_+0)throw _;return he(1,0),0n}}function sS(u,d,_,w,b,T){var I=ae();try{return X1(u,d,_,w,b,T)}catch(z){if(oe(I),z!==z+0)throw z;he(1,0)}}function nS(u,d,_,w,b,T){var I=ae();try{return Y1(u,d,_,w,b,T)}catch(z){if(oe(I),z!==z+0)throw z;he(1,0)}}function oS(u,d,_,w,b,T,I,z){var D=ae();try{return F1(u,d,_,w,b,T,I,z)}catch(W){if(oe(D),W!==W+0)throw W;he(1,0)}}function aS(u,d,_,w,b){var T=ae();try{return K1(u,d,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;return he(1,0),0n}}function iS(u,d,_,w){var b=ae();try{return Q1(u,d,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function lS(u,d,_,w){var b=ae();try{return J1(u,d,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function cS(u,d,_,w,b,T,I,z,D,W,fe,me){var $e=ae();try{return Z1(u,d,_,w,b,T,I,z,D,W,fe,me)}catch(ee){if(oe($e),ee!==ee+0)throw ee;he(1,0)}}function uS(u,d,_,w,b,T,I,z,D,W,fe){var me=ae();try{V1(u,d,_,w,b,T,I,z,D,W,fe)}catch($e){if(oe(me),$e!==$e+0)throw $e;he(1,0)}}function pS(u,d,_,w,b,T,I,z,D,W,fe,me,$e,ee,lt,$t){var st=ae();try{H1(u,d,_,w,b,T,I,z,D,W,fe,me,$e,ee,lt,$t)}catch(Zr){if(oe(st),Zr!==Zr+0)throw Zr;he(1,0)}}function dS(u,d,_,w){var b=ae();try{return ev(u,d,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function fS(u,d,_,w,b){var T=ae();try{return tv(u,d,_,w,b)}catch(I){if(oe(T),I!==I+0)throw I;he(1,0)}}function mS(u,d,_){var w=ae();try{return R1(u,d,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function hS(u,d,_){var w=ae();try{return B1(u,d,_)}catch(b){if(oe(w),b!==b+0)throw b;he(1,0)}}function _S(u,d,_,w){var b=ae();try{U1(u,d,_,w)}catch(T){if(oe(b),T!==T+0)throw T;he(1,0)}}function Ri(){if(0<xe)Ge=Ri;else if(n)g?.(e),Ue();else{for(var u=Te;0<u.length;)u.shift()(e);0<xe?Ge=Ri:(e.calledRun=!0,L||(Ue(),g?.(e)))}}return n||(_r=await Qe(),Ri()),e.PTR_SIZE=4,e.webgpuInit=u=>{let d=new WeakMap,_,w,b=1;e.webgpuRegisterDevice=z=>{if(w!==void 0)throw Error("another WebGPU EP inference session is being created.");if(z){var D=d.get(z);if(!D){let W=((fe,me=0)=>{var $e=c1(me);return me=l1(me,$e),yt($e,fe.queue),yt(me,fe),me})(z,D=e1(0));D=[b++,D,W],d.set(z,D)}return _=z,w=D[0],D}_=void 0,w=0};let T=new Map;e.webgpuOnCreateSession=z=>{if(w!==void 0){var D=w;if(w=void 0,z){let W=ap(D);T.set(z,W),D===0&&u(_??re(W))}_=void 0}},e.webgpuOnReleaseSession=z=>{T.delete(z)};let I=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(z,D,W)=>{if(W)return z[I]=[W,NaN],W;if(W=z[I])return W[1]++,W[0];if((D=T.get(D))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return D=((fe,me=0)=>(fe.mapState!="pending"||Ce(),me=i1(me,fe.mapState=="mapped"?3:1),yt(me,fe),fe.mapState=="mapped"&&(or[me]=[]),me))(z,D),z[I]=[D,1],D},e.webgpuUnregisterBuffer=z=>{let D=z[I];if(!D)throw Error("Buffer is not registered");D[1]--,D[1]===0&&(Zb(D[0]),delete z[I])},e.webgpuGetBuffer=z=>re(z),e.webgpuCreateDownloader=(z,D,W)=>{if((W=T.get(W))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let fe=re(W),me=16*Math.ceil(Number(D)/16);return async()=>{let $e=fe.createBuffer({size:me,usage:9});try{let ee=fe.createCommandEncoder();return ee.copyBufferToBuffer(z,0,$e,0,me),fe.queue.submit([ee.finish()]),await $e.mapAsync(GPUMapMode.READ),$e.getMappedRange().slice(0,D)}finally{$e.destroy()}}},e.ie=(z,D)=>{var W=D.buffer;let fe=D.byteOffset,me=D.byteLength;if(D=16*Math.ceil(Number(me)/16),z=re(z),!_){var $e=ap(w);_=re($e)}let ee=($e=_.createBuffer({mappedAtCreation:!0,size:D,usage:6})).getMappedRange();new Uint8Array(ee).set(new Uint8Array(W,fe,me)),$e.unmap(),(W=_.createCommandEncoder()).copyBufferToBuffer($e,0,z,0,D),_.queue.submit([W.finish()]),$e.destroy()}},e.webnnInit=u=>{let d=u[0];[e.Ie,e.je,e.webnnEnsureTensor,e.ke,e.webnnDownloadTensor,e.He,e.webnnEnableTraceEvent]=u.slice(1),e.webnnReleaseTensorId=e.je,e.webnnUploadTensor=e.ke,e.webnnRegisterMLContext=e.He,e.webnnOnRunStart=_=>d.onRunStart(_),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=_=>{d.onReleaseSession(_)},e.webnnCreateMLTensorDownloader=(_,w)=>d.createMLTensorDownloader(_,w),e.webnnRegisterMLTensor=(_,w,b,T)=>d.registerMLTensor(_,w,b,T),e.webnnCreateMLContext=_=>d.createMLContext(_),e.webnnRegisterMLConstant=(_,w,b,T,I,z)=>d.registerMLConstant(_,w,b,T,I,e.Zc,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)},te?e:new Promise((u,d)=>{g=u,x=d})}var rE,ck,pP=ye(()=>{"use strict";rE=lk,ck=globalThis.self?.name?.startsWith("em-pthread"),ck&&lk()}),zp,Qp,uk,Ct,sE,Yi,pk,dk,Rp,fk,$p,nE,Bp,oE,ad=ye(()=>{"use strict";od(),zp=typeof location>"u"?void 0:location.origin,Qp=import.meta.url>"file:"&&import.meta.url<"file;",uk=()=>{if(Qp){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,zp).href}return import.meta.url},Ct=uk(),sE=()=>{if(Ct&&!Ct.startsWith("blob:"))return Ct.substring(0,Ct.lastIndexOf("/")+1)},Yi=(t,e)=>{try{let r=e??Ct;return(r?new URL(t,r):new URL(t)).origin===zp}catch{return!1}},pk=(t,e)=>{let r=e??Ct;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},dk=(t,e)=>`${e??"./"}${t}`,Rp=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},fk=async t=>(await import(t)).default,$p=(uP(),tl(Zk)).default,nE=async()=>{if(!Ct)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Yi(Ct))return[void 0,$p()];let t=await Rp(Ct);return[t,$p(t)]},Bp=(pP(),tl(tE)).default,oE=async(t,e,r,s)=>{let n=Bp&&!(t||e);if(n)if(Ct)n=Yi(Ct);else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Bp];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??pk(o,e),i=r&&a&&!Yi(a,e),l=i?await Rp(a):a??dk(o,e);return[i?l:void 0,await fk(l)]}}}),Up,Ki,Wn,Dp,mk,hk,_k,id,Be,ms=ye(()=>{"use strict";ad(),Ki=!1,Wn=!1,Dp=!1,mk=()=>{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}},hk=()=>{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}},_k=()=>{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}},id=async t=>{if(Ki)return Promise.resolve();if(Wn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Dp)throw new Error("previous call to 'initializeWebAssembly()' failed.");Wn=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!_k())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!hk())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=mk();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 oE(i,o,r>1,!!p||!!c),h=!1,g=[];if(e>0&&g.push(new Promise(x=>{setTimeout(()=>{h=!0,x()},e)})),g.push(new Promise((x,k)=>{let E={numThreads:r};if(p)E.wasmBinary=p;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=sE();A&&(E.locateFile=S=>A+S)}m(E).then(A=>{Wn=!1,Ki=!0,Up=A,x(),f&&URL.revokeObjectURL(f)},A=>{Wn=!1,Dp=!0,k(A)})})),await Promise.race(g),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Be=()=>{if(Ki&&Up)return Up;throw new Error("WebAssembly is not initialized yet.")}}),Pt,sl,Oe,ld=ye(()=>{"use strict";ms(),Pt=(t,e)=>{let r=Be(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},sl=(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")sl(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}`)})},Oe=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)}}}),aE,dP=ye(()=>{"use strict";ms(),ld(),aE=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=Pt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Oe("Can't create run options."),t?.extra!==void 0&&sl(t.extra,"",new WeakSet,(a,i)=>{let l=Pt(a,s),c=Pt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&Oe(`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}}}),wk,gk,xk,Qi,Ar,yk,iE,fP=ye(()=>{"use strict";ms(),ld(),wk=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}`)}},gk=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},xk=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)},Qi=(t,e,r,s)=>{let n=Pt(e,s),o=Pt(r,s);Be()._OrtAddSessionConfigEntry(t,n,o)!==0&&Oe(`Can't set a session config entry: ${e} - ${r}.`)},Ar=(t,e,r,s)=>{let n=Pt(e,s),o=Pt(r,s);t.push([n,o])},yk=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&&Qi(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let h=n;if(h.device)if(typeof GPUDevice<"u"&&h.device instanceof GPUDevice)f=h.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:g}=e;if(typeof g=="boolean"&&g&&Ar(a,"enableGraphCapture","1",r),typeof h.preferredLayout=="string"&&Ar(a,"preferredLayout",h.preferredLayout,r),h.forceCpuNodeNames){let x=Array.isArray(h.forceCpuNodeNames)?h.forceCpuNodeNames:[h.forceCpuNodeNames];Ar(a,"forceCpuNodeNames",x.join(`
|
|
15
|
+
`),r)}h.validationMode&&Ar(a,"validationMode",h.validationMode,r)}let m=Be().webgpuRegisterDevice(f);if(m){let[h,g,x]=m;Ar(a,"deviceId",h.toString(),r),Ar(a,"webgpuInstance",g.toString(),r),Ar(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=Pt(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&&Oe(`Can't append execution provider: ${o}.`)}},iE=async t=>{let e=Be(),r=0,s=[],n=t||{};xk(n);try{let o=wk(n.graphOptimizationLevel??"all"),a=gk(n.executionMode??"sequential"),i=typeof n.logId=="string"?Pt(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"?Pt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),r===0&&Oe("Can't create session options."),n.executionProviders&&await yk(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Qi(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 h=Pt(f,s);e._OrtAddFreeDimensionOverride(r,h,m)!==0&&Oe(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&sl(n.extra,"",new WeakSet,(f,m)=>{Qi(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Oe("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),cs,el,Gs,Yn,nl,cd,ud,Jp,Ws=ye(()=>{"use strict";cs=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}`)}},el=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}`)}},Gs=(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},Yn=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}`)}},nl=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}`)}},cd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",ud=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Jp=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}`)}}}),pd,lE=ye(()=>{"use strict";od(),pd=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)}}),cE,mP=ye(()=>{"use strict";Ws(),cE=(t,e)=>new(Yn(e))(t)}),bk,vk,kk,Ek,uE,Ak,wt,pE=ye(()=>{"use strict";Ws(),bk=["V","I","W","E","F"],vk=(t,e)=>{console.log(`[${bk[t]},${new Date().toISOString()}]${e}`)},uE=(t,e)=>{kk=t,Ek=e},Ak=(t,e)=>{let r=nl(t),s=nl(kk);r>=s&&vk(r,typeof e=="function"?e():e)},wt=(...t)=>{Ek&&Ak(...t)}}),Fp,Zp,jp,Tk,Gp,Mk,Wp,qp,Vp,Sk,dE,hP=ye(()=>{"use strict";Ws(),pE(),Fp=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Zp=(t,e)=>{if(e==="int32")return t;let r=Fp.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(Yn(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'`)}},jp=(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}`)}},Tk=1,Gp=()=>Tk++,Mk=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Wp=(t,e)=>{let r=Fp.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},qp=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 Wp(this.dataType,this.tensorShape)}destroy(){wt("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=jp(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}},Vp=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=Mk.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);wt("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!==Wp(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=Zp(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 wt("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?jp(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()}},Sk=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=Gp();return this.tensorTrackersById.set(t,new Vp(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){wt("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){wt("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=Gp(),a=new qp({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new Vp(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)){wt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}wt("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 qp({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)}},dE=(...t)=>new Sk(...t)}),fE={};Kn(fE,{WebNNBackend:()=>mE});var qn,Ok,mE,_P=ye(()=>{"use strict";Ws(),ms(),mP(),hP(),pE(),qn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Ok=(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])},mE=class{constructor(t){this.tensorManager=dE(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,uE(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){wt("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){wt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)wt("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=>Ok(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){wt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=qn.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){wt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=qn.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");wt("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 cE(r,e)}}registerMLTensor(t,e,r,s){let n=qn.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return wt("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=Zp(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 wt("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=qn.get(cs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),Ik,dd,fd,Tr,Ck,Hp,ol,md,hd,Xp,_d,wd,gd,hE=ye(()=>{"use strict";fs(),dP(),fP(),Ws(),ms(),ld(),lE(),Ik=(t,e)=>{Be()._OrtInit(t,e)!==0&&Oe("Can't initialize onnxruntime.")},dd=async t=>{Ik(t.wasm.numThreads,nl(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(_P(),tl(fE)).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])}},Tr=new Map,Ck=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&&Oe("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)}},Hp=(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&&Oe("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)}},ol=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]},md=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]=ol(t);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await iE(e),e?.externalData&&n.mountExternalData){let M=[];for(let L of e.externalData){let C=typeof L=="string"?L:L.path;M.push(pd(typeof L=="string"?L:L.data).then(v=>{n.mountExternalData(C,v)}))}await Promise.all(M)}for(let M of e?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof M!="string"){let L=M,C=L?.context,v=L?.gpuDevice,G=L?.deviceType,X=L?.powerPreference;C?n.currentContext=C:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:G,powerPreference:X})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Oe("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=Ck(o),h=!!e?.enableGraphCapture,g=[],x=[],k=[],E=[],A=[];for(let M=0;M<f;M++){let[L,C,v]=Hp(o,M);L===0&&Oe("Can't get an input name."),c.push(L);let G=n.UTF8ToString(L);g.push(G),k.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:el(C),shape:v})}for(let M=0;M<m;M++){let[L,C,v]=Hp(o,M+f);L===0&&Oe("Can't get an output name."),p.push(L);let G=n.UTF8ToString(L);x.push(G),E.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:el(C),shape:v});{if(h&&e?.preferredOutputLocation===void 0){A.push("gpu-buffer");continue}let X=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[G]??"cpu",V=n.webnnIsGraphOutput;if(X==="cpu"&&V&&V(o,G)){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(h&&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&&Oe("Can't create IO binding."),S={handle:i,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>Jp(M))}),Tr.set(o,[o,c,p,S,h,!1]),[o,g,x,k,E]}catch(f){throw c.forEach(m=>n._OrtFree(m)),p.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Oe("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Oe("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Oe("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},hd=t=>{let e=Be(),r=Tr.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&&Oe("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Oe("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&&Oe("Can't release session."),Tr.delete(t)},Xp=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,h,g;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;g=Gs(cs(c),p);{let A=i.webgpuRegisterBuffer;if(!A)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=A(E,s)}}else if(f==="ml-tensor"){let E=t[2].mlTensor;g=Gs(cs(c),p);let A=i.webnnRegisterMLTensor;if(!A)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=A(s,E,cs(c),p)}else{let E=t[2];if(Array.isArray(E)){g=l*E.length,h=i._malloc(g),r.push(h);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(h+A*l,Pt(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 L=cs(c);g=Gs(L,p),m="ml-tensor";let C=i.webnnCreateTemporaryTensor,v=i.webnnUploadTensor;if(!C||!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let G=await C(s,L,p);v(G,new Uint8Array(E.buffer,E.byteOffset,E.byteLength)),h=G}else g=E.byteLength,h=i._malloc(g),r.push(h),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,g),h)}else g=E.byteLength,h=i._malloc(g),r.push(h),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,g),h)}}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 E=i._OrtCreateTensor(cs(c),h,g,k,p.length,Jp(m));E===0&&Oe(`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=Tr.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],h=l[4],g=l[5],x=e.length,k=s.length,E=0,A=[],S=[],M=[],L=[],C=[],v=a.stackSave(),G=a.stackAlloc(x*i),X=a.stackAlloc(x*i),V=a.stackAlloc(k*i),Q=a.stackAlloc(k*i);try{[E,A]=aE(o),Sr("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)await Xp(r[P],S,L,t,p[e[P]],e[P],h);for(let P=0;P<k;P++)await Xp(n[P],M,L,t,f[s[P]],x+s[P],h);Or("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)a.setValue(G+P*i,S[P],"*"),a.setValue(X+P*i,p[e[P]],"*");for(let P=0;P<k;P++)a.setValue(V+P*i,M[P],"*"),a.setValue(Q+P*i,f[s[P]],"*");if(m&&!g){let{handle:P,outputPreferredLocations:se,outputPreferredLocationsEncoded:ie}=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}).`);Sr("wasm bindInputsOutputs");for(let O=0;O<x;O++){let N=e[O];await a._OrtBindInput(P,p[N],S[O])!==0&&Oe(`Can't bind input[${O}] for session=${t}.`)}for(let O=0;O<k;O++){let N=s[O];n[O]?.[3]?(C.push(M[O]),a._OrtBindOutput(P,f[N],M[O],0)!==0&&Oe(`Can't bind pre-allocated output[${O}] for session=${t}.`)):a._OrtBindOutput(P,f[N],0,ie[N])!==0&&Oe(`Can't bind output[${O}] to ${se[O]} for session=${t}.`)}Or("wasm bindInputsOutputs"),Tr.set(t,[c,p,f,m,h,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let Y;m?Y=await a._OrtRunWithBinding(c,m.handle,k,V,E):Y=await a._OrtRun(c,X,G,x,Q,k,V,E),Y!==0&&Oe("failed to call OrtRun().");let K=[],U=[];Sr("wasm ProcessOutputTensor");for(let P=0;P<k;P++){let se=Number(a.getValue(V+P*i,"*"));if(se===M[P]||C.includes(M[P])){K.push(n[P]),se!==M[P]&&a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.");continue}let ie=a.stackSave(),O=a.stackAlloc(4*i),N=!1,$,te=0;try{a._OrtGetTensorData(se,O,O+i,O+2*i,O+3*i)!==0&&Oe(`Can't access output tensor data on index ${P}.`);let ue=i===4?"i32":"i64",Ue=Number(a.getValue(O,ue));te=a.getValue(O+i,"*");let Ce=a.getValue(O+i*2,"*"),kt=Number(a.getValue(O+i*3,ue)),Qe=[];for(let Te=0;Te<kt;Te++)Qe.push(Number(a.getValue(Ce+Te*i,ue)));a._OrtFree(Ce)!==0&&Oe("Can't free memory for tensor dims.");let Ze=Qe.reduce((Te,xe)=>Te*xe,1);$=el(Ue);let rt=m?.outputPreferredLocations[s[P]];if($==="string"){if(rt==="gpu-buffer"||rt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Te=[];for(let xe=0;xe<Ze;xe++){let Ge=a.getValue(te+xe*i,"*"),Et=a.getValue(te+(xe+1)*i,"*"),we=xe===Ze-1?void 0:Et-Ge;Te.push(a.UTF8ToString(Ge,we))}K.push([$,Qe,Te,"cpu"])}else if(rt==="gpu-buffer"&&Ze>0){let Te=a.webgpuGetBuffer;if(!Te)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=Te(te),Ge=Gs(Ue,Ze);if(Ge===void 0||!cd($))throw new Error(`Unsupported data type: ${$}`);N=!0;{a.webgpuRegisterBuffer(xe,t,te);let Et=a.webgpuCreateDownloader(xe,Ge,t);K.push([$,Qe,{gpuBuffer:xe,download:async()=>{let we=await Et();return new(Yn($))(we)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.")}},"gpu-buffer"])}}else if(rt==="ml-tensor"&&Ze>0){let Te=a.webnnEnsureTensor,xe=a.webnnIsGraphInputOutputTypeSupported;if(!Te||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Gs(Ue,Ze)===void 0||!ud($))throw new Error(`Unsupported data type: ${$}`);if(!xe(t,$,!1))throw new Error(`preferredLocation "ml-tensor" for ${$} output is not supported by current WebNN Context.`);let Ge=await Te(t,te,Ue,Qe,!1);N=!0,K.push([$,Qe,{mlTensor:Ge,download:a.webnnCreateMLTensorDownloader(te,$),dispose:()=>{a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(rt==="ml-tensor-cpu-output"&&Ze>0){let Te=a.webnnCreateMLTensorDownloader(te,$)(),xe=K.length;N=!0,U.push((async()=>{let Ge=[xe,await Te];return a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se),Ge})()),K.push([$,Qe,[],"cpu"])}else{let Te=Yn($),xe=new Te(Ze);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(a.HEAPU8.subarray(te,te+xe.byteLength)),K.push([$,Qe,xe,"cpu"])}}finally{a.stackRestore(ie),$==="string"&&te&&a._free(te),N||a._OrtReleaseTensor(se)}}m&&!h&&(a._OrtClearBoundOutputs(m.handle)!==0&&Oe("Can't clear bound outputs."),Tr.set(t,[c,p,f,m,h,!1]));for(let[P,se]of await Promise.all(U))K[P][2]=se;return Or("wasm ProcessOutputTensor"),K}finally{a.webnnOnRunEnd?.(c),a.stackRestore(v),r.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),n.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),S.forEach(Y=>a._OrtReleaseTensor(Y)),M.forEach(Y=>a._OrtReleaseTensor(Y)),L.forEach(Y=>a._free(Y)),E!==0&&a._OrtReleaseRunOptions(E),A.forEach(Y=>a._free(Y))}},wd=t=>{let e=Be(),r=Tr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Oe("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}}),Mr,Dt,js,Vn,Hn,Ji,Yp,Zi,as,is,Pk,_E,wE,gE,xE,yE,bE,vE,kE=ye(()=>{"use strict";fs(),hE(),ms(),ad(),Mr=()=>!!qe.wasm.proxy&&typeof document<"u",js=!1,Vn=!1,Hn=!1,Zi=new Map,as=(t,e)=>{let r=Zi.get(t);r?r.push(e):Zi.set(t,[e])},is=()=>{if(js||!Vn||Hn||!Dt)throw new Error("worker not ready")},Pk=t=>{switch(t.data.type){case"init-wasm":js=!1,t.data.err?(Hn=!0,Yp[1](t.data.err)):(Vn=!0,Yp[0]()),Ji&&(URL.revokeObjectURL(Ji),Ji=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Zi.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},_E=async()=>{if(!Vn){if(js)throw new Error("multiple calls to 'initWasm()' detected.");if(Hn)throw new Error("previous call to 'initWasm()' failed.");if(js=!0,Mr())return new Promise((t,e)=>{Dt?.terminate(),nE().then(([r,s])=>{try{Dt=s,Dt.onerror=o=>e(o),Dt.onmessage=Pk,Yp=[t,e];let n={type:"init-wasm",in:qe};!n.in.wasm.wasmPaths&&(r||Qp)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Dt.postMessage(n),Ji=r}catch(n){e(n)}},e)});try{await id(qe.wasm),await dd(qe),Vn=!0}catch(t){throw Hn=!0,t}finally{js=!1}}},wE=async t=>{if(Mr())return is(),new Promise((e,r)=>{as("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:qe}};Dt.postMessage(s)});await fd(qe,t)},gE=async t=>Mr()?(is(),new Promise((e,r)=>{as("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Dt.postMessage(s,[t.buffer])})):ol(t),xE=async(t,e)=>{if(Mr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return is(),new Promise((r,s)=>{as("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Dt.postMessage(n,o)})}else return md(t,e)},yE=async t=>{if(Mr())return is(),new Promise((e,r)=>{as("release",[e,r]);let s={type:"release",in:t};Dt.postMessage(s)});hd(t)},bE=async(t,e,r,s,n,o)=>{if(Mr()){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 is(),new Promise((a,i)=>{as("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Dt.postMessage(c,gd(l))})}else return _d(t,e,r,s,n,o)},vE=async t=>{if(Mr())return is(),new Promise((e,r)=>{as("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Dt.postMessage(s)});wd(t)}}),Kp,Lk,EE,wP=ye(()=>{"use strict";fs(),kE(),Ws(),od(),lE(),Kp=(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()}`)}},Lk=t=>{switch(t[3]){case"cpu":return new Jt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!cd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Jt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!ud(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Jt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},EE=class{async fetchModelAndCopyToWasmMemory(t){return gE(await pd(t))}async loadModel(t,e){ps();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await xE(r,e),ds()}async dispose(){return yE(this.sessionId)}async run(t,e,r){ps();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],h=f[1],g=this.inputNames.indexOf(m);if(g===-1)throw new Error(`invalid input '${m}'`);s.push(h),n.push(g)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],h=f[1],g=this.outputNames.indexOf(m);if(g===-1)throw new Error(`invalid output '${m}'`);o.push(h),a.push(g)});let i=s.map((f,m)=>Kp(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?Kp(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await bE(this.sessionId,n,i,a,l,r),p={};for(let f=0;f<c.length;f++)p[this.outputNames[a[f]]]=o[f]??Lk(c[f]);return ds(),p}startProfiling(){}endProfiling(){vE(this.sessionId)}}}),AE={};Kn(AE,{OnnxruntimeWebAssemblyBackend:()=>td,initializeFlags:()=>ed,wasmBackend:()=>TE});var ed,td,TE,gP=ye(()=>{"use strict";fs(),kE(),wP(),ed=()=>{(typeof qe.wasm.initTimeout!="number"||qe.wasm.initTimeout<0)&&(qe.wasm.initTimeout=0);let t=qe.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.`),qe.wasm.simd=!1),typeof qe.wasm.proxy!="boolean"&&(qe.wasm.proxy=!1),typeof qe.wasm.trace!="boolean"&&(qe.wasm.trace=!1),typeof qe.wasm.numThreads!="number"||!Number.isInteger(qe.wasm.numThreads)||qe.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)qe.wasm.numThreads=1;else{let e=typeof navigator>"u"?YC("node:os").cpus().length:navigator.hardwareConcurrency;qe.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},td=class{async init(t){ed(),await _E(),await wE(t)}async createInferenceSessionHandler(t,e){let r=new EE;return await r.loadModel(t,e),r}},TE=new td});fs();fs();fs();var xP="1.25.0-dev.20260212-1a71a5f46e",yP=Jk;{let t=(gP(),tl(AE)).wasmBackend;us("webgpu",t,5),us("webnn",t,5),us("cpu",t,10),us("wasm",t,10)}Object.defineProperty(qe.versions,"web",{value:xP,enumerable:!0});async function ME(t){let e=t.split("/").pop(),r;try{if(r=await Wi(),r){let n=await r.match(t);if(n)return n}}catch(n){console.warn(`Failed to load ${e} from cache:`,n)}let s=await 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){console.warn(`Failed to cache ${e}:`,n)}return s}async function SE(t){let e=await ME(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return console.warn("Failed to read WASM binary:",r),null}}async function OE(t){let e=await ME(t);if(!e||typeof e=="string")return null;try{let r=await e.text(),s=t.split("/").slice(0,-1).join("/");r=r.replace(/import\.meta\.url/g,`"${s}"`);let n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return console.warn("Failed to read WASM binary:",r),null}}function yd(t){return Ds(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 IE="1.24.0-dev.20251116-b39e144322";var CE="warning",vd={wasm:{},webgl:{},webgpu:{},versions:{common:IE},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}`);CE=t}},get logLevel(){return CE}};Object.defineProperty(vd,"logLevel",{enumerable:!0});var PE=(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,h=p*2,g=-1;a==="RGBA"?(f=0,m=p,h=p*2,g=p*3):a==="RGB"?(f=0,m=p,h=p*2):a==="RBG"&&(f=0,h=p,m=p*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let E=(t.data[f++]-c[0])*l[0],A=(t.data[m++]-c[1])*l[1],S=(t.data[h++]-c[2])*l[2],M=g===-1?255:(t.data[g++]-c[3])*l[3];s.fillStyle="rgba("+E+","+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")},LE=(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,h=0,g=1,x=2,k=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 L=0;L<o*n;h+=m,g+=m,x+=m,k+=m,L++)s.data[h]=(t.data[E++]-p[0])*c[0],s.data[g]=(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 kd=(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,h=1,g=2,x=3,k=0,E=c,A=c*2,S=-1;i==="RGB"&&(f=3,m=0,h=1,g=2,x=-1),l==="RGBA"?S=c*3:l==="RBG"?(k=0,A=c,E=c*2):l==="BGR"&&(A=0,E=c,k=c*2);for(let L=0;L<c;L++,m+=f,g+=f,h+=f,x+=f)p[k++]=(t[m]+a[0])/o[0],p[E++]=(t[h]+a[1])/o[1],p[A++]=(t[g]+a[2])/o[2],S!==-1&&x!==-1&&(p[S++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new ft("float32",p,[1,4,r,s]):new ft("float32",p,[1,3,r,s])},NE=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,h=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,h=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=h}else i.tensorFormat="RGBA",i.height=m,i.width=h;f.drawImage(t,0,0),a=f.getImageData(0,0,h,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 h=c(m);if(h!=null)h.putImageData(t,0,0),a=h.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,h=t.width;return f.drawImage(t,0,0,h,m),a=f.getImageData(0,0,h,m).data,i.height=m,i.width=h,kd(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,f)=>{let m=l(),h=c(m);if(!t||!h)return f();let g=new Image;g.crossOrigin="Anonymous",g.src=t,g.onload=()=>{m.width=g.width,m.height=g.height,h.drawImage(g,0,0,m.width,m.height);let x=h.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,p(kd(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return kd(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},zE=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new ft({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},RE=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new ft({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},$E=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new ft({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},BE=(t,e,r)=>new ft({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var hs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Qn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),UE=!1,DE=()=>{if(!UE){UE=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(hs.set("int64",BigInt64Array),Qn.set(BigInt64Array,"int64")),e&&(hs.set("uint64",BigUint64Array),Qn.set(BigUint64Array,"uint64")),s?(hs.set("float16",r),Qn.set(r,"float16")):hs.set("float16",Uint16Array)}};var FE=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},jE=(t,e)=>{switch(t.location){case"cpu":return new ft(t.type,t.data,e);case"cpu-pinned":return new ft({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new ft({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new ft({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new ft({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var ft=class{constructor(e,r,s){DE();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=hs.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=hs.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=Qn.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=FE(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 NE(e,r)}static fromTexture(e,r){return zE(e,r)}static fromGpuBuffer(e,r){return RE(e,r)}static fromMLTensor(e,r){return $E(e,r)}static fromPinnedBuffer(e,r,s){return BE(e,r,s)}toDataURL(e){return PE(this,e)}toImageData(e){return LE(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 jE(this,e)}};var al=ft;var bP=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"}}),vP=["verbose","info","warning","error","fatal"],VE=4,Ft=[],Ed,Vs,GE=Symbol.for("onnxruntime");if(GE in globalThis)Vs=globalThis[GE];else if(be.IS_NODE_ENV){switch(Vs=Op,process.platform){case"win32":Ft.push("dml");break;case"linux":process.arch==="x64"&&Ft.push("cuda");break;case"darwin":Ft.push("coreml");break}Ft.push("webgpu"),Ft.push("cpu"),Ed=["cpu"]}else Vs=xd,be.IS_WEBNN_AVAILABLE&&Ft.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),be.IS_WEBGPU_AVAILABLE&&Ft.push("webgpu"),Ft.push("wasm"),Ed=["wasm"];var kP=Vs.InferenceSession;function HE(t=null){if(!t)return Ed;switch(t){case"auto":return Ft;case"gpu":return Ft.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Ft.includes(t))return[bP[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Ft.join(", ")}.`)}var XE=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV,WE=Promise.resolve(),qs=null;async function EP(){return qs||(De.useWasmCache&&typeof mt?.wasm?.wasmPaths=="object"&&mt?.wasm?.wasmPaths?.wasm&&mt?.wasm?.wasmPaths?.mjs?(qs=(async()=>{let e=mt.wasm.wasmPaths;await Promise.all([e.wasm&&!yd(e.wasm)?(async()=>{try{let r=await SE(bd(e.wasm));r&&(mt.wasm.wasmBinary=r)}catch(r){console.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!yd(e.mjs)?(async()=>{try{let r=await OE(bd(e.mjs));r&&(mt.wasm.wasmPaths.mjs=r)}catch(r){console.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),qs):(qs=Promise.resolve(),qs))}async function il(t,e,r){await EP();let s=()=>kP.create(t,{logSeverityLevel:VE,...e}),n=await(XE?WE=WE.then(s):s());return n.config=r,n}var qE=Promise.resolve();async function ll(t,e){let r=()=>t.run(e);return await(XE?qE=qE.then(r):r())}function cl(t){return t instanceof Vs.Tensor}var mt=Vs?.env;mt.logLevel=vP[VE];if(mt?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&mt.versions?.web&&!mt.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${mt.versions.web}/dist/`;mt.wasm.wasmPaths=be.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}mt.wasm.proxy=!1}mt?.webgpu&&(mt.webgpu.powerPreference="high-performance");function Jn(){return mt?.wasm?.proxy}De.backends.onnx=mt;var Ir=async(t,e,r)=>{let s=await il(new Uint8Array(t),e);return(async n=>{let o=Jn(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await ll(s,a);return Array.isArray(r)?r.map(l=>new B(i[l])):new B(i[r])})},ir=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Ir([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=Ir([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=Ir([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=Ir([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=Ir([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=Ir([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=Ir([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=Ir([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 YE=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"});var KE=(function(){let t;return async function(){if(t===void 0)if(!be.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),ht=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Ad=Object.freeze({[YE.wasm]:ht.q8}),Td=Object.freeze({[ht.fp32]:"",[ht.fp16]:"_fp16",[ht.int8]:"_int8",[ht.uint8]:"_uint8",[ht.q8]:"_quantized",[ht.q4]:"_q4",[ht.q4f16]:"_q4f16",[ht.bnb4]:"_bnb4"}),Hs=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 B=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 cl(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new al(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=lr(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 AP(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=lr(f,this.dims[p],p),s.push([f,f+1]);else if(Array.isArray(f)&&f.length===2){let[m,h]=f;if(m=m===null?0:lr(m,this.dims[p],p,!1),h=h===null?this.dims[p]:lr(h,this.dims[p],p,!1),m>h)throw new Error(`Invalid slice: ${f}`);let g=[Math.max(m,0),Math.min(h,this.dims[p])];s.push(g),r.push(g[1]-g[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 h=0;h<m.length;++h)i[h]=m[h]}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,h=p;m>=0;--m){let g=n[m];f+=(h%g+s[m][0])*l[m],h=Math.floor(h/g)}i[p]=a[f]}return new t(this.type,i,r)}permute(...e){return TP(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=(c,p)=>c+p**e;if(r===null){let c=n.reduce(o,0)**(1/e);return new t(this.type,[c],[])}let[a,i,l]=Zn(o,this,r,s);if(e!==1)for(let c=0;c<i.length;++c)i[c]=i[c]**(1/e);return new t(a,i,l)}normalize_(e=2,r=1){r=lr(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 Md(this.dims)}squeeze(e=null){return new t(this.type,this.data,QE(this.dims,e))}squeeze_(e=null){return this.dims=QE(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,JE(this.dims,e))}unsqueeze_(e){return this.dims=JE(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 dl(this,e,r)}min(e=null,r=!1){if(e===null){let a=jn(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Zn((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=Me(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Zn((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=jn(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=Me(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=Md(s),c=Md(n);for(let p=0;p<o;++p){let f=p,m=0;for(let h=0;h<n.length;++h){let g=Math.floor(f/c[h]);f=f%c[h];let x=g%s[h];m+=x*l[h]}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(!Hs.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,ak(this.data),this.dims);return new t(e,Hs[e].from(this.data,r),this.dims)}};function AP(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 TP(t,e){let[r,s]=ek(t.data,t.dims,e);return new B(t.type,r,s)}function Sd(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=Zv(t.data,[o,a,i],[e,r],s,n);return new B(t.type,l,[o,e,r])}async function jt(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 ir.nearest_interpolate_4d;else if(r==="bilinear")n=await ir.bilinear_interpolate_4d;else if(r==="bicubic")n=await ir.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new B("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function ZE(t,e){return await(await ir.matmul)({a:t,b:e})}async function k3(t,e){return await(await ir.rfft)({x:t,a:e})}async function Zt(t,e){let r=await ir.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new B("int64",[BigInt(e)],[1])})}var ul=t=>new B("int64",t,[t.length]);async function pl(t,e,r,s,n){return await(await ir.slice)({x:t,s:ul(e),e:ul(r),a:ul(s),t:ul(n??new Array(s.length).fill(1))})}function eA(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 h=0,g=0,x=p*i,k=f+m;for(let A=0;A<i;++A){let S=Number(s[x+A]);g+=S,h+=r[k+A*l]*S}let E=h/g;o[c++]=E}}return new B(t.type,o,n)}function E3(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]=Od(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 h=0;h<n;++h){let g=m+h;p[g]=(c[g]-l[f])/(i[f]+r)}}return new B(t.type,p,t.dims)}function QE(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 JE(t,e){return e=lr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function lr(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 Ee(t,e=0){e=lr(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,h=p,g=1;m>=0;--m){let x=c[m],k=h%x;m===e&&(k+=a),f+=k*g,g*=r[m],h=Math.floor(h/x)}n[f]=l[p]}a+=c[e]}}return new B(o,n,r)}function Gt(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function Zn(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=lr(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,h=1;f>=0;--f){let g=a[f];if(f!==r){let x=m%g;p+=x*h,h*=i[f]}m=Math.floor(m/g)}l[p]=t(l[p],o[c],c,p)}return s||i.splice(r,1),[e.type,l,i]}function Od(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let h=n.reduce((E,A)=>E+A,0)/n.length,g=Math.sqrt(n.reduce((E,A)=>E+(A-h)**2,0)/(n.length-r)),x=new B(t.type,[h],[]);return[new B(t.type,[g],[]),x]}e=lr(e,o.length);let a=dl(t,e,s),i=a.data,[l,c,p]=Zn((m,h,g,x)=>m+(h-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 B(l,c,p),a]}function dl(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 B(t.type,[l/n.length],[])}e=lr(e,s.length);let[o,a,i]=Zn((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 B(o,a,i)}function Md(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 Id(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new B(r,new s(n).fill(e),t)}function Ve(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 Id(t,e,r,s)}function eo(t,e){return Ve(t.dims,e)}function it(t){return Id(t,1n,"int64",BigInt64Array)}function fl(t){return it(t.dims)}function Cd(t){return Id(t,0n,"int64",BigInt64Array)}function Pd(t){return Cd(t.dims)}function A3(t){let e=t.reduce((r,s)=>r*s,1);return new B("float32",Float32Array.from({length:e},()=>Math.random()),t)}function tA(t){let e=t.reduce((s,n)=>s*n,1),r=new Float32Array(e);for(let s=0;s<e;s+=2){let n=1-Math.random(),o=Math.random(),a=Math.sqrt(-2*Math.log(n)),i=2*Math.PI*o;r[s]=a*Math.cos(i),s+1<e&&(r[s+1]=a*Math.sin(i))}return new B("float32",r,t)}function rA(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 B(s,a,[t.dims[0],t.dims[1]/8])}async function Ld(t,e){return await Promise.all([at(t,"tokenizer.json",!0,e),at(t,"tokenizer_config.json",!0,e)])}function Nd(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 MP=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function SP(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"?dt(t[n],i):dt(i,t[n])}}function OP(t,e){for(let r of Object.keys(t))t[r].length=e}function _s(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 IP(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var j=class extends Je{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new Iv(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=_s(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=_s(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=_s(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=_s(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=_s(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=_s(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=IP(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 Ld(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,h)=>this._encode_plus(m,{text_pair:r[h],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?(console.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&&(console.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(Me(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&&OP(p[m],a):n&&SP(p[m],a,h=>h==="input_ids"?this.pad_token_id:0,this.padding_side));let f={};if(i){if(!(n&&o)&&p.some(h=>{for(let g of Object.keys(h))if(h[g].length!==p[0][g]?.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 h of Object.keys(p[0]))f[h]=new B("int64",BigInt64Array.from(p.flatMap(g=>g[h]).map(BigInt)),m)}else{for(let m of Object.keys(p[0]))f[m]=p.map(h=>h[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 B&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof B&&(e=Nd(e)),!Array.isArray(e)||e.length===0||!Gv(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={},...h}={}){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 g=this._compiled_template_cache.get(n);g===void 0&&(g=new jv(n),this._compiled_template_cache.set(n,g));let x=Object.create(null);for(let E of MP){let A=_s(this.config,E);A&&(x[E]=A)}let k=g.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,...h});if(a){let E=this._call(k,{add_special_tokens:!1,padding:i,truncation:l,max_length:c,return_tensor:p,...m});return f?E:E.input_ids}return k}};function Xs(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 Tf={};ts(Tf,{AlbertTokenizer:()=>zd,AutoTokenizer:()=>J,BartTokenizer:()=>Rd,BertTokenizer:()=>$d,BlenderbotSmallTokenizer:()=>Bd,BlenderbotTokenizer:()=>Ud,BloomTokenizer:()=>Dd,CLIPTokenizer:()=>jd,CamembertTokenizer:()=>Fd,CodeGenTokenizer:()=>Wd,CodeLlamaTokenizer:()=>Gd,CohereTokenizer:()=>qd,ConvBertTokenizer:()=>Vd,DebertaTokenizer:()=>Xd,DebertaV2Tokenizer:()=>Hd,DistilBertTokenizer:()=>Yd,ElectraTokenizer:()=>Kd,EsmTokenizer:()=>Qd,FalconTokenizer:()=>Jd,GPT2Tokenizer:()=>tf,GPTNeoXTokenizer:()=>ef,GemmaTokenizer:()=>Zd,HerbertTokenizer:()=>rf,LlamaTokenizer:()=>sf,M2M100Tokenizer:()=>nf,MBart50Tokenizer:()=>af,MBartTokenizer:()=>to,MPNetTokenizer:()=>uf,MarianTokenizer:()=>of,MgpstrTokenizer:()=>lf,MobileBertTokenizer:()=>cf,NllbTokenizer:()=>pf,NougatTokenizer:()=>df,PreTrainedTokenizer:()=>j,Qwen2Tokenizer:()=>ff,RoFormerTokenizer:()=>hf,RobertaTokenizer:()=>mf,SiglipTokenizer:()=>_f,SpeechT5Tokenizer:()=>wf,SqueezeBertTokenizer:()=>gf,T5Tokenizer:()=>xf,TokenizersBackend:()=>j,VitsTokenizer:()=>bf,Wav2Vec2CTCTokenizer:()=>vf,WhisperTokenizer:()=>kf,XLMRobertaTokenizer:()=>Ef,XLMTokenizer:()=>Af});var zd=class extends j{return_token_type_ids=!0};var Rd=class extends j{};var $d=class extends j{return_token_type_ids=!0};var Bd=class extends j{};var Ud=class extends j{};var Dd=class extends j{};var Fd=class extends j{};var jd=class extends j{};var Gd=class extends j{};var Wd=class extends j{};var qd=class extends j{};var Vd=class extends j{return_token_type_ids=!0};var Hd=class extends j{return_token_type_ids=!0};var Xd=class extends j{return_token_type_ids=!0};var Yd=class extends j{};var Kd=class extends j{return_token_type_ids=!0};var Qd=class extends j{};var Jd=class extends j{};var Zd=class extends j{};var ef=class extends j{};var tf=class extends j{};var rf=class extends j{return_token_type_ids=!0};var sf=class extends j{padding_side="left"};var nf=class extends j{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 Xs(this,e,r,s)}};var of=class extends j{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)),console.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)||console.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),dt([n],super._encode_text(o))}}};var to=class extends j{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 Xs(this,e,r,s)}};var af=class extends to{};var lf=class extends j{};var cf=class extends j{return_token_type_ids=!0};var uf=class extends j{};var pf=class extends j{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 Xs(this,e,r,s)}};var df=class extends j{};var ff=class extends j{};var mf=class extends j{};var hf=class extends j{return_token_type_ids=!0};var _f=class extends j{};var wf=class extends j{};var gf=class extends j{return_token_type_ids=!0};var xf=class extends j{};var yf=class extends Bt{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},bf=class extends j{constructor(e,r){super(e,r),this._tokenizer.decoder=new yf({type:"VitsDecoder"})}};var vf=class extends j{};var sA=[["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"]],ro=new Map(sA),CP=new Map([...sA.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 nA(t){t=t.toLowerCase();let e=CP.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),ro.has(t))e=t;else{let n=t.length===2?ro.keys():ro.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var PP="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",oA=new RegExp(`^[${PP}]+$`,"gu"),kf=class extends j{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,g=m+1500,x=[],k=[],E=!1,A=null,S=new Set(this.all_special_ids);for(let C of e){let v=C.tokens,G=i?C.token_timestamps:null,X=null,V=m;if("stride"in C){let[K,U,P]=C.stride;if(f-=U,A=K-P,U&&(V=U/n+m),P)for(let se=v.length-1;se>=0;--se){let ie=Number(v[se]);if(ie>=m){if(X!==null&&(ie-m)*n<A)break;X=ie}}}let Q=[],Y=[];for(let K=0;K<v.length;++K){let U=Number(v[K]);if(S.has(U)){let P=this.decode([U]),se=ro.get(P.slice(2,-2));if(se!==void 0){if(a!==null&&se!==a&&!r){x.push(Q);let ie=this.findLongestCommonSequence(x)[0],O=this.decode(ie);p.text=O,c.push(p),x=[],Q=[],p=l()}a=p.language=se}}else if(U>=m&&U<=g){let P=(U-m)*n+f,se=os(P,2);if(X!==null&&U>=X)E=!0;else if(E||x.length>0&&U<V)E=!1;else if(p.timestamp[0]===null)p.timestamp[0]=se;else if(se!==p.timestamp[0]){p.timestamp[1]=se,x.push(Q),i&&k.push(Y);let[ie,O]=this.findLongestCommonSequence(x,k),N=this.decode(ie);p.text=N,i&&(p.words=this.collateWordTimestamps(ie,O,a)),c.push(p),x=[],Q=[],k=[],Y=[],p=l()}}else if(Q.push(U),i){let P=os(G[K]+f,2),se;if(K+1<G.length){se=os(G[K+1]+f,2);let ie=this.decode([U]);oA.test(ie)&&(se=os(Math.min(P+n,se),2))}else se=null;Y.push([P,se])}}if("stride"in C){let[K,U,P]=C.stride;f+=K-P}Q.length>0?(x.push(Q),i&&k.push(Y)):x.every(K=>K.length===0)&&(p=l(),x=[],Q=[],k=[],Y=[])}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[C,v]=this.findLongestCommonSequence(x,k),G=this.decode(C);p.text=G,i&&(p.words=this.collateWordTimestamps(C,v,a)),c.push(p)}let M=Object.create(null),L=c.map(C=>C.text).join("");if(r||s){for(let C=0;C<c.length;++C){let v=c[C];r||delete v.timestamp,s||delete v.language}if(i){let C=[];for(let v of c)for(let G of v.words)C.push(G);M={chunks:C}}else M={chunks:c}}return[L,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],h=p.length;for(let M=1;M<n+h;++M){let L=Math.max(0,n-M),C=Math.min(n,n+h-M),v=s.slice(L,C),G=Math.max(0,M-n),X=Math.min(h,M),V=p.slice(G,X);if(v.length!==V.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let Q;a?Q=v.filter((U,P)=>U===V[P]&&l[L+P]<=r[c][G+P]).length:Q=v.filter((U,P)=>U===V[P]).length;let Y=M/1e4,K=Q/M+Y;Q>1&&K>f&&(f=K,m=[L,C,G,X])}let[g,x,k,E]=m,A=Math.floor((x+g)/2),S=Math.floor((E+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 B&&(e=Nd(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|>"),h=c.startsWith(" "),g=c.trim(),x=oA.test(g);if(m||h||x||o.length===0)o.push(c),a.push(p),i.push(f);else{let k=o.length-1;o[k]+=c,a[k].push(...p),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,p=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[p]=a[c]+a[p],i[p]=dt(i[c],i[p]),l[p]=dt(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]=dt(i[c],i[p]),l[c]=dt(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 Ef=class extends j{};var Af=class extends j{return_token_type_ids=!0;constructor(e,r){super(e,r),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var J=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 Ld(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",p=Tf[c];return p||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),p=j),new p(i,l)}};var Ys="https://github.com/huggingface/transformers.js/issues/new/choose";var so="preprocessor_config.json",Ks=so,aA="processor_config.json",iA="chat_template.jinja";var ne=class extends Je{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?at(e,aA,!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?Tp(e,iA,!0,r):null]);return new this(s,n,o)}};var Bl={};ts(Bl,{ChatterboxProcessor:()=>Ff,Florence2Processor:()=>Cm,Gemma3nProcessor:()=>Pm,GroundingDinoProcessor:()=>Lm,Idefics3Processor:()=>zl,JinaCLIPProcessor:()=>zm,LlavaProcessor:()=>Rm,MgpstrProcessor:()=>$m,MoonshineProcessor:()=>Bm,OwlViTProcessor:()=>Um,PaliGemmaProcessor:()=>Dm,Phi3VProcessor:()=>Fm,PixtralProcessor:()=>jm,Processor:()=>ne,PyAnnoteProcessor:()=>Gm,Qwen2VLProcessor:()=>Wm,Sam2Processor:()=>Rl,Sam2VideoProcessor:()=>qm,SamProcessor:()=>uo,SmolVLMProcessor:()=>zl,SpeechT5Processor:()=>Vm,UltravoxProcessor:()=>Hm,VLChatProcessor:()=>Nm,VoxtralProcessor:()=>Xm,Wav2Vec2Processor:()=>Ym,Wav2Vec2ProcessorWithLM:()=>Km,WhisperProcessor:()=>Qm});var ze=class extends Je{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await at(e,so,!0,r);return new this(s)}};function He(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 lo={};ts(lo,{ASTFeatureExtractor:()=>Of,ChatterboxFeatureExtractor:()=>If,ClapFeatureExtractor:()=>Cf,DacFeatureExtractor:()=>ao,EncodecFeatureExtractor:()=>oo,FeatureExtractor:()=>ze,Gemma3nAudioFeatureExtractor:()=>Pf,MoonshineFeatureExtractor:()=>Lf,ParakeetFeatureExtractor:()=>Nf,PyAnnoteFeatureExtractor:()=>io,SeamlessM4TFeatureExtractor:()=>zf,SnacFeatureExtractor:()=>Rf,SpeechT5FeatureExtractor:()=>$f,Wav2Vec2FeatureExtractor:()=>Bf,WeSpeakerFeatureExtractor:()=>Uf,WhisperFeatureExtractor:()=>Df});var LP=()=>{};var lA={fromWeb:LP};var NP=()=>{};var cA=NP;async function ml(t,e){if(be.IS_BROWSER_ENV){if(be.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(be.IS_FS_AVAILABLE){let r=e.stream(),s=lA.fromWeb(r),n=Tt.createWriteStream(t);await cA(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function Sf(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 Fs(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&console.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 dA(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 uA(t){return dA(t,.5)}function zP(t){return dA(t,.54)}var RP={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 Mf(t,e="htk"){let r=RP[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 $P={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 BP(t,e="htk"){let r=$P[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 UP(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 pA(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+s*o)}function bt(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=Mf(r,a),c=Mf(s,a),p=pA(l,c,e+2),f=BP(p,a),m;if(i){let g=n/((t-1)*2);m=Mf(Float64Array.from({length:t},(x,k)=>k*g),a),f=p}else m=pA(0,Math.floor(n/2),t);let h=UP(m,f);if(o!==null&&o==="slaney")for(let g=0;g<e;++g){let x=h[g],k=2/(f[g+2]-f[g]);for(let E=0;E<t;++E)x[E]*=k}return h}function DP(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[Bs(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[Bs(n-o,n)];return s}function fA(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=Me(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function FP(t,e=1,r=1e-5,s=null){return fA(t,20,e,r,s)}function jP(t,e=1,r=1e-10,s=null){return fA(t,10,e,r,s)}async function Mt(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:h=null,reference:g=1,min_value:x=1e-10,db_range:k=null,remove_dc_offset:E=null,min_num_frames:A=null,max_num_frames:S=null,do_pad:M=!0,transpose:L=!1,mel_offset:C=0}={}){let v=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(v!==r)throw new Error(`Length of the window (${v}) 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 N=Math.floor((n-1)/2)+1;t=DP(t,N,N);break}case"constant":{let N=Math.floor(n/2),$=new t.constructor(t.length+2*N);$.set(t,N),t=$;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let G=Math.floor(1+Math.floor((t.length-r)/s));A!==null&&G<A&&(G=A);let X=l?Math.floor(n/2)+1:n,V=G,Q=G;S!==null&&(S>G?M&&(Q=S):Q=V=S);let Y=new Vi(n),K=new Float64Array(n),U=new Float64Array(Y.outputBufferSize),P=new Float32Array(X*Q);for(let N=0;N<V;++N){let $=N*s,te=Math.min(t.length-$,r);te!==r&&K.fill(0,0,r);for(let ue=0;ue<te;++ue)K[ue]=t[$+ue];if(E){let ue=0;for(let Ce=0;Ce<te;++Ce)ue+=K[Ce];let Ue=ue/te;for(let Ce=0;Ce<te;++Ce)K[Ce]-=Ue}if(c!==null){for(let ue=te-1;ue>=1;--ue)K[ue]-=c*K[ue-1];K[0]*=1-c}for(let ue=0;ue<e.length;++ue)K[ue]*=e[ue];Y.realTransform(U,K);for(let ue=0;ue<X;++ue){let Ue=ue<<1;P[ue*Q+N]=U[Ue]**2+U[Ue+1]**2}}if(o!==null&&o!==2){let N=o/2;for(let $=0;$<P.length;++$)P[$]**=N}let se=f.length,ie=await ZE(new B("float32",f.flat(),[se,X]),new B("float32",P,[X,Q]));L&&(ie=ie.transpose(1,0));let O=ie.data;for(let N=0;N<O.length;++N)O[N]=C+Math.max(m,O[N]);if(o!==null&&h!==null){let N=Math.min(O.length,V*se);switch(h){case"log":for(let $=0;$<N;++$)O[$]=Math.log(O[$]);break;case"log10":for(let $=0;$<N;++$)O[$]=Math.log10(O[$]);break;case"dB":if(o===1)FP(O,g,x,k);else if(o===2)jP(O,g,x,k);else throw new Error(`Cannot use log_mel option '${h}' with power ${o}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${h}'`)}}return ie}function St(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=uA(o);break;case"hamming":a=zP(o);break;case"povey":a=uA(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 GP(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return hl(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),hl(n,8,"WAVE"),hl(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),hl(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function hl(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]),GP(e,this.sampling_rate)}async save(e){return ml(e,this.toBlob())}};var Of=class extends ze{constructor(e){super(e);let r=this.config.sampling_rate,s=bt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=St(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return Mt(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){He(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 oo=class extends ze{async _call(e){He(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 B("float32",e,s)}}};var If=class extends ze{async _call(e){He(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new B("float32",e,r)}}};var Cf=class extends ze{constructor(e){super(e),this.mel_filters=bt(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=bt(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=St(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(Math.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 Mt(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 He(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 ao=class extends oo{};var Pf=class extends ze{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=bt(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=St(i,"hann")}async _extract_fbank_features(e,r){return Mt(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(He(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=Ve([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Lf=class extends ze{async _call(e){He(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new B("float32",e,r)}}};var WP=1e-5,Nf=class extends ze{constructor(e){super(e),this.config.mel_filters??=bt(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=St(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 Mt(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){He(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 h=0;h<a;++h){let g=n[m+h];i[h]+=g,l[h]+=g*g}}let c=s>1?s-1:1;for(let f=0;f<a;++f){let m=i[f]/s,h=(l[f]-s*m*m)/c,x=1/(Math.sqrt(h)+WP);for(let k=0;k<s;++k){let E=k*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 B("int64",p,[1,o])}}};var io=class extends ze{async _call(e){He(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new B("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=Pe(o[l]),[p,f]=Me(c),[m,h]=[l,l+1];f!==i?(i=f,a.push({id:f,start:m,end:h,score:p})):(a.at(-1).end=h,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 zf=class extends ze{constructor(e){super(e);let r=this.config.sampling_rate,s=bt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=St(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),Mt(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}={}){He(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[g,x]=a.dims,k=a.data;for(let E=0;E<x;++E){let A=0;for(let C=0;C<g;++C)A+=k[C*x+E];let S=A/g,M=0;for(let C=0;C<g;++C)M+=(k[C*x+E]-S)**2;M/=g-1;let L=Math.sqrt(M+1e-7);for(let C=0;C<g;++C){let v=C*x+E;k[v]=(k[v]-S)/L}}}let i;if(r){let[g,x]=a.dims,k=a.data,E=g%s;if(E>0){let A=new Float32Array(x*(g+E));A.set(k),A.fill(this.config.padding_value,k.length);let S=g+E;a=new B(a.type,A,[S,x]),o&&(i=new B("int64",new BigInt64Array(S),[1,S]),i.data.fill(1n,0,g))}}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),h={input_features:m};if(o){let g=m.dims[1],x=new BigInt64Array(g);if(i){let k=i.data;for(let E=1,A=0;E<l;E+=p,++A)x[A]=k[E]}else x.fill(1n);h.attention_mask=new B("int64",x,[1,g])}return h}};var Rf=class extends ao{};var $f=class extends ze{};var Bf=class extends ze{_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){He(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 B("float32",r,s),attention_mask:new B("int64",new BigInt64Array(r.length).fill(1n),s)}}};var Uf=class extends ze{constructor(e){super(e);let r=this.config.sampling_rate,s=bt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=St(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),Mt(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){He(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 h=0;h<i;++h)n[m+h]-=s[p+h]}}}return{input_features:r}}};var Df=class extends ze{constructor(e){super(e),this.config.mel_filters??=bt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=St(this.config.n_fft,"hann")}async _extract_fbank_features(e){let r=await Mt(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)}),s=r.data,n=Me(s)[0];for(let o=0;o<s.length;++o)s[o]=(Math.max(s[o],n-8)+4)/4;return r}async _call(e,{max_length:r=null}={}){He(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&console.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 tt=class{static async from_pretrained(e,r={}){let s=await at(e,so,!0,r),n=s.feature_extractor_type,o=lo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Ys}.`);return new o(s)}};var Ff=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var qP={},_l=qP;var ws,mA,Cr,er=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV;if(er)ws=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},Cr=self.createImageBitmap,mA=self.ImageData;else if(_l)Cr=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Xe(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 VP={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},HP=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Xe=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(!er)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 Fs(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(er){let r=await Cr(e),s=ws(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=_l(await e.arrayBuffer());return await Cr(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=VP[s]??s,o=Ep(e),a=Ep(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),er){let i=this.channels,l=this.toCanvas(),c=ws(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")&&(console.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 Cr(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(er){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,c=ws(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 Cr(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(er){let i=this.channels,l=this.toCanvas(),c=ws(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 Cr(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(er){let o=this.channels,a=this.toCanvas(),i=ws(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 Cr(o)}}async toBlob(e="image/png",r=1){if(!er)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 B("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(!er)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=ws(e.width,e.height),s=new mA(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(er){if(be.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=HP.get(r)??"image/png",n=await this.toBlob(s);return ml(e,n)}else if(be.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(er)throw new Error("toSharp() is only supported in server-side environments.");return _l(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},XP=Xe.read.bind(Xe);function hA(t,e,r=0,s=null){let n=t/e,o=nk(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function jf([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function Gf([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Pr(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:[]},h=n[p],g=o[p];for(let x=0;x<i;++x){let k=h[x],E=[],A;if(s){A=k.sigmoid().data;for(let S=0;S<A.length;++S)A[S]>e&&E.push(S)}else{let S=Me(k.data)[1];if(S===l-1||(A=Pe(k.data),A[S]<e))continue;E.push(S)}for(let S of E){let M=g[x].data;M=Gf(M),f!==null&&(M=M.map((L,C)=>L*f[(C+1)%2])),m.boxes.push(M),m.classes.push(S),m.scores.push(A[S])}}c.push(m)}return c}function wl(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=Sd(i,a,"bilinear",!1));let[l,c]=a??i.dims.slice(-2),p=new B("int32",new Int32Array(l*c),[l,c]),f=i[0].data,m=p.data;for(let x=1;x<i.dims[0];++x){let k=i[x].data;for(let E=0;E<k.length;++E)k[E]>f[E]&&(f[E]=k[E],m[E]=x)}let h=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let k=m[x];h[k]=k}let g=h.filter(x=>x!==void 0);n.push({segmentation:p,labels:g})}return n}function YP(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=Me(l.data)[1];if(p===s)continue;let m=Pe(l.data)[p];m>r&&(n.push(c),o.push(m),a.push(p))}return[n,o,a]}function KP(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 QP(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new B("int32",new Int32Array(i*l),[i,l]),p=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=Sd(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 k=e[x],E=t[x].data;for(let A=0;A<E.length;++A)E[A]*=k,E[A]>m[A]&&(f[A]=x,m[A]=E[A])}let h=0,g=c.data;for(let x=0;x<r.length;++x){let k=r[x],[E,A]=KP(f,t,x,s,n);if(E){++h;for(let S of A)g[S]=h;p.push({id:h,label_id:k,score:e[x]})}}return[c,p]}function JP(t,e,r=28,s=3136,n=784*1280){if(t<r||e<r)throw new Error(`height:${t} or width:${e} must be larger than factor:${r}`);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 o=Math.round(t/r)*r,a=Math.round(e/r)*r;if(o*a>n){let i=Math.sqrt(t*e/n);o=Math.floor(t/i/r)*r,a=Math.floor(e/i/r)*r}else if(o*a<s){let i=Math.sqrt(s/(t*e));o=Math.ceil(t*i/r)*r,a=Math.ceil(e*i/r)*r}return[o,a]}function gl(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(console.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 h=0;h<c;++h){let g=o!==null?o[h]:null,x=a[h],k=l[h],[E,A,S]=YP(x,k,e,f);if(S.length===0){let[C,v]=g??k.dims.slice(-2),G=new B("int32",new Int32Array(C*v).fill(-1),[C,v]);m.push({segmentation:G,segments_info:[]});continue}let[M,L]=QP(E,A,S,r,s,n,g);m.push({segmentation:M,segments_info:L})}return m}function xl(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var q=class extends Je{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&&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=jn(s.data)[0],a=Me(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 h=0;h<s.height;++h){let g=h*s.width;for(let x=0;x<s.width;++x)(m[g+x]-n)/a<i&&(l=Math.min(l,x),c=Math.min(c,h),p=Math.max(p,x),f=Math.max(f,h))}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[h,g]=o?[Math.floor((p-l)/2),Math.floor((f-i)/2)]:[0,0];for(let x=0;x<i;++x){let k=(x+g)*p,E=x*l;for(let A=0;A<l;++A){let S=(k+A+h)*c,M=(E+A)*c;for(let L=0;L<c;++L)m[S+L]=e[M+L]}}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 E=0;E<f;++E){let A=E*p,S=Bs(E,x)*l;for(let M=0;M<p;++M){if(E<i&&M<l)continue;let L=(A+M)*c,C=(S+Bs(M,k))*c;for(let v=0;v<c;++v)m[L+v]=e[C+v]}}}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]=jf([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=hA(c*n,this.config.ensure_multiple_of),i=hA(p*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return jf([s,n],this.size_divisibility);if(this.min_pixels!==void 0&&this.max_pixels!==void 0){let i=this.config.patch_size*this.config.merge_size;return JP(n,s,i,this.min_pixels,this.max_pixels)}else 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 h,g;Number.isInteger(this.crop_size)?(h=this.crop_size,g=this.crop_size):(h=this.crop_size.width,g=this.crop_size.height),e=await e.center_crop(h,g)}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 h=this.image_mean;Array.isArray(this.image_mean)||(h=new Array(e.channels).fill(h));let g=this.image_std;if(Array.isArray(this.image_std)||(g=new Array(e.channels).fill(g)),h.length!==e.channels||g.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${h.length}) and \`image_std\` (${g.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]-h[k])/g[k]}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[h,g]=jf([f[1],f[0]],this.size_divisibility);[p,f]=this.pad_image(p,f,{width:h,height:g})}}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 h=0;h<p.length;h+=3){let g=p[h];p[h]=p[h+2],p[h+2]=g}}let m=new B("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:Gt(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 at(e,Ks,!0,r);return new this(s)}};var tn={};ts(tn,{BeitFeatureExtractor:()=>Wf,BitImageProcessor:()=>qf,CLIPFeatureExtractor:()=>Hf,CLIPImageProcessor:()=>yl,ChineseCLIPFeatureExtractor:()=>Vf,ConvNextFeatureExtractor:()=>Xf,ConvNextImageProcessor:()=>bl,DINOv3ViTImageProcessor:()=>Qf,DPTFeatureExtractor:()=>Zf,DPTImageProcessor:()=>El,DeiTFeatureExtractor:()=>Yf,DeiTImageProcessor:()=>vl,DetrFeatureExtractor:()=>Kf,DetrImageProcessor:()=>kl,DonutFeatureExtractor:()=>Jf,DonutImageProcessor:()=>Qs,EfficientNetImageProcessor:()=>em,GLPNFeatureExtractor:()=>tm,GroundingDinoImageProcessor:()=>rm,Idefics3ImageProcessor:()=>Al,ImageFeatureExtractor:()=>q,ImageProcessor:()=>q,JinaCLIPImageProcessor:()=>nm,LlavaOnevisionImageProcessor:()=>om,Mask2FormerImageProcessor:()=>im,MaskFormerFeatureExtractor:()=>am,MaskFormerImageProcessor:()=>Js,MobileNetV1FeatureExtractor:()=>lm,MobileNetV1ImageProcessor:()=>Tl,MobileNetV2FeatureExtractor:()=>cm,MobileNetV2ImageProcessor:()=>Ml,MobileNetV3FeatureExtractor:()=>um,MobileNetV3ImageProcessor:()=>Sl,MobileNetV4FeatureExtractor:()=>pm,MobileNetV4ImageProcessor:()=>Ol,MobileViTFeatureExtractor:()=>dm,MobileViTImageProcessor:()=>Il,NougatImageProcessor:()=>fm,OwlViTFeatureExtractor:()=>mm,OwlViTImageProcessor:()=>Zs,Owlv2ImageProcessor:()=>hm,Phi3VImageProcessor:()=>gm,PixtralImageProcessor:()=>xm,PvtImageProcessor:()=>ym,Qwen2VLImageProcessor:()=>bm,RTDetrImageProcessor:()=>vm,Sam2ImageProcessor:()=>co,Sam3ImageProcessor:()=>co,SamImageProcessor:()=>co,SapiensFeatureExtractor:()=>km,SapiensImageProcessor:()=>Cl,SegformerFeatureExtractor:()=>Em,SegformerImageProcessor:()=>Pl,SiglipImageProcessor:()=>Am,SmolVLMImageProcessor:()=>Al,Swin2SRImageProcessor:()=>Tm,VLMImageProcessor:()=>sm,ViTFeatureExtractor:()=>Mm,ViTImageProcessor:()=>Ll,VitMatteImageProcessor:()=>Sm,VitPoseImageProcessor:()=>Om,YolosFeatureExtractor:()=>Im,YolosImageProcessor:()=>Nl});var Wf=class extends q{};var qf=class extends q{};var Vf=class extends q{};var yl=class extends q{},Hf=class extends yl{};var bl=class extends q{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}},Xf=class extends bl{};var vl=class extends q{},Yf=class extends vl{};var kl=class extends q{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ve(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Pr(...e)}post_process_panoptic_segmentation(...e){return gl(...e)}post_process_instance_segmentation(...e){return xl(...e)}},Kf=class extends kl{};var Qf=class extends q{};var Qs=class extends q{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})}},Jf=class extends Qs{};var El=class extends q{},Zf=class extends El{};var em=class extends q{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 tm=class extends q{};var rm=class extends q{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=it([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Al=class extends q{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(L=>this.preprocess(L)));l.push(...A.map(L=>L.original_size)),c.push(...A.map(L=>L.reshaped_input_size)),A.forEach(L=>L.pixel_values.unsqueeze_(0));let{longest_edge:S}=this.max_image_size,M;if(r??this.do_image_splitting){let L=new Array(A.length),C=new Array(A.length);M=await Promise.all(A.map(async(v,G)=>{let X=this.get_resize_for_vision_encoder(v.pixel_values,S),V=await jt(v.pixel_values,{size:[X.height,X.width]}),{frames:Q,num_splits_h:Y,num_splits_w:K}=await this.split_image(V,this.max_image_size);return L[G]=Y,C[G]=K,Ee(Q,0)})),a.push(L),i.push(C)}else{let L=[S,S];M=await Promise.all(A.map(C=>jt(C.pixel_values,{size:L}))),a.push(new Array(A.length).fill(0)),i.push(new Array(A.length).fill(0))}o.push(Ee(M,0))}let p=o.length,[f,m,h,g]=o[0].dims,x,k;if(p===1)x=o[0].unsqueeze_(0),k=Ve([p,f,h,g],!0);else{let E=Math.max(...o.map(M=>M.dims.at(0)));k=Ve([p,E,h,g],!0);let A=k.data,S=E*h*g;for(let M=0;M<p;++M){let L=o[M].dims[0];if(L<E){o[M]=Ee([o[M],Ve([E-L,m,h,g],0)],0);let C=M*S+L*h*g,v=(M+1)*S;A.fill(!1,C,v)}}x=Gt(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),f=Math.ceil(i/c);for(let g=0;g<l;++g)for(let x=0;x<c;++x){let k,E,A,S;g===l-1?(E=a-p,S=a):(E=g*p,S=(g+1)*p),x===c-1?(k=i-f,A=i):(k=x*f,A=(x+1)*f);let C=await pl(e,[E,k],[S,A],[2,3]);o.push(C)}let m=s,h=n;(a!==m||i!==h)&&(e=await jt(e,{size:[m,h]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:c}}};var sm=class extends q{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 nm=class extends q{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})}};var om=class extends q{};var Js=class extends q{post_process_panoptic_segmentation(...e){return gl(...e)}post_process_instance_segmentation(...e){return xl(...e)}},am=class extends Js{};var im=class extends Js{};var Tl=class extends q{},lm=class extends Tl{};var Ml=class extends q{},cm=class extends Ml{};var Sl=class extends q{},um=class extends Sl{};var Ol=class extends q{},pm=class extends Ol{};var Il=class extends q{},dm=class extends Il{};var fm=class extends Qs{};var Zs=class extends q{post_process_object_detection(...e){return Pr(...e)}},mm=class extends Zs{};var hm=class extends Zs{};var Nt=336,ZP=[2,3],{ceil:_m,floor:en,sqrt:wm}=Math,gm=class extends q{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 en((en(r/Nt)*en(e/Nt)+1)*s+1+(en(r/Nt)+1)*wm(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=Nt*_m(o/Nt),l=Nt*_m(a/Nt),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||wm(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[h,g]=m.dims.slice(-2),x=await jt(m,{size:[Nt,Nt],mode:"bicubic"});if(r>0){let k=[],E=wm(r),A=en(g/E),S=en(h/E);for(let L=0;L<E;++L)for(let C=0;C<E;++C){let v,G,X,V;L===E-1?(G=h-S,V=h):(G=L*S,V=(L+1)*S),C===E-1?(v=g-A,X=g):(v=C*A,X=(C+1)*A);let K=await pl(m,[G,v],[V,X],ZP);k.push(K)}let M=await jt(Ee(k,0),{size:[Nt,Nt],mode:"bicubic"});i.push(Ee([x,M],0))}else i.push(x)}let l=Gt(i,0),c=a.map(m=>m.map(h=>Nt*_m(h/Nt))),p=new B("int64",c.flat(),[s,2]),f=c.map(([m,h])=>this.calc_num_image_tokens_from_image_size(h,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:p,num_img_tokens:f}}};var xm=class extends q{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,h=Math.floor((l-1)/f)+1;return[m*f,h*f]}};var ym=class extends q{};var bm=class extends q{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=Ee(Array.from({length:i},()=>a),0));let p=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/c),h=Math.floor(a.dims[3]/c),g=a.view(p,i,f,Math.floor(m/l),l,c,Math.floor(h/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(p*m*h,f*i*c*c),x=new B("int64",[p,m,h],[1,3]);return{pixel_values:g,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var vm=class extends q{post_process_object_detection(...e){return Pr(...e)}};var co=class extends q{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=Ap(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 h=0;h<e[a][m].length;++h)for(let g=0;g<e[a][m][h].length;++g)e[a][m][h][g]*=f[g%2]}return new B("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=Ap(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 B("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 jt(e[c],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,f[0]],[0,f[1]]),m=await jt(m,{mode:"bilinear",size:p}),o){let h=m.data,g=new Uint8Array(h.length);for(let x=0;x<h.length;++x)h[x]>n&&(g[x]=1);m=new B("bool",g,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 Cl=class extends q{post_process_semantic_segmentation(...e){return wl(...e)}},km=class extends Cl{};var Pl=class extends q{post_process_semantic_segmentation(...e){return wl(...e)}},Em=class extends Pl{};var Am=class extends q{};var Tm=class extends q{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 Ll=class extends q{},Mm=class extends Ll{};var Sm=class extends q{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:Gt(s.map((a,i)=>Ee([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 Om=class extends q{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],h=[];for(let g=0;g<m.length;++g){let x=m[g],k=[],E=[],A=[],S=x.at(-2)/l,M=x.at(-1)/i;for(let L=0;L<f.length;++L){let[C,v]=[0,0],G=0,X=-1/0,V=f[L];for(let Y=0;Y<V.length;++Y){let K=V[Y];for(let U=0;U<K.length;++U){let P=K[U];G+=P,X=Math.max(X,P),C+=(U+.5)*P,v+=Y*P}}if(s!=null&&X<s)continue;let Q=[S*C/G,M*v/G];k.push(Q),A.push(L),E.push(X)}h.push({bbox:x,scores:E,labels:A,keypoints:k})}c.push(h)}return c}};var Nl=class extends q{post_process_object_detection(...e){return Pr(...e)}},Im=class extends Nl{};var Re=class{static async from_pretrained(e,r={}){let s=await at(e,Ks,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=tn[n?.replace(/Fast$/,"")];return o||(n!==void 0&&console.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Ys}.`),o=q),new o(s)}};var Cm=class extends ne{static tokenizer_class=J;static image_processor_class=Re;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((h,g)=>(Number(h)+.5)/this.size_per_bin*s[g%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 Pm=class extends ne{static image_processor_class=Re;static feature_extractor_class=tt;static tokenizer_class=J;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=`
|
|
16
16
|
|
|
17
17
|
${o}${m}${i}
|
|
18
18
|
|
|
19
19
|
`,this.image_token_id=l,this.boi_token=c,this.image_token=p;let h=p.repeat(this.image_seq_length);this.full_image_sequence=`
|
|
20
20
|
|
|
21
|
-
${c}${h}${
|
|
21
|
+
${c}${h}${f}
|
|
22
22
|
|
|
23
|
-
`}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}}};function
|
|
23
|
+
`}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}}};function eL(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 Lm=class extends ne{static tokenizer_class=J;static image_processor_class=Re;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(g=>g.map(x=>Gf(x))),h=[];for(let g=0;g<l;++g){let x=o!==null?o[g]:null;x!==null&&(m[g]=m[g].map(M=>M.map((L,C)=>L*x[(C+1)%2])));let k=f[g],E=[],A=[],S=[];for(let M=0;M<c;++M){let L=k[M];if(L<=s)continue;let C=m[g][M],v=p[g][M];E.push(L),S.push(C);let G=eL(v.gt(n),r[g]);A.push(G)}h.push({scores:E,boxes:S,labels:this.batch_decode(A)})}return h}};function tL(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+=`
|
|
24
24
|
`}return a+=`
|
|
25
|
-
${s}${o}`+n.repeat(t)+`${s}`,a}function
|
|
26
|
-
`}var
|
|
27
|
-
`}):(console.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=>tL(c,n,o,rn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var mA="<|image|>",rL=/<\|image_\d+\|>/g,Dm=class extends ne{static image_processor_class=Re;static tokenizer_class=J;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(rL).join(mA.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id(mA);a.input_ids.map_(d=>d==p?-d:d)}else a=this.tokenizer(e);return{...a,...i}}};var Fm=class extends ne{static tokenizer_class=J;static image_processor_class=Re;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,h=d*m,g=Math.floor(a/h),x=Math.floor(i/h);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let k=0;k<r.length;++k){let E=l.repeat(x),A=E+c,S=E+p,M=A.repeat(g-1)+S;r[k]=r[k].replace(l,M)}}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var jm=class extends ne{static feature_extractor_class=io;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 Gm=class extends ne{static image_processor_class=Re;static tokenizer_class=J;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=o.tolist();e=e.map(p=>{for(;p.includes("<|image_pad|>");){let d=Number(c[l++].reduce((m,h)=>m*h,1n));p=p.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(d/i)))}return p.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...n}}};var uo=class extends ne{static image_processor_class=Re;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 zl=class extends uo{},Wm=class extends zl{};var qm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Vm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;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 Rl="[AUDIO]",sL="[BEGIN_AUDIO]",nL=375;function oL(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 Hm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;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(Rl))throw new Error(`The input text does not contain the audio token ${Rl}.`);Array.isArray(r)||(r=[r]);let a=e.split(Rl),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(g=>oL(g,l)),p=c.map(g=>g.length),d=c.flat(),m=(await Promise.all(d.map(g=>this.feature_extractor(g,s)))).map(g=>g.input_features);n.audio_values=m.length>1?Ee(m,0):m[0];let h=a[0];for(let g=0;g<p.length;++g){h+=sL;for(let x=0;x<p[g];++x)h+=Rl.repeat(nL);h+=a[g+1]}e=h}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var Xm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Ym=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Km=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var ut=class{static async from_pretrained(e,r={}){let s=await at(e,Ks,!0,r),{image_processor_type:n,feature_extractor_type:o,processor_class:a}=s;if(a&&$l[a])return $l[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=tn[n.replace(/Fast$/,"")];if(!c)throw new Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new c(s)}if(o){let c=tn[o];if(c)i.image_processor=new c(s);else{let p=lo[o];if(!p)throw new Error(`Unknown feature_extractor_type: '${o}'.`);i.feature_extractor=new p(s)}}let l={};return new ne(l,i,null)}};async function aL(t,e){return await at(t,"config.json",!0,e)}function sn(t){let e={},r={};switch(t.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":case"chatterbox":case"mistral3":r=sn(t.text_config);break;case"moondream1":r=sn(t.phi_config);break;case"musicgen":r=sn(t.decoder);break;case"multi_modality":r=sn(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"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":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"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"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":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=sn(t.decoder),o="num_decoder_layers"in n,a=ot(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,...ot(t,["model_type","multi_query","is_encoder_decoder"])};for(let n in e)s[n]=t[e[n]];return s}function Ul(t,e){if(["lfm2","lfm2_moe"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{layer_types:o,num_attention_heads:a,num_key_value_heads:i,hidden_size:l,conv_L_cache:c}=t,p=l/a,d=e?.batch_size??1;for(let m=0;m<o.length;++m)if(o[m]==="full_attention")for(let h of["key","value"])n[`${r}.${m}.${h}`]=[d,i,0,p];else if(o[m]==="conv")n[`${s}_conv.${m}`]=[d,l,c];else throw new Error(`Unsupported layer type: ${o[m]}`);return n}else if(["granitemoehybrid","falcon_h1"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{layer_types:o,num_hidden_layers:a,num_attention_heads:i,num_key_value_heads:l,hidden_size:c,mamba_d_conv:p,mamba_n_heads:d,mamba_d_head:m,mamba_d_state:h,mamba_n_groups:g,mamba_expand:x,mamba_d_ssm:k}=t,E=c/i,A=e?.batch_size??1,S=(k??x*c)+2*g*h;for(let M=0;M<a;++M)if((!o||o[M]==="mamba")&&(n[`${s}_conv.${M}`]=[A,S,p],n[`${s}_ssm.${M}`]=[A,d,m,h]),!o||o[M]==="attention")for(let L of["key","value"])n[`${r}.${M}.${L}`]=[A,l,0,E];return n}return iL(t,e)}function iL(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 Bl=class t{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=sn(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 aL(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(i)}},gs=class{static async from_pretrained(...e){return Bl.from_pretrained(...e)}};async function hA(t,e,r,s){let n=`${e}${s}.onnx`,o=`${r.subfolder??""}/${n}`;return await Fn(t,o,!0,r,be.IS_NODE_ENV)}async function _A(t,e,r,s,n,o={}){let a=`${e}${r}.onnx`,i=be.IS_NODE_ENV,l=[];if(n){let c;typeof n=="object"?n.hasOwnProperty(a)?c=n[a]:n.hasOwnProperty(e)?c=n[e]:c=!1:c=n;let p=+c;if(p>ji)throw new Error(`The number of external data chunks (${p}) exceeds the maximum allowed value (${ji}).`);for(let d=0;d<p;++d){let m=`${a}_data${d===0?"":"_"+d}`,h=`${s.subfolder??""}/${m}`;l.push(new Promise(async(g,x)=>{let k=await Fn(t,h,!0,s,i);g(k instanceof Uint8Array?{path:m,data:k}:m)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async c=>{if(typeof c.data=="string"){let p=await Fn(t,c.data,!0,s);return{...c,data:p}}return c}));return Promise.all(l)}async function lL(t,e,r,s=!1){let n=r.config?.["transformers.js_config"]??{},o=r.device??n.device;o&&typeof o!="string"&&(o.hasOwnProperty(e)?o=o[e]:(console.warn(`device not specified for "${e}". Using the default device.`),o=null));let a=o??(be.IS_NODE_ENV?"cpu":"wasm"),i=WE(a),l=n.device_config??{};l.hasOwnProperty(a)&&(n={...n,...l[a]});let c=r.dtype??n.dtype;if(typeof c!="string"&&(c&&c.hasOwnProperty(e)?c=c[e]:(c=Af[a]??ht.fp32,console.warn(`dtype not specified for "${e}". Using the default dtype (${c}) for this device (${a}).`))),c===ht.auto){let L=n.dtype;typeof L!="string"&&(L=L?.[e]),L&&L!==ht.auto&&ht.hasOwnProperty(L)?c=L:c=Af[a]??ht.fp32}let p=c;if(Tf.hasOwnProperty(p)){if(a==="webgpu"&&!be.IS_NODE_ENV&&p===ht.fp16&&!await HE())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${p}. Should be one of: ${Object.keys(ht).join(", ")}`);let d=n.kv_cache_dtype,m=d?typeof d=="string"?d:d[p]??"float32":void 0;if(m&&!["float32","float16"].includes(m))throw new Error(`Invalid kv_cache_dtype: ${m}. Should be one of: float32, float16`);let h=Tf[p],g={...r.session_options};g.executionProviders??=i;let x=n.free_dimension_overrides;x?g.freeDimensionOverrides??=x:a.startsWith("webnn")&&!g.freeDimensionOverrides&&console.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 k=hA(t,e,r,h),E=r.use_external_data_format??n.use_external_data_format,A=await _A(t,e,h,r,E,g);if(A.length>0&&!be.IS_NODE_ENV&&(g.externalData=A),s&&a==="webgpu"&&d!==!1){let L=Ul(r.config,{prefix:"present"});if(Object.keys(L).length>0&&!Jn()){let C={};for(let v in L)C[v]="gpu-buffer";g.preferredOutputLocation=C}}return{buffer_or_path:await k,session_options:g,session_config:{dtype:p,kv_cache_dtype:m,device:a}}}async function vt(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let{buffer_or_path:o,session_options:a,session_config:i}=await lL(t,e[n],r,n===s),l=await al(o,a,i);return[n,l]})))}function wA(t){for(let e in t)ll(t[e])?t[e]=new B(t[e]):typeof t[e]=="object"&&wA(t[e]);return t}async function ce(t,e){let r=cL(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return be.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await il(t,s);return wA(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 console.error(`An error occurred during model execution: "${s}".`),console.error("Inputs given to model:",n),s}}function cL(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof B)){s.push(a);continue}r[a]=Jn()?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));console.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Le=class{};var F=class extends Le{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},_e=class extends Le{constructor({logits:e}){super(),this.logits=e}},ge=class extends Le{constructor({logits:e}){super(),this.logits=e}},Ae=class extends Le{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},gt=class extends Le{constructor({logits:e}){super(),this.logits=e}};var Dl=class extends Le{constructor({alphas:e}){super(),this.alphas=e}};var Wt=class extends Je{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},po=class extends Je{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},xs=class extends Je{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()}},Fl=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}},jl=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}},nn=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}},Gl=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 d=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(d+1).fill(-1/0)}let l=Mp(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((d,m)=>d+m)),p=Me(l.subarray(0,this.timestamp_begin))[0];c>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},Wl=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}},ql=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}},Vl=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}},Hl=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}},Xl=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}},Yl=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}},Kl=class extends po{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}},gA=class extends po{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}},xA=class extends po{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 on=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,ot(e,Object.getOwnPropertyNames(this)))}};var an=class extends Je{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Ql=class t extends Je{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof an&&(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()}},Jl=class extends an{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)}},Zl=class extends an{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)})}},yA=class extends an{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 ys=class extends Je{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){let r=0;for(let n=0;n<e.length;++n)r+=e[n];let s=Math.random()*r;for(let n=0;n<e.length;++n)if(s-=e[n],s<=0)return n;return 0}static getSampler(e){if(e.do_sample)return new Jm(e);if(e.num_beams>1)return new Zm(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 Qm(e)}},Qm=class extends ys{async sample(e){let r=Me(e.data)[1];return[[BigInt(r),0]]}},Jm=class extends ys{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 Zt(e,r),o=Pe(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},Zm=class extends ys{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 Zt(e,r),o=Pe(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var fo=null;function vA(t){fo=t}function eh(t){if(t instanceof B)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 B("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new B("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function th(t){return new B("bool",[t],[1])}var H={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15},bA={[H.DecoderOnly]:{can_generate:!0,forward:Ot,prepare_inputs:mo},[H.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Ot,prepare_inputs:mo},[H.Seq2Seq]:{can_generate:!0,forward:ec,prepare_inputs:ho},[H.Vision2Seq]:{can_generate:!0,forward:ec,prepare_inputs:ho},[H.Musicgen]:{can_generate:!0,forward:ec},[H.EncoderDecoder]:{can_generate:!1,forward:ec},[H.ImageTextToText]:{can_generate:!0,forward:fL,prepare_inputs:tc},[H.AudioTextToText]:{can_generate:!0,forward:pL,prepare_inputs:tc},[H.Phi3V]:{can_generate:!0,prepare_inputs:tc},[H.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:tc},[H.MultiModality]:{can_generate:!0},[H.AutoEncoder]:{can_generate:!1,forward:uL},[H.Chatterbox]:{can_generate:!0,forward:qt},default:{can_generate:!1,forward:qt}},vs=new Map,rc=new Map,bs=new Map,y=class extends Je{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,r,s){super(),this.config=e,this.sessions=r,this.configs=s;let n=bs.get(this.constructor),o=vs.get(n),a=bA[o]??bA.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 h={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},g=bs.get(this),x=vs.get(g);s=h.config=await gs.from_pretrained(e,h);let k;if(x===H.DecoderOnly)k=await Promise.all([vt(e,{model:h.model_file_name??"model"},h,"model"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.Seq2Seq||x===H.Vision2Seq)k=await Promise.all([vt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h,"decoder_model_merged"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.MaskGeneration)k=await Promise.all([vt(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]);else if(x===H.EncoderDecoder)k=await Promise.all([vt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h,"decoder_model_merged")]);else if(x===H.ImageTextToText){let E={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(E.model="encoder_model"),k=await Promise.all([vt(e,E,h,"decoder_model_merged"),xr(e,{generation_config:"generation_config.json"},h)])}else if(x===H.AudioTextToText){let E={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};k=await Promise.all([vt(e,E,h,"decoder_model_merged"),xr(e,{generation_config:"generation_config.json"},h)])}else if(x===H.ImageAudioTextToText){let E={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};k=await Promise.all([vt(e,E,h),xr(e,{generation_config:"generation_config.json"},h)])}else if(x===H.Musicgen)k=await Promise.all([vt(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h,"decoder_model_merged"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.MultiModality)k=await Promise.all([vt(e,{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"},h,"model"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.Phi3V)k=await Promise.all([vt(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},h,"model"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.Chatterbox)k=await Promise.all([vt(e,{embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"},h,"model"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.AutoEncoder)k=await Promise.all([vt(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},h)]);else if(x===H.Supertonic)k=await Promise.all([vt(e,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},h)]);else{if(x===void 0){let E=g??s?.model_type;E!=="custom"&&console.warn(`Model type for '${E}' not found, assuming encoder-only architecture. Please report this at ${Ys}.`)}k=await Promise.all([vt(e,{model:h.model_file_name??"model"},h)])}return new this(s,...k)}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 xs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new ql(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new Wl(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new Xl(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new Vl(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 Hl(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new Fl(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new jl(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 nn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new Yl(e.guidance_scale)),e.temperature===0&&e.do_sample&&(console.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 Kl(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=on){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,ot(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Ql;return e.max_length!==null&&s.push(new Jl(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new Zl(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[fo.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,fo.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,fo.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,fo.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=bs.get(this.constructor),s=new Set,n=this.config.model_type;for(let a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new B("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s:s.attention_mask=Ee([s.attention_mask,it([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=ot(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,...ot(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await qt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=Ee([o,eo(o,0)],0),"attention_mask"in r&&(r.attention_mask=Ee([r.attention_mask,Pf(r.attention_mask)],0));else if(r.decoder_input_ids){let a=eh(r.decoder_input_ids).dims[0];if(a!==o.dims[0]){if(o.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${o.dims[0]}) than the decoder inputs (${a}).`);o=Ee(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 B)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=o,this.config.model_type==="musicgen")i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${n.length}`);i=n}else i=Array.from({length:e},()=>[n]);i=eh(i)}return s.decoder_attention_mask=fl(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 h=this._get_logits_processor(r,m,s),g=this._get_stopping_criteria(r,n),x=l[c].dims.at(0),k=ys.getSampler(r),E=new Array(x).fill(0),A=d.tolist();o&&o.put(A);let S,M={},L={};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 Y=this.getAttentions(S);for(let K in Y)K in M||(M[K]=[]),M[K].push(Y[K])}else this._return_dict_in_generate_keys&&Object.assign(L,ot(S,this._return_dict_in_generate_keys));let G=S.logits.slice(null,-1,null).to("float32"),X=h(A,G),V=[];for(let Y=0;Y<X.dims.at(0);++Y){let K=X[Y],U=await k(K);for(let[P,se]of U){let ie=BigInt(P);E[Y]+=se,A[Y].push(ie),V.push([ie]);break}}if(o&&o.put(V),g(A).every(Y=>Y))break;l=this._update_model_kwargs_for_generation({generated_input_ids:V,outputs:S,model_inputs:l,is_encoder_decoder:p})}o&&o.end();let C=this.getPastKeyValues(S,l.past_key_values,!0),v=new B("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:v,past_key_values:C,...M,...L};for(let G of Object.values(S))G.location==="gpu-buffer"&&G.dispose();return v}getPastKeyValues(e,r,s=!1){let n=Object.create(null);for(let o in e)if(o.startsWith("present")){let a=o.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present","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 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"?Hs.float16:Hs.float32,i=Ul(this.config,{batch_size:n});for(let l in i){let c=i[l].reduce((p,d)=>p*d,1);e[l]=new B(o,new a(c),i[l])}}}async encode_image({pixel_values:e}){return(await ce(this.sessions.vision_encoder,{pixel_values:e})).image_features}async encode_text({input_ids:e}){return(await ce(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}async encode_audio({audio_values:e}){return(await ce(this.sessions.audio_encoder,{audio_values:e})).audio_features}};async function ec(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,...o}=e;if(!r){let a=ot(e,t.sessions.model.inputNames);r=(await qt(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 Ot(t,o,!0)}async function qt(t,e){let r=t.sessions.model,s=ot(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=Pf(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=it([n[0],n[2],n[3]])}return await ce(r,s)}async function uL(t,e){let r=await t.encode(e);return await t.decode(r)}async function Ot(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=th(!!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=dL(o,n,i)}t.addPastKeyValues(o,n);let a=ot(o,s.inputNames);return await ce(s,a)}async function kA(t,{encode_function:e,merge_function:r,modality_input_name: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}){let h=m[s];if(!l){if(l=await t.encode_text({input_ids:o,...m}),h&&o.dims[1]!==1){let x=await e({[s]:h,...m});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&h&&o.dims[1]===1){let x=o.dims[1],k=Object.values(c)[0].dims.at(-2);a=Ee([it([o.dims[0],k]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}if(!i&&t.config.model_type==="qwen2_vl"){let{image_grid_thw:x,video_grid_thw:k}=m;[i]=t.get_rope_index(o,x,k,a)}return await Ot(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:p,logits_processor:d},!0)}async function pL(t,e){return await kA(t,{...e,modality_input_name:"audio_values",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 fL(t,e){return await kA(t,{...e,modality_input_name:"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 rh(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 dL(t,e=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:o}=t,{data:a,dims:i}=rh(o,r),l=new B("int64",a,i);if(e){let c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function mo(t,e,r,s){let n=r.past_key_values?Object.values(r.past_key_values)[0].dims.at(-2):0;if(!r.attention_mask){let o;for(let a of["input_ids","inputs_embeds","position_ids"])if(r[a]){o=r[a].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=it([o[0],n+o[1]])}if(r.past_key_values){let{input_ids:o,attention_mask:a}=r;a&&a.dims[1]>o.dims[1]||n<o.dims[1]&&(r.input_ids=o.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:eh(e)}}function tc(t,...e){return t.config.is_encoder_decoder?ho(t,...e):mo(t,...e)}function EA({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 cr({image_token_id:t,inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return EA({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}function sc({audio_token_id:t,inputs_embeds:e,audio_features:r,input_ids:s,attention_mask:n}){return EA({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}async function xr(t,e,r){return Object.fromEntries(await Promise.all(Object.keys(e).map(async s=>{let n=await at(t,e[s],!1,r);return[s,n]})))}var hi={};ts(hi,{ASTForAudioClassification:()=>fh,ASTModel:()=>ph,ASTPreTrainedModel:()=>go,AlbertForMaskedLM:()=>ah,AlbertForQuestionAnswering:()=>oh,AlbertForSequenceClassification:()=>nh,AlbertModel:()=>sh,AlbertPreTrainedModel:()=>ks,ApertusForCausalLM:()=>lh,ApertusModel:()=>ih,ApertusPreTrainedModel:()=>_o,ArceeForCausalLM:()=>uh,ArceeModel:()=>ch,ArceePreTrainedModel:()=>wo,BartForConditionalGeneration:()=>mh,BartForSequenceClassification:()=>hh,BartModel:()=>dh,BartPretrainedModel:()=>ln,BeitForImageClassification:()=>wh,BeitModel:()=>_h,BeitPreTrainedModel:()=>xo,BertForMaskedLM:()=>xh,BertForQuestionAnswering:()=>vh,BertForSequenceClassification:()=>yh,BertForTokenClassification:()=>bh,BertModel:()=>gh,BertPreTrainedModel:()=>Lr,BlenderbotForConditionalGeneration:()=>Eh,BlenderbotModel:()=>kh,BlenderbotPreTrainedModel:()=>yo,BlenderbotSmallForConditionalGeneration:()=>Th,BlenderbotSmallModel:()=>Ah,BlenderbotSmallPreTrainedModel:()=>bo,BloomForCausalLM:()=>Sh,BloomModel:()=>Mh,BloomPreTrainedModel:()=>vo,CLIPModel:()=>Rh,CLIPPreTrainedModel:()=>ur,CLIPSegForImageSegmentation:()=>Fh,CLIPSegModel:()=>Dh,CLIPSegPreTrainedModel:()=>Mo,CLIPTextModel:()=>$h,CLIPTextModelWithProjection:()=>To,CLIPVisionModel:()=>Bh,CLIPVisionModelWithProjection:()=>Uh,CamembertForMaskedLM:()=>Ih,CamembertForQuestionAnswering:()=>Lh,CamembertForSequenceClassification:()=>Ch,CamembertForTokenClassification:()=>Ph,CamembertModel:()=>Oh,CamembertPreTrainedModel:()=>Nr,ChatterboxModel:()=>ko,ChatterboxPreTrainedModel:()=>nc,ChineseCLIPModel:()=>Nh,ChineseCLIPPreTrainedModel:()=>oc,ClapAudioModelWithProjection:()=>Ao,ClapModel:()=>zh,ClapPreTrainedModel:()=>cn,ClapTextModelWithProjection:()=>Eo,CodeGenForCausalLM:()=>Gh,CodeGenModel:()=>jh,CodeGenPreTrainedModel:()=>So,CohereForCausalLM:()=>qh,CohereModel:()=>Wh,CoherePreTrainedModel:()=>Oo,ConvBertForMaskedLM:()=>Hh,ConvBertForQuestionAnswering:()=>Kh,ConvBertForSequenceClassification:()=>Xh,ConvBertForTokenClassification:()=>Yh,ConvBertModel:()=>Vh,ConvBertPreTrainedModel:()=>zr,ConvNextForImageClassification:()=>Jh,ConvNextModel:()=>Qh,ConvNextPreTrainedModel:()=>Io,ConvNextV2ForImageClassification:()=>e_,ConvNextV2Model:()=>Zh,ConvNextV2PreTrainedModel:()=>Co,DFineForObjectDetection:()=>n_,DFineModel:()=>s_,DFinePreTrainedModel:()=>Lo,DINOv3ConvNextModel:()=>S_,DINOv3ConvNextPreTrainedModel:()=>fc,DINOv3ViTModel:()=>O_,DINOv3ViTPreTrainedModel:()=>dc,DPTForDepthEstimation:()=>$_,DPTModel:()=>R_,DPTPreTrainedModel:()=>Uo,DacDecoderModel:()=>zo,DacDecoderOutput:()=>ic,DacEncoderModel:()=>No,DacEncoderOutput:()=>ac,DacModel:()=>o_,DacPreTrainedModel:()=>un,DebertaForMaskedLM:()=>i_,DebertaForQuestionAnswering:()=>u_,DebertaForSequenceClassification:()=>l_,DebertaForTokenClassification:()=>c_,DebertaModel:()=>a_,DebertaPreTrainedModel:()=>Rr,DebertaV2ForMaskedLM:()=>f_,DebertaV2ForQuestionAnswering:()=>h_,DebertaV2ForSequenceClassification:()=>d_,DebertaV2ForTokenClassification:()=>m_,DebertaV2Model:()=>p_,DebertaV2PreTrainedModel:()=>$r,DecisionTransformerModel:()=>__,DecisionTransformerPreTrainedModel:()=>lc,DeiTForImageClassification:()=>g_,DeiTModel:()=>w_,DeiTPreTrainedModel:()=>Ro,DepthAnythingForDepthEstimation:()=>x_,DepthAnythingPreTrainedModel:()=>cc,DepthProForDepthEstimation:()=>y_,DepthProPreTrainedModel:()=>uc,DetrForObjectDetection:()=>v_,DetrForSegmentation:()=>k_,DetrModel:()=>b_,DetrObjectDetectionOutput:()=>fn,DetrPreTrainedModel:()=>pn,DetrSegmentationOutput:()=>pc,Dinov2ForImageClassification:()=>A_,Dinov2Model:()=>E_,Dinov2PreTrainedModel:()=>$o,Dinov2WithRegistersForImageClassification:()=>M_,Dinov2WithRegistersModel:()=>T_,Dinov2WithRegistersPreTrainedModel:()=>Bo,DistilBertForMaskedLM:()=>N_,DistilBertForQuestionAnswering:()=>L_,DistilBertForSequenceClassification:()=>C_,DistilBertForTokenClassification:()=>P_,DistilBertModel:()=>I_,DistilBertPreTrainedModel:()=>Br,DonutSwinModel:()=>z_,DonutSwinPreTrainedModel:()=>mc,EdgeTamModel:()=>yy,EfficientNetForImageClassification:()=>U_,EfficientNetModel:()=>B_,EfficientNetPreTrainedModel:()=>Do,ElectraForMaskedLM:()=>F_,ElectraForQuestionAnswering:()=>W_,ElectraForSequenceClassification:()=>j_,ElectraForTokenClassification:()=>G_,ElectraModel:()=>D_,ElectraPreTrainedModel:()=>Ur,Ernie4_5ForCausalLM:()=>V_,Ernie4_5Model:()=>q_,Ernie4_5PretrainedModel:()=>Fo,EsmForMaskedLM:()=>X_,EsmForSequenceClassification:()=>Y_,EsmForTokenClassification:()=>K_,EsmModel:()=>H_,EsmPreTrainedModel:()=>Es,ExaoneForCausalLM:()=>J_,ExaoneModel:()=>Q_,ExaonePreTrainedModel:()=>jo,FalconForCausalLM:()=>ew,FalconH1ForCausalLM:()=>rw,FalconH1Model:()=>tw,FalconH1PreTrainedModel:()=>Wo,FalconModel:()=>Z_,FalconPreTrainedModel:()=>Go,FastViTForImageClassification:()=>nw,FastViTModel:()=>sw,FastViTPreTrainedModel:()=>qo,Florence2ForConditionalGeneration:()=>ow,Florence2PreTrainedModel:()=>hc,GLPNForDepthEstimation:()=>hw,GLPNModel:()=>mw,GLPNPreTrainedModel:()=>Qo,GPT2LMHeadModel:()=>Aw,GPT2Model:()=>Ew,GPT2PreTrainedModel:()=>ra,GPTBigCodeForCausalLM:()=>ww,GPTBigCodeModel:()=>_w,GPTBigCodePreTrainedModel:()=>Jo,GPTJForCausalLM:()=>Mw,GPTJModel:()=>Tw,GPTJPreTrainedModel:()=>sa,GPTNeoForCausalLM:()=>xw,GPTNeoModel:()=>gw,GPTNeoPreTrainedModel:()=>Zo,GPTNeoXForCausalLM:()=>bw,GPTNeoXModel:()=>yw,GPTNeoXPreTrainedModel:()=>ea,Gemma2ForCausalLM:()=>cw,Gemma2Model:()=>lw,Gemma2PreTrainedModel:()=>Ho,Gemma3ForCausalLM:()=>pw,Gemma3Model:()=>uw,Gemma3PreTrainedModel:()=>Xo,Gemma3nForConditionalGeneration:()=>Yo,Gemma3nPreTrainedModel:()=>_c,GemmaForCausalLM:()=>iw,GemmaModel:()=>aw,GemmaPreTrainedModel:()=>Vo,GlmForCausalLM:()=>dw,GlmModel:()=>fw,GlmPreTrainedModel:()=>Ko,GptOssForCausalLM:()=>kw,GptOssModel:()=>vw,GptOssPreTrainedModel:()=>ta,GraniteForCausalLM:()=>Ow,GraniteModel:()=>Sw,GraniteMoeHybridForCausalLM:()=>Cw,GraniteMoeHybridModel:()=>Iw,GraniteMoeHybridPreTrainedModel:()=>oa,GranitePreTrainedModel:()=>na,GroundingDinoForObjectDetection:()=>Pw,GroundingDinoPreTrainedModel:()=>wc,GroupViTModel:()=>Lw,GroupViTPreTrainedModel:()=>gc,HeliumForCausalLM:()=>zw,HeliumModel:()=>Nw,HeliumPreTrainedModel:()=>aa,HieraForImageClassification:()=>$w,HieraModel:()=>Rw,HieraPreTrainedModel:()=>ia,HubertForCTC:()=>Ww,HubertForSequenceClassification:()=>qw,HubertModel:()=>Gw,HubertPreTrainedModel:()=>jw,HunYuanDenseV1ForCausalLM:()=>Hw,HunYuanDenseV1Model:()=>Vw,HunYuanDenseV1PreTrainedModel:()=>la,IJepaForImageClassification:()=>Kw,IJepaModel:()=>Yw,IJepaPreTrainedModel:()=>ca,Idefics3ForConditionalGeneration:()=>yc,Idefics3PreTrainedModel:()=>xc,JAISLMHeadModel:()=>Jw,JAISModel:()=>Qw,JAISPreTrainedModel:()=>ua,JinaCLIPModel:()=>Zw,JinaCLIPPreTrainedModel:()=>dn,JinaCLIPTextModel:()=>pa,JinaCLIPVisionModel:()=>eg,Lfm2ForCausalLM:()=>rg,Lfm2Model:()=>tg,Lfm2MoeForCausalLM:()=>ng,Lfm2MoeModel:()=>sg,Lfm2MoePreTrainedModel:()=>da,Lfm2PreTrainedModel:()=>fa,LiteWhisperForConditionalGeneration:()=>C0,Llama4ForCausalLM:()=>ig,Llama4PreTrainedModel:()=>bc,LlamaForCausalLM:()=>ag,LlamaModel:()=>og,LlamaPreTrainedModel:()=>ma,LlavaForConditionalGeneration:()=>mn,LlavaOnevisionForConditionalGeneration:()=>mn,LlavaPreTrainedModel:()=>vc,LlavaQwen2ForCausalLM:()=>cg,LongT5ForConditionalGeneration:()=>pg,LongT5Model:()=>ug,LongT5PreTrainedModel:()=>ha,M2M100ForConditionalGeneration:()=>dg,M2M100Model:()=>fg,M2M100PreTrainedModel:()=>_a,MBartForCausalLM:()=>bg,MBartForConditionalGeneration:()=>xg,MBartForSequenceClassification:()=>yg,MBartModel:()=>gg,MBartPreTrainedModel:()=>As,MPNetForMaskedLM:()=>ox,MPNetForQuestionAnswering:()=>lx,MPNetForSequenceClassification:()=>ax,MPNetForTokenClassification:()=>ix,MPNetModel:()=>nx,MPNetPreTrainedModel:()=>Dr,MT5ForConditionalGeneration:()=>fx,MT5Model:()=>px,MT5PreTrainedModel:()=>Sa,MarianMTModel:()=>hg,MarianModel:()=>mg,MarianPreTrainedModel:()=>wa,MaskFormerForInstanceSegmentation:()=>wg,MaskFormerModel:()=>_g,MaskFormerPreTrainedModel:()=>ga,Metric3DForDepthEstimation:()=>vg,Metric3DPreTrainedModel:()=>kc,Metric3Dv2ForDepthEstimation:()=>kg,Metric3Dv2PreTrainedModel:()=>Ec,MgpstrForSceneTextRecognition:()=>Eg,MgpstrModelOutput:()=>Ac,MgpstrPreTrainedModel:()=>Tc,MimiDecoderModel:()=>ya,MimiDecoderOutput:()=>Sc,MimiEncoderModel:()=>xa,MimiEncoderOutput:()=>Mc,MimiModel:()=>Ag,MimiPreTrainedModel:()=>hn,MistralForCausalLM:()=>Mg,MistralModel:()=>Tg,MistralPreTrainedModel:()=>ba,MobileBertForMaskedLM:()=>Og,MobileBertForQuestionAnswering:()=>Cg,MobileBertForSequenceClassification:()=>Ig,MobileBertModel:()=>Sg,MobileBertPreTrainedModel:()=>Ts,MobileLLMForCausalLM:()=>Lg,MobileLLMModel:()=>Pg,MobileLLMPreTrainedModel:()=>va,MobileNetV1ForImageClassification:()=>zg,MobileNetV1ForSemanticSegmentation:()=>Rg,MobileNetV1Model:()=>Ng,MobileNetV1PreTrainedModel:()=>_n,MobileNetV2ForImageClassification:()=>Bg,MobileNetV2ForSemanticSegmentation:()=>Ug,MobileNetV2Model:()=>$g,MobileNetV2PreTrainedModel:()=>wn,MobileNetV3ForImageClassification:()=>Fg,MobileNetV3ForSemanticSegmentation:()=>jg,MobileNetV3Model:()=>Dg,MobileNetV3PreTrainedModel:()=>gn,MobileNetV4ForImageClassification:()=>Wg,MobileNetV4ForSemanticSegmentation:()=>qg,MobileNetV4Model:()=>Gg,MobileNetV4PreTrainedModel:()=>xn,MobileViTForImageClassification:()=>Hg,MobileViTModel:()=>Vg,MobileViTPreTrainedModel:()=>ka,MobileViTV2ForImageClassification:()=>Yg,MobileViTV2Model:()=>Xg,MobileViTV2PreTrainedModel:()=>Ea,ModernBertDecoderForCausalLM:()=>tx,ModernBertDecoderModel:()=>ex,ModernBertDecoderPreTrainedModel:()=>Aa,ModernBertForMaskedLM:()=>Qg,ModernBertForSequenceClassification:()=>Jg,ModernBertForTokenClassification:()=>Zg,ModernBertModel:()=>Kg,ModernBertPreTrainedModel:()=>Ms,Moondream1ForConditionalGeneration:()=>lg,MoonshineForConditionalGeneration:()=>sx,MoonshineModel:()=>rx,MoonshinePreTrainedModel:()=>Ta,MptForCausalLM:()=>ux,MptModel:()=>cx,MptPreTrainedModel:()=>Ma,MultiModalityCausalLM:()=>dx,MultiModalityPreTrainedModel:()=>Oc,MusicgenForCausalLM:()=>hx,MusicgenForConditionalGeneration:()=>Ia,MusicgenModel:()=>mx,MusicgenPreTrainedModel:()=>Oa,NanoChatForCausalLM:()=>wx,NanoChatModel:()=>_x,NanoChatPreTrainedModel:()=>Ca,NeoBertForMaskedLM:()=>xx,NeoBertForQuestionAnswering:()=>vx,NeoBertForSequenceClassification:()=>yx,NeoBertForTokenClassification:()=>bx,NeoBertModel:()=>gx,NeoBertPreTrainedModel:()=>Fr,NomicBertModel:()=>kx,NomicBertPreTrainedModel:()=>Ic,OPTForCausalLM:()=>Lx,OPTModel:()=>Px,OPTPreTrainedModel:()=>Ra,Olmo2ForCausalLM:()=>Mx,Olmo2Model:()=>Tx,Olmo2PreTrainedModel:()=>La,Olmo3ForCausalLM:()=>Ox,Olmo3Model:()=>Sx,Olmo3PreTrainedModel:()=>Na,OlmoForCausalLM:()=>Ax,OlmoModel:()=>Ex,OlmoPreTrainedModel:()=>Pa,OpenELMForCausalLM:()=>Cx,OpenELMModel:()=>Ix,OpenELMPreTrainedModel:()=>za,OwlViTForObjectDetection:()=>$x,OwlViTModel:()=>Rx,OwlViTPreTrainedModel:()=>Ba,Owlv2ForObjectDetection:()=>zx,Owlv2Model:()=>Nx,Owlv2PreTrainedModel:()=>$a,PaliGemmaForConditionalGeneration:()=>Bx,PaliGemmaPreTrainedModel:()=>Cc,ParakeetForCTC:()=>Ux,ParakeetPreTrainedModel:()=>Pc,PatchTSMixerForPrediction:()=>Fx,PatchTSMixerModel:()=>Dx,PatchTSMixerPreTrainedModel:()=>Ua,PatchTSTForPrediction:()=>Gx,PatchTSTModel:()=>jx,PatchTSTPreTrainedModel:()=>Da,Phi3ForCausalLM:()=>Hx,Phi3Model:()=>Vx,Phi3PreTrainedModel:()=>ja,Phi3VForCausalLM:()=>Ga,Phi3VPreTrainedModel:()=>Lc,PhiForCausalLM:()=>qx,PhiModel:()=>Wx,PhiPreTrainedModel:()=>Fa,PreTrainedModel:()=>y,PvtForImageClassification:()=>Yx,PvtModel:()=>Xx,PvtPreTrainedModel:()=>Wa,PyAnnoteForAudioFrameClassification:()=>Qx,PyAnnoteModel:()=>Kx,PyAnnotePreTrainedModel:()=>qa,Qwen2ForCausalLM:()=>Zx,Qwen2Model:()=>Jx,Qwen2PreTrainedModel:()=>Va,Qwen2VLForConditionalGeneration:()=>ey,Qwen2VLPreTrainedModel:()=>Nc,Qwen3ForCausalLM:()=>ry,Qwen3Model:()=>ty,Qwen3PreTrainedModel:()=>Ha,RFDetrForObjectDetection:()=>ay,RFDetrModel:()=>oy,RFDetrObjectDetectionOutput:()=>zc,RFDetrPreTrainedModel:()=>Ya,RTDetrForObjectDetection:()=>r_,RTDetrModel:()=>t_,RTDetrObjectDetectionOutput:()=>pr,RTDetrPreTrainedModel:()=>Po,RTDetrV2ForObjectDetection:()=>gy,RTDetrV2Model:()=>wy,RTDetrV2ObjectDetectionOutput:()=>Rc,RTDetrV2PreTrainedModel:()=>Ka,ResNetForImageClassification:()=>ny,ResNetModel:()=>sy,ResNetPreTrainedModel:()=>Xa,RoFormerForMaskedLM:()=>dy,RoFormerForQuestionAnswering:()=>_y,RoFormerForSequenceClassification:()=>my,RoFormerForTokenClassification:()=>hy,RoFormerModel:()=>fy,RoFormerPreTrainedModel:()=>Gr,RobertaForMaskedLM:()=>ly,RobertaForQuestionAnswering:()=>py,RobertaForSequenceClassification:()=>cy,RobertaForTokenClassification:()=>uy,RobertaModel:()=>iy,RobertaPreTrainedModel:()=>jr,Sam2ImageSegmentationOutput:()=>Uc,Sam2Model:()=>Qa,Sam2PreTrainedModel:()=>Dc,Sam3TrackerModel:()=>by,SamImageSegmentationOutput:()=>$c,SamModel:()=>xy,SamPreTrainedModel:()=>Bc,SapiensForDepthEstimation:()=>ky,SapiensForNormalEstimation:()=>Ey,SapiensForSemanticSegmentation:()=>vy,SapiensPreTrainedModel:()=>yn,SegformerForImageClassification:()=>Ty,SegformerForSemanticSegmentation:()=>My,SegformerModel:()=>Ay,SegformerPreTrainedModel:()=>bn,SiglipModel:()=>Sy,SiglipPreTrainedModel:()=>Ja,SiglipTextModel:()=>Za,SiglipVisionModel:()=>Oy,SmolLM3ForCausalLM:()=>Cy,SmolLM3Model:()=>Iy,SmolLM3PreTrainedModel:()=>ei,SmolVLMForConditionalGeneration:()=>Xw,SnacDecoderModel:()=>ri,SnacEncoderModel:()=>ti,SnacModel:()=>Py,SnacPreTrainedModel:()=>vn,SpeechT5ForSpeechToText:()=>Ny,SpeechT5ForTextToSpeech:()=>zy,SpeechT5HifiGan:()=>Ry,SpeechT5Model:()=>Ly,SpeechT5PreTrainedModel:()=>kn,SqueezeBertForMaskedLM:()=>By,SqueezeBertForQuestionAnswering:()=>Dy,SqueezeBertForSequenceClassification:()=>Uy,SqueezeBertModel:()=>$y,SqueezeBertPreTrainedModel:()=>Ss,StableLmForCausalLM:()=>jy,StableLmModel:()=>Fy,StableLmPreTrainedModel:()=>si,Starcoder2ForCausalLM:()=>Wy,Starcoder2Model:()=>Gy,Starcoder2PreTrainedModel:()=>ni,StyleTextToSpeech2Model:()=>qy,StyleTextToSpeech2PreTrainedModel:()=>Fc,SupertonicForConditionalGeneration:()=>oi,SupertonicPreTrainedModel:()=>jc,Swin2SRForImageSuperResolution:()=>Ky,Swin2SRModel:()=>Yy,Swin2SRPreTrainedModel:()=>ai,SwinForImageClassification:()=>Hy,SwinForSemanticSegmentation:()=>Xy,SwinModel:()=>Vy,SwinPreTrainedModel:()=>En,T5ForConditionalGeneration:()=>Jy,T5Model:()=>Qy,T5PreTrainedModel:()=>ii,TableTransformerForObjectDetection:()=>e0,TableTransformerModel:()=>Zy,TableTransformerObjectDetectionOutput:()=>Gc,TableTransformerPreTrainedModel:()=>li,TrOCRForCausalLM:()=>t0,TrOCRPreTrainedModel:()=>Wc,UltravoxModel:()=>Vc,UltravoxPreTrainedModel:()=>qc,UniSpeechForCTC:()=>n0,UniSpeechForSequenceClassification:()=>o0,UniSpeechModel:()=>s0,UniSpeechPreTrainedModel:()=>An,UniSpeechSatForAudioFrameClassification:()=>c0,UniSpeechSatForCTC:()=>i0,UniSpeechSatForSequenceClassification:()=>l0,UniSpeechSatModel:()=>a0,UniSpeechSatPreTrainedModel:()=>Os,VaultGemmaForCausalLM:()=>p0,VaultGemmaModel:()=>u0,VaultGemmaPreTrainedModel:()=>ci,ViTForImageClassification:()=>m0,ViTMAEModel:()=>h0,ViTMAEPreTrainedModel:()=>Hc,ViTMSNForImageClassification:()=>w0,ViTMSNModel:()=>_0,ViTMSNPreTrainedModel:()=>pi,ViTModel:()=>d0,ViTPreTrainedModel:()=>ui,VisionEncoderDecoderModel:()=>f0,VitMatteForImageMatting:()=>g0,VitMattePreTrainedModel:()=>Xc,VitPoseForPoseEstimation:()=>x0,VitPosePreTrainedModel:()=>Yc,VitsModel:()=>y0,VitsModelOutput:()=>Kc,VitsPreTrainedModel:()=>Qc,VoxtralForConditionalGeneration:()=>r0,Wav2Vec2BertForCTC:()=>v0,Wav2Vec2BertForSequenceClassification:()=>k0,Wav2Vec2BertModel:()=>b0,Wav2Vec2BertPreTrainedModel:()=>Tn,Wav2Vec2ForAudioFrameClassification:()=>Fw,Wav2Vec2ForCTC:()=>Uw,Wav2Vec2ForSequenceClassification:()=>Dw,Wav2Vec2Model:()=>Bw,Wav2Vec2PreTrainedModel:()=>tr,WavLMForAudioFrameClassification:()=>S0,WavLMForCTC:()=>A0,WavLMForSequenceClassification:()=>T0,WavLMForXVector:()=>M0,WavLMModel:()=>E0,WavLMPreTrainedModel:()=>Wr,WeSpeakerResNetModel:()=>O0,WeSpeakerResNetPreTrainedModel:()=>Zc,WhisperForConditionalGeneration:()=>tu,WhisperModel:()=>I0,WhisperPreTrainedModel:()=>fi,XLMForQuestionAnswering:()=>R0,XLMForSequenceClassification:()=>N0,XLMForTokenClassification:()=>z0,XLMModel:()=>P0,XLMPreTrainedModel:()=>qr,XLMRobertaForMaskedLM:()=>B0,XLMRobertaForQuestionAnswering:()=>F0,XLMRobertaForSequenceClassification:()=>U0,XLMRobertaForTokenClassification:()=>D0,XLMRobertaModel:()=>$0,XLMRobertaPreTrainedModel:()=>Vr,XLMWithLMHeadModel:()=>L0,XVectorOutput:()=>Jc,YolosForObjectDetection:()=>G0,YolosModel:()=>j0,YolosObjectDetectionOutput:()=>ru,YolosPreTrainedModel:()=>di,YoutuForCausalLM:()=>q0,YoutuModel:()=>W0,YoutuPreTrainedModel:()=>mi});var ks=class extends y{},sh=class extends ks{},nh=class extends ks{async _call(e){return new F(await super._call(e))}},oh=class extends ks{async _call(e){return new Ae(await super._call(e))}},ah=class extends ks{async _call(e){return new ge(await super._call(e))}};var _o=class extends y{},ih=class extends _o{},lh=class extends _o{};var wo=class extends y{},ch=class extends wo{},uh=class extends wo{};var go=class extends y{},ph=class extends go{},fh=class extends go{};var ln=class extends y{},dh=class extends ln{},mh=class extends ln{},hh=class extends ln{async _call(e){return new F(await super._call(e))}};var xo=class extends y{},_h=class extends xo{},wh=class extends xo{async _call(e){return new F(await super._call(e))}};var Lr=class extends y{},gh=class extends Lr{},xh=class extends Lr{async _call(e){return new ge(await super._call(e))}},yh=class extends Lr{async _call(e){return new F(await super._call(e))}},bh=class extends Lr{async _call(e){return new _e(await super._call(e))}},vh=class extends Lr{async _call(e){return new Ae(await super._call(e))}};var yo=class extends y{},kh=class extends yo{},Eh=class extends yo{};var bo=class extends y{},Ah=class extends bo{},Th=class extends bo{};var vo=class extends y{},Mh=class extends vo{},Sh=class extends vo{};var Nr=class extends y{},Oh=class extends Nr{},Ih=class extends Nr{async _call(e){return new ge(await super._call(e))}},Ch=class extends Nr{async _call(e){return new F(await super._call(e))}},Ph=class extends Nr{async _call(e){return new _e(await super._call(e))}},Lh=class extends Nr{async _call(e){return new Ae(await super._call(e))}};var mL=4299n,AA=6561n,nc=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"]},ko=class extends nc{async encode_speech(e){return ce(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:h=null,...g}){let x;if(!a){let E=this.sessions.embed_tokens.inputNames,A={input_ids:e};if(E.includes("exaggeration")){if(!(n instanceof B)){let S=e.dims[0];if(n==null)n=Ve([S],.5);else if(typeof n=="number")n=Ve([S],n);else if(Array.isArray(n))n=new B("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 ce(this.sessions.embed_tokens,A),p&&d&&m&&h&&(x={audio_features:p,audio_tokens:d,speaker_embeddings:m,speaker_features:h}),x||s)x??=await this.encode_speech(s),a=Ee([x.audio_features,a],1),r=it([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=Object.values(i)[0].dims.at(-2);r=it([a.dims[0],M+S])}}return{...await Ot(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==AA)-1);r.position_ids=new B("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=AA?0:i++)});r.position_ids=new B("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),mo(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=Ve([a.dims[0],3],mL),l=Ee([s,a,i],1),{waveform:c}=await ce(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var oc=class extends y{},Nh=class extends oc{};var cn=class extends y{},zh=class extends cn{},Eo=class extends cn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Ao=class extends cn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var ur=class extends y{},Rh=class extends ur{},$h=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},To=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Bh=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},Uh=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Mo=class extends y{},Dh=class extends Mo{},Fh=class extends Mo{};var So=class extends y{},jh=class extends So{},Gh=class extends So{};var Oo=class extends y{},Wh=class extends Oo{},qh=class extends Oo{};var zr=class extends y{},Vh=class extends zr{},Hh=class extends zr{async _call(e){return new ge(await super._call(e))}},Xh=class extends zr{async _call(e){return new F(await super._call(e))}},Yh=class extends zr{async _call(e){return new _e(await super._call(e))}},Kh=class extends zr{async _call(e){return new Ae(await super._call(e))}};var Io=class extends y{},Qh=class extends Io{},Jh=class extends Io{async _call(e){return new F(await super._call(e))}};var Co=class extends y{},Zh=class extends Co{},e_=class extends Co{async _call(e){return new F(await super._call(e))}};var Po=class extends y{},t_=class extends Po{},r_=class extends Po{async _call(e){return new pr(await super._call(e))}},pr=class extends Le{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Lo=class extends y{},s_=class extends Lo{},n_=class extends Lo{async _call(e){return new pr(await super._call(e))}};var ac=class extends Le{constructor({audio_codes:e}){super(),this.audio_codes=e}},ic=class extends Le{constructor({audio_values:e}){super(),this.audio_values=e}},un=class extends y{main_input_name="input_values";forward_params=["input_values"]},o_=class extends un{async encode(e){return new ac(await ce(this.sessions.encoder_model,e))}async decode(e){return new ic(await ce(this.sessions.decoder_model,e))}},No=class extends un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},zo=class extends un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Rr=class extends y{},a_=class extends Rr{},i_=class extends Rr{async _call(e){return new ge(await super._call(e))}},l_=class extends Rr{async _call(e){return new F(await super._call(e))}},c_=class extends Rr{async _call(e){return new _e(await super._call(e))}},u_=class extends Rr{async _call(e){return new Ae(await super._call(e))}};var $r=class extends y{},p_=class extends $r{},f_=class extends $r{async _call(e){return new ge(await super._call(e))}},d_=class extends $r{async _call(e){return new F(await super._call(e))}},m_=class extends $r{async _call(e){return new _e(await super._call(e))}},h_=class extends $r{async _call(e){return new Ae(await super._call(e))}};var lc=class extends y{},__=class extends lc{};var Ro=class extends y{},w_=class extends Ro{},g_=class extends Ro{async _call(e){return new F(await super._call(e))}};var cc=class extends y{},x_=class extends cc{};var uc=class extends y{},y_=class extends uc{};var pn=class extends y{},b_=class extends pn{},v_=class extends pn{async _call(e){return new fn(await super._call(e))}},k_=class extends pn{async _call(e){return new pc(await super._call(e))}},fn=class extends Le{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},pc=class extends Le{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var $o=class extends y{},E_=class extends $o{},A_=class extends $o{async _call(e){return new F(await super._call(e))}};var Bo=class extends y{},T_=class extends Bo{},M_=class extends Bo{async _call(e){return new F(await super._call(e))}};var fc=class extends y{},S_=class extends fc{};var dc=class extends y{},O_=class extends dc{};var Br=class extends y{},I_=class extends Br{},C_=class extends Br{async _call(e){return new F(await super._call(e))}},P_=class extends Br{async _call(e){return new _e(await super._call(e))}},L_=class extends Br{async _call(e){return new Ae(await super._call(e))}},N_=class extends Br{async _call(e){return new ge(await super._call(e))}};var mc=class extends y{},z_=class extends mc{};var Uo=class extends y{},R_=class extends Uo{},$_=class extends Uo{};var Do=class extends y{},B_=class extends Do{},U_=class extends Do{async _call(e){return new F(await super._call(e))}};var Ur=class extends y{},D_=class extends Ur{},F_=class extends Ur{async _call(e){return new ge(await super._call(e))}},j_=class extends Ur{async _call(e){return new F(await super._call(e))}},G_=class extends Ur{async _call(e){return new _e(await super._call(e))}},W_=class extends Ur{async _call(e){return new Ae(await super._call(e))}};var Fo=class extends y{},q_=class extends Fo{},V_=class extends Fo{};var Es=class extends y{},H_=class extends Es{},X_=class extends Es{async _call(e){return new ge(await super._call(e))}},Y_=class extends Es{async _call(e){return new F(await super._call(e))}},K_=class extends Es{async _call(e){return new _e(await super._call(e))}};var jo=class extends y{},Q_=class extends jo{},J_=class extends jo{};var Go=class extends y{},Z_=class extends Go{},ew=class extends Go{};var Wo=class extends y{},tw=class extends Wo{},rw=class extends Wo{};var qo=class extends y{},sw=class extends qo{},nw=class extends qo{async _call(e){return new F(await super._call(e))}};var hc=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"},ow=class extends hc{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:Ee([r,e],1),attention_mask:Ee([it(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 qt(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 Ot(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var Vo=class extends y{},aw=class extends Vo{},iw=class extends Vo{};var Ho=class extends y{},lw=class extends Ho{},cw=class extends Ho{};var Xo=class extends y{},uw=class extends Xo{},pw=class extends Xo{};var _c=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"]},Yo=class extends _c{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 ce(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:g}=await ce(this.sessions.vision_encoder,{pixel_values:s});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:g,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:g}=await ce(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:g,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Ot(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 cr({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 sc({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}};var Ko=class extends y{},fw=class extends Ko{},dw=class extends Ko{};var Qo=class extends y{},mw=class extends Qo{},hw=class extends Qo{};var Jo=class extends y{},_w=class extends Jo{},ww=class extends Jo{};var Zo=class extends y{},gw=class extends Zo{},xw=class extends Zo{};var ea=class extends y{},yw=class extends ea{},bw=class extends ea{};var ta=class extends y{},vw=class extends ta{},kw=class extends ta{};var ra=class extends y{},Ew=class extends ra{},Aw=class extends ra{};var sa=class extends y{},Tw=class extends sa{},Mw=class extends sa{};var na=class extends y{},Sw=class extends na{},Ow=class extends na{};var oa=class extends y{},Iw=class extends oa{},Cw=class extends oa{};var wc=class extends y{},Pw=class extends wc{};var gc=class extends y{},Lw=class extends gc{};var aa=class extends y{},Nw=class extends aa{},zw=class extends aa{};var ia=class extends y{},Rw=class extends ia{},$w=class extends ia{async _call(e){return new F(await super._call(e))}};var tr=class extends y{},Bw=class extends tr{},Uw=class extends tr{async _call(e){return new gt(await super._call(e))}},Dw=class extends tr{async _call(e){return new F(await super._call(e))}},Fw=class extends tr{async _call(e){return new _e(await super._call(e))}};var jw=class extends y{},Gw=class extends tr{},Ww=class extends tr{async _call(e){return new gt(await super._call(e))}},qw=class extends tr{async _call(e){return new F(await super._call(e))}};var la=class extends y{},Vw=class extends la{},Hw=class extends la{};var xc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},yc=class extends xc{async encode_image({pixel_values:e,pixel_attention_mask:r}){return(await ce(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:r})).image_features}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return cr({image_token_id:this.config.image_token_id,...e,image_features:s})}},Xw=class extends yc{};var ca=class extends y{},Yw=class extends ca{},Kw=class extends ca{async _call(e){return new F(await super._call(e))}};var ua=class extends y{},Qw=class extends ua{},Jw=class extends ua{};var dn=class extends y{},Zw=class extends dn{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=it([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=Ve([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}},pa=class extends dn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},eg=class extends dn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var fa=class extends y{},tg=class extends fa{},rg=class extends fa{};var da=class extends y{},sg=class extends da{},ng=class extends da{};var ma=class extends y{},og=class extends ma{},ag=class extends ma{};var bc=class extends y{},ig=class extends bc{};var vc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},mn=class extends vc{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return cr({image_token_id:this.config.image_token_index,...e,image_features:s})}},lg=class extends mn{},cg=class extends mn{};var ha=class extends y{},ug=class extends ha{},pg=class extends ha{};var _a=class extends y{},fg=class extends _a{},dg=class extends _a{};var wa=class extends y{},mg=class extends wa{},hg=class extends wa{};var ga=class extends y{},_g=class extends ga{},wg=class extends ga{};var As=class extends y{},gg=class extends As{},xg=class extends As{},yg=class extends As{async _call(e){return new F(await super._call(e))}},bg=class extends As{};var kc=class extends y{},vg=class extends kc{};var Ec=class extends y{},kg=class extends Ec{};var Ac=class extends Le{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]}},Tc=class extends y{},Eg=class extends Tc{async _call(e){return new Ac(await super._call(e))}};var Mc=class extends Le{constructor({audio_codes:e}){super(),this.audio_codes=e}},Sc=class extends Le{constructor({audio_values:e}){super(),this.audio_values=e}},hn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Ag=class extends hn{async encode(e){return new Mc(await ce(this.sessions.encoder_model,e))}async decode(e){return new Sc(await ce(this.sessions.decoder_model,e))}},xa=class extends hn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ya=class extends hn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var ba=class extends y{},Tg=class extends ba{},Mg=class extends ba{};var Ts=class extends y{},Sg=class extends Ts{},Og=class extends Ts{async _call(e){return new ge(await super._call(e))}},Ig=class extends Ts{async _call(e){return new F(await super._call(e))}},Cg=class extends Ts{async _call(e){return new Ae(await super._call(e))}};var va=class extends y{},Pg=class extends va{},Lg=class extends va{};var _n=class extends y{},Ng=class extends _n{},zg=class extends _n{async _call(e){return new F(await super._call(e))}},Rg=class extends _n{};var wn=class extends y{},$g=class extends wn{},Bg=class extends wn{async _call(e){return new F(await super._call(e))}},Ug=class extends wn{};var gn=class extends y{},Dg=class extends gn{},Fg=class extends gn{async _call(e){return new F(await super._call(e))}},jg=class extends gn{};var xn=class extends y{},Gg=class extends xn{},Wg=class extends xn{async _call(e){return new F(await super._call(e))}},qg=class extends xn{};var ka=class extends y{},Vg=class extends ka{},Hg=class extends ka{async _call(e){return new F(await super._call(e))}};var Ea=class extends y{},Xg=class extends Ea{},Yg=class extends Ea{async _call(e){return new F(await super._call(e))}};var Ms=class extends y{},Kg=class extends Ms{},Qg=class extends Ms{async _call(e){return new ge(await super._call(e))}},Jg=class extends Ms{async _call(e){return new F(await super._call(e))}},Zg=class extends Ms{async _call(e){return new _e(await super._call(e))}};var Aa=class extends y{},ex=class extends Aa{},tx=class extends Aa{};var Ta=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},rx=class extends Ta{},sx=class extends Ta{};var Dr=class extends y{},nx=class extends Dr{},ox=class extends Dr{async _call(e){return new ge(await super._call(e))}},ax=class extends Dr{async _call(e){return new F(await super._call(e))}},ix=class extends Dr{async _call(e){return new _e(await super._call(e))}},lx=class extends Dr{async _call(e){return new Ae(await super._call(e))}};var Ma=class extends y{},cx=class extends Ma{},ux=class extends Ma{};var Sa=class extends y{},px=class extends Sa{},fx=class extends Sa{};var Oc=class extends y{},dx=class extends Oc{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=ot(e,l.inputNames);s=await ce(l,c)}else{let l=this.sessions.gen_img_embeds,c=ot({image_ids:e.input_ids},l.inputNames);s=await ce(l,c)}let n={...e,...s},o=await Ot(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 ce(a,ot(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=Ee([r.input_ids,r.input_ids],0):(r.input_ids=Ee([r.input_ids,eo(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Ee([r.attention_mask,eo(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Ve([0,0,3,384,384],1)),n&&(r.images_seq_mask=new B("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new B("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 ce(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let p=Xe.fromTensor(c);l.push(p)}return l}};var Oa=class extends y{},mx=class extends Oa{},hx=class extends Oa{},Ia=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 B(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 ce(this.sessions.encodec_decode,{audio_codes:s});return n}};var Ca=class extends y{},_x=class extends Ca{},wx=class extends Ca{};var Fr=class extends y{},gx=class extends Fr{},xx=class extends Fr{async _call(e){return new ge(await super._call(e))}},yx=class extends Fr{async _call(e){return new F(await super._call(e))}},bx=class extends Fr{async _call(e){return new _e(await super._call(e))}},vx=class extends Fr{async _call(e){return new Ae(await super._call(e))}};var Ic=class extends y{},kx=class extends Ic{};var Pa=class extends y{},Ex=class extends Pa{},Ax=class extends Pa{};var La=class extends y{},Tx=class extends La{},Mx=class extends La{};var Na=class extends y{},Sx=class extends Na{},Ox=class extends Na{};var za=class extends y{},Ix=class extends za{},Cx=class extends za{};var Ra=class extends y{},Px=class extends Ra{},Lx=class extends Ra{};var $a=class extends y{},Nx=class extends $a{},zx=class extends $a{};var Ba=class extends y{},Rx=class extends Ba{},$x=class extends Ba{};var Cc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Bx=class extends Cc{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return cr({image_token_id:this.config.image_token_index,...e,image_features:s})}};var Pc=class extends y{},Ux=class extends Pc{async _call(e){return new gt(await super._call(e))}};var Ua=class extends y{},Dx=class extends Ua{},Fx=class extends Ua{};var Da=class extends y{},jx=class extends Da{},Gx=class extends Da{};var Fa=class extends y{},Wx=class extends Fa{},qx=class extends Fa{};var ja=class extends y{},Vx=class extends ja{},Hx=class extends ja{};var Lc=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Ga=class extends Lc{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 ce(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let h=this.config.normalized_config.hidden_size;m=new B("float32",[],[0,h])}({inputs_embeds:a}=await ce(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await Ot(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var Wa=class extends y{},Xx=class extends Wa{},Yx=class extends Wa{async _call(e){return new F(await super._call(e))}};var qa=class extends y{},Kx=class extends qa{},Qx=class extends qa{async _call(e){return new _e(await super._call(e))}};var Va=class extends y{},Jx=class extends Va{},Zx=class extends Va{};var Nc=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},ey=class extends Nc{get_rope_index(e,r,s,n){let{vision_config:o,image_token_id:a,video_token_id:i,vision_start_token_id:l}=this.config,c=o.spatial_merge_size??2,p=[];if(r||s){let d=e.tolist();n||(n=fl(e));let m=n.tolist(),h=Array.from({length:3},A=>Array.from({length:e.dims[0]},S=>Array.from({length:e.dims[1]},M=>1))),g=r?r.tolist():[],x=s?s.tolist():[],k=0,E=0;for(let A=0;A<d.length;++A){let S=d[A].filter((O,N)=>m[A][N]==1),L=S.reduce((O,N,$)=>(N==l&&O.push($),O),[]).map(O=>S[O+1]),C=L.filter(O=>O==a).length,v=L.filter(O=>O==i).length,G=[],X=0,V=C,Q=v;for(let O=0;O<L.length;++O){let N=S.findIndex((At,et)=>et>X&&At==a),$=S.findIndex((At,et)=>et>X&&At==i),te=V>0&&N!==-1?N:S.length+1,ue=Q>0&&$!==-1?$:S.length+1,Ue,Ce,kt,Qe;te<ue?([Ce,kt,Qe]=g[k],++k,--V,Ue=te):([Ce,kt,Qe]=x[E],++E,--Q,Ue=ue);let[Ze,rt,Te]=[Number(Ce),Math.floor(Number(kt)/c),Math.floor(Number(Qe)/c)],xe=Ue-X,Ge=G.length>0?Me(G.at(-1))[0]+1:0;G.push(Array.from({length:3*xe},(At,et)=>Ge+et%xe));let Et=xe+Ge,we=Ze*rt*Te,Ne=Array.from({length:we},(At,et)=>Et+Math.floor(et/(rt*Te))),br=Array.from({length:we},(At,et)=>Et+Math.floor(et/Te)%rt),Yr=Array.from({length:we},(At,et)=>Et+et%Te);G.push([Ne,br,Yr].flat()),X=Ue+we}if(X<S.length){let O=G.length>0?Me(G.at(-1))[0]+1:0,N=S.length-X;G.push(Array.from({length:3*N},($,te)=>O+te%N))}let Y=G.reduce((O,N)=>O+N.length,0),K=new Array(Y),U=0;for(let O=0;O<3;++O)for(let N=0;N<G.length;++N){let $=G[N],te=$.length/3;for(let ue=O*te;ue<(O+1)*te;++ue)K[U++]=$[ue]}let P=0,se=m[A];for(let O=0;O<se.length;++O)if(se[O]==1){for(let N=0;N<3;++N)h[N][A][O]=K[N*Y/3+P];++P}let ie=Me(K)[0];p.push(ie+1-d[A].length)}return[new B("int64",h.flat(1/0),[3,e.dims[0],e.dims[1]]),new B("int64",p,[p.length,1])]}else if(n){let{data:d,dims:m}=rh(n),h=BigInt64Array.from({length:3*d.length},(x,k)=>d[k%d.length]),g=Array.from({length:m[0]},(x,k)=>Me(d.subarray(m[1]*k,m[1]*(k+1)))[0]+1n+BigInt(m[1]));return[new B("int64",h,[3,...m]),new B("int64",g,[g.length,1])]}else{let[d,m]=e.dims,h=BigInt64Array.from({length:3*d*m},(g,x)=>BigInt(Math.floor(x%m/d)));return[new B("int64",h,[3,...e.dims]),Cf([d,1])]}}async encode_image({pixel_values:e,image_grid_thw:r}){return(await ce(this.sessions.vision_encoder,{pixel_values:e,grid_thw:r})).image_features}_merge_input_ids_with_image_features(e){return cr({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=BigInt(Object.values(r.past_key_values)[0].dims.at(-2)),o=r.rope_deltas.map(a=>n+a);r.position_ids=Gt([o,o,o],0)}return r}};var Ha=class extends y{},ty=class extends Ha{},ry=class extends Ha{};var Xa=class extends y{},sy=class extends Xa{},ny=class extends Xa{async _call(e){return new F(await super._call(e))}};var Ya=class extends y{},oy=class extends Ya{},ay=class extends Ya{async _call(e){return new zc(await super._call(e))}},zc=class extends pr{};var jr=class extends y{},iy=class extends jr{},ly=class extends jr{async _call(e){return new ge(await super._call(e))}},cy=class extends jr{async _call(e){return new F(await super._call(e))}},uy=class extends jr{async _call(e){return new _e(await super._call(e))}},py=class extends jr{async _call(e){return new Ae(await super._call(e))}};var Gr=class extends y{},fy=class extends Gr{},dy=class extends Gr{async _call(e){return new ge(await super._call(e))}},my=class extends Gr{async _call(e){return new F(await super._call(e))}},hy=class extends Gr{async _call(e){return new _e(await super._call(e))}},_y=class extends Gr{async _call(e){return new Ae(await super._call(e))}};var Ka=class extends y{},wy=class extends Ka{},gy=class extends Ka{async _call(e){return new Rc(await super._call(e))}},Rc=class extends pr{};var $c=class extends Le{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},Bc=class extends y{},xy=class extends Bc{async get_image_embeddings({pixel_values:e}){return await qt(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??=it(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 ce(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new $c(await super._call(e))}};var Uc=class extends Le{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}},Dc=class extends y{},Qa=class extends Dc{async get_image_embeddings({pixel_values:e}){return await qt(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??=it(a.slice(0,-1)),e.input_boxes??=Ve([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Ve([a[0],a[1],0],-1n),e.input_points=Ve([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=ot(e,n.inputNames);return await ce(n,o)}async _call(e){return new Uc(await super._call(e))}},yy=class extends Qa{},by=class extends Qa{};var yn=class extends y{},vy=class extends yn{},ky=class extends yn{},Ey=class extends yn{};var bn=class extends y{},Ay=class extends bn{},Ty=class extends bn{},My=class extends bn{};var Ja=class extends y{},Sy=class extends Ja{},Za=class extends Ja{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Oy=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var ei=class extends y{},Iy=class extends ei{},Cy=class extends ei{};var vn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Py=class extends vn{async encode(e){return await ce(this.sessions.encoder_model,e)}async decode(e){return await ce(this.sessions.decoder_model,e)}},ti=class extends vn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ri=class extends vn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var kn=class extends y{},Ly=class extends kn{},Ny=class extends kn{},zy=class extends kn{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 qt(this,i),p=l.dims[1]/this.config.reduction_factor,d=Math.floor(p*o),m=Math.floor(p*n),h=this.config.num_mel_bins,g=[],x=null,k=null,E=0;for(;;){++E;let M=th(!!k),L;k?L=k.output_sequence_out:L=new B("float32",new Float32Array(h),[1,1,h]);let C={use_cache_branch:M,output_sequence:L,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(C,x),k=await ce(this.sessions.decoder_model_merged,C),x=this.getPastKeyValues(k,x);let{prob:v,spectrum:G}=k;if(g.push(G),E>=m&&(Array.from(v.data).filter(X=>X>=s).length>0||E>=d))break}let A=Ee(g),{waveform:S}=await ce(a.sessions.model,{spectrogram:A});return{spectrogram:A,waveform:S}}},Ry=class extends y{main_input_name="spectrogram"};var Ss=class extends y{},$y=class extends Ss{},By=class extends Ss{async _call(e){return new ge(await super._call(e))}},Uy=class extends Ss{async _call(e){return new F(await super._call(e))}},Dy=class extends Ss{async _call(e){return new Ae(await super._call(e))}};var si=class extends y{},Fy=class extends si{},jy=class extends si{};var ni=class extends y{},Gy=class extends ni{},Wy=class extends ni{};var Fc=class extends y{},qy=class extends Fc{};var jc=class extends y{},oi=class extends jc{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 ce(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=d.div(o).mul_(a),h=l*i,g=m.data,x=Int32Array.from(g,V=>Math.ceil(V/h)),k=Math.max(...x),E=e.dims[0],A=new BigInt64Array(E*k);for(let V=0;V<E;++V)A.fill(1n,V*k,V*k+x[V]);let S=new B("int64",A,[E,k]),M=c*i,L=M*k,C=JE([E,M,k]),v=C.data;for(let V=0;V<E;++V)if(x[V]!==k)for(let Q=0;Q<M;++Q)v.fill(0,V*L+Q*k+x[V],V*L+(Q+1)*k);let G=Ve([E],n);for(let V=0;V<n;++V){let Q=Ve([E],V);({denoised_latents:C}=await ce(this.sessions.latent_denoiser,{style:s,noisy_latents:C,latent_mask:S,encoder_outputs:p,attention_mask:r,timestep:Q,num_inference_steps:G}))}let{waveform:X}=await ce(this.sessions.voice_decoder,{latents:C});return{waveform:X,durations:m}}};var En=class extends y{},Vy=class extends En{},Hy=class extends En{async _call(e){return new F(await super._call(e))}},Xy=class extends En{};var ai=class extends y{},Yy=class extends ai{},Ky=class extends ai{};var ii=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},Qy=class extends ii{},Jy=class extends ii{};var li=class extends y{},Zy=class extends li{},e0=class extends li{async _call(e){return new Gc(await super._call(e))}},Gc=class extends fn{};var Wc=class extends y{},t0=class extends Wc{};var qc=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Vc=class extends qc{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return sc({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...e,audio_features:s})}},r0=class extends Vc{};var An=class extends y{},s0=class extends An{},n0=class extends An{async _call(e){return new gt(await super._call(e))}},o0=class extends An{async _call(e){return new F(await super._call(e))}};var Os=class extends y{},a0=class extends Os{},i0=class extends Os{async _call(e){return new gt(await super._call(e))}},l0=class extends Os{async _call(e){return new F(await super._call(e))}},c0=class extends Os{async _call(e){return new _e(await super._call(e))}};var ci=class extends y{},u0=class extends ci{},p0=class extends ci{};var f0=class extends y{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]};var ui=class extends y{},d0=class extends ui{},m0=class extends ui{async _call(e){return new F(await super._call(e))}};var Hc=class extends y{},h0=class extends Hc{};var pi=class extends y{},_0=class extends pi{},w0=class extends pi{async _call(e){return new F(await super._call(e))}};var Xc=class extends y{},g0=class extends Xc{async _call(e){return new Dl(await super._call(e))}};var Yc=class extends y{},x0=class extends Yc{};var Kc=class extends Le{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}},Qc=class extends y{},y0=class extends Qc{async _call(e){return new Kc(await super._call(e))}};var Tn=class extends y{},b0=class extends Tn{},v0=class extends Tn{async _call(e){return new gt(await super._call(e))}},k0=class extends Tn{async _call(e){return new F(await super._call(e))}};var Jc=class extends Le{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},Wr=class extends y{},E0=class extends Wr{},A0=class extends Wr{async _call(e){return new gt(await super._call(e))}},T0=class extends Wr{async _call(e){return new F(await super._call(e))}},M0=class extends Wr{async _call(e){return new Jc(await super._call(e))}},S0=class extends Wr{async _call(e){return new _e(await super._call(e))}};var Zc=class extends y{},O0=class extends Zc{};var eu=class extends on{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 fi=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"]},I0=class extends fi{},tu=class extends fi{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,eu)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(console.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${tA(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&&(console.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 xs,s.push(new Gl(r,a))),r.begin_suppress_tokens&&(s??=new xs,s.push(new nn(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"&&console.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&&console.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&&(console.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)=>Ee(a.map(E=>E[k]),2)),l=Gt(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]=Of(l,-2,0,!0),d=l.clone();for(let x=0;x<d.dims[0];++x){let k=d[x];for(let E=0;E<k.dims[0];++E){let A=k[E],S=c[x][E][0].data,M=p[x][E][0].data;for(let L=0;L<A.dims[0];++L){let C=A[L].data;for(let v=0;v<C.length;++v)C[v]=(C[v]-M[v])/S[v];C.set(ek(C,o))}}}let m=[pl(d,1)],h=e.sequences.dims,g=new B("float32",new Float32Array(h[0]*h[1]),h);for(let x=0;x<h[0];++x){let k=m[x].neg().squeeze_(0),[E,A]=rk(k.tolist()),S=Array.from({length:E.length-1},(C,v)=>E[v+1]-E[v]),M=ft([1],S).map(C=>!!C),L=[];for(let C=0;C<M.length;++C)M[C]&&L.push(A[C]*n);g[x].data.set(L,1)}return g}},C0=class extends tu{};var qr=class extends y{},P0=class extends qr{},L0=class extends qr{async _call(e){return new ge(await super._call(e))}},N0=class extends qr{async _call(e){return new F(await super._call(e))}},z0=class extends qr{async _call(e){return new _e(await super._call(e))}},R0=class extends qr{async _call(e){return new Ae(await super._call(e))}};var Vr=class extends y{},$0=class extends Vr{},B0=class extends Vr{async _call(e){return new ge(await super._call(e))}},U0=class extends Vr{async _call(e){return new F(await super._call(e))}},D0=class extends Vr{async _call(e){return new _e(await super._call(e))}},F0=class extends Vr{async _call(e){return new Ae(await super._call(e))}};var di=class extends y{},j0=class extends di{},G0=class extends di{async _call(e){return new ru(await super._call(e))}},ru=class extends Le{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var mi=class extends y{},W0=class extends mi{},q0=class extends mi{};var hL=new Map([["bert","BertModel"],["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"]]),_L=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),wL=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),gL=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"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen3","Qwen3Model"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5_Model"],["starcoder2","Starcoder2Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),TA=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),MA=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),SA=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),OA=new Map([["bert","BertForSequenceClassification"],["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"]]),IA=new Map([["bert","BertForTokenClassification"],["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"]]),CA=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),PA=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"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen3","Qwen3ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5_ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["trocr","TrOCRForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),xL=new Map([["multi_modality","MultiModalityCausalLM"]]),LA=new Map([["bert","BertForMaskedLM"],["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"]]),NA=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"]]),zA=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),RA=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2-vl","Qwen2VLForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3n","Gemma3nForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"]]),$A=new Map([["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"]]),yL=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),BA=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"]]),UA=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),DA=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Mn=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),FA=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),jA=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),GA=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),WA=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),qA=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),VA=new Map([["wavlm","WavLMForXVector"]]),HA=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),XA=new Map([["vitmatte","VitMatteForImageMatting"]]),bL=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),YA=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),KA=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),QA=new Map([["sapiens","SapiensForNormalEstimation"]]),JA=new Map([["vitpose","VitPoseForPoseEstimation"]]),ZA=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),V0=[[hL,H.EncoderOnly],[_L,H.EncoderDecoder],[gL,H.DecoderOnlyWithoutHead],[wL,H.AutoEncoder],[OA,H.EncoderOnly],[IA,H.EncoderOnly],[CA,H.Seq2Seq],[TA,H.Seq2Seq],[PA,H.DecoderOnly],[xL,H.MultiModality],[LA,H.EncoderOnly],[NA,H.EncoderOnly],[zA,H.Vision2Seq],[RA,H.ImageTextToText],[$A,H.AudioTextToText],[BA,H.EncoderOnly],[Mn,H.EncoderOnly],[jA,H.EncoderOnly],[FA,H.EncoderOnly],[XA,H.EncoderOnly],[bL,H.EncoderOnly],[YA,H.EncoderOnly],[KA,H.EncoderOnly],[QA,H.EncoderOnly],[JA,H.EncoderOnly],[UA,H.EncoderOnly],[DA,H.EncoderOnly],[GA,H.MaskGeneration],[WA,H.EncoderOnly],[qA,H.EncoderOnly],[MA,H.Seq2Seq],[SA,H.EncoderOnly],[VA,H.EncoderOnly],[HA,H.EncoderOnly],[ZA,H.EncoderOnly]];for(let[t,e]of V0)for(let r of t.values()){vs.set(r,e);let s=hi[r];bs.set(s,r),rc.set(r,s)}var vL=[["MusicgenForConditionalGeneration",Ia,H.Musicgen],["Phi3VForCausalLM",Ga,H.Phi3V],["CLIPTextModelWithProjection",To,H.EncoderOnly],["SiglipTextModel",Za,H.EncoderOnly],["JinaCLIPTextModel",pa,H.EncoderOnly],["ClapTextModelWithProjection",Eo,H.EncoderOnly],["ClapAudioModelWithProjection",Ao,H.EncoderOnly],["DacEncoderModel",No,H.EncoderOnly],["DacDecoderModel",zo,H.EncoderOnly],["MimiEncoderModel",xa,H.EncoderOnly],["MimiDecoderModel",ya,H.EncoderOnly],["SnacEncoderModel",ti,H.EncoderOnly],["SnacDecoderModel",ri,H.EncoderOnly],["Gemma3nForConditionalGeneration",Yo,H.ImageAudioTextToText],["SupertonicForConditionalGeneration",oi,H.Supertonic],["ChatterboxModel",ko,H.Chatterbox]];for(let[t,e,r]of vL)vs.set(t,r),bs.set(e,t),rc.set(t,e);var H0=new Map([["modnet",Mn],["birefnet",Mn],["isnet",Mn],["ben",Mn]]);for(let[t,e]of H0.entries())e.set(t,"PreTrainedModel"),vs.set(t,H.EncoderOnly),rc.set(t,y);vs.set("PreTrainedModel",H.EncoderOnly);bs.set(y,"PreTrainedModel");var Ie={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:OA,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:IA,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:MA,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:SA,MODEL_FOR_MASKED_LM_MAPPING_NAMES:LA,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:NA,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:BA,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Mn,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:FA,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:jA,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:UA,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:DA,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:GA,MODEL_FOR_CTC_MAPPING_NAMES:WA,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:qA,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:VA,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:HA,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:yL,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:XA,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:YA,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:KA,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:QA,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:JA,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:ZA,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:RA,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:$A,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:CA,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:TA,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:PA,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:zA};vA(Ie);var Se=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;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 h={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(h.config=await gs.from_pretrained(e,h),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let g=h.config.model_type;for(let x of this.MODEL_CLASS_MAPPINGS){let k=x.get(g);if(!k){for(let E of x.values())if(E[0]===g){k=E;break}if(!k)continue}return await hi[k].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return H0.has(g)||console.warn(`Unknown model class "${g}", attempting to construct from base class.`),await y.from_pretrained(e,h);throw Error(`Unsupported model type: ${g}`)}},yr=class extends Se{static MODEL_CLASS_MAPPINGS=V0.map(e=>e[0]);static BASE_IF_FAIL=!0},_i=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},su=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Sn=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},nu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},ou=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},au=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},iu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},lu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},cu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},uu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},pu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},wi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},gi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},xi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},fu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},du=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},e2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},mu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_CTC_MAPPING_NAMES]},hu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},t2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},r2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},_u=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},s2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},wu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},gu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},n2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},o2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},xu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},a2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},i2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function Ke(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Xe.read(e)))}async function Hr(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?Md(r,e):r instanceof Float64Array?new Float32Array(r):r))}function yi(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 pe=class extends Je{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 yu=class extends pe{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 B("float32",Pe(c.data),c.dims),l=[];for(let c of n.logits){let p=i(c),d=await Zt(p,r),m=d[0].tolist(),g=d[1].tolist().map((x,k)=>({label:a?a[x]:`LABEL_${x}`,score:m[k]}));r===1?l.push(...g):l.push(g)}return Array.isArray(e)||r===1?l:l[0]}};var bu=class extends pe{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 h=0;h<d.dims[0];++h){let g=d[h],x=Me(g.data)[1],k=i?i[x]:`LABEL_${x}`;if(r.includes(k))continue;let E=this.tokenizer.decode([p[h].item()],{skip_special_tokens:!0});if(E==="")continue;let A=Pe(g.data);m.push({entity:k,score:A[x],index:h,word:E})}l.push(m)}return s?l:l[0]}};var vu=class extends pe{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 h=0;h<a.dims[0];++h){let g=l[h],x=g.findIndex(C=>C==d),k=a[h].tolist(),E=i[h].tolist();for(let C=1;C<k.length;++C)(c[h]==0||C<=x||p.findIndex(v=>v==g[C])!==-1)&&(k[C]=-1/0,E[C]=-1/0);let A=Pe(k).map((C,v)=>[C,v]),S=Pe(E).map((C,v)=>[C,v]);A[0][0]=0,S[0][0]=0;let M=Fv(A,S).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,v)=>v[2]-C[2]),L=[];for(let C=0;C<Math.min(M.length,s);++C){let[v,G,X]=M[C],V=g.slice(v,G+1),Q=this.tokenizer.decode(V,{skip_special_tokens:!0});L.push({answer:Q,score:X})}s===1?m.push(...L):m.push(L)}return o?m:m[0]}};var ku=class extends pe{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],h=await Zt(new B("float32",Pe(m.data),m.dims),r),g=h[0].tolist(),x=h[1].tolist();i.push(x.map((k,E)=>{let A=p.slice();return A[d]=k,{score:g[E],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 Xr=class extends pe{_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 Eu=class extends Xr{_key="summary_text"};var Au=class extends Xr{_key="translation_text"};function l2(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Tu=class extends pe{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(g=>typeof g=="string"))s=!0,i=e;else{if(l2(e))e=[e];else if(Array.isArray(e)&&e.every(l2))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(g=>this.tokenizer.apply_chat_template(g,{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(g=>g.length));let h=Array.from({length:e.length},g=>[]);for(let g=0;g<d.length;++g){let x=Math.floor(g/p.dims[0]*e.length);m&&(d[g]=d[g].slice(m[x])),h[x].push({generated_text:n?[...e[x],{role:"assistant",content:d[g]}]:d[g]})}return!s&&h.length===1?h[0]:h}};var Mu=class extends pe{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&&(console.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&&(console.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 h of a){let g=this.tokenizer(c,{text_pair:h,padding:!0,truncation:!0}),x=await this.model(g);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(h=>Pe(h)[1]):Pe(p)).map((h,g)=>[h,g]).sort((h,g)=>g[0]-h[0]);l.push({sequence:c,labels:m.map(h=>r[h[1]]),scores:m.map(h=>h[0])})}return o?l:l[0]}};var Su=class extends pe{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await Hr(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 Zt(new B("float32",Pe(p.data),p.dims),r),m=d[0].tolist(),g=d[1].tolist().map((x,k)=>({label:o?o[x]:`LABEL_${x}`,score:m[k]}));a.push(g)}return Array.isArray(e)?a:a[0]}};var Ou=class extends pe{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 Hr(e,i),c=[];for(let p of l){let d=await this.processor(p),m=await this.model({...a,...d}),h=Pe(m.logits_per_audio.data);c.push([...h].map((g,x)=>({score:g,label:r[x]})))}return n?c[0]:c}};var Iu=class extends pe{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&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&console.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 Hr(n,o),i=[];for(let l of a){let c=await this.processor(l),d=(await this.model(c)).logits[0],m=[];for(let g of d)m.push(Me(g.data)[1]);let h=this.tokenizer.decode(m,{skip_special_tokens:!0}).trim();i.push({text:h})}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,h=p.sampling_rate,g=await Hr(c,h),x=[];for(let k of g){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=h*n,L=h*a,C=M-2*L,v=0;for(;;){let G=v+M,X=k.subarray(v,G),V=await this.processor(X),Q=v===0,Y=G>=k.length;if(E.push({stride:[X.length,Q?0:L,Y?0:L],input_features:V.input_features,is_last:Y}),Y)break;v+=C}}else E=[{stride:[k.length,0,0],input_features:(await this.processor(k)).input_features,is_last:!0}];for(let M of E){i.num_frames=Math.floor(M.stride[0]/m);let L=await this.model.generate({inputs:M.input_features,...i});s==="word"?(M.tokens=L.sequences.tolist()[0],M.token_timestamps=L.token_timestamps.tolist()[0].map(C=>os(C,2))):M.tokens=L[0].tolist(),M.stride=M.stride.map(C=>C/h)}let[A,S]=this.tokenizer._decode_asr(E,{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 Hr(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 Cu=class extends pe{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 fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new B("float32",e,[e.length]);else if(!(e instanceof B))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||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await yr.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 Pu=class extends pe{async _call(e,r={}){let s=Array.isArray(e),n=await Ke(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 Lu=class extends pe{async _call(e,{top_k:r=5}={}){let s=await Ke(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 Zt(new B("float32",Pe(l.data),l.dims),r),p=c[0].tolist(),m=c[1].tolist().map((h,g)=>({label:a?a[h]:`LABEL_${h}`,score:p[g]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var c2={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},On=class extends pe{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 Ke(e),p=c.map(A=>[A.height,A.width]),d=await this.processor(c),{inputNames:m,outputNames:h}=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 g=await this.model(d),x=null;if(i!==null)x=c2[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(c2))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,E=[];if(i)if(i==="panoptic"||i==="instance"){let A=x(g,r,s,n,o,a??p)[0],S=A.segmentation;for(let M of A.segments_info){let L=new Uint8ClampedArray(S.data.length);for(let v=0;v<S.data.length;++v)S.data[v]===M.id&&(L[v]=255);let C=new Xe(L,S.dims[1],S.dims[0],1);E.push({score:M.score,label:k[M.label_id],mask:C})}}else if(i==="semantic"){let{segmentation:A,labels:S}=x(g,a??p)[0];for(let M of S){let L=new Uint8ClampedArray(A.data.length);for(let v=0;v<A.data.length;++v)A.data[v]===M&&(L[v]=255);let C=new Xe(L,A.dims[1],A.dims[0],1);E.push({score:null,label:k[M],mask:C})}}else throw Error(`Subtask ${i} not supported.`);else{let S=g[h[0]];for(let M=0;M<p.length;++M){let L=p[M],C=S[M];C.data.some(G=>G<-1e-5||G>1+1e-5)&&C.sigmoid_();let v=await Xe.fromTensor(C.mul_(255).to("uint8")).resize(L[1],L[0]);E.push({label:null,score:null,mask:v})}}return E}};var Nu=class extends On{async _call(e,r={}){let s=await Ke(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 zu=class extends pe{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await Ke(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=>Pe(m.data),d=[];for(let m of c.logits_per_image){let g=[...p(m)].map((x,k)=>({score:x,label:r[k]}));g.sort((x,k)=>k.score-x.score),d.push(g)}return n?d:d[0]}};var Ru=class extends pe{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 Ke(e),a=s?null:o.map(h=>[h.height,h.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(h=>h.boxes.map((g,x)=>({score:h.scores[x],label:d[h.classes[x]],box:yi(g,!s)})));return n?m:m[0]}};var $u=class extends pe{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await Ke(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],h=o?null:[[m.height,m.width]],g=c.pixel_values[d].unsqueeze_(0),x=await this.model({...l,pixel_values:g}),k;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:h})[0];k=E.boxes.map((A,S)=>({score:E.scores[S],label:E.labels[S],box:yi(A,!o)}))}else{let E=this.processor.image_processor.post_process_object_detection(x,s,h,!0)[0];k=E.boxes.map((A,S)=>({score:E.scores[S],label:r[E.classes[S]],box:yi(A,!o)}))}k.sort((E,A)=>A.score-E.score),n!==null&&(k=k.slice(0,n)),p.push(k)}return a?p:p[0]}};var Bu=class extends pe{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 Ke(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 Uu=class extends pe{async _call(e){let r=await Ke(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(Xe.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var Du=class extends pe{async _call(e){let r=await Ke(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 jt(i.view(1,1,l,c),{size:[d,p],mode:"bilinear"})).view(d,p),h=m.min().item(),g=m.max().item(),x=m.sub(h).div_(g-h).mul_(255).to("uint8").unsqueeze(0),k=Xe.fromTensor(x);o.push({predicted_depth:m,depth:k})}return Array.isArray(e)?o:o[0]}};var Fu=class extends pe{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=QE(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=ZE(l,o)),l}};var ju=class extends pe{async _call(e,{pool:r=null}={}){let s=await Ke(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 u2=Object.freeze({"text-classification":{tokenizer:J,pipeline:yu,model:_i,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:J,pipeline:bu,model:su,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:J,pipeline:vu,model:cu,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:J,pipeline:ku,model:lu,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{tokenizer:J,pipeline:Eu,model:Sn,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:J,pipeline:Au,model:Sn,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:J,pipeline:Xr,model:Sn,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:J,pipeline:Tu,model:iu,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{tokenizer:J,pipeline:Mu,model:_i,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Su,model:hu,processor:ut,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:J,pipeline:Ou,model:yr,processor:ut,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:J,pipeline:Iu,model:[nu,mu],processor:ut,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:J,pipeline:Cu,model:[au,ou],processor:[ut,null],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{tokenizer:J,pipeline:Pu,model:uu,processor:ut,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Lu,model:pu,processor:ut,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:On,model:[wi,gi,xi],processor:ut,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:Nu,model:[wi,gi,xi],processor:ut,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:J,pipeline:zu,model:yr,processor:ut,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:Ru,model:fu,processor:ut,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:J,pipeline:$u,model:du,processor:ut,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:J,pipeline:Bu,model:_u,processor:ut,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Uu,model:wu,processor:ut,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Du,model:gu,processor:ut,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{tokenizer:J,pipeline:Fu,model:yr,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{processor:ut,pipeline:ju,model:[xu,yr],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),kL=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Kte(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=kL[t]??t;let h=u2[t.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(u2)}]`);e||(e=h.default.model,console.log(`No model specified. Using default model: "${e}".`),!l&&h.default.dtype&&(l=h.default.dtype));let g={progress_callback:r,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},x=new Map([["tokenizer",h.tokenizer],["model",h.model],["processor",h.processor]]),k=await EL(x,e,g);k.task=t,gr(r,{status:"ready",task:t,model:e});let E=h.pipeline;return new E(k)}async function EL(t,e,r){let s=Object.create(null),n=[];for(let[o,a]of t.entries()){if(!a)continue;let i;Array.isArray(a)?i=new Promise(async(l,c)=>{let p;for(let d of a){if(d===null){l(null);return}try{l(await d.from_pretrained(e,r));return}catch(m){if(m.message?.includes("Unsupported model type"))p=m;else if(m.message?.includes("Could not locate file"))p=m;else{c(m);return}}}c(p)}):i=a.from_pretrained(e,r),s[o]=i,n.push(i)}await Promise.all(n);for(let[o,a]of Object.entries(s))s[o]=await a;return s}var AL=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,X0=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},p2=be.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),Y0=class extends X0{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??p2,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}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];this.token_callback_function?.(s),this.token_cache=ft(this.token_cache,s);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),o;r||n.endsWith(`
|
|
28
|
-
`)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&
|
|
29
|
-
`)}},f2=class extends Y0{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 bi=class{constructor(e,r){this.image=e,this.timestamp=r}},Gu=class{constructor(e,r){e.length>0&&e[0]instanceof Xe&&(e=e.map((s,n)=>new bi(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 TL(t,{num_frames:e=null,fps:r=null}={}){if(!be.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 fetch(n.src)).blob();n.src=URL.createObjectURL(m),await new Promise(h=>n.onloadedmetadata=h)}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),h=new Xe(m.data,c.width,c.height,4),g=new bi(h,d);s.push(g)}return n.remove(),new Gu(s,o)}export{Sd as ASTFeatureExtractor,fh as ASTForAudioClassification,ph as ASTModel,go as ASTPreTrainedModel,ah as AlbertForMaskedLM,oh as AlbertForQuestionAnswering,nh as AlbertForSequenceClassification,sh as AlbertModel,ks as AlbertPreTrainedModel,zf as AlbertTokenizer,lh as ApertusForCausalLM,ih as ApertusModel,_o as ApertusPreTrainedModel,uh as ArceeForCausalLM,ch as ArceeModel,wo as ArceePreTrainedModel,Su as AudioClassificationPipeline,gs as AutoConfig,tt as AutoFeatureExtractor,Re as AutoImageProcessor,yr as AutoModel,hu as AutoModelForAudioClassification,r2 as AutoModelForAudioFrameClassification,i2 as AutoModelForAudioTextToText,mu as AutoModelForCTC,iu as AutoModelForCausalLM,gu as AutoModelForDepthEstimation,_u as AutoModelForDocumentQuestionAnswering,pu as AutoModelForImageClassification,xu as AutoModelForImageFeatureExtraction,s2 as AutoModelForImageMatting,wi as AutoModelForImageSegmentation,a2 as AutoModelForImageTextToText,wu as AutoModelForImageToImage,e2 as AutoModelForMaskGeneration,lu as AutoModelForMaskedLM,n2 as AutoModelForNormalEstimation,fu as AutoModelForObjectDetection,o2 as AutoModelForPoseEstimation,cu as AutoModelForQuestionAnswering,gi as AutoModelForSemanticSegmentation,Sn as AutoModelForSeq2SeqLM,_i as AutoModelForSequenceClassification,nu as AutoModelForSpeechSeq2Seq,ou as AutoModelForTextToSpectrogram,au as AutoModelForTextToWaveform,su as AutoModelForTokenClassification,xi as AutoModelForUniversalSegmentation,uu as AutoModelForVision2Seq,t2 as AutoModelForXVector,du as AutoModelForZeroShotObjectDetection,ut as AutoProcessor,J as AutoTokenizer,Iu as AutomaticSpeechRecognitionPipeline,Nu as BackgroundRemovalPipeline,mh as BartForConditionalGeneration,hh as BartForSequenceClassification,dh as BartModel,ln as BartPretrainedModel,Rf as BartTokenizer,X0 as BaseStreamer,Gd as BeitFeatureExtractor,wh as BeitForImageClassification,_h as BeitModel,xo as BeitPreTrainedModel,xh as BertForMaskedLM,vh as BertForQuestionAnswering,yh as BertForSequenceClassification,bh as BertForTokenClassification,gh as BertModel,Lr as BertPreTrainedModel,$f as BertTokenizer,Wd as BitImageProcessor,Eh as BlenderbotForConditionalGeneration,kh as BlenderbotModel,yo as BlenderbotPreTrainedModel,Th as BlenderbotSmallForConditionalGeneration,Ah as BlenderbotSmallModel,bo as BlenderbotSmallPreTrainedModel,Bf as BlenderbotSmallTokenizer,Uf as BlenderbotTokenizer,Sh as BloomForCausalLM,Mh as BloomModel,vo as BloomPreTrainedModel,Df as BloomTokenizer,Vd as CLIPFeatureExtractor,xl as CLIPImageProcessor,Rh as CLIPModel,ur as CLIPPreTrainedModel,Fh as CLIPSegForImageSegmentation,Dh as CLIPSegModel,Mo as CLIPSegPreTrainedModel,$h as CLIPTextModel,To as CLIPTextModelWithProjection,jf as CLIPTokenizer,Bh as CLIPVisionModel,Uh as CLIPVisionModelWithProjection,Ih as CamembertForMaskedLM,Lh as CamembertForQuestionAnswering,Ch as CamembertForSequenceClassification,Ph as CamembertForTokenClassification,Oh as CamembertModel,Nr as CamembertPreTrainedModel,Ff as CamembertTokenizer,Od as ChatterboxFeatureExtractor,ko as ChatterboxModel,nc as ChatterboxPreTrainedModel,Dd as ChatterboxProcessor,qd as ChineseCLIPFeatureExtractor,Nh as ChineseCLIPModel,oc as ChineseCLIPPreTrainedModel,Ao as ClapAudioModelWithProjection,Id as ClapFeatureExtractor,zh as ClapModel,cn as ClapPreTrainedModel,Eo as ClapTextModelWithProjection,Yl as ClassifierFreeGuidanceLogitsProcessor,Gh as CodeGenForCausalLM,jh as CodeGenModel,So as CodeGenPreTrainedModel,Wf as CodeGenTokenizer,Gf as CodeLlamaTokenizer,qh as CohereForCausalLM,Wh as CohereModel,Oo as CoherePreTrainedModel,qf as CohereTokenizer,Hh as ConvBertForMaskedLM,Kh as ConvBertForQuestionAnswering,Xh as ConvBertForSequenceClassification,Yh as ConvBertForTokenClassification,Vh as ConvBertModel,zr as ConvBertPreTrainedModel,Vf as ConvBertTokenizer,Hd as ConvNextFeatureExtractor,Jh as ConvNextForImageClassification,yl as ConvNextImageProcessor,Qh as ConvNextModel,Io as ConvNextPreTrainedModel,e_ as ConvNextV2ForImageClassification,Zh as ConvNextV2Model,Co as ConvNextV2PreTrainedModel,n_ as DFineForObjectDetection,s_ as DFineModel,Lo as DFinePreTrainedModel,S_ as DINOv3ConvNextModel,fc as DINOv3ConvNextPreTrainedModel,Kd as DINOv3ViTImageProcessor,O_ as DINOv3ViTModel,dc as DINOv3ViTPreTrainedModel,Jd as DPTFeatureExtractor,$_ as DPTForDepthEstimation,kl as DPTImageProcessor,R_ as DPTModel,Uo as DPTPreTrainedModel,zo as DacDecoderModel,ic as DacDecoderOutput,No as DacEncoderModel,ac as DacEncoderOutput,ao as DacFeatureExtractor,o_ as DacModel,un as DacPreTrainedModel,i_ as DebertaForMaskedLM,u_ as DebertaForQuestionAnswering,l_ as DebertaForSequenceClassification,c_ as DebertaForTokenClassification,a_ as DebertaModel,Rr as DebertaPreTrainedModel,Xf as DebertaTokenizer,f_ as DebertaV2ForMaskedLM,h_ as DebertaV2ForQuestionAnswering,d_ as DebertaV2ForSequenceClassification,m_ as DebertaV2ForTokenClassification,p_ as DebertaV2Model,$r as DebertaV2PreTrainedModel,Hf as DebertaV2Tokenizer,__ as DecisionTransformerModel,lc as DecisionTransformerPreTrainedModel,Xd as DeiTFeatureExtractor,g_ as DeiTForImageClassification,bl as DeiTImageProcessor,w_ as DeiTModel,Ro as DeiTPreTrainedModel,x_ as DepthAnythingForDepthEstimation,cc as DepthAnythingPreTrainedModel,Du as DepthEstimationPipeline,y_ as DepthProForDepthEstimation,uc as DepthProPreTrainedModel,Yd as DetrFeatureExtractor,v_ as DetrForObjectDetection,k_ as DetrForSegmentation,vl as DetrImageProcessor,b_ as DetrModel,fn as DetrObjectDetectionOutput,pn as DetrPreTrainedModel,pc as DetrSegmentationOutput,A_ as Dinov2ForImageClassification,E_ as Dinov2Model,$o as Dinov2PreTrainedModel,M_ as Dinov2WithRegistersForImageClassification,T_ as Dinov2WithRegistersModel,Bo as Dinov2WithRegistersPreTrainedModel,N_ as DistilBertForMaskedLM,L_ as DistilBertForQuestionAnswering,C_ as DistilBertForSequenceClassification,P_ as DistilBertForTokenClassification,I_ as DistilBertModel,Br as DistilBertPreTrainedModel,Yf as DistilBertTokenizer,Bu as DocumentQuestionAnsweringPipeline,Qd as DonutFeatureExtractor,Qs as DonutImageProcessor,z_ as DonutSwinModel,mc as DonutSwinPreTrainedModel,yy as EdgeTamModel,U_ as EfficientNetForImageClassification,Zd as EfficientNetImageProcessor,B_ as EfficientNetModel,Do as EfficientNetPreTrainedModel,F_ as ElectraForMaskedLM,W_ as ElectraForQuestionAnswering,j_ as ElectraForSequenceClassification,G_ as ElectraForTokenClassification,D_ as ElectraModel,Ur as ElectraPreTrainedModel,Kf as ElectraTokenizer,oo as EncodecFeatureExtractor,Zl as EosTokenCriteria,V_ as Ernie4_5ForCausalLM,q_ as Ernie4_5Model,Fo as Ernie4_5PretrainedModel,X_ as EsmForMaskedLM,Y_ as EsmForSequenceClassification,K_ as EsmForTokenClassification,H_ as EsmModel,Es as EsmPreTrainedModel,Qf as EsmTokenizer,J_ as ExaoneForCausalLM,Q_ as ExaoneModel,jo as ExaonePreTrainedModel,ew as FalconForCausalLM,rw as FalconH1ForCausalLM,tw as FalconH1Model,Wo as FalconH1PreTrainedModel,Z_ as FalconModel,Go as FalconPreTrainedModel,Jf as FalconTokenizer,nw as FastViTForImageClassification,sw as FastViTModel,qo as FastViTPreTrainedModel,Fu as FeatureExtractionPipeline,ze as FeatureExtractor,ku as FillMaskPipeline,ow as Florence2ForConditionalGeneration,hc as Florence2PreTrainedModel,Im as Florence2Processor,Fl as ForcedBOSTokenLogitsProcessor,jl as ForcedEOSTokenLogitsProcessor,em as GLPNFeatureExtractor,hw as GLPNForDepthEstimation,mw as GLPNModel,Qo as GLPNPreTrainedModel,Aw as GPT2LMHeadModel,Ew as GPT2Model,ra as GPT2PreTrainedModel,td as GPT2Tokenizer,ww as GPTBigCodeForCausalLM,_w as GPTBigCodeModel,Jo as GPTBigCodePreTrainedModel,Mw as GPTJForCausalLM,Tw as GPTJModel,sa as GPTJPreTrainedModel,xw as GPTNeoForCausalLM,gw as GPTNeoModel,Zo as GPTNeoPreTrainedModel,bw as GPTNeoXForCausalLM,yw as GPTNeoXModel,ea as GPTNeoXPreTrainedModel,ed as GPTNeoXTokenizer,cw as Gemma2ForCausalLM,lw as Gemma2Model,Ho as Gemma2PreTrainedModel,pw as Gemma3ForCausalLM,uw as Gemma3Model,Xo as Gemma3PreTrainedModel,Cd as Gemma3nAudioFeatureExtractor,Yo as Gemma3nForConditionalGeneration,_c as Gemma3nPreTrainedModel,Cm as Gemma3nProcessor,iw as GemmaForCausalLM,aw as GemmaModel,Vo as GemmaPreTrainedModel,Zf as GemmaTokenizer,dw as GlmForCausalLM,fw as GlmModel,Ko as GlmPreTrainedModel,kw as GptOssForCausalLM,vw as GptOssModel,ta as GptOssPreTrainedModel,Ow as GraniteForCausalLM,Sw as GraniteModel,Cw as GraniteMoeHybridForCausalLM,Iw as GraniteMoeHybridModel,oa as GraniteMoeHybridPreTrainedModel,na as GranitePreTrainedModel,Pw as GroundingDinoForObjectDetection,tm as GroundingDinoImageProcessor,wc as GroundingDinoPreTrainedModel,Pm as GroundingDinoProcessor,Lw as GroupViTModel,gc as GroupViTPreTrainedModel,zw as HeliumForCausalLM,Nw as HeliumModel,aa as HeliumPreTrainedModel,rd as HerbertTokenizer,$w as HieraForImageClassification,Rw as HieraModel,ia as HieraPreTrainedModel,Ww as HubertForCTC,qw as HubertForSequenceClassification,Gw as HubertModel,jw as HubertPreTrainedModel,Hw as HunYuanDenseV1ForCausalLM,Vw as HunYuanDenseV1Model,la as HunYuanDenseV1PreTrainedModel,Kw as IJepaForImageClassification,Yw as IJepaModel,ca as IJepaPreTrainedModel,yc as Idefics3ForConditionalGeneration,El as Idefics3ImageProcessor,xc as Idefics3PreTrainedModel,Nl as Idefics3Processor,Lu as ImageClassificationPipeline,ju as ImageFeatureExtractionPipeline,q as ImageFeatureExtractor,q as ImageProcessor,On as ImageSegmentationPipeline,Uu as ImageToImagePipeline,Pu as ImageToTextPipeline,yA as InterruptableStoppingCriteria,Jw as JAISLMHeadModel,Qw as JAISModel,ua as JAISPreTrainedModel,sm as JinaCLIPImageProcessor,Zw as JinaCLIPModel,dn as JinaCLIPPreTrainedModel,Nm as JinaCLIPProcessor,pa as JinaCLIPTextModel,eg as JinaCLIPVisionModel,rg as Lfm2ForCausalLM,tg as Lfm2Model,ng as Lfm2MoeForCausalLM,sg as Lfm2MoeModel,da as Lfm2MoePreTrainedModel,fa as Lfm2PreTrainedModel,C0 as LiteWhisperForConditionalGeneration,ig as Llama4ForCausalLM,bc as Llama4PreTrainedModel,ag as LlamaForCausalLM,og as LlamaModel,ma as LlamaPreTrainedModel,sd as LlamaTokenizer,mn as LlavaForConditionalGeneration,mn as LlavaOnevisionForConditionalGeneration,nm as LlavaOnevisionImageProcessor,vc as LlavaPreTrainedModel,zm as LlavaProcessor,cg as LlavaQwen2ForCausalLM,Wt as LogitsProcessor,xs as LogitsProcessorList,po as LogitsWarper,pg as LongT5ForConditionalGeneration,ug as LongT5Model,ha as LongT5PreTrainedModel,dg as M2M100ForConditionalGeneration,fg as M2M100Model,_a as M2M100PreTrainedModel,nd as M2M100Tokenizer,ad as MBart50Tokenizer,bg as MBartForCausalLM,xg as MBartForConditionalGeneration,yg as MBartForSequenceClassification,gg as MBartModel,As as MBartPreTrainedModel,to as MBartTokenizer,ox as MPNetForMaskedLM,lx as MPNetForQuestionAnswering,ax as MPNetForSequenceClassification,ix as MPNetForTokenClassification,nx as MPNetModel,Dr as MPNetPreTrainedModel,cd as MPNetTokenizer,fx as MT5ForConditionalGeneration,px as MT5Model,Sa as MT5PreTrainedModel,hg as MarianMTModel,mg as MarianModel,wa as MarianPreTrainedModel,od as MarianTokenizer,am as Mask2FormerImageProcessor,om as MaskFormerFeatureExtractor,wg as MaskFormerForInstanceSegmentation,Js as MaskFormerImageProcessor,_g as MaskFormerModel,ga as MaskFormerPreTrainedModel,Jl as MaxLengthCriteria,vg as Metric3DForDepthEstimation,kc as Metric3DPreTrainedModel,kg as Metric3Dv2ForDepthEstimation,Ec as Metric3Dv2PreTrainedModel,Eg as MgpstrForSceneTextRecognition,Ac as MgpstrModelOutput,Tc as MgpstrPreTrainedModel,Rm as MgpstrProcessor,id as MgpstrTokenizer,ya as MimiDecoderModel,Sc as MimiDecoderOutput,xa as MimiEncoderModel,Mc as MimiEncoderOutput,Ag as MimiModel,hn as MimiPreTrainedModel,Vl as MinLengthLogitsProcessor,Hl as MinNewTokensLengthLogitsProcessor,Mg as MistralForCausalLM,Tg as MistralModel,ba as MistralPreTrainedModel,Og as MobileBertForMaskedLM,Cg as MobileBertForQuestionAnswering,Ig as MobileBertForSequenceClassification,Sg as MobileBertModel,Ts as MobileBertPreTrainedModel,ld as MobileBertTokenizer,Lg as MobileLLMForCausalLM,Pg as MobileLLMModel,va as MobileLLMPreTrainedModel,im as MobileNetV1FeatureExtractor,zg as MobileNetV1ForImageClassification,Rg as MobileNetV1ForSemanticSegmentation,Al as MobileNetV1ImageProcessor,Ng as MobileNetV1Model,_n as MobileNetV1PreTrainedModel,lm as MobileNetV2FeatureExtractor,Bg as MobileNetV2ForImageClassification,Ug as MobileNetV2ForSemanticSegmentation,Tl as MobileNetV2ImageProcessor,$g as MobileNetV2Model,wn as MobileNetV2PreTrainedModel,cm as MobileNetV3FeatureExtractor,Fg as MobileNetV3ForImageClassification,jg as MobileNetV3ForSemanticSegmentation,Ml as MobileNetV3ImageProcessor,Dg as MobileNetV3Model,gn as MobileNetV3PreTrainedModel,um as MobileNetV4FeatureExtractor,Wg as MobileNetV4ForImageClassification,qg as MobileNetV4ForSemanticSegmentation,Sl as MobileNetV4ImageProcessor,Gg as MobileNetV4Model,xn as MobileNetV4PreTrainedModel,pm as MobileViTFeatureExtractor,Hg as MobileViTForImageClassification,Ol as MobileViTImageProcessor,Vg as MobileViTModel,ka as MobileViTPreTrainedModel,Yg as MobileViTV2ForImageClassification,Xg as MobileViTV2Model,Ea as MobileViTV2PreTrainedModel,tx as ModernBertDecoderForCausalLM,ex as ModernBertDecoderModel,Aa as ModernBertDecoderPreTrainedModel,Qg as ModernBertForMaskedLM,Jg as ModernBertForSequenceClassification,Zg as ModernBertForTokenClassification,Kg as ModernBertModel,Ms as ModernBertPreTrainedModel,lg as Moondream1ForConditionalGeneration,Pd as MoonshineFeatureExtractor,sx as MoonshineForConditionalGeneration,rx as MoonshineModel,Ta as MoonshinePreTrainedModel,$m as MoonshineProcessor,ux as MptForCausalLM,cx as MptModel,Ma as MptPreTrainedModel,dx as MultiModalityCausalLM,Oc as MultiModalityPreTrainedModel,hx as MusicgenForCausalLM,Ia as MusicgenForConditionalGeneration,mx as MusicgenModel,Oa as MusicgenPreTrainedModel,wx as NanoChatForCausalLM,_x as NanoChatModel,Ca as NanoChatPreTrainedModel,xx as NeoBertForMaskedLM,vx as NeoBertForQuestionAnswering,yx as NeoBertForSequenceClassification,bx as NeoBertForTokenClassification,gx as NeoBertModel,Fr as NeoBertPreTrainedModel,ud as NllbTokenizer,Xl as NoBadWordsLogitsProcessor,Wl as NoRepeatNGramLogitsProcessor,kx as NomicBertModel,Ic as NomicBertPreTrainedModel,fm as NougatImageProcessor,pd as NougatTokenizer,Lx as OPTForCausalLM,Px as OPTModel,Ra as OPTPreTrainedModel,Ru as ObjectDetectionPipeline,Mx as Olmo2ForCausalLM,Tx as Olmo2Model,La as Olmo2PreTrainedModel,Ox as Olmo3ForCausalLM,Sx as Olmo3Model,Na as Olmo3PreTrainedModel,Ax as OlmoForCausalLM,Ex as OlmoModel,Pa as OlmoPreTrainedModel,Cx as OpenELMForCausalLM,Ix as OpenELMModel,za as OpenELMPreTrainedModel,dm as OwlViTFeatureExtractor,$x as OwlViTForObjectDetection,Zs as OwlViTImageProcessor,Rx as OwlViTModel,Ba as OwlViTPreTrainedModel,Bm as OwlViTProcessor,zx as Owlv2ForObjectDetection,mm as Owlv2ImageProcessor,Nx as Owlv2Model,$a as Owlv2PreTrainedModel,Bx as PaliGemmaForConditionalGeneration,Cc as PaliGemmaPreTrainedModel,Um as PaliGemmaProcessor,Ld as ParakeetFeatureExtractor,Ux as ParakeetForCTC,Pc as ParakeetPreTrainedModel,Fx as PatchTSMixerForPrediction,Dx as PatchTSMixerModel,Ua as PatchTSMixerPreTrainedModel,Gx as PatchTSTForPrediction,jx as PatchTSTModel,Da as PatchTSTPreTrainedModel,Hx as Phi3ForCausalLM,Vx as Phi3Model,ja as Phi3PreTrainedModel,Ga as Phi3VForCausalLM,wm as Phi3VImageProcessor,Lc as Phi3VPreTrainedModel,Dm as Phi3VProcessor,qx as PhiForCausalLM,Wx as PhiModel,Fa as PhiPreTrainedModel,gm as PixtralImageProcessor,Fm as PixtralProcessor,y as PreTrainedModel,j as PreTrainedTokenizer,Bl as PretrainedConfig,ne as Processor,Yx as PvtForImageClassification,xm as PvtImageProcessor,Xx as PvtModel,Wa as PvtPreTrainedModel,io as PyAnnoteFeatureExtractor,Qx as PyAnnoteForAudioFrameClassification,Kx as PyAnnoteModel,qa as PyAnnotePreTrainedModel,jm as PyAnnoteProcessor,vu as QuestionAnsweringPipeline,Zx as Qwen2ForCausalLM,Jx as Qwen2Model,Va as Qwen2PreTrainedModel,fd as Qwen2Tokenizer,ey as Qwen2VLForConditionalGeneration,ym as Qwen2VLImageProcessor,Nc as Qwen2VLPreTrainedModel,Gm as Qwen2VLProcessor,ry as Qwen3ForCausalLM,ty as Qwen3Model,Ha as Qwen3PreTrainedModel,ay as RFDetrForObjectDetection,oy as RFDetrModel,zc as RFDetrObjectDetectionOutput,Ya as RFDetrPreTrainedModel,r_ as RTDetrForObjectDetection,bm as RTDetrImageProcessor,t_ as RTDetrModel,pr as RTDetrObjectDetectionOutput,Po as RTDetrPreTrainedModel,gy as RTDetrV2ForObjectDetection,wy as RTDetrV2Model,Rc as RTDetrV2ObjectDetectionOutput,Ka as RTDetrV2PreTrainedModel,no as RawAudio,Xe as RawImage,Gu as RawVideo,bi as RawVideoFrame,ql as RepetitionPenaltyLogitsProcessor,ny as ResNetForImageClassification,sy as ResNetModel,Xa as ResNetPreTrainedModel,dy as RoFormerForMaskedLM,_y as RoFormerForQuestionAnswering,my as RoFormerForSequenceClassification,hy as RoFormerForTokenClassification,fy as RoFormerModel,Gr as RoFormerPreTrainedModel,md as RoFormerTokenizer,ly as RobertaForMaskedLM,py as RobertaForQuestionAnswering,cy as RobertaForSequenceClassification,uy as RobertaForTokenClassification,iy as RobertaModel,jr as RobertaPreTrainedModel,dd as RobertaTokenizer,co as Sam2ImageProcessor,Uc as Sam2ImageSegmentationOutput,Qa as Sam2Model,Dc as Sam2PreTrainedModel,zl as Sam2Processor,Wm as Sam2VideoProcessor,co as Sam3ImageProcessor,by as Sam3TrackerModel,co as SamImageProcessor,$c as SamImageSegmentationOutput,xy as SamModel,Bc as SamPreTrainedModel,uo as SamProcessor,vm as SapiensFeatureExtractor,ky as SapiensForDepthEstimation,Ey as SapiensForNormalEstimation,vy as SapiensForSemanticSegmentation,Il as SapiensImageProcessor,yn as SapiensPreTrainedModel,Nd as SeamlessM4TFeatureExtractor,km as SegformerFeatureExtractor,Ty as SegformerForImageClassification,My as SegformerForSemanticSegmentation,Cl as SegformerImageProcessor,Ay as SegformerModel,bn as SegformerPreTrainedModel,Em as SiglipImageProcessor,Sy as SiglipModel,Ja as SiglipPreTrainedModel,Za as SiglipTextModel,hd as SiglipTokenizer,Oy as SiglipVisionModel,Cy as SmolLM3ForCausalLM,Iy as SmolLM3Model,ei as SmolLM3PreTrainedModel,Xw as SmolVLMForConditionalGeneration,El as SmolVLMImageProcessor,Nl as SmolVLMProcessor,ri as SnacDecoderModel,ti as SnacEncoderModel,zd as SnacFeatureExtractor,Py as SnacModel,vn as SnacPreTrainedModel,Rd as SpeechT5FeatureExtractor,Ny as SpeechT5ForSpeechToText,zy as SpeechT5ForTextToSpeech,Ry as SpeechT5HifiGan,Ly as SpeechT5Model,kn as SpeechT5PreTrainedModel,qm as SpeechT5Processor,_d as SpeechT5Tokenizer,By as SqueezeBertForMaskedLM,Dy as SqueezeBertForQuestionAnswering,Uy as SqueezeBertForSequenceClassification,$y as SqueezeBertModel,Ss as SqueezeBertPreTrainedModel,wd as SqueezeBertTokenizer,jy as StableLmForCausalLM,Fy as StableLmModel,si as StableLmPreTrainedModel,Wy as Starcoder2ForCausalLM,Gy as Starcoder2Model,ni as Starcoder2PreTrainedModel,an as StoppingCriteria,Ql as StoppingCriteriaList,qy as StyleTextToSpeech2Model,Fc as StyleTextToSpeech2PreTrainedModel,Eu as SummarizationPipeline,oi as SupertonicForConditionalGeneration,jc as SupertonicPreTrainedModel,nn as SuppressTokensAtBeginLogitsProcessor,Ky as Swin2SRForImageSuperResolution,Am as Swin2SRImageProcessor,Yy as Swin2SRModel,ai as Swin2SRPreTrainedModel,Hy as SwinForImageClassification,Xy as SwinForSemanticSegmentation,Vy as SwinModel,En as SwinPreTrainedModel,Jy as T5ForConditionalGeneration,Qy as T5Model,ii as T5PreTrainedModel,gd as T5Tokenizer,e0 as TableTransformerForObjectDetection,Zy as TableTransformerModel,Gc as TableTransformerObjectDetectionOutput,li as TableTransformerPreTrainedModel,Kl as TemperatureLogitsWarper,B as Tensor,Xr as Text2TextGenerationPipeline,yu as TextClassificationPipeline,Tu as TextGenerationPipeline,Y0 as TextStreamer,Cu as TextToAudioPipeline,bu as TokenClassificationPipeline,j as TokenizersBackend,xA as TopKLogitsWarper,gA as TopPLogitsWarper,t0 as TrOCRForCausalLM,Wc as TrOCRPreTrainedModel,Au as TranslationPipeline,Vc as UltravoxModel,qc as UltravoxPreTrainedModel,Vm as UltravoxProcessor,n0 as UniSpeechForCTC,o0 as UniSpeechForSequenceClassification,s0 as UniSpeechModel,An as UniSpeechPreTrainedModel,c0 as UniSpeechSatForAudioFrameClassification,i0 as UniSpeechSatForCTC,l0 as UniSpeechSatForSequenceClassification,a0 as UniSpeechSatModel,Os as UniSpeechSatPreTrainedModel,Lm as VLChatProcessor,rm as VLMImageProcessor,p0 as VaultGemmaForCausalLM,u0 as VaultGemmaModel,ci as VaultGemmaPreTrainedModel,Tm as ViTFeatureExtractor,m0 as ViTForImageClassification,Pl as ViTImageProcessor,h0 as ViTMAEModel,Hc as ViTMAEPreTrainedModel,w0 as ViTMSNForImageClassification,_0 as ViTMSNModel,pi as ViTMSNPreTrainedModel,d0 as ViTModel,ui as ViTPreTrainedModel,f0 as VisionEncoderDecoderModel,g0 as VitMatteForImageMatting,Mm as VitMatteImageProcessor,Xc as VitMattePreTrainedModel,x0 as VitPoseForPoseEstimation,Sm as VitPoseImageProcessor,Yc as VitPosePreTrainedModel,y0 as VitsModel,Kc as VitsModelOutput,Qc as VitsPreTrainedModel,yd as VitsTokenizer,r0 as VoxtralForConditionalGeneration,Hm as VoxtralProcessor,v0 as Wav2Vec2BertForCTC,k0 as Wav2Vec2BertForSequenceClassification,b0 as Wav2Vec2BertModel,Tn as Wav2Vec2BertPreTrainedModel,bd as Wav2Vec2CTCTokenizer,$d as Wav2Vec2FeatureExtractor,Fw as Wav2Vec2ForAudioFrameClassification,Uw as Wav2Vec2ForCTC,Dw as Wav2Vec2ForSequenceClassification,Bw as Wav2Vec2Model,tr as Wav2Vec2PreTrainedModel,Xm as Wav2Vec2Processor,Ym as Wav2Vec2ProcessorWithLM,S0 as WavLMForAudioFrameClassification,A0 as WavLMForCTC,T0 as WavLMForSequenceClassification,M0 as WavLMForXVector,E0 as WavLMModel,Wr as WavLMPreTrainedModel,Bd as WeSpeakerFeatureExtractor,O0 as WeSpeakerResNetModel,Zc as WeSpeakerResNetPreTrainedModel,Ud as WhisperFeatureExtractor,tu as WhisperForConditionalGeneration,I0 as WhisperModel,fi as WhisperPreTrainedModel,Km as WhisperProcessor,f2 as WhisperTextStreamer,Gl as WhisperTimeStampLogitsProcessor,vd as WhisperTokenizer,R0 as XLMForQuestionAnswering,N0 as XLMForSequenceClassification,z0 as XLMForTokenClassification,P0 as XLMModel,qr as XLMPreTrainedModel,B0 as XLMRobertaForMaskedLM,F0 as XLMRobertaForQuestionAnswering,U0 as XLMRobertaForSequenceClassification,D0 as XLMRobertaForTokenClassification,$0 as XLMRobertaModel,Vr as XLMRobertaPreTrainedModel,kd as XLMRobertaTokenizer,Ed as XLMTokenizer,L0 as XLMWithLMHeadModel,Jc as XVectorOutput,Om as YolosFeatureExtractor,G0 as YolosForObjectDetection,Ll as YolosImageProcessor,j0 as YolosModel,ru as YolosObjectDetectionOutput,di as YolosPreTrainedModel,q0 as YoutuForCausalLM,W0 as YoutuModel,mi as YoutuPreTrainedModel,Ou as ZeroShotAudioClassificationPipeline,Mu as ZeroShotClassificationPipeline,zu as ZeroShotImageClassificationPipeline,$u as ZeroShotObjectDetectionPipeline,Ee as cat,RC as cos_sim,Jv as dot,De as env,Ve as full,eo as full_like,Sf as interpolate,jt as interpolate_4d,b3 as layer_norm,qP as load_image,TL as load_video,Mp as log_softmax,KE as matmul,pl as mean,QE as mean_pooling,it as ones,fl as ones_like,kP as permute,Kte as pipeline,ZE as quantize_embeddings,v3 as rand,JE as randn,Md as read_audio,y3 as rfft,ul as slice,Pe as softmax,Gt as stack,Of as std_mean,Zt as topk,Cf as zeros,Pf as zeros_like};
|
|
25
|
+
${s}${o}`+n.repeat(t)+`${s}`,a}function rL(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function sL(t,e,r,s,n,o){return t===0&&e===0?rL(r,s,n,o):tL(r,t,e,s,n,o)}var zl=class extends ne{static image_processor_class=Re;static tokenizer_class=J;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],h=o[f],g=a[f];l.push(qv(m,this.image_token));let x=h.map((A,S)=>sL(A,g[S],i,this.fake_image_token,this.image_token,this.global_img_token)),k=m.split(this.image_token);if(k.length===0)throw new Error("The image token should be present in the text.");let E=k[0];for(let A=0;A<x.length;++A)E+=x[A]+k[A+1];c.push(E)}return{...this.tokenizer(c),...n}}};var Nm=class extends ne{static image_processor_class=Re;static tokenizer_class=J;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(k=>k.images).flatMap(k=>k.images).map(k=>Xe.read(k)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=k=>n.encode(k,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[c,p,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),m=a(i[0]),h=new Array(m.length).fill(!1);for(let k=1;k<i.length;++k){let E=new Array(this.num_image_tokens).fill(c),A=a(i[k]);m=dt(m,[p],E,[f],A);let S=new Array(this.num_image_tokens).fill(!0);h=dt(h,[!1],S,[!1],new Array(A.length).fill(!1))}let g=[1,m.length],x={input_ids:new B("int64",m,g),attention_mask:new B("int64",new Array(m.length).fill(1),g),images_seq_mask:new B("bool",h,g),images_emb_mask:new B("bool",new Array(l*this.num_image_tokens).fill(!0),[1,l,this.num_image_tokens])};if(r&&r.length>0){let k=await this.image_processor(r);return k.pixel_values.unsqueeze_(0),{...x,...k}}return x}};var zm=class extends ne{static tokenizer_class=J;static image_processor_class=Re;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 Rm=class extends ne{static tokenizer_class=J;static image_processor_class=Re;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 _A={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},$m=class extends ne{static tokenizer_class=J;static image_processor_class=Re;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(!_A.hasOwnProperty(r))throw new Error(`Format ${r} is not supported.`);let[s,n]=_A[r],o=this[s].bind(this),[a,i]=e.dims,l=[],c=[],p=e.tolist();for(let m=0;m<a;++m){let h=p[m],g=[],x=[];for(let E=1;E<i;++E){let[A,S]=Me(Pe(h[E]));if(x.push(A),S==n)break;g.push(S)}let k=x.length>0?x.reduce((E,A)=>E*A,1):0;c.push(g),l.push(k)}return[o(c),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,c]=this._decode_helper(s,"wp"),p=[],f=[];for(let m=0;m<n.length;++m){let[h,g]=Me([o[m],i[m],c[m]]);p.push([n[m],a[m],l[m]][g]),f.push(h)}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 J.from_pretrained("Xenova/gpt2"),n=await J.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 Bm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Um=class extends ne{static tokenizer_class=J;static image_processor_class=Re};var rn="<image>";function nL(t,e,r,s,n){return`${s.repeat(r*n)}${e}${t}
|
|
26
|
+
`}var Dm=class extends ne{static tokenizer_class=J;static image_processor_class=Re;static uses_processor_config=!1;async _call(e,r=null,s={}){r||(console.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(rn))?a=r.map(c=>{let p=c.replaceAll(rn,rn.repeat(o)),f=p.lastIndexOf(rn),m=f===-1?0:f+rn.length;return p.slice(0,m)+n+p.slice(m)+`
|
|
27
|
+
`}):(console.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=>nL(c,n,o,rn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var wA="<|image|>",oL=/<\|image_\d+\|>/g,Fm=class extends ne{static image_processor_class=Re;static tokenizer_class=J;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(oL).join(wA.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let p=this.tokenizer._tokenizer.token_to_id(wA);a.input_ids.map_(f=>f==p?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var jm=class extends ne{static tokenizer_class=J;static image_processor_class=Re;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,h=f*m,g=Math.floor(a/h),x=Math.floor(i/h);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let k=0;k<r.length;++k){let E=l.repeat(x),A=E+c,S=E+p,M=A.repeat(g-1)+S;r[k]=r[k].replace(l,M)}}let o=r?this.tokenizer(r,s):{};return{...n,...o}}};var Gm=class extends ne{static feature_extractor_class=io;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 Wm=class extends ne{static image_processor_class=Re;static tokenizer_class=J;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=o.tolist();e=e.map(p=>{for(;p.includes("<|image_pad|>");){let f=Number(c[l++].reduce((m,h)=>m*h,1n));p=p.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(f/i)))}return p.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...n}}};var uo=class extends ne{static image_processor_class=Re;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 Rl=class extends uo{},qm=class extends Rl{};var Vm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Hm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;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 $l="[AUDIO]",aL="[BEGIN_AUDIO]",iL=375;function lL(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 Xm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;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($l))throw new Error(`The input text does not contain the audio token ${$l}.`);Array.isArray(r)||(r=[r]);let a=e.split($l),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(g=>lL(g,l)),p=c.map(g=>g.length),f=c.flat(),m=(await Promise.all(f.map(g=>this.feature_extractor(g,s)))).map(g=>g.input_features);n.audio_values=m.length>1?Ee(m,0):m[0];let h=a[0];for(let g=0;g<p.length;++g){h+=aL;for(let x=0;x<p[g];++x)h+=$l.repeat(iL);h+=a[g+1]}e=h}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};var Ym=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Km=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var Qm=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e){return await this.feature_extractor(e)}};var ut=class{static async from_pretrained(e,r={}){let s=await at(e,Ks,!0,r),{image_processor_type:n,feature_extractor_type:o,processor_class:a}=s;if(a&&Bl[a])return Bl[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=tn[n.replace(/Fast$/,"")];if(!c)throw new Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new c(s)}if(o){let c=tn[o];if(c)i.image_processor=new c(s);else{let p=lo[o];if(!p)throw new Error(`Unknown feature_extractor_type: '${o}'.`);i.feature_extractor=new p(s)}}let l={};return new ne(l,i,null)}};async function cL(t,e){return await at(t,"config.json",!0,e)}function sn(t){let e={},r={};switch(t.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":case"chatterbox":case"mistral3":r=sn(t.text_config);break;case"moondream1":r=sn(t.phi_config);break;case"musicgen":r=sn(t.decoder);break;case"multi_modality":r=sn(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"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"starcoder2":case"qwen2":case"qwen2_vl":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"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"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":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=sn(t.decoder),o="num_decoder_layers"in n,a=ot(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,...ot(t,["model_type","multi_query","is_encoder_decoder"])};for(let n in e)s[n]=t[e[n]];return s}function Dl(t,e){if(["lfm2","lfm2_moe"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{layer_types:o,num_attention_heads:a,num_key_value_heads:i,hidden_size:l,conv_L_cache:c}=t,p=l/a,f=e?.batch_size??1;for(let m=0;m<o.length;++m)if(o[m]==="full_attention")for(let h of["key","value"])n[`${r}.${m}.${h}`]=[f,i,0,p];else if(o[m]==="conv")n[`${s}_conv.${m}`]=[f,l,c];else throw new Error(`Unsupported layer type: ${o[m]}`);return n}else if(["granitemoehybrid","falcon_h1"].includes(t.model_type)){let r=e?.prefix??"past_key_values",s=r==="present"?"present":"past",n={},{layer_types:o,num_hidden_layers:a,num_attention_heads:i,num_key_value_heads:l,hidden_size:c,mamba_d_conv:p,mamba_n_heads:f,mamba_d_head:m,mamba_d_state:h,mamba_n_groups:g,mamba_expand:x,mamba_d_ssm:k}=t,E=c/i,A=e?.batch_size??1,S=(k??x*c)+2*g*h;for(let M=0;M<a;++M)if((!o||o[M]==="mamba")&&(n[`${s}_conv.${M}`]=[A,S,p],n[`${s}_ssm.${M}`]=[A,f,m,h]),!o||o[M]==="attention")for(let L of["key","value"])n[`${r}.${M}.${L}`]=[A,l,0,E];return n}return uL(t,e)}function uL(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 Ul=class t{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=sn(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 cL(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(i)}},gs=class{static async from_pretrained(...e){return Ul.from_pretrained(...e)}};async function gA(t,e,r,s){let n=`${e}${s}.onnx`,o=`${r.subfolder??""}/${n}`;return await Fn(t,o,!0,r,be.IS_NODE_ENV)}async function xA(t,e,r,s,n,o={}){let a=`${e}${r}.onnx`,i=be.IS_NODE_ENV,l=[];if(n){let c;typeof n=="object"?n.hasOwnProperty(a)?c=n[a]:n.hasOwnProperty(e)?c=n[e]:c=!1:c=n;let p=+c;if(p>Gi)throw new Error(`The number of external data chunks (${p}) exceeds the maximum allowed value (${Gi}).`);for(let f=0;f<p;++f){let m=`${a}_data${f===0?"":"_"+f}`,h=`${s.subfolder??""}/${m}`;l.push(new Promise(async(g,x)=>{let k=await Fn(t,h,!0,s,i);g(k instanceof Uint8Array?{path:m,data:k}:m)}))}}else o.externalData!==void 0&&(l=o.externalData.map(async c=>{if(typeof c.data=="string"){let p=await Fn(t,c.data,!0,s);return{...c,data:p}}return c}));return Promise.all(l)}async function pL(t,e,r,s=!1){let n=r.config?.["transformers.js_config"]??{},o=r.device??n.device;o&&typeof o!="string"&&(o.hasOwnProperty(e)?o=o[e]:(console.warn(`device not specified for "${e}". Using the default device.`),o=null));let a=o??(be.IS_NODE_ENV?"cpu":"wasm"),i=HE(a),l=n.device_config??{};l.hasOwnProperty(a)&&(n={...n,...l[a]});let c=r.dtype??n.dtype;if(typeof c!="string"&&(c&&c.hasOwnProperty(e)?c=c[e]:(c=Ad[a]??ht.fp32,console.warn(`dtype not specified for "${e}". Using the default dtype (${c}) for this device (${a}).`))),c===ht.auto){let L=n.dtype;typeof L!="string"&&(L=L?.[e]),L&&L!==ht.auto&&ht.hasOwnProperty(L)?c=L:c=Ad[a]??ht.fp32}let p=c;if(Td.hasOwnProperty(p)){if(a==="webgpu"&&!be.IS_NODE_ENV&&p===ht.fp16&&!await KE())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${p}. Should be one of: ${Object.keys(ht).join(", ")}`);let f=n.kv_cache_dtype,m=f?typeof f=="string"?f:f[p]??"float32":void 0;if(m&&!["float32","float16"].includes(m))throw new Error(`Invalid kv_cache_dtype: ${m}. Should be one of: float32, float16`);let h=Td[p],g={...r.session_options};g.executionProviders??=i;let x=n.free_dimension_overrides;x?g.freeDimensionOverrides??=x:a.startsWith("webnn")&&!g.freeDimensionOverrides&&console.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 k=gA(t,e,r,h),E=r.use_external_data_format??n.use_external_data_format,A=await xA(t,e,h,r,E,g);if(A.length>0&&!be.IS_NODE_ENV&&(g.externalData=A),s&&a==="webgpu"&&f!==!1){let L=Dl(r.config,{prefix:"present"});if(Object.keys(L).length>0&&!Jn()){let C={};for(let v in L)C[v]="gpu-buffer";g.preferredOutputLocation=C}}return{buffer_or_path:await k,session_options:g,session_config:{dtype:p,kv_cache_dtype:m,device:a}}}async function vt(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let{buffer_or_path:o,session_options:a,session_config:i}=await pL(t,e[n],r,n===s),l=await il(o,a,i);return[n,l]})))}function yA(t){for(let e in t)cl(t[e])?t[e]=new B(t[e]):typeof t[e]=="object"&&yA(t[e]);return t}async function ce(t,e){let r=dL(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return be.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await ll(t,s);return yA(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 console.error(`An error occurred during model execution: "${s}".`),console.error("Inputs given to model:",n),s}}function dL(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof B)){s.push(a);continue}r[a]=Jn()?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));console.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Le=class{};var F=class extends Le{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},_e=class extends Le{constructor({logits:e}){super(),this.logits=e}},ge=class extends Le{constructor({logits:e}){super(),this.logits=e}},Ae=class extends Le{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},gt=class extends Le{constructor({logits:e}){super(),this.logits=e}};var Fl=class extends Le{constructor({alphas:e}){super(),this.alphas=e}};var Wt=class extends Je{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},po=class extends Je{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},xs=class extends Je{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()}},jl=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}},Gl=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}},nn=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}},Wl=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=Sp(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),p=Me(l.subarray(0,this.timestamp_begin))[0];c>p&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},ql=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}},Vl=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}},Hl=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}},Xl=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}},Yl=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}},Kl=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}},Ql=class extends po{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}},bA=class extends po{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}},vA=class extends po{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 on=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,ot(e,Object.getOwnPropertyNames(this)))}};var an=class extends Je{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Jl=class t extends Je{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof an&&(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()}},Zl=class extends an{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)}},ec=class extends an{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)})}},kA=class extends an{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 ys=class extends Je{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){let r=0;for(let n=0;n<e.length;++n)r+=e[n];let s=Math.random()*r;for(let n=0;n<e.length;++n)if(s-=e[n],s<=0)return n;return 0}static getSampler(e){if(e.do_sample)return new Zm(e);if(e.num_beams>1)return new eh(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 Jm(e)}},Jm=class extends ys{async sample(e){let r=Me(e.data)[1];return[[BigInt(r),0]]}},Zm=class extends ys{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 Zt(e,r),o=Pe(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},eh=class extends ys{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 Zt(e,r),o=Pe(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var fo=null;function AA(t){fo=t}function th(t){if(t instanceof B)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 B("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new B("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function rh(t){return new B("bool",[t],[1])}var H={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15},EA={[H.DecoderOnly]:{can_generate:!0,forward:Ot,prepare_inputs:mo},[H.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Ot,prepare_inputs:mo},[H.Seq2Seq]:{can_generate:!0,forward:tc,prepare_inputs:ho},[H.Vision2Seq]:{can_generate:!0,forward:tc,prepare_inputs:ho},[H.Musicgen]:{can_generate:!0,forward:tc},[H.EncoderDecoder]:{can_generate:!1,forward:tc},[H.ImageTextToText]:{can_generate:!0,forward:hL,prepare_inputs:rc},[H.AudioTextToText]:{can_generate:!0,forward:mL,prepare_inputs:rc},[H.Phi3V]:{can_generate:!0,prepare_inputs:rc},[H.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:rc},[H.MultiModality]:{can_generate:!0},[H.AutoEncoder]:{can_generate:!1,forward:fL},[H.Chatterbox]:{can_generate:!0,forward:qt},default:{can_generate:!1,forward:qt}},vs=new Map,sc=new Map,bs=new Map,y=class extends Je{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,r,s){super(),this.config=e,this.sessions=r,this.configs=s;let n=bs.get(this.constructor),o=vs.get(n),a=EA[o]??EA.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:f=null,session_options:m={}}={}){let h={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},g=bs.get(this),x=vs.get(g);s=h.config=await gs.from_pretrained(e,h);let k;if(x===H.DecoderOnly)k=await Promise.all([vt(e,{model:h.model_file_name??"model"},h,"model"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.Seq2Seq||x===H.Vision2Seq)k=await Promise.all([vt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h,"decoder_model_merged"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.MaskGeneration)k=await Promise.all([vt(e,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]);else if(x===H.EncoderDecoder)k=await Promise.all([vt(e,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h,"decoder_model_merged")]);else if(x===H.ImageTextToText){let E={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(E.model="encoder_model"),k=await Promise.all([vt(e,E,h,"decoder_model_merged"),xr(e,{generation_config:"generation_config.json"},h)])}else if(x===H.AudioTextToText){let E={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};k=await Promise.all([vt(e,E,h,"decoder_model_merged"),xr(e,{generation_config:"generation_config.json"},h)])}else if(x===H.ImageAudioTextToText){let E={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};k=await Promise.all([vt(e,E,h),xr(e,{generation_config:"generation_config.json"},h)])}else if(x===H.Musicgen)k=await Promise.all([vt(e,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h,"decoder_model_merged"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.MultiModality)k=await Promise.all([vt(e,{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"},h,"model"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.Phi3V)k=await Promise.all([vt(e,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},h,"model"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.Chatterbox)k=await Promise.all([vt(e,{embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"},h,"model"),xr(e,{generation_config:"generation_config.json"},h)]);else if(x===H.AutoEncoder)k=await Promise.all([vt(e,{encoder_model:"encoder_model",decoder_model:"decoder_model"},h)]);else if(x===H.Supertonic)k=await Promise.all([vt(e,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},h)]);else{if(x===void 0){let E=g??s?.model_type;E!=="custom"&&console.warn(`Model type for '${E}' not found, assuming encoder-only architecture. Please report this at ${Ys}.`)}k=await Promise.all([vt(e,{model:h.model_file_name??"model"},h)])}return new this(s,...k)}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 xs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new Vl(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new ql(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new Yl(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new Hl(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 Xl(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new jl(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new Gl(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 nn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new Kl(e.guidance_scale)),e.temperature===0&&e.do_sample&&(console.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 Ql(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=on){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,ot(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Jl;return e.max_length!==null&&s.push(new Zl(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new ec(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[fo.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,fo.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,fo.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,fo.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=bs.get(this.constructor),s=new Set,n=this.config.model_type;for(let a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new B("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s:s.attention_mask=Ee([s.attention_mask,it([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=ot(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,...ot(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await qt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=Ee([o,eo(o,0)],0),"attention_mask"in r&&(r.attention_mask=Ee([r.attention_mask,Pd(r.attention_mask)],0));else if(r.decoder_input_ids){let a=th(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=Ee(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 B)){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=th(i)}return s.decoder_attention_mask=fl(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 h=this._get_logits_processor(r,m,s),g=this._get_stopping_criteria(r,n),x=l[c].dims.at(0),k=ys.getSampler(r),E=new Array(x).fill(0),A=f.tolist();o&&o.put(A);let S,M={},L={};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 Y=this.getAttentions(S);for(let K in Y)K in M||(M[K]=[]),M[K].push(Y[K])}else this._return_dict_in_generate_keys&&Object.assign(L,ot(S,this._return_dict_in_generate_keys));let G=S.logits.slice(null,-1,null).to("float32"),X=h(A,G),V=[];for(let Y=0;Y<X.dims.at(0);++Y){let K=X[Y],U=await k(K);for(let[P,se]of U){let ie=BigInt(P);E[Y]+=se,A[Y].push(ie),V.push([ie]);break}}if(o&&o.put(V),g(A).every(Y=>Y))break;l=this._update_model_kwargs_for_generation({generated_input_ids:V,outputs:S,model_inputs:l,is_encoder_decoder:p})}o&&o.end();let C=this.getPastKeyValues(S,l.past_key_values,!0),v=new B("int64",A.flat(),[A.length,A[0].length]);if(r.return_dict_in_generate)return{sequences:v,past_key_values:C,...M,...L};for(let G of Object.values(S))G.location==="gpu-buffer"&&G.dispose();return v}getPastKeyValues(e,r,s=!1){let n=Object.create(null);for(let o in e)if(o.startsWith("present")){let a=o.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present","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 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"?Hs.float16:Hs.float32,i=Dl(this.config,{batch_size:n});for(let l in i){let c=i[l].reduce((p,f)=>p*f,1);e[l]=new B(o,new a(c),i[l])}}}async encode_image({pixel_values:e}){return(await ce(this.sessions.vision_encoder,{pixel_values:e})).image_features}async encode_text({input_ids:e}){return(await ce(this.sessions.embed_tokens,{input_ids:e})).inputs_embeds}async encode_audio({audio_values:e}){return(await ce(this.sessions.audio_encoder,{audio_values:e})).audio_features}};async function tc(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,...o}=e;if(!r){let a=ot(e,t.sessions.model.inputNames);r=(await qt(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 Ot(t,o,!0)}async function qt(t,e){let r=t.sessions.model,s=ot(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=Pd(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=it([n[0],n[2],n[3]])}return await ce(r,s)}async function fL(t,e){let r=await t.encode(e);return await t.decode(r)}async function Ot(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=rh(!!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=_L(o,n,i)}t.addPastKeyValues(o,n);let a=ot(o,s.inputNames);return await ce(s,a)}async function TA(t,{encode_function:e,merge_function:r,modality_input_name: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}){let h=m[s];if(!l){if(l=await t.encode_text({input_ids:o,...m}),h&&o.dims[1]!==1){let x=await e({[s]:h,...m});({inputs_embeds:l,attention_mask:a}=r({[n]:x,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&h&&o.dims[1]===1){let x=o.dims[1],k=Object.values(c)[0].dims.at(-2);a=Ee([it([o.dims[0],k]),a.slice(null,[a.dims[1]-x,a.dims[1]])],1)}}if(!i&&t.config.model_type==="qwen2_vl"){let{image_grid_thw:x,video_grid_thw:k}=m;[i]=t.get_rope_index(o,x,k,a)}return await Ot(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:p,logits_processor:f},!0)}async function mL(t,e){return await TA(t,{...e,modality_input_name:"audio_values",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 hL(t,e){return await TA(t,{...e,modality_input_name:"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 sh(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 _L(t,e=null,r=0){let{input_ids:s,inputs_embeds:n,attention_mask:o}=t,{data:a,dims:i}=sh(o,r),l=new B("int64",a,i);if(e){let c=-(s??n).dims.at(1);l=l.slice(null,[c,null])}return l}function mo(t,e,r,s){let n=r.past_key_values?Object.values(r.past_key_values)[0].dims.at(-2):0;if(!r.attention_mask){let o;for(let a of["input_ids","inputs_embeds","position_ids"])if(r[a]){o=r[a].dims;break}if(!o)throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs.");r.attention_mask=it([o[0],n+o[1]])}if(r.past_key_values){let{input_ids:o,attention_mask:a}=r;a&&a.dims[1]>o.dims[1]||n<o.dims[1]&&(r.input_ids=o.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:th(e)}}function rc(t,...e){return t.config.is_encoder_decoder?ho(t,...e):mo(t,...e)}function MA({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 cr({image_token_id:t,inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return MA({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}function nc({audio_token_id:t,inputs_embeds:e,audio_features:r,input_ids:s,attention_mask:n}){return MA({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n})}async function xr(t,e,r){return Object.fromEntries(await Promise.all(Object.keys(e).map(async s=>{let n=await at(t,e[s],!1,r);return[s,n]})))}var _i={};ts(_i,{ASTForAudioClassification:()=>fh,ASTModel:()=>dh,ASTPreTrainedModel:()=>go,AlbertForMaskedLM:()=>ih,AlbertForQuestionAnswering:()=>ah,AlbertForSequenceClassification:()=>oh,AlbertModel:()=>nh,AlbertPreTrainedModel:()=>ks,ApertusForCausalLM:()=>ch,ApertusModel:()=>lh,ApertusPreTrainedModel:()=>_o,ArceeForCausalLM:()=>ph,ArceeModel:()=>uh,ArceePreTrainedModel:()=>wo,BartForConditionalGeneration:()=>hh,BartForSequenceClassification:()=>_h,BartModel:()=>mh,BartPretrainedModel:()=>ln,BeitForImageClassification:()=>gh,BeitModel:()=>wh,BeitPreTrainedModel:()=>xo,BertForMaskedLM:()=>yh,BertForQuestionAnswering:()=>kh,BertForSequenceClassification:()=>bh,BertForTokenClassification:()=>vh,BertModel:()=>xh,BertPreTrainedModel:()=>Lr,BlenderbotForConditionalGeneration:()=>Ah,BlenderbotModel:()=>Eh,BlenderbotPreTrainedModel:()=>yo,BlenderbotSmallForConditionalGeneration:()=>Mh,BlenderbotSmallModel:()=>Th,BlenderbotSmallPreTrainedModel:()=>bo,BloomForCausalLM:()=>Oh,BloomModel:()=>Sh,BloomPreTrainedModel:()=>vo,CLIPModel:()=>$h,CLIPPreTrainedModel:()=>ur,CLIPSegForImageSegmentation:()=>jh,CLIPSegModel:()=>Fh,CLIPSegPreTrainedModel:()=>Mo,CLIPTextModel:()=>Bh,CLIPTextModelWithProjection:()=>To,CLIPVisionModel:()=>Uh,CLIPVisionModelWithProjection:()=>Dh,CamembertForMaskedLM:()=>Ch,CamembertForQuestionAnswering:()=>Nh,CamembertForSequenceClassification:()=>Ph,CamembertForTokenClassification:()=>Lh,CamembertModel:()=>Ih,CamembertPreTrainedModel:()=>Nr,ChatterboxModel:()=>ko,ChatterboxPreTrainedModel:()=>oc,ChineseCLIPModel:()=>zh,ChineseCLIPPreTrainedModel:()=>ac,ClapAudioModelWithProjection:()=>Ao,ClapModel:()=>Rh,ClapPreTrainedModel:()=>cn,ClapTextModelWithProjection:()=>Eo,CodeGenForCausalLM:()=>Wh,CodeGenModel:()=>Gh,CodeGenPreTrainedModel:()=>So,Cohere2ForCausalLM:()=>Xh,Cohere2Model:()=>Hh,Cohere2PreTrainedModel:()=>Io,CohereForCausalLM:()=>Vh,CohereModel:()=>qh,CoherePreTrainedModel:()=>Oo,ConvBertForMaskedLM:()=>Kh,ConvBertForQuestionAnswering:()=>Zh,ConvBertForSequenceClassification:()=>Qh,ConvBertForTokenClassification:()=>Jh,ConvBertModel:()=>Yh,ConvBertPreTrainedModel:()=>zr,ConvNextForImageClassification:()=>t_,ConvNextModel:()=>e_,ConvNextPreTrainedModel:()=>Co,ConvNextV2ForImageClassification:()=>s_,ConvNextV2Model:()=>r_,ConvNextV2PreTrainedModel:()=>Po,DFineForObjectDetection:()=>i_,DFineModel:()=>a_,DFinePreTrainedModel:()=>No,DINOv3ConvNextModel:()=>C_,DINOv3ConvNextPreTrainedModel:()=>fc,DINOv3ViTModel:()=>P_,DINOv3ViTPreTrainedModel:()=>mc,DPTForDepthEstimation:()=>D_,DPTModel:()=>U_,DPTPreTrainedModel:()=>Do,DacDecoderModel:()=>Ro,DacDecoderOutput:()=>lc,DacEncoderModel:()=>zo,DacEncoderOutput:()=>ic,DacModel:()=>l_,DacPreTrainedModel:()=>un,DebertaForMaskedLM:()=>u_,DebertaForQuestionAnswering:()=>f_,DebertaForSequenceClassification:()=>p_,DebertaForTokenClassification:()=>d_,DebertaModel:()=>c_,DebertaPreTrainedModel:()=>Rr,DebertaV2ForMaskedLM:()=>h_,DebertaV2ForQuestionAnswering:()=>g_,DebertaV2ForSequenceClassification:()=>__,DebertaV2ForTokenClassification:()=>w_,DebertaV2Model:()=>m_,DebertaV2PreTrainedModel:()=>$r,DecisionTransformerModel:()=>x_,DecisionTransformerPreTrainedModel:()=>cc,DeiTForImageClassification:()=>b_,DeiTModel:()=>y_,DeiTPreTrainedModel:()=>$o,DepthAnythingForDepthEstimation:()=>v_,DepthAnythingPreTrainedModel:()=>uc,DepthProForDepthEstimation:()=>k_,DepthProPreTrainedModel:()=>pc,DetrForObjectDetection:()=>A_,DetrForSegmentation:()=>T_,DetrModel:()=>E_,DetrObjectDetectionOutput:()=>dn,DetrPreTrainedModel:()=>pn,DetrSegmentationOutput:()=>dc,Dinov2ForImageClassification:()=>S_,Dinov2Model:()=>M_,Dinov2PreTrainedModel:()=>Bo,Dinov2WithRegistersForImageClassification:()=>I_,Dinov2WithRegistersModel:()=>O_,Dinov2WithRegistersPreTrainedModel:()=>Uo,DistilBertForMaskedLM:()=>$_,DistilBertForQuestionAnswering:()=>R_,DistilBertForSequenceClassification:()=>N_,DistilBertForTokenClassification:()=>z_,DistilBertModel:()=>L_,DistilBertPreTrainedModel:()=>Br,DonutSwinModel:()=>B_,DonutSwinPreTrainedModel:()=>hc,EdgeTamModel:()=>ky,EfficientNetForImageClassification:()=>j_,EfficientNetModel:()=>F_,EfficientNetPreTrainedModel:()=>Fo,ElectraForMaskedLM:()=>W_,ElectraForQuestionAnswering:()=>H_,ElectraForSequenceClassification:()=>q_,ElectraForTokenClassification:()=>V_,ElectraModel:()=>G_,ElectraPreTrainedModel:()=>Ur,Ernie4_5ForCausalLM:()=>Y_,Ernie4_5Model:()=>X_,Ernie4_5PretrainedModel:()=>jo,EsmForMaskedLM:()=>Q_,EsmForSequenceClassification:()=>J_,EsmForTokenClassification:()=>Z_,EsmModel:()=>K_,EsmPreTrainedModel:()=>Es,ExaoneForCausalLM:()=>tw,ExaoneModel:()=>ew,ExaonePreTrainedModel:()=>Go,FalconForCausalLM:()=>sw,FalconH1ForCausalLM:()=>ow,FalconH1Model:()=>nw,FalconH1PreTrainedModel:()=>qo,FalconModel:()=>rw,FalconPreTrainedModel:()=>Wo,FastViTForImageClassification:()=>iw,FastViTModel:()=>aw,FastViTPreTrainedModel:()=>Vo,Florence2ForConditionalGeneration:()=>lw,Florence2PreTrainedModel:()=>_c,GLPNForDepthEstimation:()=>gw,GLPNModel:()=>ww,GLPNPreTrainedModel:()=>Jo,GPT2LMHeadModel:()=>Sw,GPT2Model:()=>Mw,GPT2PreTrainedModel:()=>sa,GPTBigCodeForCausalLM:()=>yw,GPTBigCodeModel:()=>xw,GPTBigCodePreTrainedModel:()=>Zo,GPTJForCausalLM:()=>Iw,GPTJModel:()=>Ow,GPTJPreTrainedModel:()=>na,GPTNeoForCausalLM:()=>vw,GPTNeoModel:()=>bw,GPTNeoPreTrainedModel:()=>ea,GPTNeoXForCausalLM:()=>Ew,GPTNeoXModel:()=>kw,GPTNeoXPreTrainedModel:()=>ta,Gemma2ForCausalLM:()=>dw,Gemma2Model:()=>pw,Gemma2PreTrainedModel:()=>Xo,Gemma3ForCausalLM:()=>mw,Gemma3Model:()=>fw,Gemma3PreTrainedModel:()=>Yo,Gemma3nForConditionalGeneration:()=>Ko,Gemma3nPreTrainedModel:()=>wc,GemmaForCausalLM:()=>uw,GemmaModel:()=>cw,GemmaPreTrainedModel:()=>Ho,GlmForCausalLM:()=>_w,GlmModel:()=>hw,GlmPreTrainedModel:()=>Qo,GptOssForCausalLM:()=>Tw,GptOssModel:()=>Aw,GptOssPreTrainedModel:()=>ra,GraniteForCausalLM:()=>Pw,GraniteModel:()=>Cw,GraniteMoeHybridForCausalLM:()=>Nw,GraniteMoeHybridModel:()=>Lw,GraniteMoeHybridPreTrainedModel:()=>aa,GranitePreTrainedModel:()=>oa,GroundingDinoForObjectDetection:()=>zw,GroundingDinoPreTrainedModel:()=>gc,GroupViTModel:()=>Rw,GroupViTPreTrainedModel:()=>xc,HeliumForCausalLM:()=>Bw,HeliumModel:()=>$w,HeliumPreTrainedModel:()=>ia,HieraForImageClassification:()=>Dw,HieraModel:()=>Uw,HieraPreTrainedModel:()=>la,HubertForCTC:()=>Hw,HubertForSequenceClassification:()=>Xw,HubertModel:()=>Vw,HubertPreTrainedModel:()=>qw,HunYuanDenseV1ForCausalLM:()=>Kw,HunYuanDenseV1Model:()=>Yw,HunYuanDenseV1PreTrainedModel:()=>ca,IJepaForImageClassification:()=>Zw,IJepaModel:()=>Jw,IJepaPreTrainedModel:()=>ua,Idefics3ForConditionalGeneration:()=>bc,Idefics3PreTrainedModel:()=>yc,JAISLMHeadModel:()=>tg,JAISModel:()=>eg,JAISPreTrainedModel:()=>pa,JinaCLIPModel:()=>rg,JinaCLIPPreTrainedModel:()=>fn,JinaCLIPTextModel:()=>da,JinaCLIPVisionModel:()=>sg,Lfm2ForCausalLM:()=>og,Lfm2Model:()=>ng,Lfm2MoeForCausalLM:()=>ig,Lfm2MoeModel:()=>ag,Lfm2MoePreTrainedModel:()=>ma,Lfm2PreTrainedModel:()=>fa,LiteWhisperForConditionalGeneration:()=>N0,Llama4ForCausalLM:()=>ug,Llama4PreTrainedModel:()=>vc,LlamaForCausalLM:()=>cg,LlamaModel:()=>lg,LlamaPreTrainedModel:()=>ha,LlavaForConditionalGeneration:()=>mn,LlavaOnevisionForConditionalGeneration:()=>mn,LlavaPreTrainedModel:()=>kc,LlavaQwen2ForCausalLM:()=>dg,LongT5ForConditionalGeneration:()=>mg,LongT5Model:()=>fg,LongT5PreTrainedModel:()=>_a,M2M100ForConditionalGeneration:()=>_g,M2M100Model:()=>hg,M2M100PreTrainedModel:()=>wa,MBartForCausalLM:()=>Eg,MBartForConditionalGeneration:()=>vg,MBartForSequenceClassification:()=>kg,MBartModel:()=>bg,MBartPreTrainedModel:()=>As,MPNetForMaskedLM:()=>lx,MPNetForQuestionAnswering:()=>px,MPNetForSequenceClassification:()=>cx,MPNetForTokenClassification:()=>ux,MPNetModel:()=>ix,MPNetPreTrainedModel:()=>Dr,MT5ForConditionalGeneration:()=>hx,MT5Model:()=>mx,MT5PreTrainedModel:()=>Oa,MarianMTModel:()=>gg,MarianModel:()=>wg,MarianPreTrainedModel:()=>ga,MaskFormerForInstanceSegmentation:()=>yg,MaskFormerModel:()=>xg,MaskFormerPreTrainedModel:()=>xa,Metric3DForDepthEstimation:()=>Ag,Metric3DPreTrainedModel:()=>Ec,Metric3Dv2ForDepthEstimation:()=>Tg,Metric3Dv2PreTrainedModel:()=>Ac,MgpstrForSceneTextRecognition:()=>Mg,MgpstrModelOutput:()=>Tc,MgpstrPreTrainedModel:()=>Mc,MimiDecoderModel:()=>ba,MimiDecoderOutput:()=>Oc,MimiEncoderModel:()=>ya,MimiEncoderOutput:()=>Sc,MimiModel:()=>Sg,MimiPreTrainedModel:()=>hn,MistralForCausalLM:()=>Ig,MistralModel:()=>Og,MistralPreTrainedModel:()=>va,MobileBertForMaskedLM:()=>Pg,MobileBertForQuestionAnswering:()=>Ng,MobileBertForSequenceClassification:()=>Lg,MobileBertModel:()=>Cg,MobileBertPreTrainedModel:()=>Ts,MobileLLMForCausalLM:()=>Rg,MobileLLMModel:()=>zg,MobileLLMPreTrainedModel:()=>ka,MobileNetV1ForImageClassification:()=>Bg,MobileNetV1ForSemanticSegmentation:()=>Ug,MobileNetV1Model:()=>$g,MobileNetV1PreTrainedModel:()=>_n,MobileNetV2ForImageClassification:()=>Fg,MobileNetV2ForSemanticSegmentation:()=>jg,MobileNetV2Model:()=>Dg,MobileNetV2PreTrainedModel:()=>wn,MobileNetV3ForImageClassification:()=>Wg,MobileNetV3ForSemanticSegmentation:()=>qg,MobileNetV3Model:()=>Gg,MobileNetV3PreTrainedModel:()=>gn,MobileNetV4ForImageClassification:()=>Hg,MobileNetV4ForSemanticSegmentation:()=>Xg,MobileNetV4Model:()=>Vg,MobileNetV4PreTrainedModel:()=>xn,MobileViTForImageClassification:()=>Kg,MobileViTModel:()=>Yg,MobileViTPreTrainedModel:()=>Ea,MobileViTV2ForImageClassification:()=>Jg,MobileViTV2Model:()=>Qg,MobileViTV2PreTrainedModel:()=>Aa,ModernBertDecoderForCausalLM:()=>nx,ModernBertDecoderModel:()=>sx,ModernBertDecoderPreTrainedModel:()=>Ta,ModernBertForMaskedLM:()=>ex,ModernBertForSequenceClassification:()=>tx,ModernBertForTokenClassification:()=>rx,ModernBertModel:()=>Zg,ModernBertPreTrainedModel:()=>Ms,Moondream1ForConditionalGeneration:()=>pg,MoonshineForConditionalGeneration:()=>ax,MoonshineModel:()=>ox,MoonshinePreTrainedModel:()=>Ma,MptForCausalLM:()=>fx,MptModel:()=>dx,MptPreTrainedModel:()=>Sa,MultiModalityCausalLM:()=>_x,MultiModalityPreTrainedModel:()=>Ic,MusicgenForCausalLM:()=>gx,MusicgenForConditionalGeneration:()=>Ca,MusicgenModel:()=>wx,MusicgenPreTrainedModel:()=>Ia,NanoChatForCausalLM:()=>yx,NanoChatModel:()=>xx,NanoChatPreTrainedModel:()=>Pa,NeoBertForMaskedLM:()=>vx,NeoBertForQuestionAnswering:()=>Ax,NeoBertForSequenceClassification:()=>kx,NeoBertForTokenClassification:()=>Ex,NeoBertModel:()=>bx,NeoBertPreTrainedModel:()=>Fr,NomicBertModel:()=>Tx,NomicBertPreTrainedModel:()=>Cc,OPTForCausalLM:()=>Rx,OPTModel:()=>zx,OPTPreTrainedModel:()=>$a,Olmo2ForCausalLM:()=>Ix,Olmo2Model:()=>Ox,Olmo2PreTrainedModel:()=>Na,Olmo3ForCausalLM:()=>Px,Olmo3Model:()=>Cx,Olmo3PreTrainedModel:()=>za,OlmoForCausalLM:()=>Sx,OlmoModel:()=>Mx,OlmoPreTrainedModel:()=>La,OpenELMForCausalLM:()=>Nx,OpenELMModel:()=>Lx,OpenELMPreTrainedModel:()=>Ra,OwlViTForObjectDetection:()=>Dx,OwlViTModel:()=>Ux,OwlViTPreTrainedModel:()=>Ua,Owlv2ForObjectDetection:()=>Bx,Owlv2Model:()=>$x,Owlv2PreTrainedModel:()=>Ba,PaliGemmaForConditionalGeneration:()=>Fx,PaliGemmaPreTrainedModel:()=>Pc,ParakeetForCTC:()=>jx,ParakeetPreTrainedModel:()=>Lc,PatchTSMixerForPrediction:()=>Wx,PatchTSMixerModel:()=>Gx,PatchTSMixerPreTrainedModel:()=>Da,PatchTSTForPrediction:()=>Vx,PatchTSTModel:()=>qx,PatchTSTPreTrainedModel:()=>Fa,Phi3ForCausalLM:()=>Kx,Phi3Model:()=>Yx,Phi3PreTrainedModel:()=>Ga,Phi3VForCausalLM:()=>Wa,Phi3VPreTrainedModel:()=>Nc,PhiForCausalLM:()=>Xx,PhiModel:()=>Hx,PhiPreTrainedModel:()=>ja,PreTrainedModel:()=>y,PvtForImageClassification:()=>Jx,PvtModel:()=>Qx,PvtPreTrainedModel:()=>qa,PyAnnoteForAudioFrameClassification:()=>ey,PyAnnoteModel:()=>Zx,PyAnnotePreTrainedModel:()=>Va,Qwen2ForCausalLM:()=>ry,Qwen2Model:()=>ty,Qwen2PreTrainedModel:()=>Ha,Qwen2VLForConditionalGeneration:()=>sy,Qwen2VLPreTrainedModel:()=>zc,Qwen3ForCausalLM:()=>oy,Qwen3Model:()=>ny,Qwen3PreTrainedModel:()=>Xa,RFDetrForObjectDetection:()=>cy,RFDetrModel:()=>ly,RFDetrObjectDetectionOutput:()=>Rc,RFDetrPreTrainedModel:()=>Ka,RTDetrForObjectDetection:()=>o_,RTDetrModel:()=>n_,RTDetrObjectDetectionOutput:()=>pr,RTDetrPreTrainedModel:()=>Lo,RTDetrV2ForObjectDetection:()=>by,RTDetrV2Model:()=>yy,RTDetrV2ObjectDetectionOutput:()=>$c,RTDetrV2PreTrainedModel:()=>Qa,ResNetForImageClassification:()=>iy,ResNetModel:()=>ay,ResNetPreTrainedModel:()=>Ya,RoFormerForMaskedLM:()=>_y,RoFormerForQuestionAnswering:()=>xy,RoFormerForSequenceClassification:()=>wy,RoFormerForTokenClassification:()=>gy,RoFormerModel:()=>hy,RoFormerPreTrainedModel:()=>Gr,RobertaForMaskedLM:()=>py,RobertaForQuestionAnswering:()=>my,RobertaForSequenceClassification:()=>dy,RobertaForTokenClassification:()=>fy,RobertaModel:()=>uy,RobertaPreTrainedModel:()=>jr,Sam2ImageSegmentationOutput:()=>Dc,Sam2Model:()=>Ja,Sam2PreTrainedModel:()=>Fc,Sam3TrackerModel:()=>Ey,SamImageSegmentationOutput:()=>Bc,SamModel:()=>vy,SamPreTrainedModel:()=>Uc,SapiensForDepthEstimation:()=>Ty,SapiensForNormalEstimation:()=>My,SapiensForSemanticSegmentation:()=>Ay,SapiensPreTrainedModel:()=>yn,SegformerForImageClassification:()=>Oy,SegformerForSemanticSegmentation:()=>Iy,SegformerModel:()=>Sy,SegformerPreTrainedModel:()=>bn,SiglipModel:()=>Cy,SiglipPreTrainedModel:()=>Za,SiglipTextModel:()=>ei,SiglipVisionModel:()=>Py,SmolLM3ForCausalLM:()=>Ny,SmolLM3Model:()=>Ly,SmolLM3PreTrainedModel:()=>ti,SmolVLMForConditionalGeneration:()=>Qw,SnacDecoderModel:()=>si,SnacEncoderModel:()=>ri,SnacModel:()=>zy,SnacPreTrainedModel:()=>vn,SpeechT5ForSpeechToText:()=>$y,SpeechT5ForTextToSpeech:()=>By,SpeechT5HifiGan:()=>Uy,SpeechT5Model:()=>Ry,SpeechT5PreTrainedModel:()=>kn,SqueezeBertForMaskedLM:()=>Fy,SqueezeBertForQuestionAnswering:()=>Gy,SqueezeBertForSequenceClassification:()=>jy,SqueezeBertModel:()=>Dy,SqueezeBertPreTrainedModel:()=>Ss,StableLmForCausalLM:()=>qy,StableLmModel:()=>Wy,StableLmPreTrainedModel:()=>ni,Starcoder2ForCausalLM:()=>Hy,Starcoder2Model:()=>Vy,Starcoder2PreTrainedModel:()=>oi,StyleTextToSpeech2Model:()=>Xy,StyleTextToSpeech2PreTrainedModel:()=>jc,SupertonicForConditionalGeneration:()=>ai,SupertonicPreTrainedModel:()=>Gc,Swin2SRForImageSuperResolution:()=>Zy,Swin2SRModel:()=>Jy,Swin2SRPreTrainedModel:()=>ii,SwinForImageClassification:()=>Ky,SwinForSemanticSegmentation:()=>Qy,SwinModel:()=>Yy,SwinPreTrainedModel:()=>En,T5ForConditionalGeneration:()=>t0,T5Model:()=>e0,T5PreTrainedModel:()=>li,TableTransformerForObjectDetection:()=>s0,TableTransformerModel:()=>r0,TableTransformerObjectDetectionOutput:()=>Wc,TableTransformerPreTrainedModel:()=>ci,TrOCRForCausalLM:()=>n0,TrOCRPreTrainedModel:()=>qc,UltravoxModel:()=>Hc,UltravoxPreTrainedModel:()=>Vc,UniSpeechForCTC:()=>i0,UniSpeechForSequenceClassification:()=>l0,UniSpeechModel:()=>a0,UniSpeechPreTrainedModel:()=>An,UniSpeechSatForAudioFrameClassification:()=>d0,UniSpeechSatForCTC:()=>u0,UniSpeechSatForSequenceClassification:()=>p0,UniSpeechSatModel:()=>c0,UniSpeechSatPreTrainedModel:()=>Os,VaultGemmaForCausalLM:()=>m0,VaultGemmaModel:()=>f0,VaultGemmaPreTrainedModel:()=>ui,ViTForImageClassification:()=>w0,ViTMAEModel:()=>g0,ViTMAEPreTrainedModel:()=>Xc,ViTMSNForImageClassification:()=>y0,ViTMSNModel:()=>x0,ViTMSNPreTrainedModel:()=>di,ViTModel:()=>_0,ViTPreTrainedModel:()=>pi,VisionEncoderDecoderModel:()=>h0,VitMatteForImageMatting:()=>b0,VitMattePreTrainedModel:()=>Yc,VitPoseForPoseEstimation:()=>v0,VitPosePreTrainedModel:()=>Kc,VitsModel:()=>k0,VitsModelOutput:()=>Qc,VitsPreTrainedModel:()=>Jc,VoxtralForConditionalGeneration:()=>o0,Wav2Vec2BertForCTC:()=>A0,Wav2Vec2BertForSequenceClassification:()=>T0,Wav2Vec2BertModel:()=>E0,Wav2Vec2BertPreTrainedModel:()=>Tn,Wav2Vec2ForAudioFrameClassification:()=>Ww,Wav2Vec2ForCTC:()=>jw,Wav2Vec2ForSequenceClassification:()=>Gw,Wav2Vec2Model:()=>Fw,Wav2Vec2PreTrainedModel:()=>tr,WavLMForAudioFrameClassification:()=>C0,WavLMForCTC:()=>S0,WavLMForSequenceClassification:()=>O0,WavLMForXVector:()=>I0,WavLMModel:()=>M0,WavLMPreTrainedModel:()=>Wr,WeSpeakerResNetModel:()=>P0,WeSpeakerResNetPreTrainedModel:()=>eu,WhisperForConditionalGeneration:()=>ru,WhisperModel:()=>L0,WhisperPreTrainedModel:()=>fi,XLMForQuestionAnswering:()=>U0,XLMForSequenceClassification:()=>$0,XLMForTokenClassification:()=>B0,XLMModel:()=>z0,XLMPreTrainedModel:()=>qr,XLMRobertaForMaskedLM:()=>F0,XLMRobertaForQuestionAnswering:()=>W0,XLMRobertaForSequenceClassification:()=>j0,XLMRobertaForTokenClassification:()=>G0,XLMRobertaModel:()=>D0,XLMRobertaPreTrainedModel:()=>Vr,XLMWithLMHeadModel:()=>R0,XVectorOutput:()=>Zc,YolosForObjectDetection:()=>V0,YolosModel:()=>q0,YolosObjectDetectionOutput:()=>su,YolosPreTrainedModel:()=>mi,YoutuForCausalLM:()=>X0,YoutuModel:()=>H0,YoutuPreTrainedModel:()=>hi});var ks=class extends y{},nh=class extends ks{},oh=class extends ks{async _call(e){return new F(await super._call(e))}},ah=class extends ks{async _call(e){return new Ae(await super._call(e))}},ih=class extends ks{async _call(e){return new ge(await super._call(e))}};var _o=class extends y{},lh=class extends _o{},ch=class extends _o{};var wo=class extends y{},uh=class extends wo{},ph=class extends wo{};var go=class extends y{},dh=class extends go{},fh=class extends go{};var ln=class extends y{},mh=class extends ln{},hh=class extends ln{},_h=class extends ln{async _call(e){return new F(await super._call(e))}};var xo=class extends y{},wh=class extends xo{},gh=class extends xo{async _call(e){return new F(await super._call(e))}};var Lr=class extends y{},xh=class extends Lr{},yh=class extends Lr{async _call(e){return new ge(await super._call(e))}},bh=class extends Lr{async _call(e){return new F(await super._call(e))}},vh=class extends Lr{async _call(e){return new _e(await super._call(e))}},kh=class extends Lr{async _call(e){return new Ae(await super._call(e))}};var yo=class extends y{},Eh=class extends yo{},Ah=class extends yo{};var bo=class extends y{},Th=class extends bo{},Mh=class extends bo{};var vo=class extends y{},Sh=class extends vo{},Oh=class extends vo{};var Nr=class extends y{},Ih=class extends Nr{},Ch=class extends Nr{async _call(e){return new ge(await super._call(e))}},Ph=class extends Nr{async _call(e){return new F(await super._call(e))}},Lh=class extends Nr{async _call(e){return new _e(await super._call(e))}},Nh=class extends Nr{async _call(e){return new Ae(await super._call(e))}};var wL=4299n,SA=6561n,oc=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"]},ko=class extends oc{async encode_speech(e){return ce(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:h=null,...g}){let x;if(!a){let E=this.sessions.embed_tokens.inputNames,A={input_ids:e};if(E.includes("exaggeration")){if(!(n instanceof B)){let S=e.dims[0];if(n==null)n=Ve([S],.5);else if(typeof n=="number")n=Ve([S],n);else if(Array.isArray(n))n=new B("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 ce(this.sessions.embed_tokens,A),p&&f&&m&&h&&(x={audio_features:p,audio_tokens:f,speaker_embeddings:m,speaker_features:h}),x||s)x??=await this.encode_speech(s),a=Ee([x.audio_features,a],1),r=it([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=Object.values(i)[0].dims.at(-2);r=it([a.dims[0],M+S])}}return{...await Ot(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==SA)-1);r.position_ids=new B("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=SA?0:i++)});r.position_ids=new B("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),mo(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=Ve([a.dims[0],3],wL),l=Ee([s,a,i],1),{waveform:c}=await ce(this.sessions.conditional_decoder,{speech_tokens:l,speaker_features:o,speaker_embeddings:n});return c}};var ac=class extends y{},zh=class extends ac{};var cn=class extends y{},Rh=class extends cn{},Eo=class extends cn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Ao=class extends cn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var ur=class extends y{},$h=class extends ur{},Bh=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},To=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Uh=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},Dh=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Mo=class extends y{},Fh=class extends Mo{},jh=class extends Mo{};var So=class extends y{},Gh=class extends So{},Wh=class extends So{};var Oo=class extends y{},qh=class extends Oo{},Vh=class extends Oo{};var Io=class extends y{},Hh=class extends Io{},Xh=class extends Io{};var zr=class extends y{},Yh=class extends zr{},Kh=class extends zr{async _call(e){return new ge(await super._call(e))}},Qh=class extends zr{async _call(e){return new F(await super._call(e))}},Jh=class extends zr{async _call(e){return new _e(await super._call(e))}},Zh=class extends zr{async _call(e){return new Ae(await super._call(e))}};var Co=class extends y{},e_=class extends Co{},t_=class extends Co{async _call(e){return new F(await super._call(e))}};var Po=class extends y{},r_=class extends Po{},s_=class extends Po{async _call(e){return new F(await super._call(e))}};var Lo=class extends y{},n_=class extends Lo{},o_=class extends Lo{async _call(e){return new pr(await super._call(e))}},pr=class extends Le{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var No=class extends y{},a_=class extends No{},i_=class extends No{async _call(e){return new pr(await super._call(e))}};var ic=class extends Le{constructor({audio_codes:e}){super(),this.audio_codes=e}},lc=class extends Le{constructor({audio_values:e}){super(),this.audio_values=e}},un=class extends y{main_input_name="input_values";forward_params=["input_values"]},l_=class extends un{async encode(e){return new ic(await ce(this.sessions.encoder_model,e))}async decode(e){return new lc(await ce(this.sessions.decoder_model,e))}},zo=class extends un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Ro=class extends un{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Rr=class extends y{},c_=class extends Rr{},u_=class extends Rr{async _call(e){return new ge(await super._call(e))}},p_=class extends Rr{async _call(e){return new F(await super._call(e))}},d_=class extends Rr{async _call(e){return new _e(await super._call(e))}},f_=class extends Rr{async _call(e){return new Ae(await super._call(e))}};var $r=class extends y{},m_=class extends $r{},h_=class extends $r{async _call(e){return new ge(await super._call(e))}},__=class extends $r{async _call(e){return new F(await super._call(e))}},w_=class extends $r{async _call(e){return new _e(await super._call(e))}},g_=class extends $r{async _call(e){return new Ae(await super._call(e))}};var cc=class extends y{},x_=class extends cc{};var $o=class extends y{},y_=class extends $o{},b_=class extends $o{async _call(e){return new F(await super._call(e))}};var uc=class extends y{},v_=class extends uc{};var pc=class extends y{},k_=class extends pc{};var pn=class extends y{},E_=class extends pn{},A_=class extends pn{async _call(e){return new dn(await super._call(e))}},T_=class extends pn{async _call(e){return new dc(await super._call(e))}},dn=class extends Le{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},dc=class extends Le{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var Bo=class extends y{},M_=class extends Bo{},S_=class extends Bo{async _call(e){return new F(await super._call(e))}};var Uo=class extends y{},O_=class extends Uo{},I_=class extends Uo{async _call(e){return new F(await super._call(e))}};var fc=class extends y{},C_=class extends fc{};var mc=class extends y{},P_=class extends mc{};var Br=class extends y{},L_=class extends Br{},N_=class extends Br{async _call(e){return new F(await super._call(e))}},z_=class extends Br{async _call(e){return new _e(await super._call(e))}},R_=class extends Br{async _call(e){return new Ae(await super._call(e))}},$_=class extends Br{async _call(e){return new ge(await super._call(e))}};var hc=class extends y{},B_=class extends hc{};var Do=class extends y{},U_=class extends Do{},D_=class extends Do{};var Fo=class extends y{},F_=class extends Fo{},j_=class extends Fo{async _call(e){return new F(await super._call(e))}};var Ur=class extends y{},G_=class extends Ur{},W_=class extends Ur{async _call(e){return new ge(await super._call(e))}},q_=class extends Ur{async _call(e){return new F(await super._call(e))}},V_=class extends Ur{async _call(e){return new _e(await super._call(e))}},H_=class extends Ur{async _call(e){return new Ae(await super._call(e))}};var jo=class extends y{},X_=class extends jo{},Y_=class extends jo{};var Es=class extends y{},K_=class extends Es{},Q_=class extends Es{async _call(e){return new ge(await super._call(e))}},J_=class extends Es{async _call(e){return new F(await super._call(e))}},Z_=class extends Es{async _call(e){return new _e(await super._call(e))}};var Go=class extends y{},ew=class extends Go{},tw=class extends Go{};var Wo=class extends y{},rw=class extends Wo{},sw=class extends Wo{};var qo=class extends y{},nw=class extends qo{},ow=class extends qo{};var Vo=class extends y{},aw=class extends Vo{},iw=class extends Vo{async _call(e){return new F(await super._call(e))}};var _c=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"},lw=class extends _c{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:Ee([r,e],1),attention_mask:Ee([it(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 qt(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 Ot(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i},!0)}};var Ho=class extends y{},cw=class extends Ho{},uw=class extends Ho{};var Xo=class extends y{},pw=class extends Xo{},dw=class extends Xo{};var Yo=class extends y{},fw=class extends Yo{},mw=class extends Yo{};var wc=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"]},Ko=class extends wc{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 ce(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:g}=await ce(this.sessions.vision_encoder,{pixel_values:s});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:g,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:g}=await ce(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:g,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Ot(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 cr({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 nc({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}};var Qo=class extends y{},hw=class extends Qo{},_w=class extends Qo{};var Jo=class extends y{},ww=class extends Jo{},gw=class extends Jo{};var Zo=class extends y{},xw=class extends Zo{},yw=class extends Zo{};var ea=class extends y{},bw=class extends ea{},vw=class extends ea{};var ta=class extends y{},kw=class extends ta{},Ew=class extends ta{};var ra=class extends y{},Aw=class extends ra{},Tw=class extends ra{};var sa=class extends y{},Mw=class extends sa{},Sw=class extends sa{};var na=class extends y{},Ow=class extends na{},Iw=class extends na{};var oa=class extends y{},Cw=class extends oa{},Pw=class extends oa{};var aa=class extends y{},Lw=class extends aa{},Nw=class extends aa{};var gc=class extends y{},zw=class extends gc{};var xc=class extends y{},Rw=class extends xc{};var ia=class extends y{},$w=class extends ia{},Bw=class extends ia{};var la=class extends y{},Uw=class extends la{},Dw=class extends la{async _call(e){return new F(await super._call(e))}};var tr=class extends y{},Fw=class extends tr{},jw=class extends tr{async _call(e){return new gt(await super._call(e))}},Gw=class extends tr{async _call(e){return new F(await super._call(e))}},Ww=class extends tr{async _call(e){return new _e(await super._call(e))}};var qw=class extends y{},Vw=class extends tr{},Hw=class extends tr{async _call(e){return new gt(await super._call(e))}},Xw=class extends tr{async _call(e){return new F(await super._call(e))}};var ca=class extends y{},Yw=class extends ca{},Kw=class extends ca{};var yc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},bc=class extends yc{async encode_image({pixel_values:e,pixel_attention_mask:r}){return(await ce(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:r})).image_features}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return cr({image_token_id:this.config.image_token_id,...e,image_features:s})}},Qw=class extends bc{};var ua=class extends y{},Jw=class extends ua{},Zw=class extends ua{async _call(e){return new F(await super._call(e))}};var pa=class extends y{},eg=class extends pa{},tg=class extends pa{};var fn=class extends y{},rg=class extends fn{async forward(e){let r=!e.input_ids,s=!e.pixel_values;if(r&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(r&&(e.input_ids=it([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=Ve([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}},da=class extends fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},sg=class extends fn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var fa=class extends y{},ng=class extends fa{},og=class extends fa{};var ma=class extends y{},ag=class extends ma{},ig=class extends ma{};var ha=class extends y{},lg=class extends ha{},cg=class extends ha{};var vc=class extends y{},ug=class extends vc{};var kc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},mn=class extends kc{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return cr({image_token_id:this.config.image_token_index,...e,image_features:s})}},pg=class extends mn{},dg=class extends mn{};var _a=class extends y{},fg=class extends _a{},mg=class extends _a{};var wa=class extends y{},hg=class extends wa{},_g=class extends wa{};var ga=class extends y{},wg=class extends ga{},gg=class extends ga{};var xa=class extends y{},xg=class extends xa{},yg=class extends xa{};var As=class extends y{},bg=class extends As{},vg=class extends As{},kg=class extends As{async _call(e){return new F(await super._call(e))}},Eg=class extends As{};var Ec=class extends y{},Ag=class extends Ec{};var Ac=class extends y{},Tg=class extends Ac{};var Tc=class extends Le{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]}},Mc=class extends y{},Mg=class extends Mc{async _call(e){return new Tc(await super._call(e))}};var Sc=class extends Le{constructor({audio_codes:e}){super(),this.audio_codes=e}},Oc=class extends Le{constructor({audio_values:e}){super(),this.audio_values=e}},hn=class extends y{main_input_name="input_values";forward_params=["input_values"]},Sg=class extends hn{async encode(e){return new Sc(await ce(this.sessions.encoder_model,e))}async decode(e){return new Oc(await ce(this.sessions.decoder_model,e))}},ya=class extends hn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},ba=class extends hn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var va=class extends y{},Og=class extends va{},Ig=class extends va{};var Ts=class extends y{},Cg=class extends Ts{},Pg=class extends Ts{async _call(e){return new ge(await super._call(e))}},Lg=class extends Ts{async _call(e){return new F(await super._call(e))}},Ng=class extends Ts{async _call(e){return new Ae(await super._call(e))}};var ka=class extends y{},zg=class extends ka{},Rg=class extends ka{};var _n=class extends y{},$g=class extends _n{},Bg=class extends _n{async _call(e){return new F(await super._call(e))}},Ug=class extends _n{};var wn=class extends y{},Dg=class extends wn{},Fg=class extends wn{async _call(e){return new F(await super._call(e))}},jg=class extends wn{};var gn=class extends y{},Gg=class extends gn{},Wg=class extends gn{async _call(e){return new F(await super._call(e))}},qg=class extends gn{};var xn=class extends y{},Vg=class extends xn{},Hg=class extends xn{async _call(e){return new F(await super._call(e))}},Xg=class extends xn{};var Ea=class extends y{},Yg=class extends Ea{},Kg=class extends Ea{async _call(e){return new F(await super._call(e))}};var Aa=class extends y{},Qg=class extends Aa{},Jg=class extends Aa{async _call(e){return new F(await super._call(e))}};var Ms=class extends y{},Zg=class extends Ms{},ex=class extends Ms{async _call(e){return new ge(await super._call(e))}},tx=class extends Ms{async _call(e){return new F(await super._call(e))}},rx=class extends Ms{async _call(e){return new _e(await super._call(e))}};var Ta=class extends y{},sx=class extends Ta{},nx=class extends Ta{};var Ma=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},ox=class extends Ma{},ax=class extends Ma{};var Dr=class extends y{},ix=class extends Dr{},lx=class extends Dr{async _call(e){return new ge(await super._call(e))}},cx=class extends Dr{async _call(e){return new F(await super._call(e))}},ux=class extends Dr{async _call(e){return new _e(await super._call(e))}},px=class extends Dr{async _call(e){return new Ae(await super._call(e))}};var Sa=class extends y{},dx=class extends Sa{},fx=class extends Sa{};var Oa=class extends y{},mx=class extends Oa{},hx=class extends Oa{};var Ic=class extends y{},_x=class extends Ic{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=ot(e,l.inputNames);s=await ce(l,c)}else{let l=this.sessions.gen_img_embeds,c=ot({image_ids:e.input_ids},l.inputNames);s=await ce(l,c)}let n={...e,...s},o=await Ot(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 ce(a,ot(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=Ee([r.input_ids,r.input_ids],0):(r.input_ids=Ee([r.input_ids,eo(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Ee([r.attention_mask,eo(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Ve([0,0,3,384,384],1)),n&&(r.images_seq_mask=new B("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new B("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 ce(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let p=Xe.fromTensor(c);l.push(p)}return l}};var Ia=class extends y{},wx=class extends Ia{},gx=class extends Ia{},Ca=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 B(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 ce(this.sessions.encodec_decode,{audio_codes:s});return n}};var Pa=class extends y{},xx=class extends Pa{},yx=class extends Pa{};var Fr=class extends y{},bx=class extends Fr{},vx=class extends Fr{async _call(e){return new ge(await super._call(e))}},kx=class extends Fr{async _call(e){return new F(await super._call(e))}},Ex=class extends Fr{async _call(e){return new _e(await super._call(e))}},Ax=class extends Fr{async _call(e){return new Ae(await super._call(e))}};var Cc=class extends y{},Tx=class extends Cc{};var La=class extends y{},Mx=class extends La{},Sx=class extends La{};var Na=class extends y{},Ox=class extends Na{},Ix=class extends Na{};var za=class extends y{},Cx=class extends za{},Px=class extends za{};var Ra=class extends y{},Lx=class extends Ra{},Nx=class extends Ra{};var $a=class extends y{},zx=class extends $a{},Rx=class extends $a{};var Ba=class extends y{},$x=class extends Ba{},Bx=class extends Ba{};var Ua=class extends y{},Ux=class extends Ua{},Dx=class extends Ua{};var Pc=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Fx=class extends Pc{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return cr({image_token_id:this.config.image_token_index,...e,image_features:s})}};var Lc=class extends y{},jx=class extends Lc{async _call(e){return new gt(await super._call(e))}};var Da=class extends y{},Gx=class extends Da{},Wx=class extends Da{};var Fa=class extends y{},qx=class extends Fa{},Vx=class extends Fa{};var ja=class extends y{},Hx=class extends ja{},Xx=class extends ja{};var Ga=class extends y{},Yx=class extends Ga{},Kx=class extends Ga{};var Nc=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},Wa=class extends Nc{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 ce(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let h=this.config.normalized_config.hidden_size;m=new B("float32",[],[0,h])}({inputs_embeds:a}=await ce(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:m}))}return await Ot(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c},!1)}};var qa=class extends y{},Qx=class extends qa{},Jx=class extends qa{async _call(e){return new F(await super._call(e))}};var Va=class extends y{},Zx=class extends Va{},ey=class extends Va{async _call(e){return new _e(await super._call(e))}};var Ha=class extends y{},ty=class extends Ha{},ry=class extends Ha{};var zc=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},sy=class extends zc{get_rope_index(e,r,s,n){let{vision_config:o,image_token_id:a,video_token_id:i,vision_start_token_id:l}=this.config,c=o.spatial_merge_size??2,p=[];if(r||s){let f=e.tolist();n||(n=fl(e));let m=n.tolist(),h=Array.from({length:3},A=>Array.from({length:e.dims[0]},S=>Array.from({length:e.dims[1]},M=>1))),g=r?r.tolist():[],x=s?s.tolist():[],k=0,E=0;for(let A=0;A<f.length;++A){let S=f[A].filter((O,N)=>m[A][N]==1),L=S.reduce((O,N,$)=>(N==l&&O.push($),O),[]).map(O=>S[O+1]),C=L.filter(O=>O==a).length,v=L.filter(O=>O==i).length,G=[],X=0,V=C,Q=v;for(let O=0;O<L.length;++O){let N=S.findIndex((At,et)=>et>X&&At==a),$=S.findIndex((At,et)=>et>X&&At==i),te=V>0&&N!==-1?N:S.length+1,ue=Q>0&&$!==-1?$:S.length+1,Ue,Ce,kt,Qe;te<ue?([Ce,kt,Qe]=g[k],++k,--V,Ue=te):([Ce,kt,Qe]=x[E],++E,--Q,Ue=ue);let[Ze,rt,Te]=[Number(Ce),Math.floor(Number(kt)/c),Math.floor(Number(Qe)/c)],xe=Ue-X,Ge=G.length>0?Me(G.at(-1))[0]+1:0;G.push(Array.from({length:3*xe},(At,et)=>Ge+et%xe));let Et=xe+Ge,we=Ze*rt*Te,Ne=Array.from({length:we},(At,et)=>Et+Math.floor(et/(rt*Te))),br=Array.from({length:we},(At,et)=>Et+Math.floor(et/Te)%rt),Yr=Array.from({length:we},(At,et)=>Et+et%Te);G.push([Ne,br,Yr].flat()),X=Ue+we}if(X<S.length){let O=G.length>0?Me(G.at(-1))[0]+1:0,N=S.length-X;G.push(Array.from({length:3*N},($,te)=>O+te%N))}let Y=G.reduce((O,N)=>O+N.length,0),K=new Array(Y),U=0;for(let O=0;O<3;++O)for(let N=0;N<G.length;++N){let $=G[N],te=$.length/3;for(let ue=O*te;ue<(O+1)*te;++ue)K[U++]=$[ue]}let P=0,se=m[A];for(let O=0;O<se.length;++O)if(se[O]==1){for(let N=0;N<3;++N)h[N][A][O]=K[N*Y/3+P];++P}let ie=Me(K)[0];p.push(ie+1-f[A].length)}return[new B("int64",h.flat(1/0),[3,e.dims[0],e.dims[1]]),new B("int64",p,[p.length,1])]}else if(n){let{data:f,dims:m}=sh(n),h=BigInt64Array.from({length:3*f.length},(x,k)=>f[k%f.length]),g=Array.from({length:m[0]},(x,k)=>Me(f.subarray(m[1]*k,m[1]*(k+1)))[0]+1n+BigInt(m[1]));return[new B("int64",h,[3,...m]),new B("int64",g,[g.length,1])]}else{let[f,m]=e.dims,h=BigInt64Array.from({length:3*f*m},(g,x)=>BigInt(Math.floor(x%m/f)));return[new B("int64",h,[3,...e.dims]),Cd([f,1])]}}async encode_image({pixel_values:e,image_grid_thw:r}){return(await ce(this.sessions.vision_encoder,{pixel_values:e,grid_thw:r})).image_features}_merge_input_ids_with_image_features(e){return cr({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=BigInt(Object.values(r.past_key_values)[0].dims.at(-2)),o=r.rope_deltas.map(a=>n+a);r.position_ids=Gt([o,o,o],0)}return r}};var Xa=class extends y{},ny=class extends Xa{},oy=class extends Xa{};var Ya=class extends y{},ay=class extends Ya{},iy=class extends Ya{async _call(e){return new F(await super._call(e))}};var Ka=class extends y{},ly=class extends Ka{},cy=class extends Ka{async _call(e){return new Rc(await super._call(e))}},Rc=class extends pr{};var jr=class extends y{},uy=class extends jr{},py=class extends jr{async _call(e){return new ge(await super._call(e))}},dy=class extends jr{async _call(e){return new F(await super._call(e))}},fy=class extends jr{async _call(e){return new _e(await super._call(e))}},my=class extends jr{async _call(e){return new Ae(await super._call(e))}};var Gr=class extends y{},hy=class extends Gr{},_y=class extends Gr{async _call(e){return new ge(await super._call(e))}},wy=class extends Gr{async _call(e){return new F(await super._call(e))}},gy=class extends Gr{async _call(e){return new _e(await super._call(e))}},xy=class extends Gr{async _call(e){return new Ae(await super._call(e))}};var Qa=class extends y{},yy=class extends Qa{},by=class extends Qa{async _call(e){return new $c(await super._call(e))}},$c=class extends pr{};var Bc=class extends Le{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},Uc=class extends y{},vy=class extends Uc{async get_image_embeddings({pixel_values:e}){return await qt(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??=it(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 ce(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new Bc(await super._call(e))}};var Dc=class extends Le{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}},Fc=class extends y{},Ja=class extends Fc{async get_image_embeddings({pixel_values:e}){return await qt(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??=it(a.slice(0,-1)),e.input_boxes??=Ve([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Ve([a[0],a[1],0],-1n),e.input_points=Ve([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=ot(e,n.inputNames);return await ce(n,o)}async _call(e){return new Dc(await super._call(e))}},ky=class extends Ja{},Ey=class extends Ja{};var yn=class extends y{},Ay=class extends yn{},Ty=class extends yn{},My=class extends yn{};var bn=class extends y{},Sy=class extends bn{},Oy=class extends bn{},Iy=class extends bn{};var Za=class extends y{},Cy=class extends Za{},ei=class extends Za{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Py=class extends ur{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var ti=class extends y{},Ly=class extends ti{},Ny=class extends ti{};var vn=class extends y{main_input_name="input_values";forward_params=["input_values"]},zy=class extends vn{async encode(e){return await ce(this.sessions.encoder_model,e)}async decode(e){return await ce(this.sessions.decoder_model,e)}},ri=class extends vn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},si=class extends vn{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var kn=class extends y{},Ry=class extends kn{},$y=class extends kn{},By=class extends kn{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 qt(this,i),p=l.dims[1]/this.config.reduction_factor,f=Math.floor(p*o),m=Math.floor(p*n),h=this.config.num_mel_bins,g=[],x=null,k=null,E=0;for(;;){++E;let M=rh(!!k),L;k?L=k.output_sequence_out:L=new B("float32",new Float32Array(h),[1,1,h]);let C={use_cache_branch:M,output_sequence:L,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};this.addPastKeyValues(C,x),k=await ce(this.sessions.decoder_model_merged,C),x=this.getPastKeyValues(k,x);let{prob:v,spectrum:G}=k;if(g.push(G),E>=m&&(Array.from(v.data).filter(X=>X>=s).length>0||E>=f))break}let A=Ee(g),{waveform:S}=await ce(a.sessions.model,{spectrogram:A});return{spectrogram:A,waveform:S}}},Uy=class extends y{main_input_name="spectrogram"};var Ss=class extends y{},Dy=class extends Ss{},Fy=class extends Ss{async _call(e){return new ge(await super._call(e))}},jy=class extends Ss{async _call(e){return new F(await super._call(e))}},Gy=class extends Ss{async _call(e){return new Ae(await super._call(e))}};var ni=class extends y{},Wy=class extends ni{},qy=class extends ni{};var oi=class extends y{},Vy=class extends oi{},Hy=class extends oi{};var jc=class extends y{},Xy=class extends jc{};var Gc=class extends y{},ai=class extends Gc{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 ce(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=f.div(o).mul_(a),h=l*i,g=m.data,x=Int32Array.from(g,V=>Math.ceil(V/h)),k=Math.max(...x),E=e.dims[0],A=new BigInt64Array(E*k);for(let V=0;V<E;++V)A.fill(1n,V*k,V*k+x[V]);let S=new B("int64",A,[E,k]),M=c*i,L=M*k,C=tA([E,M,k]),v=C.data;for(let V=0;V<E;++V)if(x[V]!==k)for(let Q=0;Q<M;++Q)v.fill(0,V*L+Q*k+x[V],V*L+(Q+1)*k);let G=Ve([E],n);for(let V=0;V<n;++V){let Q=Ve([E],V);({denoised_latents:C}=await ce(this.sessions.latent_denoiser,{style:s,noisy_latents:C,latent_mask:S,encoder_outputs:p,attention_mask:r,timestep:Q,num_inference_steps:G}))}let{waveform:X}=await ce(this.sessions.voice_decoder,{latents:C});return{waveform:X,durations:m}}};var En=class extends y{},Yy=class extends En{},Ky=class extends En{async _call(e){return new F(await super._call(e))}},Qy=class extends En{};var ii=class extends y{},Jy=class extends ii{},Zy=class extends ii{};var li=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},e0=class extends li{},t0=class extends li{};var ci=class extends y{},r0=class extends ci{},s0=class extends ci{async _call(e){return new Wc(await super._call(e))}},Wc=class extends dn{};var qc=class extends y{},n0=class extends qc{};var Vc=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Hc=class extends Vc{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return nc({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...e,audio_features:s})}},o0=class extends Hc{};var An=class extends y{},a0=class extends An{},i0=class extends An{async _call(e){return new gt(await super._call(e))}},l0=class extends An{async _call(e){return new F(await super._call(e))}};var Os=class extends y{},c0=class extends Os{},u0=class extends Os{async _call(e){return new gt(await super._call(e))}},p0=class extends Os{async _call(e){return new F(await super._call(e))}},d0=class extends Os{async _call(e){return new _e(await super._call(e))}};var ui=class extends y{},f0=class extends ui{},m0=class extends ui{};var h0=class extends y{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]};var pi=class extends y{},_0=class extends pi{},w0=class extends pi{async _call(e){return new F(await super._call(e))}};var Xc=class extends y{},g0=class extends Xc{};var di=class extends y{},x0=class extends di{},y0=class extends di{async _call(e){return new F(await super._call(e))}};var Yc=class extends y{},b0=class extends Yc{async _call(e){return new Fl(await super._call(e))}};var Kc=class extends y{},v0=class extends Kc{};var Qc=class extends Le{constructor({waveform:e,spectrogram:r}){super(),this.waveform=e,this.spectrogram=r}},Jc=class extends y{},k0=class extends Jc{async _call(e){return new Qc(await super._call(e))}};var Tn=class extends y{},E0=class extends Tn{},A0=class extends Tn{async _call(e){return new gt(await super._call(e))}},T0=class extends Tn{async _call(e){return new F(await super._call(e))}};var Zc=class extends Le{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},Wr=class extends y{},M0=class extends Wr{},S0=class extends Wr{async _call(e){return new gt(await super._call(e))}},O0=class extends Wr{async _call(e){return new F(await super._call(e))}},I0=class extends Wr{async _call(e){return new Zc(await super._call(e))}},C0=class extends Wr{async _call(e){return new _e(await super._call(e))}};var eu=class extends y{},P0=class extends eu{};var tu=class extends on{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 fi=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"]},L0=class extends fi{},ru=class extends fi{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,tu)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(console.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${nA(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&&(console.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 xs,s.push(new Wl(r,a))),r.begin_suppress_tokens&&(s??=new xs,s.push(new nn(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"&&console.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&&console.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&&(console.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)=>Ee(a.map(E=>E[k]),2)),l=Gt(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]=Od(l,-2,0,!0),f=l.clone();for(let x=0;x<f.dims[0];++x){let k=f[x];for(let E=0;E<k.dims[0];++E){let A=k[E],S=c[x][E][0].data,M=p[x][E][0].data;for(let L=0;L<A.dims[0];++L){let C=A[L].data;for(let v=0;v<C.length;++v)C[v]=(C[v]-M[v])/S[v];C.set(sk(C,o))}}}let m=[dl(f,1)],h=e.sequences.dims,g=new B("float32",new Float32Array(h[0]*h[1]),h);for(let x=0;x<h[0];++x){let k=m[x].neg().squeeze_(0),[E,A]=ok(k.tolist()),S=Array.from({length:E.length-1},(C,v)=>E[v+1]-E[v]),M=dt([1],S).map(C=>!!C),L=[];for(let C=0;C<M.length;++C)M[C]&&L.push(A[C]*n);g[x].data.set(L,1)}return g}},N0=class extends ru{};var qr=class extends y{},z0=class extends qr{},R0=class extends qr{async _call(e){return new ge(await super._call(e))}},$0=class extends qr{async _call(e){return new F(await super._call(e))}},B0=class extends qr{async _call(e){return new _e(await super._call(e))}},U0=class extends qr{async _call(e){return new Ae(await super._call(e))}};var Vr=class extends y{},D0=class extends Vr{},F0=class extends Vr{async _call(e){return new ge(await super._call(e))}},j0=class extends Vr{async _call(e){return new F(await super._call(e))}},G0=class extends Vr{async _call(e){return new _e(await super._call(e))}},W0=class extends Vr{async _call(e){return new Ae(await super._call(e))}};var mi=class extends y{},q0=class extends mi{},V0=class extends mi{async _call(e){return new su(await super._call(e))}},su=class extends Le{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var hi=class extends y{},H0=class extends hi{},X0=class extends hi{};var gL=new Map([["bert","BertModel"],["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"]]),xL=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),yL=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),bL=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"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen3","Qwen3Model"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5_Model"],["starcoder2","Starcoder2Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),OA=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"]]),IA=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),CA=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),PA=new Map([["bert","BertForSequenceClassification"],["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"]]),LA=new Map([["bert","BertForTokenClassification"],["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"]]),NA=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),zA=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"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen3","Qwen3ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5_ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["trocr","TrOCRForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),vL=new Map([["multi_modality","MultiModalityCausalLM"]]),RA=new Map([["bert","BertForMaskedLM"],["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"]]),$A=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"]]),BA=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),UA=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2-vl","Qwen2VLForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3n","Gemma3nForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"]]),DA=new Map([["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"]]),kL=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),FA=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"]]),jA=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),GA=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),Mn=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),WA=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),qA=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),VA=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),HA=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),XA=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),YA=new Map([["wavlm","WavLMForXVector"]]),KA=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),QA=new Map([["vitmatte","VitMatteForImageMatting"]]),EL=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),JA=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),ZA=new Map([["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),e2=new Map([["sapiens","SapiensForNormalEstimation"]]),t2=new Map([["vitpose","VitPoseForPoseEstimation"]]),r2=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),Y0=[[gL,H.EncoderOnly],[xL,H.EncoderDecoder],[bL,H.DecoderOnlyWithoutHead],[yL,H.AutoEncoder],[PA,H.EncoderOnly],[LA,H.EncoderOnly],[NA,H.Seq2Seq],[OA,H.Seq2Seq],[zA,H.DecoderOnly],[vL,H.MultiModality],[RA,H.EncoderOnly],[$A,H.EncoderOnly],[BA,H.Vision2Seq],[UA,H.ImageTextToText],[DA,H.AudioTextToText],[FA,H.EncoderOnly],[Mn,H.EncoderOnly],[qA,H.EncoderOnly],[WA,H.EncoderOnly],[QA,H.EncoderOnly],[EL,H.EncoderOnly],[JA,H.EncoderOnly],[ZA,H.EncoderOnly],[e2,H.EncoderOnly],[t2,H.EncoderOnly],[jA,H.EncoderOnly],[GA,H.EncoderOnly],[VA,H.MaskGeneration],[HA,H.EncoderOnly],[XA,H.EncoderOnly],[IA,H.Seq2Seq],[CA,H.EncoderOnly],[YA,H.EncoderOnly],[KA,H.EncoderOnly],[r2,H.EncoderOnly]];for(let[t,e]of Y0)for(let r of t.values()){vs.set(r,e);let s=_i[r];bs.set(s,r),sc.set(r,s)}var AL=[["MusicgenForConditionalGeneration",Ca,H.Musicgen],["Phi3VForCausalLM",Wa,H.Phi3V],["CLIPTextModelWithProjection",To,H.EncoderOnly],["SiglipTextModel",ei,H.EncoderOnly],["JinaCLIPTextModel",da,H.EncoderOnly],["ClapTextModelWithProjection",Eo,H.EncoderOnly],["ClapAudioModelWithProjection",Ao,H.EncoderOnly],["DacEncoderModel",zo,H.EncoderOnly],["DacDecoderModel",Ro,H.EncoderOnly],["MimiEncoderModel",ya,H.EncoderOnly],["MimiDecoderModel",ba,H.EncoderOnly],["SnacEncoderModel",ri,H.EncoderOnly],["SnacDecoderModel",si,H.EncoderOnly],["Gemma3nForConditionalGeneration",Ko,H.ImageAudioTextToText],["SupertonicForConditionalGeneration",ai,H.Supertonic],["ChatterboxModel",ko,H.Chatterbox]];for(let[t,e,r]of AL)vs.set(t,r),bs.set(e,t),sc.set(t,e);var K0=new Map([["modnet",Mn],["birefnet",Mn],["isnet",Mn],["ben",Mn]]);for(let[t,e]of K0.entries())e.set(t,"PreTrainedModel"),vs.set(t,H.EncoderOnly),sc.set(t,y);vs.set("PreTrainedModel",H.EncoderOnly);bs.set(y,"PreTrainedModel");var Ie={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:PA,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:LA,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:IA,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:CA,MODEL_FOR_MASKED_LM_MAPPING_NAMES:RA,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:$A,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:FA,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:Mn,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:WA,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:qA,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:jA,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:GA,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:VA,MODEL_FOR_CTC_MAPPING_NAMES:HA,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:XA,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:YA,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:KA,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:kL,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:QA,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:JA,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:ZA,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:e2,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:t2,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:r2,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:UA,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:DA,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:NA,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:OA,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:zA,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:BA};AA(Ie);var Se=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;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 h={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(h.config=await gs.from_pretrained(e,h),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let g=h.config.model_type;for(let x of this.MODEL_CLASS_MAPPINGS){let k=x.get(g);if(!k){for(let E of x.values())if(E[0]===g){k=E;break}if(!k)continue}return await _i[k].from_pretrained(e,h)}if(this.BASE_IF_FAIL)return K0.has(g)||console.warn(`Unknown model class "${g}", attempting to construct from base class.`),await y.from_pretrained(e,h);throw Error(`Unsupported model type: ${g}`)}},yr=class extends Se{static MODEL_CLASS_MAPPINGS=Y0.map(e=>e[0]);static BASE_IF_FAIL=!0},wi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},nu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},Sn=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},ou=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},au=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},iu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},lu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},cu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},uu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},pu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},du=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},gi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},xi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},yi=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},fu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},mu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},s2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},hu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_CTC_MAPPING_NAMES]},_u=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},n2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},o2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},wu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},a2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},gu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},xu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},i2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},l2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},yu=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},c2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},u2=class extends Se{static MODEL_CLASS_MAPPINGS=[Ie.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function Ke(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>Xe.read(e)))}async function Hr(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?Sf(r,e):r instanceof Float64Array?new Float32Array(r):r))}function bi(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 pe=class extends Je{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 bu=class extends pe{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 B("float32",Pe(c.data),c.dims),l=[];for(let c of n.logits){let p=i(c),f=await Zt(p,r),m=f[0].tolist(),g=f[1].tolist().map((x,k)=>({label:a?a[x]:`LABEL_${x}`,score:m[k]}));r===1?l.push(...g):l.push(g)}return Array.isArray(e)||r===1?l:l[0]}};var vu=class extends pe{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 h=0;h<f.dims[0];++h){let g=f[h],x=Me(g.data)[1],k=i?i[x]:`LABEL_${x}`;if(r.includes(k))continue;let E=this.tokenizer.decode([p[h].item()],{skip_special_tokens:!0});if(E==="")continue;let A=Pe(g.data);m.push({entity:k,score:A[x],index:h,word:E})}l.push(m)}return s?l:l[0]}};var ku=class extends pe{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 h=0;h<a.dims[0];++h){let g=l[h],x=g.findIndex(C=>C==f),k=a[h].tolist(),E=i[h].tolist();for(let C=1;C<k.length;++C)(c[h]==0||C<=x||p.findIndex(v=>v==g[C])!==-1)&&(k[C]=-1/0,E[C]=-1/0);let A=Pe(k).map((C,v)=>[C,v]),S=Pe(E).map((C,v)=>[C,v]);A[0][0]=0,S[0][0]=0;let M=Wv(A,S).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,v)=>v[2]-C[2]),L=[];for(let C=0;C<Math.min(M.length,s);++C){let[v,G,X]=M[C],V=g.slice(v,G+1),Q=this.tokenizer.decode(V,{skip_special_tokens:!0});L.push({answer:Q,score:X})}s===1?m.push(...L):m.push(L)}return o?m:m[0]}};var Eu=class extends pe{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(k=>k==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][f],h=await Zt(new B("float32",Pe(m.data),m.dims),r),g=h[0].tolist(),x=h[1].tolist();i.push(x.map((k,E)=>{let A=p.slice();return A[f]=k,{score:g[E],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 Xr=class extends pe{_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 Au=class extends Xr{_key="summary_text"};var Tu=class extends Xr{_key="translation_text"};function p2(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Mu=class extends pe{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(g=>typeof g=="string"))s=!0,i=e;else{if(p2(e))e=[e];else if(Array.isArray(e)&&e.every(p2))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(g=>this.tokenizer.apply_chat_template(g,{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(g=>g.length));let h=Array.from({length:e.length},g=>[]);for(let g=0;g<f.length;++g){let x=Math.floor(g/p.dims[0]*e.length);m&&(f[g]=f[g].slice(m[x])),h[x].push({generated_text:n?[...e[x],{role:"assistant",content:f[g]}]:f[g]})}return!s&&h.length===1?h[0]:h}};var Su=class extends pe{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&&(console.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&&(console.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 h of a){let g=this.tokenizer(c,{text_pair:h,padding:!0,truncation:!0}),x=await this.model(g);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(h=>Pe(h)[1]):Pe(p)).map((h,g)=>[h,g]).sort((h,g)=>g[0]-h[0]);l.push({sequence:c,labels:m.map(h=>r[h[1]]),scores:m.map(h=>h[0])})}return o?l:l[0]}};var Ou=class extends pe{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await Hr(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 Zt(new B("float32",Pe(p.data),p.dims),r),m=f[0].tolist(),g=f[1].tolist().map((x,k)=>({label:o?o[x]:`LABEL_${x}`,score:m[k]}));a.push(g)}return Array.isArray(e)?a:a[0]}};var Iu=class extends pe{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 Hr(e,i),c=[];for(let p of l){let f=await this.processor(p),m=await this.model({...a,...f}),h=Pe(m.logits_per_audio.data);c.push([...h].map((g,x)=>({score:g,label:r[x]})))}return n?c[0]:c}};var Cu=class extends pe{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&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&console.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 Hr(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).logits[0],m=[];for(let g of f)m.push(Me(g.data)[1]);let h=this.tokenizer.decode(m,{skip_special_tokens:!0}).trim();i.push({text:h})}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,h=p.sampling_rate,g=await Hr(c,h),x=[];for(let k of g){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=h*n,L=h*a,C=M-2*L,v=0;for(;;){let G=v+M,X=k.subarray(v,G),V=await this.processor(X),Q=v===0,Y=G>=k.length;if(E.push({stride:[X.length,Q?0:L,Y?0:L],input_features:V.input_features,is_last:Y}),Y)break;v+=C}}else E=[{stride:[k.length,0,0],input_features:(await this.processor(k)).input_features,is_last:!0}];for(let M of E){i.num_frames=Math.floor(M.stride[0]/m);let L=await this.model.generate({inputs:M.input_features,...i});s==="word"?(M.tokens=L.sequences.tolist()[0],M.token_timestamps=L.token_timestamps.tolist()[0].map(C=>os(C,2))):M.tokens=L[0].tolist(),M.stride=M.stride.map(C=>C/h)}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 Hr(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 Pu=class extends pe{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 fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new B("float32",e,[e.length]);else if(!(e instanceof B))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 no(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||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await yr.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 Lu=class extends pe{async _call(e,r={}){let s=Array.isArray(e),n=await Ke(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 Nu=class extends pe{async _call(e,{top_k:r=5}={}){let s=await Ke(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 Zt(new B("float32",Pe(l.data),l.dims),r),p=c[0].tolist(),m=c[1].tolist().map((h,g)=>({label:a?a[h]:`LABEL_${h}`,score:p[g]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var d2={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},On=class extends pe{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 Ke(e),p=c.map(A=>[A.height,A.width]),f=await this.processor(c),{inputNames:m,outputNames:h}=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 g=await this.model(f),x=null;if(i!==null)x=d2[i];else if(this.processor.image_processor){for(let[A,S]of Object.entries(d2))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,E=[];if(i)if(i==="panoptic"||i==="instance"){let A=x(g,r,s,n,o,a??p)[0],S=A.segmentation;for(let M of A.segments_info){let L=new Uint8ClampedArray(S.data.length);for(let v=0;v<S.data.length;++v)S.data[v]===M.id&&(L[v]=255);let C=new Xe(L,S.dims[1],S.dims[0],1);E.push({score:M.score,label:k[M.label_id],mask:C})}}else if(i==="semantic"){let{segmentation:A,labels:S}=x(g,a??p)[0];for(let M of S){let L=new Uint8ClampedArray(A.data.length);for(let v=0;v<A.data.length;++v)A.data[v]===M&&(L[v]=255);let C=new Xe(L,A.dims[1],A.dims[0],1);E.push({score:null,label:k[M],mask:C})}}else throw Error(`Subtask ${i} not supported.`);else{let S=g[h[0]];for(let M=0;M<p.length;++M){let L=p[M],C=S[M];C.data.some(G=>G<-1e-5||G>1+1e-5)&&C.sigmoid_();let v=await Xe.fromTensor(C.mul_(255).to("uint8")).resize(L[1],L[0]);E.push({label:null,score:null,mask:v})}}return E}};var zu=class extends On{async _call(e,r={}){let s=await Ke(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 Ru=class extends pe{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await Ke(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=>Pe(m.data),f=[];for(let m of c.logits_per_image){let g=[...p(m)].map((x,k)=>({score:x,label:r[k]}));g.sort((x,k)=>k.score-x.score),f.push(g)}return n?f:f[0]}};var $u=class extends pe{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 Ke(e),a=s?null:o.map(h=>[h.height,h.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(h=>h.boxes.map((g,x)=>({score:h.scores[x],label:f[h.classes[x]],box:bi(g,!s)})));return n?m:m[0]}};var Bu=class extends pe{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await Ke(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],h=o?null:[[m.height,m.width]],g=c.pixel_values[f].unsqueeze_(0),x=await this.model({...l,pixel_values:g}),k;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:h})[0];k=E.boxes.map((A,S)=>({score:E.scores[S],label:E.labels[S],box:bi(A,!o)}))}else{let E=this.processor.image_processor.post_process_object_detection(x,s,h,!0)[0];k=E.boxes.map((A,S)=>({score:E.scores[S],label:r[E.classes[S]],box:bi(A,!o)}))}k.sort((E,A)=>A.score-E.score),n!==null&&(k=k.slice(0,n)),p.push(k)}return a?p:p[0]}};var Uu=class extends pe{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 Ke(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 Du=class extends pe{async _call(e){let r=await Ke(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(Xe.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var Fu=class extends pe{async _call(e){let r=await Ke(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 jt(i.view(1,1,l,c),{size:[f,p],mode:"bilinear"})).view(f,p),h=m.min().item(),g=m.max().item(),x=m.sub(h).div_(g-h).mul_(255).to("uint8").unsqueeze(0),k=Xe.fromTensor(x);o.push({predicted_depth:m,depth:k})}return Array.isArray(e)?o:o[0]}};var ju=class extends pe{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=eA(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=rA(l,o)),l}};var Gu=class extends pe{async _call(e,{pool:r=null}={}){let s=await Ke(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 f2=Object.freeze({"text-classification":{tokenizer:J,pipeline:bu,model:wi,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:J,pipeline:vu,model:nu,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:J,pipeline:ku,model:uu,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:J,pipeline:Eu,model:cu,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{tokenizer:J,pipeline:Au,model:Sn,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:J,pipeline:Tu,model:Sn,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:J,pipeline:Xr,model:Sn,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:J,pipeline:Mu,model:lu,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{tokenizer:J,pipeline:Su,model:wi,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Ou,model:_u,processor:ut,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:J,pipeline:Iu,model:yr,processor:ut,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:J,pipeline:Cu,model:[ou,hu],processor:ut,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:J,pipeline:Pu,model:[iu,au],processor:[ut,null],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{tokenizer:J,pipeline:Lu,model:pu,processor:ut,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Nu,model:du,processor:ut,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:On,model:[gi,xi,yi],processor:ut,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:zu,model:[gi,xi,yi],processor:ut,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:J,pipeline:Ru,model:yr,processor:ut,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:$u,model:fu,processor:ut,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:J,pipeline:Bu,model:mu,processor:ut,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:J,pipeline:Uu,model:wu,processor:ut,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Du,model:gu,processor:ut,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Fu,model:xu,processor:ut,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{tokenizer:J,pipeline:ju,model:yr,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{processor:ut,pipeline:Gu,model:[yu,yr],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),TL=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function rre(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=TL[t]??t;let h=f2[t.split("_",1)[0]];if(!h)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(f2)}]`);e||(e=h.default.model,console.log(`No model specified. Using default model: "${e}".`),!l&&h.default.dtype&&(l=h.default.dtype));let g={progress_callback:r,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},x=new Map([["tokenizer",h.tokenizer],["model",h.model],["processor",h.processor]]),k=await ML(x,e,g);k.task=t,gr(r,{status:"ready",task:t,model:e});let E=h.pipeline;return new E(k)}async function ML(t,e,r){let s=Object.create(null),n=[];for(let[o,a]of t.entries()){if(!a)continue;let i;Array.isArray(a)?i=new Promise(async(l,c)=>{let p;for(let f of a){if(f===null){l(null);return}try{l(await f.from_pretrained(e,r));return}catch(m){if(m.message?.includes("Unsupported model type"))p=m;else if(m.message?.includes("Could not locate file"))p=m;else{c(m);return}}}c(p)}):i=a.from_pretrained(e,r),s[o]=i,n.push(i)}await Promise.all(n);for(let[o,a]of Object.entries(s))s[o]=await a;return s}var SL=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,Q0=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},m2=be.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),J0=class extends Q0{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??m2,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=dt(this.token_cache,s);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),o;r||n.endsWith(`
|
|
28
|
+
`)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&SL(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===m2&&be.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
|
|
29
|
+
`)}},h2=class extends J0{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 vi=class{constructor(e,r){this.image=e,this.timestamp=r}},Wu=class{constructor(e,r){e.length>0&&e[0]instanceof Xe&&(e=e.map((s,n)=>new vi(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 OL(t,{num_frames:e=null,fps:r=null}={}){if(!be.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 fetch(n.src)).blob();n.src=URL.createObjectURL(m),await new Promise(h=>n.onloadedmetadata=h)}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),h=new Xe(m.data,c.width,c.height,4),g=new vi(h,f);s.push(g)}return n.remove(),new Wu(s,o)}export{Of as ASTFeatureExtractor,fh as ASTForAudioClassification,dh as ASTModel,go as ASTPreTrainedModel,ih as AlbertForMaskedLM,ah as AlbertForQuestionAnswering,oh as AlbertForSequenceClassification,nh as AlbertModel,ks as AlbertPreTrainedModel,zd as AlbertTokenizer,ch as ApertusForCausalLM,lh as ApertusModel,_o as ApertusPreTrainedModel,ph as ArceeForCausalLM,uh as ArceeModel,wo as ArceePreTrainedModel,Ou as AudioClassificationPipeline,gs as AutoConfig,tt as AutoFeatureExtractor,Re as AutoImageProcessor,yr as AutoModel,_u as AutoModelForAudioClassification,o2 as AutoModelForAudioFrameClassification,u2 as AutoModelForAudioTextToText,hu as AutoModelForCTC,lu as AutoModelForCausalLM,xu as AutoModelForDepthEstimation,wu as AutoModelForDocumentQuestionAnswering,du as AutoModelForImageClassification,yu as AutoModelForImageFeatureExtraction,a2 as AutoModelForImageMatting,gi as AutoModelForImageSegmentation,c2 as AutoModelForImageTextToText,gu as AutoModelForImageToImage,s2 as AutoModelForMaskGeneration,cu as AutoModelForMaskedLM,i2 as AutoModelForNormalEstimation,fu as AutoModelForObjectDetection,l2 as AutoModelForPoseEstimation,uu as AutoModelForQuestionAnswering,xi as AutoModelForSemanticSegmentation,Sn as AutoModelForSeq2SeqLM,wi as AutoModelForSequenceClassification,ou as AutoModelForSpeechSeq2Seq,au as AutoModelForTextToSpectrogram,iu as AutoModelForTextToWaveform,nu as AutoModelForTokenClassification,yi as AutoModelForUniversalSegmentation,pu as AutoModelForVision2Seq,n2 as AutoModelForXVector,mu as AutoModelForZeroShotObjectDetection,ut as AutoProcessor,J as AutoTokenizer,Cu as AutomaticSpeechRecognitionPipeline,zu as BackgroundRemovalPipeline,hh as BartForConditionalGeneration,_h as BartForSequenceClassification,mh as BartModel,ln as BartPretrainedModel,Rd as BartTokenizer,Q0 as BaseStreamer,Wf as BeitFeatureExtractor,gh as BeitForImageClassification,wh as BeitModel,xo as BeitPreTrainedModel,yh as BertForMaskedLM,kh as BertForQuestionAnswering,bh as BertForSequenceClassification,vh as BertForTokenClassification,xh as BertModel,Lr as BertPreTrainedModel,$d as BertTokenizer,qf as BitImageProcessor,Ah as BlenderbotForConditionalGeneration,Eh as BlenderbotModel,yo as BlenderbotPreTrainedModel,Mh as BlenderbotSmallForConditionalGeneration,Th as BlenderbotSmallModel,bo as BlenderbotSmallPreTrainedModel,Bd as BlenderbotSmallTokenizer,Ud as BlenderbotTokenizer,Oh as BloomForCausalLM,Sh as BloomModel,vo as BloomPreTrainedModel,Dd as BloomTokenizer,Hf as CLIPFeatureExtractor,yl as CLIPImageProcessor,$h as CLIPModel,ur as CLIPPreTrainedModel,jh as CLIPSegForImageSegmentation,Fh as CLIPSegModel,Mo as CLIPSegPreTrainedModel,Bh as CLIPTextModel,To as CLIPTextModelWithProjection,jd as CLIPTokenizer,Uh as CLIPVisionModel,Dh as CLIPVisionModelWithProjection,Ch as CamembertForMaskedLM,Nh as CamembertForQuestionAnswering,Ph as CamembertForSequenceClassification,Lh as CamembertForTokenClassification,Ih as CamembertModel,Nr as CamembertPreTrainedModel,Fd as CamembertTokenizer,If as ChatterboxFeatureExtractor,ko as ChatterboxModel,oc as ChatterboxPreTrainedModel,Ff as ChatterboxProcessor,Vf as ChineseCLIPFeatureExtractor,zh as ChineseCLIPModel,ac as ChineseCLIPPreTrainedModel,Ao as ClapAudioModelWithProjection,Cf as ClapFeatureExtractor,Rh as ClapModel,cn as ClapPreTrainedModel,Eo as ClapTextModelWithProjection,Kl as ClassifierFreeGuidanceLogitsProcessor,Wh as CodeGenForCausalLM,Gh as CodeGenModel,So as CodeGenPreTrainedModel,Wd as CodeGenTokenizer,Gd as CodeLlamaTokenizer,Xh as Cohere2ForCausalLM,Hh as Cohere2Model,Io as Cohere2PreTrainedModel,Vh as CohereForCausalLM,qh as CohereModel,Oo as CoherePreTrainedModel,qd as CohereTokenizer,Kh as ConvBertForMaskedLM,Zh as ConvBertForQuestionAnswering,Qh as ConvBertForSequenceClassification,Jh as ConvBertForTokenClassification,Yh as ConvBertModel,zr as ConvBertPreTrainedModel,Vd as ConvBertTokenizer,Xf as ConvNextFeatureExtractor,t_ as ConvNextForImageClassification,bl as ConvNextImageProcessor,e_ as ConvNextModel,Co as ConvNextPreTrainedModel,s_ as ConvNextV2ForImageClassification,r_ as ConvNextV2Model,Po as ConvNextV2PreTrainedModel,i_ as DFineForObjectDetection,a_ as DFineModel,No as DFinePreTrainedModel,C_ as DINOv3ConvNextModel,fc as DINOv3ConvNextPreTrainedModel,Qf as DINOv3ViTImageProcessor,P_ as DINOv3ViTModel,mc as DINOv3ViTPreTrainedModel,Zf as DPTFeatureExtractor,D_ as DPTForDepthEstimation,El as DPTImageProcessor,U_ as DPTModel,Do as DPTPreTrainedModel,Ro as DacDecoderModel,lc as DacDecoderOutput,zo as DacEncoderModel,ic as DacEncoderOutput,ao as DacFeatureExtractor,l_ as DacModel,un as DacPreTrainedModel,u_ as DebertaForMaskedLM,f_ as DebertaForQuestionAnswering,p_ as DebertaForSequenceClassification,d_ as DebertaForTokenClassification,c_ as DebertaModel,Rr as DebertaPreTrainedModel,Xd as DebertaTokenizer,h_ as DebertaV2ForMaskedLM,g_ as DebertaV2ForQuestionAnswering,__ as DebertaV2ForSequenceClassification,w_ as DebertaV2ForTokenClassification,m_ as DebertaV2Model,$r as DebertaV2PreTrainedModel,Hd as DebertaV2Tokenizer,x_ as DecisionTransformerModel,cc as DecisionTransformerPreTrainedModel,Yf as DeiTFeatureExtractor,b_ as DeiTForImageClassification,vl as DeiTImageProcessor,y_ as DeiTModel,$o as DeiTPreTrainedModel,v_ as DepthAnythingForDepthEstimation,uc as DepthAnythingPreTrainedModel,Fu as DepthEstimationPipeline,k_ as DepthProForDepthEstimation,pc as DepthProPreTrainedModel,Kf as DetrFeatureExtractor,A_ as DetrForObjectDetection,T_ as DetrForSegmentation,kl as DetrImageProcessor,E_ as DetrModel,dn as DetrObjectDetectionOutput,pn as DetrPreTrainedModel,dc as DetrSegmentationOutput,S_ as Dinov2ForImageClassification,M_ as Dinov2Model,Bo as Dinov2PreTrainedModel,I_ as Dinov2WithRegistersForImageClassification,O_ as Dinov2WithRegistersModel,Uo as Dinov2WithRegistersPreTrainedModel,$_ as DistilBertForMaskedLM,R_ as DistilBertForQuestionAnswering,N_ as DistilBertForSequenceClassification,z_ as DistilBertForTokenClassification,L_ as DistilBertModel,Br as DistilBertPreTrainedModel,Yd as DistilBertTokenizer,Uu as DocumentQuestionAnsweringPipeline,Jf as DonutFeatureExtractor,Qs as DonutImageProcessor,B_ as DonutSwinModel,hc as DonutSwinPreTrainedModel,ky as EdgeTamModel,j_ as EfficientNetForImageClassification,em as EfficientNetImageProcessor,F_ as EfficientNetModel,Fo as EfficientNetPreTrainedModel,W_ as ElectraForMaskedLM,H_ as ElectraForQuestionAnswering,q_ as ElectraForSequenceClassification,V_ as ElectraForTokenClassification,G_ as ElectraModel,Ur as ElectraPreTrainedModel,Kd as ElectraTokenizer,oo as EncodecFeatureExtractor,ec as EosTokenCriteria,Y_ as Ernie4_5ForCausalLM,X_ as Ernie4_5Model,jo as Ernie4_5PretrainedModel,Q_ as EsmForMaskedLM,J_ as EsmForSequenceClassification,Z_ as EsmForTokenClassification,K_ as EsmModel,Es as EsmPreTrainedModel,Qd as EsmTokenizer,tw as ExaoneForCausalLM,ew as ExaoneModel,Go as ExaonePreTrainedModel,sw as FalconForCausalLM,ow as FalconH1ForCausalLM,nw as FalconH1Model,qo as FalconH1PreTrainedModel,rw as FalconModel,Wo as FalconPreTrainedModel,Jd as FalconTokenizer,iw as FastViTForImageClassification,aw as FastViTModel,Vo as FastViTPreTrainedModel,ju as FeatureExtractionPipeline,ze as FeatureExtractor,Eu as FillMaskPipeline,lw as Florence2ForConditionalGeneration,_c as Florence2PreTrainedModel,Cm as Florence2Processor,jl as ForcedBOSTokenLogitsProcessor,Gl as ForcedEOSTokenLogitsProcessor,tm as GLPNFeatureExtractor,gw as GLPNForDepthEstimation,ww as GLPNModel,Jo as GLPNPreTrainedModel,Sw as GPT2LMHeadModel,Mw as GPT2Model,sa as GPT2PreTrainedModel,tf as GPT2Tokenizer,yw as GPTBigCodeForCausalLM,xw as GPTBigCodeModel,Zo as GPTBigCodePreTrainedModel,Iw as GPTJForCausalLM,Ow as GPTJModel,na as GPTJPreTrainedModel,vw as GPTNeoForCausalLM,bw as GPTNeoModel,ea as GPTNeoPreTrainedModel,Ew as GPTNeoXForCausalLM,kw as GPTNeoXModel,ta as GPTNeoXPreTrainedModel,ef as GPTNeoXTokenizer,dw as Gemma2ForCausalLM,pw as Gemma2Model,Xo as Gemma2PreTrainedModel,mw as Gemma3ForCausalLM,fw as Gemma3Model,Yo as Gemma3PreTrainedModel,Pf as Gemma3nAudioFeatureExtractor,Ko as Gemma3nForConditionalGeneration,wc as Gemma3nPreTrainedModel,Pm as Gemma3nProcessor,uw as GemmaForCausalLM,cw as GemmaModel,Ho as GemmaPreTrainedModel,Zd as GemmaTokenizer,_w as GlmForCausalLM,hw as GlmModel,Qo as GlmPreTrainedModel,Tw as GptOssForCausalLM,Aw as GptOssModel,ra as GptOssPreTrainedModel,Pw as GraniteForCausalLM,Cw as GraniteModel,Nw as GraniteMoeHybridForCausalLM,Lw as GraniteMoeHybridModel,aa as GraniteMoeHybridPreTrainedModel,oa as GranitePreTrainedModel,zw as GroundingDinoForObjectDetection,rm as GroundingDinoImageProcessor,gc as GroundingDinoPreTrainedModel,Lm as GroundingDinoProcessor,Rw as GroupViTModel,xc as GroupViTPreTrainedModel,Bw as HeliumForCausalLM,$w as HeliumModel,ia as HeliumPreTrainedModel,rf as HerbertTokenizer,Dw as HieraForImageClassification,Uw as HieraModel,la as HieraPreTrainedModel,Hw as HubertForCTC,Xw as HubertForSequenceClassification,Vw as HubertModel,qw as HubertPreTrainedModel,Kw as HunYuanDenseV1ForCausalLM,Yw as HunYuanDenseV1Model,ca as HunYuanDenseV1PreTrainedModel,Zw as IJepaForImageClassification,Jw as IJepaModel,ua as IJepaPreTrainedModel,bc as Idefics3ForConditionalGeneration,Al as Idefics3ImageProcessor,yc as Idefics3PreTrainedModel,zl as Idefics3Processor,Nu as ImageClassificationPipeline,Gu as ImageFeatureExtractionPipeline,q as ImageFeatureExtractor,q as ImageProcessor,On as ImageSegmentationPipeline,Du as ImageToImagePipeline,Lu as ImageToTextPipeline,kA as InterruptableStoppingCriteria,tg as JAISLMHeadModel,eg as JAISModel,pa as JAISPreTrainedModel,nm as JinaCLIPImageProcessor,rg as JinaCLIPModel,fn as JinaCLIPPreTrainedModel,zm as JinaCLIPProcessor,da as JinaCLIPTextModel,sg as JinaCLIPVisionModel,og as Lfm2ForCausalLM,ng as Lfm2Model,ig as Lfm2MoeForCausalLM,ag as Lfm2MoeModel,ma as Lfm2MoePreTrainedModel,fa as Lfm2PreTrainedModel,N0 as LiteWhisperForConditionalGeneration,ug as Llama4ForCausalLM,vc as Llama4PreTrainedModel,cg as LlamaForCausalLM,lg as LlamaModel,ha as LlamaPreTrainedModel,sf as LlamaTokenizer,mn as LlavaForConditionalGeneration,mn as LlavaOnevisionForConditionalGeneration,om as LlavaOnevisionImageProcessor,kc as LlavaPreTrainedModel,Rm as LlavaProcessor,dg as LlavaQwen2ForCausalLM,Wt as LogitsProcessor,xs as LogitsProcessorList,po as LogitsWarper,mg as LongT5ForConditionalGeneration,fg as LongT5Model,_a as LongT5PreTrainedModel,_g as M2M100ForConditionalGeneration,hg as M2M100Model,wa as M2M100PreTrainedModel,nf as M2M100Tokenizer,af as MBart50Tokenizer,Eg as MBartForCausalLM,vg as MBartForConditionalGeneration,kg as MBartForSequenceClassification,bg as MBartModel,As as MBartPreTrainedModel,to as MBartTokenizer,lx as MPNetForMaskedLM,px as MPNetForQuestionAnswering,cx as MPNetForSequenceClassification,ux as MPNetForTokenClassification,ix as MPNetModel,Dr as MPNetPreTrainedModel,uf as MPNetTokenizer,hx as MT5ForConditionalGeneration,mx as MT5Model,Oa as MT5PreTrainedModel,gg as MarianMTModel,wg as MarianModel,ga as MarianPreTrainedModel,of as MarianTokenizer,im as Mask2FormerImageProcessor,am as MaskFormerFeatureExtractor,yg as MaskFormerForInstanceSegmentation,Js as MaskFormerImageProcessor,xg as MaskFormerModel,xa as MaskFormerPreTrainedModel,Zl as MaxLengthCriteria,Ag as Metric3DForDepthEstimation,Ec as Metric3DPreTrainedModel,Tg as Metric3Dv2ForDepthEstimation,Ac as Metric3Dv2PreTrainedModel,Mg as MgpstrForSceneTextRecognition,Tc as MgpstrModelOutput,Mc as MgpstrPreTrainedModel,$m as MgpstrProcessor,lf as MgpstrTokenizer,ba as MimiDecoderModel,Oc as MimiDecoderOutput,ya as MimiEncoderModel,Sc as MimiEncoderOutput,Sg as MimiModel,hn as MimiPreTrainedModel,Hl as MinLengthLogitsProcessor,Xl as MinNewTokensLengthLogitsProcessor,Ig as MistralForCausalLM,Og as MistralModel,va as MistralPreTrainedModel,Pg as MobileBertForMaskedLM,Ng as MobileBertForQuestionAnswering,Lg as MobileBertForSequenceClassification,Cg as MobileBertModel,Ts as MobileBertPreTrainedModel,cf as MobileBertTokenizer,Rg as MobileLLMForCausalLM,zg as MobileLLMModel,ka as MobileLLMPreTrainedModel,lm as MobileNetV1FeatureExtractor,Bg as MobileNetV1ForImageClassification,Ug as MobileNetV1ForSemanticSegmentation,Tl as MobileNetV1ImageProcessor,$g as MobileNetV1Model,_n as MobileNetV1PreTrainedModel,cm as MobileNetV2FeatureExtractor,Fg as MobileNetV2ForImageClassification,jg as MobileNetV2ForSemanticSegmentation,Ml as MobileNetV2ImageProcessor,Dg as MobileNetV2Model,wn as MobileNetV2PreTrainedModel,um as MobileNetV3FeatureExtractor,Wg as MobileNetV3ForImageClassification,qg as MobileNetV3ForSemanticSegmentation,Sl as MobileNetV3ImageProcessor,Gg as MobileNetV3Model,gn as MobileNetV3PreTrainedModel,pm as MobileNetV4FeatureExtractor,Hg as MobileNetV4ForImageClassification,Xg as MobileNetV4ForSemanticSegmentation,Ol as MobileNetV4ImageProcessor,Vg as MobileNetV4Model,xn as MobileNetV4PreTrainedModel,dm as MobileViTFeatureExtractor,Kg as MobileViTForImageClassification,Il as MobileViTImageProcessor,Yg as MobileViTModel,Ea as MobileViTPreTrainedModel,Jg as MobileViTV2ForImageClassification,Qg as MobileViTV2Model,Aa as MobileViTV2PreTrainedModel,nx as ModernBertDecoderForCausalLM,sx as ModernBertDecoderModel,Ta as ModernBertDecoderPreTrainedModel,ex as ModernBertForMaskedLM,tx as ModernBertForSequenceClassification,rx as ModernBertForTokenClassification,Zg as ModernBertModel,Ms as ModernBertPreTrainedModel,pg as Moondream1ForConditionalGeneration,Lf as MoonshineFeatureExtractor,ax as MoonshineForConditionalGeneration,ox as MoonshineModel,Ma as MoonshinePreTrainedModel,Bm as MoonshineProcessor,fx as MptForCausalLM,dx as MptModel,Sa as MptPreTrainedModel,_x as MultiModalityCausalLM,Ic as MultiModalityPreTrainedModel,gx as MusicgenForCausalLM,Ca as MusicgenForConditionalGeneration,wx as MusicgenModel,Ia as MusicgenPreTrainedModel,yx as NanoChatForCausalLM,xx as NanoChatModel,Pa as NanoChatPreTrainedModel,vx as NeoBertForMaskedLM,Ax as NeoBertForQuestionAnswering,kx as NeoBertForSequenceClassification,Ex as NeoBertForTokenClassification,bx as NeoBertModel,Fr as NeoBertPreTrainedModel,pf as NllbTokenizer,Yl as NoBadWordsLogitsProcessor,ql as NoRepeatNGramLogitsProcessor,Tx as NomicBertModel,Cc as NomicBertPreTrainedModel,fm as NougatImageProcessor,df as NougatTokenizer,Rx as OPTForCausalLM,zx as OPTModel,$a as OPTPreTrainedModel,$u as ObjectDetectionPipeline,Ix as Olmo2ForCausalLM,Ox as Olmo2Model,Na as Olmo2PreTrainedModel,Px as Olmo3ForCausalLM,Cx as Olmo3Model,za as Olmo3PreTrainedModel,Sx as OlmoForCausalLM,Mx as OlmoModel,La as OlmoPreTrainedModel,Nx as OpenELMForCausalLM,Lx as OpenELMModel,Ra as OpenELMPreTrainedModel,mm as OwlViTFeatureExtractor,Dx as OwlViTForObjectDetection,Zs as OwlViTImageProcessor,Ux as OwlViTModel,Ua as OwlViTPreTrainedModel,Um as OwlViTProcessor,Bx as Owlv2ForObjectDetection,hm as Owlv2ImageProcessor,$x as Owlv2Model,Ba as Owlv2PreTrainedModel,Fx as PaliGemmaForConditionalGeneration,Pc as PaliGemmaPreTrainedModel,Dm as PaliGemmaProcessor,Nf as ParakeetFeatureExtractor,jx as ParakeetForCTC,Lc as ParakeetPreTrainedModel,Wx as PatchTSMixerForPrediction,Gx as PatchTSMixerModel,Da as PatchTSMixerPreTrainedModel,Vx as PatchTSTForPrediction,qx as PatchTSTModel,Fa as PatchTSTPreTrainedModel,Kx as Phi3ForCausalLM,Yx as Phi3Model,Ga as Phi3PreTrainedModel,Wa as Phi3VForCausalLM,gm as Phi3VImageProcessor,Nc as Phi3VPreTrainedModel,Fm as Phi3VProcessor,Xx as PhiForCausalLM,Hx as PhiModel,ja as PhiPreTrainedModel,xm as PixtralImageProcessor,jm as PixtralProcessor,y as PreTrainedModel,j as PreTrainedTokenizer,Ul as PretrainedConfig,ne as Processor,Jx as PvtForImageClassification,ym as PvtImageProcessor,Qx as PvtModel,qa as PvtPreTrainedModel,io as PyAnnoteFeatureExtractor,ey as PyAnnoteForAudioFrameClassification,Zx as PyAnnoteModel,Va as PyAnnotePreTrainedModel,Gm as PyAnnoteProcessor,ku as QuestionAnsweringPipeline,ry as Qwen2ForCausalLM,ty as Qwen2Model,Ha as Qwen2PreTrainedModel,ff as Qwen2Tokenizer,sy as Qwen2VLForConditionalGeneration,bm as Qwen2VLImageProcessor,zc as Qwen2VLPreTrainedModel,Wm as Qwen2VLProcessor,oy as Qwen3ForCausalLM,ny as Qwen3Model,Xa as Qwen3PreTrainedModel,cy as RFDetrForObjectDetection,ly as RFDetrModel,Rc as RFDetrObjectDetectionOutput,Ka as RFDetrPreTrainedModel,o_ as RTDetrForObjectDetection,vm as RTDetrImageProcessor,n_ as RTDetrModel,pr as RTDetrObjectDetectionOutput,Lo as RTDetrPreTrainedModel,by as RTDetrV2ForObjectDetection,yy as RTDetrV2Model,$c as RTDetrV2ObjectDetectionOutput,Qa as RTDetrV2PreTrainedModel,no as RawAudio,Xe as RawImage,Wu as RawVideo,vi as RawVideoFrame,Vl as RepetitionPenaltyLogitsProcessor,iy as ResNetForImageClassification,ay as ResNetModel,Ya as ResNetPreTrainedModel,_y as RoFormerForMaskedLM,xy as RoFormerForQuestionAnswering,wy as RoFormerForSequenceClassification,gy as RoFormerForTokenClassification,hy as RoFormerModel,Gr as RoFormerPreTrainedModel,hf as RoFormerTokenizer,py as RobertaForMaskedLM,my as RobertaForQuestionAnswering,dy as RobertaForSequenceClassification,fy as RobertaForTokenClassification,uy as RobertaModel,jr as RobertaPreTrainedModel,mf as RobertaTokenizer,co as Sam2ImageProcessor,Dc as Sam2ImageSegmentationOutput,Ja as Sam2Model,Fc as Sam2PreTrainedModel,Rl as Sam2Processor,qm as Sam2VideoProcessor,co as Sam3ImageProcessor,Ey as Sam3TrackerModel,co as SamImageProcessor,Bc as SamImageSegmentationOutput,vy as SamModel,Uc as SamPreTrainedModel,uo as SamProcessor,km as SapiensFeatureExtractor,Ty as SapiensForDepthEstimation,My as SapiensForNormalEstimation,Ay as SapiensForSemanticSegmentation,Cl as SapiensImageProcessor,yn as SapiensPreTrainedModel,zf as SeamlessM4TFeatureExtractor,Em as SegformerFeatureExtractor,Oy as SegformerForImageClassification,Iy as SegformerForSemanticSegmentation,Pl as SegformerImageProcessor,Sy as SegformerModel,bn as SegformerPreTrainedModel,Am as SiglipImageProcessor,Cy as SiglipModel,Za as SiglipPreTrainedModel,ei as SiglipTextModel,_f as SiglipTokenizer,Py as SiglipVisionModel,Ny as SmolLM3ForCausalLM,Ly as SmolLM3Model,ti as SmolLM3PreTrainedModel,Qw as SmolVLMForConditionalGeneration,Al as SmolVLMImageProcessor,zl as SmolVLMProcessor,si as SnacDecoderModel,ri as SnacEncoderModel,Rf as SnacFeatureExtractor,zy as SnacModel,vn as SnacPreTrainedModel,$f as SpeechT5FeatureExtractor,$y as SpeechT5ForSpeechToText,By as SpeechT5ForTextToSpeech,Uy as SpeechT5HifiGan,Ry as SpeechT5Model,kn as SpeechT5PreTrainedModel,Vm as SpeechT5Processor,wf as SpeechT5Tokenizer,Fy as SqueezeBertForMaskedLM,Gy as SqueezeBertForQuestionAnswering,jy as SqueezeBertForSequenceClassification,Dy as SqueezeBertModel,Ss as SqueezeBertPreTrainedModel,gf as SqueezeBertTokenizer,qy as StableLmForCausalLM,Wy as StableLmModel,ni as StableLmPreTrainedModel,Hy as Starcoder2ForCausalLM,Vy as Starcoder2Model,oi as Starcoder2PreTrainedModel,an as StoppingCriteria,Jl as StoppingCriteriaList,Xy as StyleTextToSpeech2Model,jc as StyleTextToSpeech2PreTrainedModel,Au as SummarizationPipeline,ai as SupertonicForConditionalGeneration,Gc as SupertonicPreTrainedModel,nn as SuppressTokensAtBeginLogitsProcessor,Zy as Swin2SRForImageSuperResolution,Tm as Swin2SRImageProcessor,Jy as Swin2SRModel,ii as Swin2SRPreTrainedModel,Ky as SwinForImageClassification,Qy as SwinForSemanticSegmentation,Yy as SwinModel,En as SwinPreTrainedModel,t0 as T5ForConditionalGeneration,e0 as T5Model,li as T5PreTrainedModel,xf as T5Tokenizer,s0 as TableTransformerForObjectDetection,r0 as TableTransformerModel,Wc as TableTransformerObjectDetectionOutput,ci as TableTransformerPreTrainedModel,Ql as TemperatureLogitsWarper,B as Tensor,Xr as Text2TextGenerationPipeline,bu as TextClassificationPipeline,Mu as TextGenerationPipeline,J0 as TextStreamer,Pu as TextToAudioPipeline,vu as TokenClassificationPipeline,j as TokenizersBackend,vA as TopKLogitsWarper,bA as TopPLogitsWarper,n0 as TrOCRForCausalLM,qc as TrOCRPreTrainedModel,Tu as TranslationPipeline,Hc as UltravoxModel,Vc as UltravoxPreTrainedModel,Hm as UltravoxProcessor,i0 as UniSpeechForCTC,l0 as UniSpeechForSequenceClassification,a0 as UniSpeechModel,An as UniSpeechPreTrainedModel,d0 as UniSpeechSatForAudioFrameClassification,u0 as UniSpeechSatForCTC,p0 as UniSpeechSatForSequenceClassification,c0 as UniSpeechSatModel,Os as UniSpeechSatPreTrainedModel,Nm as VLChatProcessor,sm as VLMImageProcessor,m0 as VaultGemmaForCausalLM,f0 as VaultGemmaModel,ui as VaultGemmaPreTrainedModel,Mm as ViTFeatureExtractor,w0 as ViTForImageClassification,Ll as ViTImageProcessor,g0 as ViTMAEModel,Xc as ViTMAEPreTrainedModel,y0 as ViTMSNForImageClassification,x0 as ViTMSNModel,di as ViTMSNPreTrainedModel,_0 as ViTModel,pi as ViTPreTrainedModel,h0 as VisionEncoderDecoderModel,b0 as VitMatteForImageMatting,Sm as VitMatteImageProcessor,Yc as VitMattePreTrainedModel,v0 as VitPoseForPoseEstimation,Om as VitPoseImageProcessor,Kc as VitPosePreTrainedModel,k0 as VitsModel,Qc as VitsModelOutput,Jc as VitsPreTrainedModel,bf as VitsTokenizer,o0 as VoxtralForConditionalGeneration,Xm as VoxtralProcessor,A0 as Wav2Vec2BertForCTC,T0 as Wav2Vec2BertForSequenceClassification,E0 as Wav2Vec2BertModel,Tn as Wav2Vec2BertPreTrainedModel,vf as Wav2Vec2CTCTokenizer,Bf as Wav2Vec2FeatureExtractor,Ww as Wav2Vec2ForAudioFrameClassification,jw as Wav2Vec2ForCTC,Gw as Wav2Vec2ForSequenceClassification,Fw as Wav2Vec2Model,tr as Wav2Vec2PreTrainedModel,Ym as Wav2Vec2Processor,Km as Wav2Vec2ProcessorWithLM,C0 as WavLMForAudioFrameClassification,S0 as WavLMForCTC,O0 as WavLMForSequenceClassification,I0 as WavLMForXVector,M0 as WavLMModel,Wr as WavLMPreTrainedModel,Uf as WeSpeakerFeatureExtractor,P0 as WeSpeakerResNetModel,eu as WeSpeakerResNetPreTrainedModel,Df as WhisperFeatureExtractor,ru as WhisperForConditionalGeneration,L0 as WhisperModel,fi as WhisperPreTrainedModel,Qm as WhisperProcessor,h2 as WhisperTextStreamer,Wl as WhisperTimeStampLogitsProcessor,kf as WhisperTokenizer,U0 as XLMForQuestionAnswering,$0 as XLMForSequenceClassification,B0 as XLMForTokenClassification,z0 as XLMModel,qr as XLMPreTrainedModel,F0 as XLMRobertaForMaskedLM,W0 as XLMRobertaForQuestionAnswering,j0 as XLMRobertaForSequenceClassification,G0 as XLMRobertaForTokenClassification,D0 as XLMRobertaModel,Vr as XLMRobertaPreTrainedModel,Ef as XLMRobertaTokenizer,Af as XLMTokenizer,R0 as XLMWithLMHeadModel,Zc as XVectorOutput,Im as YolosFeatureExtractor,V0 as YolosForObjectDetection,Nl as YolosImageProcessor,q0 as YolosModel,su as YolosObjectDetectionOutput,mi as YolosPreTrainedModel,X0 as YoutuForCausalLM,H0 as YoutuModel,hi as YoutuPreTrainedModel,Iu as ZeroShotAudioClassificationPipeline,Su as ZeroShotClassificationPipeline,Ru as ZeroShotImageClassificationPipeline,Bu as ZeroShotObjectDetectionPipeline,Ee as cat,UC as cos_sim,tk as dot,De as env,Ve as full,eo as full_like,Sd as interpolate,jt as interpolate_4d,E3 as layer_norm,XP as load_image,OL as load_video,Sp as log_softmax,ZE as matmul,dl as mean,eA as mean_pooling,it as ones,fl as ones_like,TP as permute,rre as pipeline,rA as quantize_embeddings,A3 as rand,tA as randn,Sf as read_audio,k3 as rfft,pl as slice,Pe as softmax,Gt as stack,Od as std_mean,Zt as topk,Cd as zeros,Pd as zeros_like};
|