1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[4803],{9911:(e,t,s)=>{s.d(t,{YOx:()=>ax,_K2:()=>$,oye:()=>od,rKH:()=>w9});var n,r,a,i,o,l=s(5645),c=s(7481),d=s(5704),u=Object.defineProperty,_=(e,t)=>{for(var s in t)u(e,s,{get:t[s],enumerable:!0})},h={},p={},m="undefined"!=typeof self,f=!B(h),g=!B(p),w=m&&"caches"in self;globalThis.Bun;var x=void 0!==globalThis.Deno&&w&&!f,y=void 0!==d,b=y&&d?.release?.name==="node"&&!x,M="undefined"!=typeof window&&void 0!==window.document,k=m&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),v=b||"undefined"!=typeof navigator&&"gpu"in navigator,E="undefined"!=typeof navigator&&"ml"in navigator,A="undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues,C="undefined"!=typeof chrome&&void 0!==chrome.runtime&&"string"==typeof chrome.runtime.id,F=Object.freeze({IS_BROWSER_ENV:M,IS_WEBWORKER_ENV:k,IS_WEB_ENV:M||k||x,IS_SERVICE_WORKER_ENV:"undefined"!=typeof ServiceWorkerGlobalScope&&m&&self instanceof ServiceWorkerGlobalScope,IS_DENO_WEB_RUNTIME:x,IS_WEB_CACHE_AVAILABLE:w,IS_WEBGPU_AVAILABLE:v,IS_WEBNN_AVAILABLE:E,IS_SAFARI:(()=>{if("undefined"==typeof navigator)return!1;let e=navigator.userAgent,t=(navigator.vendor||"").indexOf("Apple")>-1,s=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return t&&s})(),IS_PROCESS_AVAILABLE:y,IS_NODE_ENV:b,IS_FS_AVAILABLE:f,IS_PATH_AVAILABLE:g,IS_CRYPTO_AVAILABLE:A,IS_CHROME_AVAILABLE:C}),S=f&&g,T="./";if(S){let e=Object({}).url;e?T=p.dirname(p.dirname(({}).fileURLToPath(e))):"undefined"!=typeof __dirname&&(T=p.dirname(__dirname))}var P=S?p.join(T,"/.cache/"):null,z="/models/",L=S?p.join(T,z):z,O="function"==typeof globalThis.fetch?globalThis.fetch.bind(globalThis):void 0,I=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),N=I.WARNING,$={version:"4.2.0",backends:{onnx:{}},get logLevel(){return N},set logLevel(level){N=level,$.backends.onnx?.setLogLevel?.(level)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(M||k||x),localModelPath:L,useFS:f,useBrowserCache:w,useFSCache:f,cacheDir:P,useCustomCache:!1,customCache:null,useWasmCache:w||f,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:O};function B(e){return 0===Object.keys(e).length}var D=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(){throw Error("Must implement _call method in subclass")}},V=class extends D{constructor(e,t){super(),this.callback=e,this.files_loading=t}_call(e){if("progress"===e.status){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let t=Object.values(this.files_loading).reduce((e,t)=>e+t.loaded,0),s=Object.values(this.files_loading).reduce((e,t)=>e+t.total,0);this.callback({status:"progress_total",name:e.name,progress:s>0?t/s*100:0,loaded:t,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function q(e){return null==e||-1===e}function G(e){let t=[],s=e;for(;Array.isArray(s);)t.push(s.length),s=s[0];return t}function j(...e){return Array.prototype.concat.apply([],e)}function R(e,t){return Math.abs((e+t)%(2*t)-t)}function U(e,t){return Object.assign({},...t.map(t=>{if(void 0!==e[t])return{[t]:e[t]}}))}var W={error(...e){$.logLevel<=I.ERROR&&console.error(...e)},warn(...e){$.logLevel<=I.WARNING&&console.warn(...e)},info(...e){$.logLevel<=I.INFO&&console.log(...e)},debug(...e){$.logLevel<=I.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},Q=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let s of e){let e=t;for(let t=0;t<s.length;++t){let n=s[t];e=e[n]??=Object.create(null)}e.end=s}return t}split(e){let t=[],s=e.length,n=0,r=0;for(;r<s;){let a=this.trie,i=null,o=r;for(;o<s&&(a=a[e[o]]);)a.end&&(i=a.end),++o;i?(r>n&&t.push(e.slice(n,r)),t.push(i),r+=i.length,n=r):++r}return n<s&&t.push(e.slice(n)),t}},H=class{constructor(e){this.content=e.content,this.id=e.id,this.single_word=e.single_word??!1,this.lstrip=e.lstrip??!1,this.rstrip=e.rstrip??!1,this.special=e.special??!1,this.normalized=e.normalized??!this.special}},X=(()=>{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),s=0;for(let n=0;n<256;++n)e.includes(n)||(e.push(n),t.push(256+s),s+=1);let n=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,n[t]]))})(),J=Object.fromEntries(Object.entries(X).map(([e,t])=>[t,e])),K=".,!?â¦ãï¼ãà¥¤ÛØ",Y=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]|[v
1V][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${K}])]+`,` ?[^\\s${K}]+`]]),Z="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",ee=e=>e.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"),et=(e,t=!0)=>{if(void 0!==e.Regex){let t=e.Regex.replace(/\\([#&~])/g,"$1");for(let[e,s]of(t=t.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)"),Y))t=t.replaceAll(e,s);try{return RegExp(t,"gu")}catch(n){if(!(n instanceof SyntaxError)||!n.message.toLowerCase().includes("invalid property name"))throw n;let e=!1,s=t.replace(/(\\[pP])\{([^}=]+)\}/g,(t,s,n)=>{try{return RegExp(`\\p{${n}}`,"u"),`${s}{${n}}`}catch{return e=!0,`${s}{Script=${n}}`}});if(!e)throw n;try{return RegExp(s,"gu")}catch(e){throw n}}}if(void 0===e.String)return console.warn("Unknown pattern type:",e),null;{let s=es(e.String);return RegExp(t?s:`(${s})`,"gu")}},es=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),en=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,er=e=>{let t=0;for(let s of e)++t;return t},ea=(...e)=>Array.prototype.concat.apply([],e),ei=e=>new Map(Object.entries(e)),eo=e=>e.replace(/\p{M}/gu,""),el=(e,t,s=[])=>{if(!e||Array.isArray(e)||"object"!=typeof e)return`${t} must be a valid object`;for(let n of s)if(!(n in e))return`${t} must contain a "${n}" property`;return null},ec=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},ed=class extends ec{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},eu=class extends ed{tokenize_chinese_chars(e){let t=[];for(let s=0;s<e.length;++s){let n=e[s];en(n.charCodeAt(0))?(t.push(" "),t.push(n),t.push(" ")):t.push(n)}return t.join("")}strip_accents(e){return e.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(e){switch(e){case" ":case"\n":case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(e)}}clean_text(e){let t=[];for(let s of e){let e=s.charCodeAt(0);0===e||65533===e||this.is_control(s)||(/^\s$/.test(s)?t.push(" "):t.push(s))}return t.join("")}normalize(e){return this.config.clean_text&&(e=this.clean_text(e)),this.config.handle_chinese_chars&&(e=this.tokenize_chinese_chars(e)),this.config.lowercase?(e=e.toLowerCase(),!1!==this.config.strip_accents&&(e=this.strip_accents(e))):this.config.strip_accents&&(e=this.strip_accents(e)),e}},e_=class extends ed{constructor(e){super(e),this.charsmap=e.precompiled_charsmap??null}normalize(e){return e=(e=(e=e.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,"")).replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," ")).includes("ï½")?e.split("ï½").map(e=>e.normalize("NFKC")).join("ï½"):e.normalize("NFKC")}},eh=class extends ed{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>ev(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},ep=class extends ed{normalize(e){let t=et(this.config.pattern??{});return null===t?e:e.replaceAll(t,this.config.content??"")}},em=class extends ed{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form)}},ef=class extends em{constructor(){super(...arguments),this.form="NFC"}},eg=class extends em{constructor(){super(...arguments),this.form="NFD"}},ew=class extends em{constructor(){super(...arguments),this.form="NFKC"}},ex=class extends em{constructor(){super(...arguments),this.form="NFKD"}},ey=class extends ed{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},eb=class extends ed{normalize(e){return eo(e)}},eM=class extends ed{normalize(e){return e.toLowerCase()}}
1,ek=class extends ed{normalize(e){return e=this.config.prepend+e}},ev=function(e){if(null===e)return null;switch(e.type){case"BertNormalizer":return new eu(e);case"Precompiled":return new e_(e);case"Sequence":return new eh(e);case"Replace":return new ep(e);case"NFC":return new ef(e);case"NFD":return new eg(e);case"NFKC":return new ew(e);case"NFKD":return new ex(e);case"Strip":return new ey(e);case"StripAccents":return new eb(e);case"Lowercase":return new eM(e);case"Prepend":return new ek(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}},eE=class extends ec{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},eA=class extends eE{constructor(e){super(),this.config=e,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=X,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(""))}},eC=class extends eE{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},eF=class extends eE{constructor(e){super(),this.replacement=e.replacement??"â",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){let{section_index:s}=t??{},n=e.replaceAll(" ",this.str_rep);return n.startsWith(this.replacement)||"always"!==this.prepend_scheme&&("first"!==this.prepend_scheme||0!==s)||(n=this.str_rep+n),[n]}},eS=class extends eE{constructor(e){super(),this.config=e,this.pattern=et(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return null===this.pattern?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(e=>e):((e,t)=>{let s=[],n=0;for(let r of e.matchAll(t)){let t=r[0];n<r.index&&s.push(e.slice(n,r.index)),t.length>0&&s.push(t),n=r.index+t.length}return n<e.length&&s.push(e.slice(n)),s})(e,this.pattern)}},eT=class extends eE{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${Z}]+|[${Z}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},eP=class extends eE{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},ez=class extends eE{constructor(){super(),this.pattern=RegExp(`[^\\s${Z}]+|[${Z}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},eL=class extends eE{constructor(e){super(),this.config=e,this.pattern=et(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return null===this.pattern?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},eO=class extends eE{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>e$(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,s)=>s?s.pre_tokenize(e,t):e,[e])}},eI=class extends eE{pre_tokenize_text(e){return e.match(/\S+/g)||[]}},eN=class extends eE{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let s=0;s<e.length;s+=this._length)t.push(e.slice(s,s+this._length));return t}},e$=function(e){if(null===e)return null;switch(e.type){case"BertPreTokenizer":return new ez;case"Sequence":return new eO(e);case"Whitespace":return new eC;case"WhitespaceSplit":return new eI;case"Metaspace":return new eF(e);case"ByteLevel":return new eA(e);case"Split":return new eS(e);case"Punctuation":return new eT(e);case"Digits":return new eP(e);case"Replace":return new eL(e);
1case"FixedLength":return new eN(e);default:throw Error(`Unknown PreTokenizer type: ${e.type}`)}},eB=class extends ec{constructor(e){super(),this.config=e,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(e){let t=this.encode(e);return this.fuse_unk&&(t=((e,t,s)=>{let n=[],r=0;for(;r<e.length;){if(n.push(e[r]),(t.get(e[r])??s)!==s){++r;continue}for(;++r<e.length&&(t.get(e[r])??s)===s;)t.get(n.at(-1))!==s&&(n[n.length-1]+=e[r])}return n})(t,this.tokens_to_ids,this.unk_token_id)),t}},eD=class extends eB{constructor(e){for(let[t,s]of(super(e),this.max_input_chars_per_word=100,this.tokens_to_ids=ei(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.max_input_chars_per_word=e.max_input_chars_per_word??100,this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[s]=t}encode(e){let t=[];for(let s of e){let e=[...s];if(e.length>this.max_input_chars_per_word){t.push(this.unk_token);continue}let n=!1,r=0,a=[];for(;r<e.length;){let t=e.length,s=null;for(;r<t;){let n=e.slice(r,t).join("");if(r>0&&(n=this.config.continuing_subword_prefix+n),this.tokens_to_ids.has(n)){s=n;break}--t}if(null===s){n=!0;break}a.push(s),r=t}n?t.push(this.unk_token):t.push(...a)}return t}},eV=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,new Map)}},eq=class{constructor(){this.root=eV.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let s of e){let e=t.children.get(s);void 0===e&&(e=eV.default(),t.children.set(s,e)),t=e}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(void 0===t)return;let s="";for(let n of e){if(s+=n,void 0===(t=t.children.get(n)))return;t.is_leaf&&(yield s)}}},eG=class e{constructor(e,t,s,n,r){this.token_id=e,this.node_id=t,this.pos=s,this.length=n,this.score=r,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},ej=class{constructor(e,t,s){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=s,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let n=new eG(this.bos_token_id??0,0,0,0,0),r=new eG(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(n.clone()),this.nodes.push(r.clone()),this.begin_nodes[this.len].push(r),this.end_nodes[0].push(n)}insert(e,t,s,n){let r=new eG(n,this.nodes.length,e,t,s);this.begin_nodes[e].push(r),this.end_nodes[e+t].push(r),this.nodes.push(r)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(0==this.begin_nodes[t].length)return[];for(let e of this.begin_nodes[t]){e.prev=null;let s=0,n=null;for(let r of this.end_nodes[t]){let t=r.backtrace_score+e.score;(null===n||t>s)&&(n=r.clone(),s=t)}if(null===n)return[];e.prev=n,e.backtrace_score=s}++t}let s=[],n=this.begin_nodes[e][0].prev;if(null===n)return[];let r=n.clone();for(;null!==r.prev;)s.push(r.clone()),r=r.clone().prev.clone();return s.reverse(),s}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},eR=class extends eB{constructor(e,t){super(e);let s=e.vocab.length;this.vocab=Array(s),this.scores=Array(s);for(let t=0;t<s;++t)[this.vocab[t],this.scores[t]]=e.vocab[t];this.unk_token_id=e.unk_id,this.unk_token=this.vocab[e.unk_id],this.tokens_to_ids=new Map(this.vocab.map((e,t)=>[e,t])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=function(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],s=n);return[t,s]}(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new eq,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,s=0;for(;s<t.length;){let n=!1,r=[],a=t.slice(s).join("");for(let t of this.trie.common_prefix_search(a)){r.push(t);let a=this.tokens_to_ids.get(t),i=this.scores[a],o=er(t);e.insert(s,o,i,a),n||1!==o||(n=!0)}n||e.insert(s,1,this.unk_score,this.unk_token_id),s+=1}}tokenize(e){let t=new ej(e,this.bos_token_id,this.eos_token_id);return this.populate_nodes(t),t.tokens()}encode(e){let t=[];for(let s of e){let e=this.tokenize(s);t.push(...e)}return t}},eU=class{constructor(e=(e,t)=>e>t,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return 0===this.size}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size<this._max_size)this._heap.push(t),this._sift_up();else{let e=this._smallest();this._comparator(t,this._heap[e])&&(this._heap[e]=t,this._sift_up_from(e))}return this.size}pop(){let e=this.peek(),t=this.size-1;return t>0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let s=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=s}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)<this.size&&this._greater(this._left(e),e)||this._right(e)<this.size&&this._greater(this._right(e),e);){let t=this._right(e)<this.size&&this._greater(this._right(e),this._left(e))?this._right(e):this._left(e);this._swap(e,t),e=t}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},eW=class{constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}put(e,t){this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},eQ=class extends eB{constructor(e){for(let[t,s]of(super(e),this.tokens_to_ids=ei(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[s]=t;let t=Array.isArray(e.merges[0]);this.merges=t?e.merges:e.merges.map(e=>e.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.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 eW(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(0===e.length)return[];let t=this.cache.get(e);if(void 0!==t)return t;let s=Array.from(e);this.end_of_word_suffix&&(s[s.length-1]+=this.end_of_word_suffix);let n=[];if(s.length>1){let e=new eU((e,t)=>e.score<t.score),t={token:s[0],bias:0,prev:null,next:null},r=t;for(let t=1;t<s.length;++t){let n={bias:t/s.length,token:s[t],prev:r,next:null};r.next=n,this.add_node(e,r),r=n}for(;!e.is_empty();){let s=e.pop();if(s.deleted||!s.next||s.next.deleted)continue;if(s.deleted=!0,s.next.deleted=!0,s.prev){let e={...s.prev};s.prev.deleted=!0,s.prev=e,e.prev?e.prev.next=e:t=e}let n={token:s.token+s.next.token,bias:s.bias,prev:s.prev,next:s.next.next};n.prev?(n.prev.next=n,this.add_node(e,n.prev)):t=n,n.next&&(n.next.prev=n,this.add_node(e,n))}for(let e=t;null!==e;e=e.next)n.push(e.token)}else n=s;if(this.continuing_subword_suffix)for(let e=0;e<n.length-1;++e)n[e]+=this.continuing_subword_suffix;return e.length<this.max_length_to_cache&&this.cache.put(e,n),n}add_node(e,t){let s=this.bpe_ranks.get(JSON.stringify([t.token,t.next.token]));void 0!==s&&(t.score=s+t.bias,e.push(t))}encode(e){let t=[];for(let s of e){if(this.ignore_merges&&this.tokens_to_ids.has(s)){t.push(s);continue}for(let e of this.bpe(s))if(this.tokens_to_ids.has(e))t.push(e);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(e)).map(e=>`<0x${e.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(e=>this.tokens_to_ids.has(e))?t.push(...s):null!=this.unk_token&&t.pu
1sh(this.unk_token)}else null!=this.unk_token&&t.push(this.unk_token)}return t}},eH=class extends eB{constructor(e,t){super(e);let s=e.vocab;for(let[e,n]of(this.tokens_to_ids=ei(t.target_lang?s[t.target_lang]:s),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size),this.tokens_to_ids))this.vocab[n]=e}encode(e){return e}},eX=function(e,t){switch(e.type){case"WordPiece":return new eD(e);case"Unigram":return new eR(e,t.eos_token);case"BPE":return new eQ(e);default:if(e.vocab)if(Array.isArray(e.vocab))return new eR(e,t.eos_token);else if(!(Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")))return new eH(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});else if(Object.hasOwn(e,"merges"))return new eQ(e);else return new eD(e);throw Error(`Unknown TokenizerModel type: ${e?.type}`)}},eJ=class extends ec{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},eK=class extends eJ{post_process(e,t=null,s=!0){let n=null===t?this.config.single:this.config.pair,r=[],a=[];for(let i of n)"SpecialToken"in i?s&&(r.push(i.SpecialToken.id),a.push(i.SpecialToken.type_id)):"Sequence"in i&&("A"===i.Sequence.id?(r=ea(r,e),a=ea(a,Array(e.length).fill(i.Sequence.type_id))):"B"===i.Sequence.id&&(r=ea(r,t),a=ea(a,Array(t.length).fill(i.Sequence.type_id))));return{tokens:r,token_type_ids:a}}},eY=class extends eJ{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},eZ=class extends eJ{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,s=!0){s&&(e=ea([this.cls[0]],e,[this.sep[0]]));let n=Array(e.length).fill(0);if(t){let r=[],a=s?[this.sep[0]]:[];e=ea(e,r,t,a),n=ea(n,Array(t.length+r.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},e0=class extends eJ{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,s=!0){s&&(e=ea([this.cls[0]],e,[this.sep[0]]));let n=Array(e.length).fill(0);if(t){let r=s?[this.sep[0]]:[],a=s?[this.sep[0]]:[];e=ea(e,r,t,a),n=ea(n,Array(t.length+r.length+a.length).fill(1))}return{tokens:e,token_type_ids:n}}},e1=class extends eJ{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>e2(e))}post_process(e,t=null,s=!0){let n={tokens:e,tokens_pair:t};for(let e of this.processors)n=e.post_process(n.tokens,n.tokens_pair,s);return n}},e2=function(e){if(null===e)return null;switch(e.type){case"TemplateProcessing":return new eK(e);case"ByteLevel":return new eY(e);case"BertProcessing":return new eZ(e);case"RobertaProcessing":return new e0(e);case"Sequence":return new e1(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}},e3=class extends ec{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in e&&e.trim_offsets}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}},e4=class extends e3{constructor(e){super(e),this.byte_decoder=J,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=new Uint8Array([...e.join("")].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(t)}decode_chain(e){let t=[],s=[];for(let n of e)void 0!==this.added_tokens.find(e=>e.content===n)?(s.length>0&&(t.push(this.convert_tokens_to_string(s)),s=[]),t.push(n)):s.push(n);return s.length>0&&t.push(this.convert_tokens_to_string(s)),t}},e8=class extends e3{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(0!==t){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,""):" "+e}return this.cleanup&&(e=ee(e)),e})}},e6=class extends e3{constructor(e){super(e),this.replacement=e.replacement??"â"}decode_chain(e){let t=[];for(let s=0;s<e.length;++s){let n=e[s].replaceAll(this.replacement," ");0==s&&n.startsWith(" ")&&(n=n.substring(1)),t.push(n)}return t}}
1,e5=class extends e3{constructor(e){super(e),this.suffix=e.suffix??""}decode_chain(e){return e.map((t,s)=>t.replaceAll(this.suffix,s===e.length-1?"":" "))}},e9=class extends e3{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(0===e.length)return"";let t=[e[0]];for(let s=1;s<e.length;++s)e[s]!==t.at(-1)&&t.push(e[s]);let s=t.filter(e=>e!==this.pad_token).join("");return this.cleanup&&(s=ee(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}},e7=class extends e3{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>tr(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},te=class extends e3{decode_chain(e){let t=et(this.config.pattern),s=this.config.content??"";return null===t?e:e.map(e=>e.replaceAll(t,s))}},tt=class extends e3{decode_chain(e){return[e.join("")]}},ts=class extends e3{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let s=0;s<this.start;++s)if(e[s]===this.content){t=s+1;continue}else break;let s=e.length;for(let t=0;t<this.stop;++t){let n=e.length-t-1;if(e[n]===this.content){s=n;continue}break}return e.slice(t,s)})}},tn=class extends e3{constructor(e){super(e),this.text_decoder=new TextDecoder}decode_chain(e){let t=[],s=[];for(let n of e){let e=null;if(6===n.length&&n.startsWith("<0x")&&n.endsWith(">")){let t=parseInt(n.slice(3,5),16);isNaN(t)||(e=t)}if(null!==e)s.push(e);else{if(s.length>0){let e=this.text_decoder.decode(Uint8Array.from(s));t.push(e),s=[]}t.push(n)}}if(s.length>0){let e=this.text_decoder.decode(Uint8Array.from(s));t.push(e),s=[]}return t}},tr=function(e){if(null===e)return null;switch(e.type){case"ByteLevel":return new e4(e);case"WordPiece":return new e8(e);case"Metaspace":return new e6(e);case"BPEDecoder":return new e5(e);case"CTC":return new e9(e);case"Sequence":return new e7(e);case"Replace":return new te(e);case"Fuse":return new tt(e);case"Strip":return new ts(e);case"ByteFallback":return new tn(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}},ta=class{constructor(e,t){let s=el(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(s)throw Error(s);let n=el(t,"Config");if(n)throw Error(n);this.tokenizer=e,this.config=t,this.normalizer=ev(this.tokenizer.normalizer),this.pre_tokenizer=e$(this.tokenizer.pre_tokenizer),this.model=eX(this.tokenizer.model,this.config),this.post_processor=e2(this.tokenizer.post_processor),this.decoder=tr(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let r=[],a=[];for(let e of(this.added_tokens_map=new Map,this.tokenizer.added_tokens)){let t=new H(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&null!==this.normalizer){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else r.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),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 Q(r),this.splitter_normalized=new Q(a),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(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{tokens:r,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:s}),i=r.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),o={ids:i,tokens:r,attention_mask:Array(i.length).fill(1)};return n&&a&&(o.token_type_ids=a),o}decode(e,t={}){let s;if(!Array.isArray(e)||0===e.length||!(Number.isInteger(s=e[0])||"bigint"==typeof s))throw Error("token_ids must be a non-empty array of integers.");let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&
1(r=ee(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:s=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:s}).tokens}encode_text(e){if(null===e)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,s)=>{let n=this.added_tokens_map.get(e);n&&(n.lstrip&&s>0&&(t[s-1]=t[s-1].trimEnd()),n.rstrip&&s<t.length-1&&(t[s+1]=t[s+1].trimStart()))}),t.flatMap((e,t)=>{if(0===e.length)return[];if(this.added_tokens_map.has(e))return[e];if(!0===this.remove_space&&(e=e.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(e=eo(e.toLowerCase())),null!==this.normalizer&&(e=this.normalizer(e)),0===e.length)return[];let s=this.splitter_normalized.split(e);return s.forEach((e,t)=>{let n=this.added_tokens_map.get(e);n&&(n.lstrip&&t>0&&(s[t-1]=s[t-1].trimEnd()),n.rstrip&&t<s.length-1&&(s[t+1]=s[t+1].trimStart()))}),s.flatMap(e=>{if(0===e.length)return[];if(this.added_tokens_map.has(e))return[e];let s=null!==this.pre_tokenizer?this.pre_tokenizer(e,{section_index:t}):[e];return this.model(s)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:s=!0}){let n=this.encode_text(e),r=this.encode_text(t||null);return this.post_processor?this.post_processor(n,r,s):{tokens:ea(n??[],r??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let s=0;s<this.model.vocab.length;++s){let n=this.model.vocab[s];(e||!this.added_tokens_map.has(n))&&t.set(n,s)}return t}},ti=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"}),to=class{constructor(e,t){this.value=e,this.type=t}};function tl(e){return/\w/.test(e)}function tc(e){return/[0-9]/.test(e)}function td(e){return/\s/.test(e)}var tu=[["{%",ti.OpenStatement],["%}",ti.CloseStatement],["{{",ti.OpenExpression],["}}",ti.CloseExpression],["(",ti.OpenParen],[")",ti.CloseParen],["{",ti.OpenCurlyBracket],["}",ti.CloseCurlyBracket],["[",ti.OpenSquareBracket],["]",ti.CloseSquareBracket],[",",ti.Comma],[".",ti.Dot],[":",ti.Colon],["|",ti.Pipe],["<=",ti.ComparisonBinaryOperator],[">=",ti.ComparisonBinaryOperator],["==",ti.ComparisonBinaryOperator],["!=",ti.ComparisonBinaryOperator],["<",ti.ComparisonBinaryOperator],[">",ti.ComparisonBinaryOperator],["+",ti.AdditiveBinaryOperator],["-",ti.AdditiveBinaryOperator],["~",ti.AdditiveBinaryOperator],["*",ti.MultiplicativeBinaryOperator],["/",ti.MultiplicativeBinaryOperator],["%",ti.MultiplicativeBinaryOperator],["=",ti.Equals]],t_=new Map([["n","\n"],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]),th=class{type="Statement"},tp=class extends th{constructor(e){super(),this.body=e}type="Program"},tm=class extends th{constructor(e,t,s){super(),this.test=e,this.body=t,this.alternate=s}type="If"},tf=class extends th{constructor(e,t,s,n){super(),this.loopvar=e,this.iterable=t,this.body=s,this.defaultBlock=n}type="For"},tg=class extends th{type="Break"},tw=class extends th{type="Continue"},tx=class extends th{constructor(e,t,s){super(),this.assignee=e,this.value=t,this.body=s}type="Set"},ty=class extends th{constructor(e,t,s){super(),this.name=e,this.args=t,this.body=s}type="Macro"},tb=class extends th{constructor(e){super(),this.value=e}type="Comment"},tM=class extends th{type="Expression"},tk=class extends tM{constructor(e,t,s){super(),this.object=e,this.property=t,this.computed=s}type="MemberExpression"},tv=class extends tM{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},tE=class extends tM{constructor(e){super(),this.value=e}type="Identifier"},tA=class extends tM{constructor(e){super(),this.value=e}type="Literal"},tC=class extends tA{type="IntegerLiteral"},tF=class extends tA{type="FloatLiteral"},tS=class extends tA{type="StringLiteral"},tT=class extends tA{type="ArrayLiteral"},tP=class extends tA{type="TupleLiteral"},tz=class extends tA{type="ObjectLiteral"},tL=class extends tM{constructor(e,t,s){super(),this.operator=e,this.left=t,this.right=s}type="BinaryExpression"},tO=class extends tM{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},tI=class extends th{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},tN=class extends tM{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},t$=class extends tM{constructor(e,t,s){super(),this.operand=e,this.negate=t,this.test=s}type="TestExpression"},tB=class extends tM{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},tD=class extends tM{constructor(e,t,s){super(),this.start=e,this.stop=t,this.step=s}type="SliceExpression"},tV=class extends tM{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},tq=class extends tM{constructor(e){super(),this.argument=e}type="SpreadExpression"},tG=class extends th{constructor(e,t,s){super(),this.call=e,this.callerArgs=t,this.body=s}type="CallStatement"},tj=class extends tM{constructor(e,t,s){super(),this.condition=e,this.trueExpr=t,this.falseExpr=s}type="Ternary"};function tR(e,t,s=1){if(void 0===t&&(t=e,e=0),0===s)throw Error("range() step must not be zero");let n=[];if(s>0)for(let r=e;r<t;r+=s)n.push(r);else for(let r=e;r>t;r+=s)n.push(r);return n}function tU(e,t,s,n=1){let r=Math.sign(n);r>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),s=(s??=e.length)<0?Math.max(e.length+s,0):Math.min(s,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),s=(s??=-1)<-1?Math.max(e.length+s,-1):Math.min(s,e.length-1));let a=[];for(let i=t;r*i<r*s;i+=n)a.push(e[i]);return a}function tW(e){return function(e,t){let s=new Intl.DateTimeFormat(void 0,{month:"long"}),n=new Intl.DateTimeFormat(void 0,{month:"short"}),r=e=>e<10?"0"+e:e.toString();return t.replace(/%[YmdbBHM%]/g,t=>{switch(t){case"%Y":return e.getFullYear().toString();case"%m":return r(e.getMonth()+1);case"%d":return r(e.getDate());case"%b":return n.format(e);case"%B":return s.format(e);case"%H":return r(e.getHours());case"%M":return r(e.getMinutes());case"%%":return"%";default:return t}})}(new Date,e)}
1var tQ=class extends Error{},tH=class extends Error{},tX=class{type="RuntimeValue";value;builtins=new Map;constructor(e){this.value=e}__bool__(){return new tZ(!!this.value)}toString(){return String(this.value)}},tJ=class extends tX{type="IntegerValue"},tK=class extends tX{type="FloatValue";toString(){return this.value%1==0?this.value.toFixed(1):this.value.toString()}},tY=class extends tX{type="StringValue";builtins=new Map([["upper",new t5(()=>new tY(this.value.toUpperCase()))],["lower",new t5(()=>new tY(this.value.toLowerCase()))],["strip",new t5(()=>new tY(this.value.trim()))],["title",new t5(()=>new tY(this.value.replace(/\b\w/g,e=>e.toUpperCase())))],["capitalize",new t5(()=>new tY(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new tJ(this.value.length)],["rstrip",new t5(()=>new tY(this.value.trimEnd()))],["lstrip",new t5(()=>new tY(this.value.trimStart()))],["startswith",new t5(e=>{if(0===e.length)throw Error("startswith() requires at least one argument");let t=e[0];if(t instanceof tY)return new tZ(this.value.startsWith(t.value));if(t instanceof t8){for(let e of t.value){if(!(e instanceof tY))throw Error("startswith() tuple elements must be strings");if(this.value.startsWith(e.value))return new tZ(!0)}return new tZ(!1)}throw Error("startswith() argument must be a string or tuple of strings")})],["endswith",new t5(e=>{if(0===e.length)throw Error("endswith() requires at least one argument");let t=e[0];if(t instanceof tY)return new tZ(this.value.endsWith(t.value));if(t instanceof t8){for(let e of t.value){if(!(e instanceof tY))throw Error("endswith() tuple elements must be strings");if(this.value.endsWith(e.value))return new tZ(!0)}return new tZ(!1)}throw Error("endswith() argument must be a string or tuple of strings")})],["split",new t5(e=>{let t=e[0]??new t9;if(!(t instanceof tY||t instanceof t9))throw Error("sep argument must be a string or null");let s=e[1]??new tJ(-1);if(!(s instanceof tJ))throw Error("maxsplit argument must be a number");let n=[];if(t instanceof t9){let e=this.value.trimStart();for(let{0:t,index:r}of e.matchAll(/\S+/g)){if(-1!==s.value&&n.length>=s.value&&void 0!==r){n.push(t+e.slice(r+t.length));break}n.push(t)}}else{if(""===t.value)throw Error("empty separator");n=this.value.split(t.value),-1!==s.value&&n.length>s.value&&n.push(n.splice(s.value).join(t.value))}return new t8(n.map(e=>new tY(e)))})],["replace",new t5(e=>{let t;if(e.length<2)throw Error("replace() requires at least two arguments");let s=e[0],n=e[1];if(!(s instanceof tY&&n instanceof tY))throw Error("replace() arguments must be strings");if(!((t=e.length>2?"KeywordArgumentsValue"===e[2].type?e[2].value.get("count")??new t9:e[2]:new t9)instanceof tJ||t instanceof t9))throw Error("replace() count argument must be a number or null");return new tY(function(e,t,s,n){if(0===n)return e;let r=null==n||n<0?1/0:n,a=0===t.length?RegExp("(?=)","gu"):RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gu");return e.replaceAll(a,e=>r>0?(--r,s):e)}(this.value,s.value,n.value,t.value))})]])},tZ=class extends tX{type="BooleanValue"},t0=/[\x7f-\uffff]/g;function t1(e){return e.replace(t0,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function t2(e,t={},s=0,n=!0){let r,a,{indent:i=null,ensureAscii:o=!1,separators:l=null,sortKeys:c=!1}=t;switch(l?[r,a]=l:(r=i?",":", ",a=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return n?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let t=JSON.stringify(e.value);return o&&(t=t1(t)),t}case"ArrayValue":case"ObjectValue":{let l=i?" ".repeat(i):"",d="\n"+l.repeat(s),u=d+l;if("ArrayValue"===e.type){let a=e.value.map(e=>t2(e,t,s+1,n));return i?`[${u}${a.join(`${r}${u}`)}${d}]`:`[${a.join(r)}]`}{let l=Array.from(e.value.entries());c&&(l=l.sort(([e],[t])=>e.localeCompare(t)));let _=l.map(([e,r])=>{let l=JSON.stringify(e);o&&(l=t1(l));let c=`${l}${a}${t2(r,t,s+1,n)}`;return i?`${u}${c}`:c});return i?`{${_.join(r)}${d}}`:`{${_.join(r)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var t3=class extends tX{type="ObjectValue";__bool__(){return new tZ(this.value.size>0)}builtins=new Map([["get",new t5(([e,t])=>
1{if(!(e instanceof tY))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new t9})],["items",new t5(()=>this.items())],["keys",new t5(()=>this.keys())],["values",new t5(()=>this.values())],["dictsort",new t5(e=>{let t=new Map,s=e.filter(e=>!(e instanceof t4)||(t=e.value,!1)),n=s.at(0)??t.get("case_sensitive")??new tZ(!1);if(!(n instanceof tZ))throw Error("case_sensitive must be a boolean");let r=s.at(1)??t.get("by")??new tY("key");if(!(r instanceof tY))throw Error("by must be a string");if(!["key","value"].includes(r.value))throw Error("by must be either 'key' or 'value'");let a=s.at(2)??t.get("reverse")??new tZ(!1);if(!(a instanceof tZ))throw Error("reverse must be a boolean");let i=Array.from(this.value.entries()).map(([e,t])=>new t8([new tY(e),t])).sort((e,t)=>{let s=+("key"!==r.value),i=ss(e.value[s],t.value[s],n.value);return a.value?-i:i});return new t8(i)})]]);items(){return new t8(Array.from(this.value.entries()).map(([e,t])=>new t8([new tY(e),t])))}keys(){return new t8(Array.from(this.value.keys()).map(e=>new tY(e)))}
1values(){return new t8(Array.from(this.value.values()))}toString(){return t2(this,{},0,!1)}},t4=class extends t3{type="KeywordArgumentsValue"},t8=class extends tX{type="ArrayValue";builtins=new Map([["length",new tJ(this.value.length)]]);__bool__(){return new tZ(this.value.length>0)}toString(){return t2(this,{},0,!1)}},t6=class extends t8{type="TupleValue"},t5=class extends tX{type="FunctionValue"},t9=class extends tX{type="NullValue"},t7=class extends tX{type="UndefinedValue"},se=class{constructor(e){this.parent=e}variables=new Map([["namespace",new t5(e=>{if(0===e.length)return new t3(new Map);if(1!==e.length||!(e[0]instanceof t3))throw Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([["boolean",e=>"BooleanValue"===e.type],["callable",e=>e instanceof t5],["odd",e=>{if(!(e instanceof tJ))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],["even",e=>{if(!(e instanceof tJ))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],["false",e=>"BooleanValue"===e.type&&!e.value],["true",e=>"BooleanValue"===e.type&&e.value],["none",e=>"NullValue"===e.type],["string",e=>"StringValue"===e.type],["number",e=>e instanceof tJ||e instanceof tK],["integer",e=>e instanceof tJ],["iterable",e=>"ArrayValue"===e.type||"StringValue"===e.type],["mapping",e=>e instanceof t3],["sequence",e=>e instanceof t8||e instanceof t3||e instanceof tY],["lower",e=>{let t=e.value;return"StringValue"===e.type&&t===t.toLowerCase()}],["upper",e=>{let t=e.value;return"StringValue"===e.type&&t===t.toUpperCase()}],["none",e=>"NullValue"===e.type],["defined",e=>"UndefinedValue"!==e.type],["undefined",e=>"UndefinedValue"===e.type],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,function e(t){switch(typeof t){case"number":return Number.isInteger(t)?new tJ(t):new tK(t);case"string":return new tY(t);case"boolean":return new tZ(t);case"undefined":return new t7;case"object":if(null===t)return new t9;if(Array.isArray(t))return new t8(t.map(e));return new t3(new Map(Object.entries(t).map(([t,s])=>[t,e(s)])));case"function":return new t5((s,n)=>e(t(...s.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${t}`)}}(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new t7}catch{return new t7}}};function st(e,t){let s=t.split("."),n=e;for(let e of s)if(n instanceof t3)n=n.value.get(e)??new t7;else{if(!(n instanceof t8))return new t7;let t=parseInt(e,10);if(isNaN(t)||!(t>=0)||!(t<n.value.length))return new t7;n=n.value[t]}return n}function ss(e,t,s=!1){if(e instanceof t9&&t instanceof t9)return 0;if(e instanceof t9||t instanceof t9)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof t7&&t instanceof t7)return 0;if(e instanceof t7||t instanceof t7)throw Error(`Cannot compare ${e.type} with ${t.type}`);let n=e=>e instanceof tJ||e instanceof tK||e instanceof tZ,r=e=>e instanceof tZ?+!!e.value:e.value;if(n(e)&&n(t)){let s=r(e),n=r(t);return s<n?-1:+(s>n)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);if("StringValue"===e.type){let n=e.value,r=t.value;return s||(n=n.toLowerCase(),r=r.toLowerCase()),n<r?-1:+(n>r)}throw Error(`Cannot compare type: ${e.type}`)}var sn=class{global;constructor(e){this.global=e??new se}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let s=this.evaluate(e.left,t);switch(e.operator.value){case"and":return s.__bool__().value?this.evaluate(e.right,t):s;case"or":return s.__bool__().value?s:this.evaluate(e.right,t)}let n=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new tZ(s.value==n.value);case"!=":return new tZ(s.value!=n.value)}if(s instanceof t7||n instanceof t7){if(n instanceof t7&&["in","not in"].includes(e.operator.value))return new tZ("not in"===e.operator.value);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}if(s instanceof t9||n instanceof t9)throw Error("Cannot perform operation on null values");if("~"===e.operator.value)return new tY(s.value.toString()+n.value.toString());if((s instanceof tJ||s instanceof tK)&&(n instanceof tJ||n instanceof tK)){let t=s.value,r=n.value;switch(e.operator.value){case"+":case"-":case"*":{let a="+"===e.operator.value?t+r:"-"===e.operator.value?t-r:t*r;return s instanceof tK||n instanceof tK?new tK(a):new tJ(a)}case"/":return new tK(t/r);case"%":{let e=t%r;return s instanceof tK||n instanceof tK?new tK(e):new tJ(e)}case"<":return new tZ(t<r);case">":return new tZ(t>r);case">=":return new tZ(t>=r);case"<=":return new tZ(t<=r)}}else if(s instanceof t8&&n instanceof t8){if("+"===e.operator.value)return new t8(s.value.concat(n.value))}else if(n instanceof t8){let t=void 0!==n.value.find(e=>e.value===s.value);switch(e.operator.value){case"in":return new tZ(t);case"not in":return new tZ(!t)}}if((s instanceof tY||n instanceof tY)&&"+"===e.operator.value)return new tY(s.value.toString()+n.value.toString());if(s instanceof tY&&n instanceof tY)switch(e.operator.value){case"in":return new tZ(n.value.includes(s.value));case"not in":return new tZ(!n.value.includes(s.value))}if(s instanceof tY&&n instanceof t3)switch(e.operator.value){case"in":return new tZ(n.value.has(s.value));case"not in":return new tZ(!n.value.has(s.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${s.type} and ${n.type}`)}evaluateArguments(e,t){let s=[],n=new Map;for(let r of e)if("SpreadExpression"===r.type){let e=this.evaluate(r.argument,t);if(!(e instanceof t8))throw Error(`Cannot unpack non-iterable type: ${e.type}`);for(let t of e.value)s.push(t)}else if("KeywordArgumentExpression"===r.type)n.set(r.key.value,this.evaluate(r.value,t));else{if(n.size>0)throw Error("Positional arguments must come before keyword arguments");s.push(this.evaluate(r,t))}return[s,n]}applyFilter(e,t,s){if("Identifier"===t.type){if("safe"===t.value)return e;if("tojson"===t.value)return new tY(t2(e,{}));if(e instanceof t8)switch(t.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new tJ(e.value.length);case"reverse":return new t8(e.value.slice().reverse());case"sort":return new t8(e.value.slice().sort((e,t)=>
1ss(e,t,!1)));case"join":return new tY(e.value.map(e=>e.value).join(""));case"string":return new tY(t2(e,{},0,!1));case"unique":{let t=new Set,s=[];for(let n of e.value)t.has(n.value)||(t.add(n.value),s.push(n));return new t8(s)}default:throw Error(`Unknown ArrayValue filter: ${t.value}`)}if(e instanceof tY)switch(t.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=e.builtins.get(t.value);if(n instanceof t5)return n.value([],s);if(n instanceof tJ)return n;throw Error(`Unknown StringValue filter: ${t.value}`)}case"trim":return new tY(e.value.trim());case"indent":return new tY(e.value.split("\n").map((e,t)=>0===t||0===e.length?e:" "+e).join("\n"));case"join":case"string":return e;case"int":{let t=parseInt(e.value,10);return new tJ(isNaN(t)?0:t)}case"float":{let t=parseFloat(e.value);return new tK(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${t.value}`)}if(e instanceof tJ||e instanceof tK)switch(t.value){case"abs":return e instanceof tJ?new tJ(Math.abs(e.value)):new tK(Math.abs(e.value));case"int":return new tJ(Math.floor(e.value));case"float":return new tK(e.value);case"string":return new tY(e.toString());default:throw Error(`Unknown NumericValue filter: ${t.value}`)}else if(e instanceof t3)switch(t.value){case"items":return new t8(Array.from(e.value.entries()).map(([e,t])=>new t8([new tY(e),t])));case"length":return new tJ(e.value.size);default:{let n=e.builtins.get(t.value);if(n){if(n instanceof t5)return n.value([],s);return n}throw Error(`Unknown ObjectValue filter: ${t.value}`)}}else if(e instanceof tZ)switch(t.value){case"bool":return new tZ(e.value);case"int":return new tJ(+!!e.value);case"float":return new tK(+!!e.value);case"string":return new tY(e.value?"true":"false");default:throw Error(`Unknown BooleanValue filter: ${t.value}`)}throw Error(`Cannot apply filter "${t.value}" to type: ${e.type}`)}if("CallExpression"===t.type){if("Identifier"!==t.callee.type)throw Error(`Unknown filter: ${t.callee.type}`);let n=t.callee.value;if("tojson"===n){let[,n]=this.evaluateArguments(t.args,s),r=n.get("indent")??new t9;if(!(r instanceof tJ||r instanceof t9))throw Error("If set, indent must be a number");let a=n.get("ensure_ascii")??new tZ(!1);if(!(a instanceof tZ))throw Error("If set, ensure_ascii must be a boolean");let i=n.get("sort_keys")??new tZ(!1);if(!(i instanceof tZ))throw Error("If set, sort_keys must be a boolean");let o=n.get("separators")??new t9,l=null;if(o instanceof t8||o instanceof t6){if(2!==o.value.length)throw Error("separators must be a tuple of two strings");let[e,t]=o.value;if(!(e instanceof tY)||!(t instanceof tY))throw Error("separators must be a tuple of two strings");l=[e.value,t.value]}else if(!(o instanceof t9))throw Error("If set, separators must be a tuple of two strings");return new tY(t2(e,{indent:r.value,ensureAscii:a.value,sortKeys:i.value,separators:l}))}if("join"===n){let r;if(e instanceof tY)r=Array.from(e.value);else if(e instanceof t8)r=e.value.map(e=>e.value);else throw Error(`Cannot apply filter "${n}" to type: ${e.type}`);let[a,i]=this.evaluateArguments(t.args,s),o=a.at(0)??i.get("separator")??new tY("");if(!(o instanceof tY))throw Error("separator must be a string");return new tY(r.join(o.value))}if("int"===n||"float"===n){let[r,a]=this.evaluateArguments(t.args,s),i=r.at(0)??a.get("default")??("int"===n?new tJ(0):new tK(0));if(e instanceof tY){let t="int"===n?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?i:"int"===n?new tJ(t):new tK(t)}if(e instanceof tJ||e instanceof tK)return e;if(e instanceof tZ)return"int"===n?new tJ(+!!e.value):new tK(+!!e.value);else throw Error(`Cannot apply filter "${n}" to type: ${e.type}`)}else if("default"===n){let[n,r]=this.evaluateArguments(t.args,s),a=n[0]??new tY(""),i=n[1]??r.get("boolean")??new tZ(!1);if(!(i instanceof tZ))throw Error("`default` filter flag must be a boolean");return e instanceof t7||i.value&&!e.__bool__().value?a:e}if(e instanceof t8){switch(n){case"sort":{let[n,r]=this.evaluateArguments(t.args,s),a=n.at(0)??r.get("reverse")??new tZ(!1);if(!(a instanceof tZ))throw Error("reverse must be a boolean");
1let i=n.at(1)??r.get("case_sensitive")??new tZ(!1);if(!(i instanceof tZ))throw Error("case_sensitive must be a boolean");let o=n.at(2)??r.get("attribute")??new t9;if(!(o instanceof tY||o instanceof tJ||o instanceof t9))throw Error("attribute must be a string, integer, or null");let l=e=>o instanceof t9?e:st(e,o instanceof tJ?String(o.value):o.value);return new t8(e.value.slice().sort((e,t)=>{let s=ss(l(e),l(t),i.value);return a.value?-s:s}))}case"selectattr":case"rejectattr":{let r,a="selectattr"===n;if(e.value.some(e=>!(e instanceof t3)))throw Error(`\`${n}\` can only be applied to array of objects`);if(t.args.some(e=>"StringLiteral"!==e.type))throw Error(`arguments of \`${n}\` must be strings`);let[i,o,l]=t.args.map(e=>this.evaluate(e,s));if(o){let e=s.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);r=e}else r=(...e)=>e[0].__bool__().value;return new t8(e.value.filter(e=>{let t=e.value.get(i.value),s=!!t&&r(t,l);return a?s:!s}))}case"map":{let[,n]=this.evaluateArguments(t.args,s);if(n.has("attribute")){let t=n.get("attribute");if(!(t instanceof tY))throw Error("attribute must be a string");let s=n.get("default");return new t8(e.value.map(e=>{if(!(e instanceof t3))throw Error("items in map must be an object");let n=st(e,t.value);return n instanceof t7?s??new t7:n}))}throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${n}`)}if(e instanceof tY){switch(n){case"indent":{let[n,r]=this.evaluateArguments(t.args,s),a=n.at(0)??r.get("width")??new tJ(4);if(!(a instanceof tJ))throw Error("width must be a number");let i=n.at(1)??r.get("first")??new tZ(!1),o=n.at(2)??r.get("blank")??new tZ(!1),l=e.value.split("\n"),c=" ".repeat(a.value);return new tY(l.map((e,t)=>(i.value||0!==t)&&(o.value||0!==e.length)?c+e:e).join("\n"))}case"replace":{let n=e.builtins.get("replace");if(!(n instanceof t5))throw Error("replace filter not available");let[r,a]=this.evaluateArguments(t.args,s);return n.value([...r,new t4(a)],s)}}throw Error(`Unknown StringValue filter: ${n}`)}if(e instanceof t3){let r=e.builtins.get(n);if(r&&r instanceof t5){let[e,n]=this.evaluateArguments(t.args,s);return n.size>0&&e.push(new t4(n)),r.value(e,s)}throw Error(`Unknown ObjectValue filter: ${n}`)}else throw Error(`Cannot apply filter "${n}" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let s=this.evaluate(e.operand,t);return this.applyFilter(s,e.filter,t)}evaluateTestExpression(e,t){let s=this.evaluate(e.operand,t),n=t.tests.get(e.test.value);if(!n)throw Error(`Unknown test: ${e.test.value}`);let r=n(s);return new tZ(e.negate?!r:r)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new t7}evaluateUnaryExpression(e,t){let s=this.evaluate(e.argument,t);if("not"===e.operator.value)return new tZ(!s.value);throw SyntaxError(`Unknown operator: ${e.operator.value}`)}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let s="";for(let n of e){let e=this.evaluate(n,t);"NullValue"!==e.type&&"UndefinedValue"!==e.type&&(s+=e.toString())}return new tY(s)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[s,n]=this.evaluateArguments(e.args,t);n.size>0&&s.push(new t4(n));let r=this.evaluate(e.callee,t);if("FunctionValue"!==r.type)throw Error(`Cannot call something that is not a function: got ${r.type}`);return r.value(s,t)}evaluateSliceExpression(e,t,s){if(!(e instanceof t8||e instanceof tY))throw Error("Slice object must be an array or string");let n=this.evaluate(t.start,s),r=this.evaluate(t.stop,s),a=this.evaluate(t.step,s);if(!(n instanceof tJ||n instanceof t7))throw Error("Slice start must be numeric or undefined");if(!(r instanceof tJ||r instanceof t7))throw Error("Slice stop must be numeric or undefined");if(!(a instanceof tJ||a instanceof t7))throw Error("Slice step must be numeric or undefined");return e instanceof t8?new t8(tU(e.value,n.value,r.value,a.value)):new tY(tU(Array.from(e.value),n.value,r.value,a.value).join(""))}evaluateMemberExpression(e,t){let s,n,r=this.evaluate(e.object,t);if(e.computed)if("SliceExpression"===e.property.type)return this.evaluateSliceExpression(r,e.property,t);else s=this.evaluate(e.property,t);else s=new tY(e.property.value);if(r instanceof t3){if(!(s instanceof tY))throw Error(`Cannot access property with non-string: got ${s.type}`);
1n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof t8||r instanceof tY)if(s instanceof tJ)n=r.value.at(s.value),r instanceof tY&&(n=new tY(r.value.at(s.value)));else if(s instanceof tY)n=r.builtins.get(s.value);else throw Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof tY))throw Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof tX?n:new t7}evaluateSet(e,t){let s=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if("Identifier"===e.assignee.type){let n=e.assignee.value;t.setVariable(n,s)}else if("TupleLiteral"===e.assignee.type){let n=e.assignee;if(!(s instanceof t8))throw Error(`Cannot unpack non-iterable type in set: ${s.type}`);let r=s.value;if(r.length!==n.value.length)throw Error(`Too ${n.value.length>r.length?"few":"many"} items to unpack in set`);for(let e=0;e<n.value.length;++e){let s=n.value[e];if("Identifier"!==s.type)throw Error(`Cannot unpack to non-identifier in set: ${s.type}`);t.setVariable(s.value,r[e])}}else if("MemberExpression"===e.assignee.type){let n=e.assignee,r=this.evaluate(n.object,t);if(!(r instanceof t3))throw Error("Cannot assign to member of non-object");if("Identifier"!==n.property.type)throw Error("Cannot assign to member with non-identifier property");r.value.set(n.property.value,s)}else throw Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new t9}evaluateIf(e,t){let s=this.evaluate(e.test,t);return this.evaluateBlock(s.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){let s,n,r=new se(t);if("SelectExpression"===e.iterable.type){let t=e.iterable;n=this.evaluate(t.lhs,r),s=t.test}else n=this.evaluate(e.iterable,r);if(!(n instanceof t8||n instanceof t3))throw Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof t3&&(n=n.keys());let a=[],i=[];for(let t=0;t<n.value.length;++t){let o,l=new se(r),c=n.value[t];if("Identifier"===e.loopvar.type)o=t=>t.setVariable(e.loopvar.value,c);else if("TupleLiteral"===e.loopvar.type){let t=e.loopvar;if("ArrayValue"!==c.type)throw Error(`Cannot unpack non-iterable type: ${c.type}`);if(t.value.length!==c.value.length)throw Error(`Too ${t.value.length>c.value.length?"few":"many"} items to unpack`);o=e=>{for(let s=0;s<t.value.length;++s){if("Identifier"!==t.value[s].type)throw Error(`Cannot unpack non-identifier type: ${t.value[s].type}`);e.setVariable(t.value[s].value,c.value[s])}}}else throw Error(`Invalid loop variable(s): ${e.loopvar.type}`);(!s||(o(l),this.evaluate(s,l).__bool__().value))&&(a.push(c),i.push(o))}let o="",l=!0;for(let t=0;t<a.length;++t){let s=new Map([["index",new tJ(t+1)],["index0",new tJ(t)],["revindex",new tJ(a.length-t)],["revindex0",new tJ(a.length-t-1)],["first",new tZ(0===t)],["last",new tZ(t===a.length-1)],["length",new tJ(a.length)],["previtem",t>0?a[t-1]:new t7],["nextitem",t<a.length-1?a[t+1]:new t7]]);r.setVariable("loop",new t3(s)),i[t](r);try{let t=this.evaluateBlock(e.body,r);o+=t.value}catch(e){if(e instanceof tH)continue;if(e instanceof tQ)break;throw e}l=!1}return l&&(o+=this.evaluateBlock(e.defaultBlock,r).value),new tY(o)}evaluateMacro(e,t){return t.setVariable(e.name.value,new t5((t,s)=>{let n,r=new se(s);t=t.slice(),t.at(-1)?.type==="KeywordArgumentsValue"&&(n=t.pop());for(let s=0;s<e.args.length;++s){let a=e.args[s],i=t[s];if("Identifier"===a.type){if(!i)throw Error(`Missing positional argument: ${a.value}`);r.setVariable(a.value,i)}else if("KeywordArgumentExpression"===a.type){let e=i??n?.value.get(a.key.value)??this.evaluate(a.value,r);r.setVariable(a.key.value,e)}else throw Error(`Unknown argument type: ${a.type}`)}return this.evaluateBlock(e.body,r)})),new t9}evaluateCallStatement(e,t){let s=new t5((t,s)=>{let n=new se(s);if(e.callerArgs)for(let s=0;s<e.callerArgs.length;++s){let r=e.callerArgs[s];if("Identifier"!==r.type)throw Error(`Caller parameter must be an identifier, got ${r.type}`);n.setVariable(r.value,t[s]??new t7)}return this.evaluateBlock(e.body,n)}),[n,r]=this.evaluateArguments(e.call.args,t);n.push(new t4(r));let a=this.evaluate(e.call.callee,t);if("FunctionValue"!==a.type)throw Error(`Cannot call something that is not a function: got ${a.type}`);let i=new se(t);
1return i.setVariable("caller",s),a.value(n,i)}evaluateFilterStatement(e,t){let s=this.evaluateBlock(e.body,t);return this.applyFilter(s,e.filter,t)}evaluate(e,t){if(!e)return new t7;switch(e.type){case"Program":return this.evalProgram(e,t);case"Set":return this.evaluateSet(e,t);case"If":return this.evaluateIf(e,t);case"For":return this.evaluateFor(e,t);case"Macro":return this.evaluateMacro(e,t);case"CallStatement":return this.evaluateCallStatement(e,t);case"Break":throw new tQ;case"Continue":throw new tH;case"IntegerLiteral":return new tJ(e.value);case"FloatLiteral":return new tK(e.value);case"StringLiteral":return new tY(e.value);case"ArrayLiteral":return new t8(e.value.map(e=>this.evaluate(e,t)));case"TupleLiteral":return new t6(e.value.map(e=>this.evaluate(e,t)));case"ObjectLiteral":{let s=new Map;for(let[n,r]of e.value){let e=this.evaluate(n,t);if(!(e instanceof tY))throw Error(`Object keys must be strings: got ${e.type}`);s.set(e.value,this.evaluate(r,t))}return new t3(s)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new t9;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function sr(...e){return"{%- "+e.join(" ")+" -%}"}function sa(e,t=-1){switch(e.type){case"SpreadExpression":return`*${sa(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":case"FloatLiteral":return`${e.value}`;case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{let s=function(e){switch(e.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":if("and"===e.operator.value)return 1;if("in"===e.operator.value||"not in"===e.operator.value)return 2}return 0}(e),n=sa(e.left,s),r=sa(e.right,s+1),a=`${n} ${e.operator.value} ${r}`;return s<t?`(${a})`:a}case"UnaryExpression":return e.operator.value+("not"===e.operator.value?" ":"")+sa(e.argument,1/0);case"CallExpression":{let t=e.args.map(sa).join(", ");return`${sa(e.callee)}(${t})`}case"MemberExpression":{let t=sa(e.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(e.object.type)||(t=`(${t})`);let s=sa(e.property);return e.computed||"Identifier"===e.property.type||(s=`(${s})`),e.computed?`${t}[${s}]`:`${t}.${s}`}case"FilterExpression":{let t=sa(e.operand,1/0);if("CallExpression"===e.filter.type)return`${t} | ${sa(e.filter)}`;return`${t} | ${e.filter.value}`}case"SelectExpression":return`${sa(e.lhs)} if ${sa(e.test)}`;case"TestExpression":return`${sa(e.operand)} is${e.negate?" not":""} ${e.test.value}`;case"ArrayLiteral":case"TupleLiteral":{let t=e.value.map(sa),s="ArrayLiteral"===e.type?"[]":"()";return`${s[0]}${t.join(", ")}${s[1]}`}case"ObjectLiteral":{let t=Array.from(e.value.entries()).map(([e,t])=>`${sa(e)}: ${sa(t)}`);return`{${t.join(", ")}}`}case"SliceExpression":{let t=e.start?sa(e.start):"",s=e.stop?sa(e.stop):"",n=e.step?`:${sa(e.step)}`:"";return`${t}:${s}${n}`}case"KeywordArgumentExpression":return`${e.key.value}=${sa(e.value)}`;case"Ternary":{let s=`${sa(e.trueExpr)} if ${sa(e.condition,0)} else ${sa(e.falseExpr)}`;return t>-1?`(${s})`:s}default:throw Error(`Unknown expression type: ${e.type}`)}}var si=class{parsed;constructor(e){let t=function(e,t={}){let s=[],n=function(e,t={}){return e.endsWith("\n")&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}(e,t),r=0,a=0,i=e=>{let t="";for(;e(n[r]);){if("\\"===n[r]){if(++r>=n.length)throw SyntaxError("Unexpected end of input");let e=n[r++],s=t_.get(e);if(void 0===s)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=s;continue}if(t+=n[r++],r>=n.length)throw SyntaxError("Unexpected end of input")}return t},o=()=>{let e=s.at(-1);e&&e.type===ti.Text&&(e.value=e.value.trimEnd(),""===e.value&&s.pop())},l=()=>{for(;r<n.length&&td(n[r]);)++r};e:for(;r<n.length;){let e=s.at(-1)?.type;
1if(void 0===e||e===ti.CloseStatement||e===ti.CloseExpression||e===ti.Comment){let e="";for(;r<n.length&&("{"!==n[r]||"%"!==n[r+1]&&"{"!==n[r+1]&&"#"!==n[r+1]);)e+=n[r++];if(e.length>0){s.push(new to(e,ti.Text));continue}}if("{"===n[r]&&"#"===n[r+1]){let e="-"===n[r+=2];e&&++r;let t="";for(;"#"!==n[r]||"}"!==n[r+1];){if(r+2>=n.length)throw SyntaxError("Missing end of comment tag");t+=n[r++]}let a=t.endsWith("-");a&&(t=t.slice(0,-1)),e&&o(),s.push(new to(t,ti.Comment)),r+=2,a&&l();continue}if("{%-"===n.slice(r,r+3)){o(),s.push(new to("{%",ti.OpenStatement)),r+=3;continue}if("{{-"===n.slice(r,r+3)){o(),s.push(new to("{{",ti.OpenExpression)),a=0,r+=3;continue}if(i(td),"-%}"===n.slice(r,r+3)){s.push(new to("%}",ti.CloseStatement)),r+=3,l();continue}if("-}}"===n.slice(r,r+3)){s.push(new to("}}",ti.CloseExpression)),r+=3,l();continue}let t=n[r];if("-"===t||"+"===t){let e=s.at(-1)?.type;if(e===ti.Text||void 0===e)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case ti.Identifier:case ti.NumericLiteral:case ti.StringLiteral:case ti.CloseParen:case ti.CloseSquareBracket:break;default:{++r;let e=i(tc);s.push(new to(`${t}${e}`,e.length>0?ti.NumericLiteral:ti.UnaryOperator));continue}}}for(let[e,t]of tu)if(("}}"!==e||!(a>0))&&n.slice(r,r+e.length)===e){s.push(new to(e,t)),t===ti.OpenExpression?a=0:t===ti.OpenCurlyBracket?++a:t===ti.CloseCurlyBracket&&--a,r+=e.length;continue e}if("'"===t||'"'===t){++r;let e=i(e=>e!==t);s.push(new to(e,ti.StringLiteral)),++r;continue}if(tc(t)){let e=i(tc);if("."===n[r]&&tc(n[r+1])){++r;let t=i(tc);e=`${e}.${t}`}s.push(new to(e,ti.NumericLiteral));continue}if(tl(t)){let e=i(tl);s.push(new to(e,ti.Identifier));continue}throw SyntaxError(`Unexpected character: ${t}`)}return s}(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=function(e){let t=new tp([]),s=0;function n(t,n){let r=e[s++];if(!r||r.type!==t)throw Error(`Parser Error: ${n}. ${r.type} !== ${t}.`);return r}function r(e){if(!o(e))throw SyntaxError(`Expected ${e}`);++s}function a(...t){return s+t.length<=e.length&&t.every((t,n)=>t===e[s+n].type)}function i(...t){return e[s]?.type===ti.OpenStatement&&e[s+1]?.type===ti.Identifier&&t.includes(e[s+1]?.value)}function o(...t){return s+t.length<=e.length&&t.every((t,n)=>"Identifier"===e[s+n].type&&t===e[s+n].value)}function l(e=!1){let t=e?x:c,n=[t()],r=a(ti.Comma);for(;r&&(++s,n.push(t()),a(ti.Comma)););return r?new tP(n):n[0]}function c(){return function e(){let t=d();if(o("if")){++s;let n=d();return o("else")?(++s,new tj(n,t,e())):new tN(t,n)}return t}()}function d(){let t=u();for(;o("or");){let n=e[s];++s,t=new tL(n,t,u())}return t}function u(){let t=_();for(;o("and");){let n=e[s];++s,t=new tL(n,t,_())}return t}function _(){let t;for(;o("not");){let n=e[s];++s,t=new tB(n,_())}return t??function(){let t=h();for(;;){let n;if(o("not","in"))n=new to("not in",ti.Identifier),s+=2;else if(o("in"))n=e[s++];else if(a(ti.ComparisonBinaryOperator))n=e[s++];else break;t=new tL(n,t,h())}return t}()}function h(){let t=g();for(;a(ti.AdditiveBinaryOperator);){let n=e[s];++s,t=new tL(n,t,g())}return t}function p(e){let t=new tv(e,m());return t=f(t),a(ti.OpenParen)&&(t=p(t)),t}function m(){n(ti.OpenParen,"Expected opening parenthesis for arguments list");let t=function(){let t=[];for(;!a(ti.CloseParen);){let n;if(e[s].type===ti.MultiplicativeBinaryOperator&&"*"===e[s].value)++s,n=new tq(c());else if(n=c(),a(ti.Equals)){if(++s,!(n instanceof tE))throw SyntaxError("Expected identifier for keyword argument");n=new tV(n,c())}t.push(n),a(ti.Comma)&&++s}return t}();return n(ti.CloseParen,"Expected closing parenthesis for arguments list"),t}function f(t){for(;a(ti.Dot)||a(ti.OpenSquareBracket);){let r,i=e[s];++s;let o=i.type===ti.OpenSquareBracket;if(o)r=function(){let e=[],t=!1;for(;!a(ti.CloseSquareBracket);)a(ti.Colon)?(e.push(void 0),++s,t=!0):(e.push(c()),a(ti.Colon)&&(++s,t=!0));if(0===e.length)throw SyntaxError("Expected at least one argument for member/slice expression");if(t){if(e.length>3)throw SyntaxError("Expected 0-3 arguments for slice expression");return new tD(...e)}return e[0]}(),n(ti.CloseSquareBracket,"Expected closing square bracket");else if("Identifier"!==(r=x()).type)throw SyntaxError("Expected identifier following dot operator");t=new tk(t,r,o)}return t}function g(){let t=w();for(;a(ti.MultiplicativeBinaryOperator);)t=new tL(e[s++],t,w());return t}function w(){let e=function(){let e=function(){let e=f(x());return a(ti.OpenParen)?p(e):e}();for(;a(ti.Pipe);){++s;let t=x();if(!(t instanceof tE))throw SyntaxError("Expected identifier for the filter");a(ti.OpenParen)&&(t=p(t)),e=new tO(e,t)}return e}();for(;o("is");){++s;
1let t=o("not");t&&++s;let n=x();if(!(n instanceof tE))throw SyntaxError("Expected identifier for the test");e=new t$(e,t,n)}return e}function x(){let t=e[s++];switch(t.type){case ti.NumericLiteral:{let e=t.value;return e.includes(".")?new tF(Number(e)):new tC(Number(e))}case ti.StringLiteral:{let n=t.value;for(;a(ti.StringLiteral);)n+=e[s++].value;return new tS(n)}case ti.Identifier:return new tE(t.value);case ti.OpenParen:{let e=l();return n(ti.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),e}case ti.OpenSquareBracket:{let e=[];for(;!a(ti.CloseSquareBracket);)e.push(c()),a(ti.Comma)&&++s;return++s,new tT(e)}case ti.OpenCurlyBracket:{let e=new Map;for(;!a(ti.CloseCurlyBracket);){let t=c();n(ti.Colon,"Expected colon between key and value in object literal");let r=c();e.set(t,r),a(ti.Comma)&&++s}return++s,new tz(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;s<e.length;)t.body.push(function t(){switch(e[s].type){case ti.Comment:return new tb(e[s++].value);case ti.Text:return new tS(n(ti.Text,"Expected text token").value);case ti.OpenStatement:return function(){let d;if(n(ti.OpenStatement,"Expected opening statement token"),e[s].type!==ti.Identifier)throw SyntaxError(`Unknown statement, got ${e[s].type}`);let u=e[s].value;switch(u){case"set":++s,d=function(){let e=l(),o=null,c=[];if(a(ti.Equals))++s,o=l();else{for(n(ti.CloseStatement,"Expected %} token");!i("endset");)c.push(t());n(ti.OpenStatement,"Expected {% token"),r("endset")}return n(ti.CloseStatement,"Expected closing statement token"),new tx(e,o,c)}();break;case"if":++s,d=function e(){let r=c();n(ti.CloseStatement,"Expected closing statement token");let a=[],o=[];for(;!i("elif","else","endif");)a.push(t());if(i("elif")){++s,++s;let t=e();o.push(t)}else if(i("else"))for(++s,++s,n(ti.CloseStatement,"Expected closing statement token");!i("endif");)o.push(t());return new tm(r,a,o)}(),n(ti.OpenStatement,"Expected {% token"),r("endif"),n(ti.CloseStatement,"Expected %} token");break;case"macro":++s,d=function(){let e=x();if("Identifier"!==e.type)throw SyntaxError("Expected identifier following macro statement");let s=m();n(ti.CloseStatement,"Expected closing statement token");let r=[];for(;!i("endmacro");)r.push(t());return new ty(e,s,r)}(),n(ti.OpenStatement,"Expected {% token"),r("endmacro"),n(ti.CloseStatement,"Expected %} token");break;case"for":++s,d=function(){let e=l(!0);if(!(e instanceof tE||e instanceof tP))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);if(!o("in"))throw SyntaxError("Expected `in` keyword following loop variable");++s;let r=c();n(ti.CloseStatement,"Expected closing statement token");let a=[];for(;!i("endfor","else");)a.push(t());let d=[];if(i("else"))for(++s,++s,n(ti.CloseStatement,"Expected closing statement token");!i("endfor");)d.push(t());return new tf(e,r,a,d)}(),n(ti.OpenStatement,"Expected {% token"),r("endfor"),n(ti.CloseStatement,"Expected %} token");break;case"call":{++s;let e=null;a(ti.OpenParen)&&(e=m());let o=x();if("Identifier"!==o.type)throw SyntaxError("Expected identifier following call statement");let l=m();n(ti.CloseStatement,"Expected closing statement token");let c=[];for(;!i("endcall");)c.push(t());n(ti.OpenStatement,"Expected '{%'"),r("endcall"),n(ti.CloseStatement,"Expected closing statement token"),d=new tG(new tv(o,l),e,c);break}case"break":++s,n(ti.CloseStatement,"Expected closing statement token"),d=new tg;break;case"continue":++s,n(ti.CloseStatement,"Expected closing statement token"),d=new tw;break;case"filter":{++s;let e=x();e instanceof tE&&a(ti.OpenParen)&&(e=p(e)),n(ti.CloseStatement,"Expected closing statement token");let o=[];for(;!i("endfilter");)o.push(t());n(ti.OpenStatement,"Expected '{%'"),r("endfilter"),n(ti.CloseStatement,"Expected '%}'"),d=new tI(e,o);break}default:throw SyntaxError(`Unknown statement type: ${u}`)}return d}();case ti.OpenExpression:n(ti.OpenExpression,"Expected opening expression token");let d=c();return n(ti.CloseExpression,"Expected closing expression token"),d;default:throw SyntaxError(`Unexpected token type: ${e[s].type}`)}}());return t}(t)}render(e){let t=new se;if(t.set("false",!1),t.set("true",!0),t.set("none",null),t.set("raise_exception",e=>{throw Error(e)}),t.set("range",tR),t.set("strftime_now",tW),t.set("True",!0),t.set("False",!1),t.set("None",null),e)for(let[s,n]of Object.entries(e))t.set(s,n);return new sn(t).run(this.parsed).value}format(e){return function(e,t=" "){let s="number"==typeof t?" ".repeat(t):t;return(function e(t,s,n){return t.map(t=>(function(t,s,n){let r=n.repeat(s);switch(t.type){case"Program":return e(t.body,s,n);case"If":return function(t,s,n){let r=n.repeat(s),a=[],i=t;for(;i;)if(a.push({test:i.test,body:i.body}),1===i.alternate.length&&"If"===i.alternate[0].type)i=i.alternate[0];else break;let o=r+sr("if",sa(a[0].test))+"\n"+e(a[0].body,s+1,n);for(let t=1;t<a.length;++t)o+="\n"+r+sr("elif",sa(a[t].test))+"\n"+e(a[t].body,s+1,n);return i&&i.alternate.length>0&&(o+="\n"+r+sr("else")+"\n"+e(i.alternate,s+1,n)),o+="\n"+r+sr("endif")}(t,s,n);case"For":var a=t,i=s,o=n;let l=o.repeat(i),c="";if("SelectExpression"===a.iterable.type){let e=a.iterable;c=`${sa(e.lhs)} if ${sa(e.test)}`}else c=sa(a.iterable);let d=l+sr("for",sa(a.loopvar),"in",c)+"\n"+e(a.body,i+1,o);return a.defaultBlock.length>0&&(d+="\n"+l+sr("else")+"\n"+e(a.defaultBlock,i+1,o)),d+="\n"+l+sr("endfor");case"Set":var u=t,_=s,h=n;let p=h.repeat(_),m=sa(u.assignee),f=u.value?sa(u.value):"",g=p+sr("set",`${m}${u.value?" = "+f:""}`);return 0===u.body.length?g:g+"\n"+e(u.body,_+1,h)+"\n"+p+sr("endset");case"Macro":var w=t,x=s,y=n;let b=y.repeat(x),M=w.args.map(sa).join(", ");return b+sr("macro",`${w.name.value}(${M})`)+"\n"+e(w.body,x+1,y)+"\n"+b+sr("endmacro");case"Break":return r+sr("break");case"Continue":return r+sr("continue");case"CallStatement":var k=t,v=s,E=n;let A=E.repeat(v),C=k.callerArgs&&k.callerArgs.length>0?`(${k.callerArgs.map(sa).join(", ")}
1)`:"",F=A+sr(`call${C}`,sa(k.call))+"\n";return F+=e(k.body,v+1,E)+"\n",F+=A+sr("endcall");case"FilterStatement":var S=t,T=s,P=n;let z=P.repeat(T),L=z+sr("filter","Identifier"===S.filter.type?S.filter.value:sa(S.filter))+"\n";return L+=e(S.body,T+1,P)+"\n",L+=z+sr("endfilter");case"Comment":return r+"{# "+t.value+" #}";default:return r+"{{- "+sa(t)+" -}}"}})(t,s,n)).join("\n")})(e.body,0,s).replace(/\n$/,"")}(this.parsed,e?.indent||" ")}},so={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"},sl=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=h.existsSync(e),this.exists){this.status=200,this.statusText="OK";let t=h.statSync(e);this.headers.set("content-length",t.size.toString()),this.updateContentType();let s=h.createReadStream(e);this.body=new ReadableStream({start(e){s.on("data",t=>e.enqueue(t)),s.on("end",()=>e.close()),s.on("error",t=>e.error(t))},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",so[e]??"application/octet-stream")}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await h.promises.readFile(this.filePath)).buffer}async blob(){return new Blob([await h.promises.readFile(this.filePath)],{type:this.headers.get("content-type")})}async text(){return await h.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},sc=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(null==e)if(F.IS_CRYPTO_AVAILABLE){let t=new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0;let t=this._mt,s=(e,t)=>Math.imul(e,t)>>>0,n=[];for(let t=e||0;t>0;t=Math.floor(t/0x100000000))n.push(0|t);n.length||n.push(0),t[0]=0x12bd6aa;for(let e=1;e<624;++e)t[e]=s(0x6c078965,t[e-1]^t[e-1]>>>30)+e>>>0;let r=1,a=0;for(let e=Math.max(624,n.length);e>0;--e,++r,++a)r>=624&&(t[0]=t[623],r=1),a>=n.length&&(a=0),t[r]=(t[r]^s(t[r-1]^t[r-1]>>>30,1664525))+n[a]+a>>>0;for(let e=623;e>0;--e,++r)r>=624&&(t[0]=t[623],r=1),t[r]=(t[r]^s(t[r-1]^t[r-1]>>>30,0x5d588b65))-r>>>0;t[0]=0x80000000,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let s=0x80000000&e[t]|0x7fffffff&e[(t+1)%624];e[t]=(e[(t+397)%624]^s>>>1^(1&s?0x9908b0df:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&0x9d2c5680,t^=t<<15&0xefc60000,(t^=t>>>18)>>>0}random(){return((this._int32()>>>5)*0x4000000+(this._int32()>>>6))/0x20000000000000}gauss(e=0,t=1){let s=this._gauss_next;if(this._gauss_next=null,null===s){let e=2*this.random()*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+s*t}shuffle(e){for(let t=e.length-1;t>0;--t){let s=32-Math.clz32(t+1),n=this._int32()>>>32-s;for(;n>t;)n=this._int32()>>>32-s;let r=e[t];e[t]=e[n],e[n]=r}}choices(e,t){return e[sd(this._random_fn,t)]}};function sd(e,t){let s=0;for(let e=0;e<t.length;++e)s+=t[e];let n=e()*s;for(let e=0;e<t.length;++e)if((n-=t[e])<0)return e;return t.length-1}var su=new sc,s_=Object.freeze({Random:sc,seed:su.seed.bind(su),random:su.random.bind(su),gauss:su.gauss.bind(su),shuffle:su.shuffle.bind(su),choices:su.choices.bind(su)}),sh=new sc,sp=class{constructor(e){this.path=e}async match(e){let t=new sl(p.join(this.path,e));return t.exists?t:void 0}async put(e,t,s){let n=p.join(this.path,e),r=F.IS_PROCESS_AVAILABLE?d.pid:Date.now(),a=sh._int32().toString(36),i=n+`.tmp.${r}.${a}`;try{let e=t.headers.get("Content-Length"),r=parseInt(e??"0"),a=0;await h.promises.mkdir(p.dirname(n),{recursive:!0});let o=h.createWriteStream(i),l=t.body.getReader();for(;;){let{done:e,value:t}=await l.read();if(e)break;await new Promise((e,s)=>{o.write(t,t=>{if(t)return void s(t);e()})}),a+=t.length;let n=r?a/r*100:0;s?.({progress:n,loaded:a,total:r})}await new Promise((e,t)=>
1{o.close(s=>s?t(s):e())}),await h.promises.rename(i,n)}catch(e){try{await h.promises.unlink(i)}catch{}throw e}}async delete(e){let t=p.join(this.path,e);try{return await h.promises.unlink(t),!0}catch(e){return!1}}},sm={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"},sf=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function sg(...e){return(e=e.map((t,s)=>(s&&(t=t.replace(RegExp("^/"),"")),s!==e.length-1&&(t=t.replace(RegExp("/$"),"")),t))).join("/")}function sw(e,t=null,s=null){let n;try{n=new URL(e)}catch(e){return!1}return(!t||!!t.includes(n.protocol))&&(!s||!!s.includes(n.hostname))}async function sx(e,t,s){let n=e.headers.get("Content-Length"),r=n?parseInt(n,10):s??0;null!==n||s||W.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let a=new Uint8Array(r),i=0,o=e.body.getReader();async function l(){let{done:e,value:s}=await o.read();if(e)return;let n=i+s.length;if(n>r){let e=new Uint8Array(r=n);e.set(a),a=e}return a.set(s,i),t({progress:(i=n)/r*100,loaded:i,total:r}),l()}return await l(),a}function sy(e){return sw(e,["blob:"])}function sb(e){let t;return new URL(e,t="undefined"!=typeof location&&location.href?location.href:"file:///vercel/path1/node_modules/@huggingface/transformers/dist/transformers.web.js").href}var sM="SHA-256",sk=e=>({algorithm:sM,value:e}),sv=class{#e=null;_getHashCache=()=>(this.#e??=caches.open("experimental_transformers-hash-cache"),this.#e);static isAvailable=()=>"undefined"!=typeof navigator&&"crossOriginStorage"in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let[e]=await navigator.crossOriginStorage.requestFileHandles([sk(t)]),s=await e.getFile();return new Response(s,{headers:{"Content-Length":String(s.size)}})}catch{return}};put=async(e,t)=>{let s=await this._getFileHash(e);if(s){let e=await t.blob();await this._storeBlobInCOS(e,s)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let[s]=await navigator.crossOriginStorage.requestFileHandles([sk(t)],{create:!0}),n=await s.createWritable();await n.write(e),await n.close()};_processAndStore=async(e,t)=>{try{let s=[];for await(let e of t)s.push(e);let n=new Blob(s),r=await this._getBlobHash(n);await this._storeBlobInCOS(n,r);try{let t=await this._getHashCache();await t.put(e,new Response(r))}catch{}}catch{}};delete=async e=>{try{let t=await this._getHashCache();return await t.delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),s=await t.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);if(n)return await t.put(e,new Response(n)),n;return null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let t=e.replace("/resolve/","/raw/");try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer();return Array.from(new Uint8Array(await crypto.subtle.digest(sM,t))).map(e=>e.toString(16).padStart(2,"0")).join("")}};async function sE(e=null){let t=null;if($.useCustomCache){if(!$.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!$.customCache.match||!$.customCache.put)throw 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");t=$.customCache}if(!t&&$.experimental_useCrossOriginStorage&&sv.isAvailable()&&(t=new sv),!t&&$.useBrowserCache){if("undefined"==typeof caches)throw Error("Browser cache is not available in this environment.");try{t=await caches.open($.cacheKey)}catch(e){W.warn("An error occurred while opening the browser cache:",e)}}if(!t&&$.useFSCache){if(!F.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new sp(e??$.cacheDir)}return t}async function sA(e,...t){for(let s of t)try{let t=await e.match(s);if(t)return t}catch(e){continue}}var sC=new class{#t;#s;constructor(e){this.#t=e,this.#s=new Map}get(e){if(!this.#s.has(e))return;let t=this.#s.get(e);return this.#s.delete(e),this.#s.set(e,t),t}put(e,t){this.#s.has(e)&&this.#s.delete(e),this.#s.set(e,t),this.#s.size>this.#t&&this.#s.delete(this.#s.keys().next().value)}delete(e){return this.#s.delete(e)}clear(){this.#s.clear()}}(100);function sF(e,t){let s=sC.get(e);if(void 0!==s)return s;let n=t().then(e=>e,t=>(sC.delete(e),Promise.reject(t)));return sC.put(e,n),n}async function sS(e){if(!sw(e,["http:","https:"]))return null;let t=sL(e);return t.set("Range","bytes=0-0"),$.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function sT(e,t,s={}){return sF(JSON.stringify([e,t,s?.revision,s?.cache_dir,s?.local_files_only]),()=>
1sP(e,t,s))}async function sP(e,t,s){let n=await sE(s?.cache_dir),{localPath:r,remoteURL:a,proposedCacheKey:i,validModelId:o}=sO(e,t,s,n),l=await sI(n,r,i);if(void 0!==l&&"string"!=typeof l){let e=l.headers.get("content-length"),t=l.headers.get("content-type");return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if($.allowLocalModels&&!sw(r,["http:","https:"]))try{let e=await sz(r);if("string"!=typeof e&&404!==e.status){let t=e.headers.get("content-length"),s=e.headers.get("content-type");return{exists:!0,size:t?parseInt(t,10):void 0,contentType:s||void 0,fromCache:!1}}}catch(e){}if($.allowRemoteModels&&!s.local_files_only&&o)try{let e=await sS(a);if(e&&e.status>=200&&e.status<300){let t,s=e.headers.get("content-type");if(206===e.status){let s=e.headers.get("content-range");if(s){let e=s.match(/bytes \d+-\d+\/(\d+)/);e&&(t=parseInt(e[1],10))}}else if(200===e.status)try{await e.body?.cancel()}catch(e){}if(void 0===t){let s=e.headers.get("content-length");t=s?parseInt(s,10):void 0}return{exists:!0,size:t,contentType:s||void 0,fromCache:!1}}}catch(e){W.warn(`Unable to fetch file metadata for "${a}": ${e}`)}return{exists:!1,fromCache:!1}}async function sz(e){return $.useFS&&!sw(e,["http:","https:","blob:"])?new sl(e instanceof URL?"file:"===e.protocol?e.pathname:e.toString():e):$.fetch(e,{headers:sL(e)})}function sL(e){let t=void 0!==d&&d?.release?.name==="node",s=new Headers;if(t){let t=!!d.env?.TESTING_REMOTELY,n=$.version;if(s.set("User-Agent",`transformers.js/${n}; is_ci/${t};`),sw(e,["http:","https:"],["huggingface.co","hf.co"])){let e=d.env?.HF_TOKEN??d.env?.HF_ACCESS_TOKEN;e&&s.set("Authorization",`Bearer ${e}`)}}return s}function sO(e,t,s={},n=null){let r=s.revision??"main",a=sg(e,t),i=!(!sf.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb")),o=i?sg($.localModelPath,a):a,l=sg($.remoteHost,$.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(r)),t),c=n instanceof sp?"main"===r?a:sg(e,r,t):l;return{requestURL:a,localPath:o,remoteURL:l,proposedCacheKey:c,validModelId:i}}async function sI(e,t,s){if(e)return await sA(e,t,s)}async function sN(e,t,s,n,r,a,i={}){if(await s.match(n)===void 0)if(a){if("string"!=typeof r){let e=new Headers(r.headers);e.set("content-length",a.byteLength.toString()),await s.put(n,new Response(a,{headers:e})).catch(e=>{W.warn(`Unable to add response to browser cache: ${e}.`)})}}else{let a=i.progress_callback?s=>{var n,r;return n=i.progress_callback,r={status:"progress",name:e,file:t,...s},void(n&&n(r))}:void 0;await s.put(n,r,a)}}async function s$(e,t,s=!0,n={},r=!1,a=null){let i,o,l,{requestURL:c,localPath:d,remoteURL:u,proposedCacheKey:_,validModelId:h}=sO(e,t,n,a),p=!1,m=void 0!==(o=await sI(a,d,_));if(m)i=_;else{if($.allowLocalModels)if(sw(c,["http:","https:"])){if(n.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${c}.`);else if(!$.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${c}.`)}else try{o=await sz(d),i=d}catch(e){W.warn(`Unable to load from local path "${d}": "${e}"`)}if(void 0===o||"string"!=typeof o&&404===o.status){if(n.local_files_only||!$.allowRemoteModels)if(!s)return null;else throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${d}".`);if(!h)throw Error(`Local file missing at "${d}" and download aborted due to invalid model ID "${e}".`);if(200!==(o=await sz(u)).status){var f,g,w,x,y,b,M,k=o.status;if(!s)return null;let e=sm[k]??`Error (${k}) occurred while trying to load file`;throw Error(`${e}: "${u}".`)}i=_}p=a&&"undefined"!=typeof Response&&o instanceof Response&&200===o.status}if(f=n.progress_callback,g={status:"download",name:e,file:t},f&&f(g),F.IS_NODE_ENV&&r);else{let s;if("string"!=typeof o)if(n.progress_callback)if(m&&"undefined"!=typeof navigator&&/firefox/i.test(navigator.userAgent))s=new Uint8Array(await o.arrayBuffer()),w=n.progress_callback,x={status:"progress",name:e,file:t,progress:100,loaded:s.length,total:s.length},w&&w(x);else{let r,a=o.headers.get("content-length");if(a)r=parseInt(a,10);else try{let s=await sT(e,t,n);s.size&&(r=s.size)}catch(e){}s=await sx(o,s=>{var r,a;r=n.progress_callback,a={status:"progress",name:e,file:t,...s},r&&r(a)},r)}else s=new Uint8Array(await o.arrayBuffer());l=s}if(p&&i&&"string"!=typeof o&&await sN(e,t,a,i,o,l,n),F.IS_NODE_ENV&&r&&n.progress_callback&&"string"!=typeof o){let s=parseInt(o.headers.get("content-length"),10)||0;y=n.progress_callback,y&&y({status:"progress",name:e,file:t,progress:100,loaded:s,total:s})}if(b=n.progress_callback,M={status:"done",name:e,file:t},b&&b(M),l){if(!F.IS_NODE_ENV&&r)throw Error("Cannot return path in a browser environment.");return l}if(o instanceof sl)return o.filePath;let v=await a?.match(i);if(v instanceof sl)return v.filePath;if(v instanceof Response)return new Uint8Array(await v.arrayBuffer());if("string"==typeof v)return v;throw Error("Unable to get model file path or buffer.")}var sB=new Map;async function sD(e,t,s=!0,n={},r=!1){var a;
1if(!$.allowLocalModels){if(n.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`).");else if(!$.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}a=n.progress_callback,a&&a({status:"initiate",name:e,file:t});let i=`${e}::${t}`,o=sB.get(i);if(!o){let a=await sE(n?.cache_dir);o=s$(e,t,s,n,r,a).then(e=>(sB.delete(i),e),e=>{throw sB.delete(i),e}),sB.set(i,o)}return await o}async function sV(e,t,s=!0,n={}){let r=await sD(e,t,s,n,!1);return null===r?null:new TextDecoder("utf-8").decode(r)}async function sq(e,t,s=!0,n={}){let r=await sV(e,t,s,n);return null===r?{}:JSON.parse(r)}function sG(e){let t=sR(e)[0],s=e.map(e=>Math.exp(e-t)),n=s.reduce((e,t)=>e+t,0);return s.map(e=>e/n)}function sj(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let n=1;n<e.length;++n)e[n]<t&&(t=e[n],s=n);return[t,s]}function sR(e){if(0===e.length)throw Error("Array must not be empty");let t=e[0],s=0;for(let n=1;n<e.length;++n)e[n]>t&&(t=e[n],s=n);return[t,s]}function sU(e){return e>0&&(e&e-1)==0}var sW=class{constructor(e){if(this.size=0|e,this.size<=1||!sU(this.size))throw Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(2*this.size);for(let e=0;e<this.table.length;e+=2){let t=Math.PI*e/this.size;this.table[e]=Math.cos(t),this.table[e+1]=-Math.sin(t)}let t=0;for(let e=1;this.size>e;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<<this._width);for(let e=0;e<this._bitrev.length;++e){this._bitrev[e]=0;for(let t=0;t<this._width;t+=2){let s=this._width-t-2;this._bitrev[e]|=(e>>>t&3)<<s}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,t){let s=t||Array(e.length>>>1);for(let t=0;t<e.length;t+=2)s[t>>>1]=e[t];return s}toComplexArray(e,t){let s=t||this.createComplexArray();for(let t=0;t<s.length;t+=2)s[t]=e[t>>>1],s[t+1]=0;return s}transform(e,t){if(e===t)throw Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let t=0;t<e.length;++t)e[t]/=this.size}_transform4(e,t,s){let n,r,a=this._csize,i=1<<this._width,o=a/i<<1,l=this._bitrev;if(4===o)for(n=0,r=0;n<a;n+=o,++r){let s=l[r];this._singleTransform2(t,e,n,s,i)}else for(n=0,r=0;n<a;n+=o,++r){let a=l[r];this._singleTransform4(t,e,n,a,i,s)}let c=this.table;for(i>>=2;i>=2;i>>=2){let t=(o=a/i<<1)>>>2;for(n=0;n<a;n+=o){let r=n+t-1;for(let a=n,o=0;a<r;a+=2,o+=i){let n=a,r=n+t,i=r+t,l=i+t,d=e[n],u=e[n+1],_=e[r],h=e[r+1],p=e[i],m=e[i+1],f=e[l],g=e[l+1],w=c[o],x=s*c[o+1],y=_*w-h*x,b=_*x+h*w,M=c[2*o],k=s*c[2*o+1],v=p*M-m*k,E=p*k+m*M,A=c[3*o],C=s*c[3*o+1],F=f*A-g*C,S=f*C+g*A,T=d+v,P=u+E,z=d-v,L=u-E,O=y+F,I=b+S,N=s*(y-F),$=s*(b-S);e[n]=T+O,e[n+1]=P+I,e[r]=z+$,e[r+1]=L-N,e[i]=T-O,e[i+1]=P-I,e[l]=z-$,e[l+1]=L+N}}}}_singleTransform2(e,t,s,n,r){let a=e[n],i=e[n+1],o=e[n+r],l=e[n+r+1];t[s]=a+o,t[s+1]=i+l,t[s+2]=a-o,t[s+3]=i-l}_singleTransform4(e,t,s,n,r,a){let i=2*r,o=3*r,l=e[n],c=e[n+1],d=e[n+r],u=e[n+r+1],_=e[n+i],h=e[n+i+1],p=e[n+o],m=e[n+o+1],f=l+_,g=c+h,w=l-_,x=c-h,y=d+p,b=u+m,M=a*(d-p),k=a*(u-m);t[s]=f+y,t[s+1]=g+b,t[s+2]=w+k,t[s+3]=x-M,t[s+4]=f-y,t[s+5]=g-b,t[s+6]=w-k,t[s+7]=x+M}_realTransform4(e,t,s){let n,r,a=this._csize,i=1<<this._width,o=a/i<<1,l=this._bitrev;if(4===o)for(n=0,r=0;n<a;n+=o,++r){let s=l[r];this._singleRealTransform2(t,e,n,s>>>1,i>>>1)}else for(n=0,r=0;n<a;n+=o,++r){let a=l[r];this._singleRealTransform4(t,e,n,a>>>1,i>>>1,s)}let c=this.table;for(i>>=2;i>=2;i>>=2){let t=(o=a/i<<1)>>>1,r=t>>>1,l=r>>>1;for(n=0;n<a;n+=o)for(let a=0,o=0;a<=l;a+=2,o+=i){let i=n+a,d=i+r,u=d+r,_=u+r,h=e[i],p=e[i+1],m=e[d],f=e[d+1],g=e[u],w=e[u+1],x=e[_],y=e[_+1],b=c[o],M=s*c[o+1],k=m*b-f*M,v=m*M+f*b,E=c[2*o],A=s*c[2*o+1],C=g*E-w*A,F=g*A+w*E,S=c[3*o],T=s*c[3*o+1],P=x*S-y*T,z=x*T+y*S,L=h+C,O=p+F,I=h-C,N=p-F,$=k+P,B=v+z,D=s*(k-P),V=s*(v-z);if(e[i]=L+$,e[i+1]=O+B,e[d]=I+V,e[d+1]=N-D,0===a){e[u]=L-$,e[u+1]=O-B;continue}if(a===l)continue;let q=n+r-a,G=n+t-a;e[q]=I-s*V,e[q+1]=-N-s*D,e[G]=L-s*$,e[G+1]=-O+s*B}}let d=a>>>1;for(let t=2;t<d;t+=2)e[a-t]=e[t],e[a-t+1]=-e[t+1]}_singleRealTransform2(e,t,s,n,r){let a=e[n],i=e[n+r];t[s]=a+i,t[s+1]=0,t[s+2]=a-i,t[s+3]=0}_singleRealTransform4(e,t,s,n,r,a){let i=e[n],o=e[n+r],l=e[n+2*r],c=e[n+3*r],d=i+l,u=i-l,_=o+c,h=a*(o-c);t[s]=d+_,t[s+1]=0,t[s+2]=u,t[s+3]=-h,t[s+4]=d-_,t[s+5]=0,t[s+6]=u,t[s+7]=h}},sQ=class{constructor(e){let t=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=t;let r=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,o=Math.cos(i),l=Math.sin(i);for(let t=0;t<s>>1;++t){let s=(t+1-e)**2/2,n=Math.sqrt(o**2+l**2)**s,i=s*Math.atan2(l,o),c=2*t;r[c]=n*Math.cos(i),r[c+1]=n*Math.sin(i),a[c]=r[c],a[c+1]=-r[c+1]}this._slicedChirpBuffer=r.subarray(t,s),this._f=new sW(n>>1),this._f.transform(this._chirpBuffer,a)}
1_transform(e,t,s){let n=this._buffer1,r=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,o=this._chirpBuffer,l=this._slicedChirpBuffer,c=this._a;if(s)for(let e=0;e<l.length;e+=2){let s=e+1,r=t[e>>1];n[e]=r*l[e],n[s]=r*l[s]}else for(let e=0;e<l.length;e+=2){let s=e+1;n[e]=t[e]*l[e]-t[s]*l[s],n[s]=t[e]*l[s]+t[s]*l[e]}this._f.transform(a,n);for(let e=0;e<o.length;e+=2){let t=e+1;r[e]=a[e]*o[e]-a[t]*o[t],r[t]=a[e]*o[t]+a[t]*o[e]}this._f.inverseTransform(i,r);for(let t=0;t<i.length;t+=2){let s=i[t+c],n=i[t+c+1],r=l[t],a=l[t+1];e[t]=s*r-n*a,e[t+1]=s*a+n*r}}transform(e,t){this._transform(e,t,!1)}realTransform(e,t){this._transform(e,t,!0)}},sH=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=sU(e),this.isPowerOfTwo?(this.fft=new sW(e),this.outputBufferSize=2*e):(this.fft=new sQ(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,t){this.fft.realTransform(e,t)}transform(e,t){this.fft.transform(e,t)}};function sX(e,t){let s=Math.pow(10,t);return Math.round(e*s)/s}var sJ=function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let t=new ArrayBuffer(4),s=new Uint32Array(t),n=new Float32Array(t);for(let t=0;t<e.length;++t){let r=0,a=(32768&t)<<16,i=(31744&t)>>10,o=1023&t;if(31===i)r=0x7f800000|a|o<<13;else if(0===i)if(0===o)r=a;else{let e=113;for(;(1024&o)==0;)o<<=1,--e;o&=-1025,r=a|e<<23|o<<13}else r=a|i+112<<23|o<<13;s[0]=r,e[t]=n[0]}}let s=t.length,n=e,r=new Float32Array(s);for(let e=0;e<s;++e)r[e]=n[t[e]];return r}}(),sK={};_(sK,{default:()=>sY});var sY={};async function sZ(e){let t,s=e.split("/").pop();try{if(t=await sE()){let s=await t.match(e);if(s)return s}}catch(e){W.warn(`Failed to load ${s} from cache:`,e)}let n=await $.fetch(e);if(!n.ok)throw Error(`Failed to fetch ${s}: ${n.status} ${n.statusText}`);if(t)try{await t.put(e,n.clone())}catch(e){W.warn(`Failed to cache ${s}:`,e)}return n}async function s0(e){let t=await sZ(e);if(!t||"string"==typeof t)return null;try{return await t.arrayBuffer()}catch(e){return W.warn("Failed to read WASM binary:",e),null}}async function s1(e){if(F.IS_SERVICE_WORKER_ENV||F.IS_CHROME_AVAILABLE)return e;let t=await sZ(e);if(!t||"string"==typeof t)return null;try{let e=await t.text();e=e.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([e],{type:"text/javascript"});return URL.createObjectURL(s)}catch(e){return W.warn("Failed to read WASM factory:",e),null}}var s2=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function s3(e){return e<=I.DEBUG?0:e<=I.INFO?2:e<=I.WARNING?3:e<=I.ERROR?3:4}var s4={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},s8=[],s6=Symbol.for("onnxruntime");if(s6 in globalThis)r=globalThis[s6];else if(F.IS_NODE_ENV){switch(r=sK,d.platform){case"win32":s8.push("dml");break;case"linux":"x64"===d.arch&&s8.push("cuda");break;case"darwin":s8.push("coreml")}s8.push("webgpu"),s8.push("cpu"),n=["cpu"]}else r=l,F.IS_WEBNN_AVAILABLE&&s8.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),F.IS_WEBGPU_AVAILABLE&&s8.push("webgpu"),s8.push("wasm"),n=["wasm"];var s5=r.InferenceSession,s9=Promise.resolve(),s7=null;async function ne(){if(s7)return s7;if(!($.useWasmCache&&"object"==typeof na?.wasm?.wasmPaths&&na?.wasm?.wasmPaths?.wasm&&na?.wasm?.wasmPaths?.mjs)){if(F.IS_DENO_WEB_RUNTIME)throw Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return s7=Promise.resolve()}return s7=(async()=>{let e=na.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!sy(e.wasm)?(async()=>{try{let s=await s0(sb(e.wasm));s&&(na.wasm.wasmBinary=s,t=!0)}catch(e){W.warn("Failed to pre-load WASM binary:",e)}})():Promise.resolve(),e.mjs&&!sy(e.mjs)?(async()=>{try{let t=await s1(sb(e.mjs));t&&(na.wasm.wasmPaths.mjs=t)}catch(e){W.warn("Failed to pre-load WASM factory:",e)}})():Promise.resolve()]),t||(na.wasm.wasmPaths.mjs=e.mjs)})()}async function nt(e,t,s){await ne();let n=s3($.logLevel??I.WARNING),r=()=>s5.create(e,{logSeverityLevel:n,...t}),a=await (F.IS_WEB_ENV?s9=s9.then(r):r());return a.config=s,a}var ns=Promise.resolve();async function nn(e,t){let s=()=>e.run(t);return F.IS_WEB_ENV?ns=ns.then(s):s()}function nr(e){return e instanceof r.Tensor}var na=r?.env;function ni(){return na?.wasm?.proxy}if(na){let e=function(e){na.logLevel=s4[s3(e)]};if(na.wasm){if(!("undefined"!=typeof ServiceWorkerGlobalScope&&self instanceof ServiceWorkerGlobalScope)&&na.versions?.web&&!na.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${na.versions.web}/dist/`;na.wasm.wasmPaths=F.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}na.wasm.proxy=!1}na.webgpu&&(na.webgpu.powerPreference="high-performance"),e($.logLevel??I.WARNING),$.backends.onnx={...na,setLogLevel:e}}var no=async(e,t,s)=>
1{let n=await nt(new Uint8Array(e),t);return async e=>{let t=ni(),r=Object.fromEntries(Object.entries(e).map(([e,s])=>[e,(t?s.clone():s).ort_tensor])),a=await nn(n,r);return Array.isArray(s)?s.map(e=>new nx(a[e])):new nx(a[s])}},nl=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=no([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=no([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=no([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=no([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=no([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=no([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=no([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=no([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}},nc=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"}),nd=F.IS_NODE_ENV?"cpu":"wasm";function nu(e,t,{warn:s}={}){return e?"string"==typeof e?e:e.hasOwnProperty(t)?e[t]:(s&&s(`device not specified for "${t}". Using the default device (${nd}).`),nd):nd}var n_=function(){let e;return async function(){if(void 0===e)if(F.IS_WEBGPU_AVAILABLE)try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch(t){e=!1}else e=!1;return e}}(),nh=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),np=nh.fp32,nm=Object.freeze({[nc.wasm]:nh.q8}),nf=Object.freeze({[nh.fp32]:"",[nh.fp16]:"_fp16",[nh.int8]:"_int8",[nh.uint8]:"_uint8",[nh.q8]:"_quantized",[nh.q4]:"_q4",[nh.q2]:"_q2",[nh.q1]:"_q1",[nh.q4f16
1]:"_q4f16",[nh.q2f16]:"_q2f16",[nh.q1f16]:"_q1f16",[nh.bnb4]:"_bnb4"});function ng(e,t,s,{configDtype:n=null,warn:r}={}){let a,i,o=!1;if(e&&"string"!=typeof e?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e,a===nh.auto){if(n){let e="string"==typeof n?n:n?.[t];if(e&&e!==nh.auto&&nh.hasOwnProperty(e))return e}i=nm[s]??np}else i=a&&nh.hasOwnProperty(a)?a:nm[s]??np;return o&&r&&r(`dtype not specified for "${t}". Using the default dtype (${i}) for this device (${s}).`),i}var nw=Object.freeze({float32:Float32Array,float16:"undefined"!=typeof Float16Array?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}),nx=class e{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 nr(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new c.qY(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if("string"==typeof t){let s=Number(t);if(Number.isInteger(s))return e._getitem(s)}return e[t]},set:(e,t,s)=>e[t]=s})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let s=t.reduce((e,t)=>e*t);for(let n=0;n<e;++n)yield this._subarray(n,s,t)}else yield*this.data}_getitem(t){let[s,...n]=this.dims;if(t=nF(t,s),!(n.length>0))return new e(this.type,[this.data[t]],n);{let e=n.reduce((e,t)=>e*t);return this._subarray(t,e,n)}}indexOf(e){let t=this.data;for(let s=0;s<t.length;++s)if(t[s]==e)return s;return -1}_subarray(t,s,n){let r=t*s,a=(t+1)*s,i="subarray"in this.data?this.data.subarray(r,a):this.data.slice(r,a);return new e(this.type,i,n)}item(){let e=this.data;if(1!==e.length)throw Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return function(e,t){let s=e.length;if(s!==t.reduce((e,t)=>e*t))throw Error(`cannot reshape array of size ${s} into shape (${t})`);let n=e;for(let e=t.length-1;e>=0;e--)n=n.reduce((s,n)=>{let r=s[s.length-1];return r.length<t[e]?r.push(n):s.push([n]),s},[[]]);return n[0]}(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=1/(1+Math.exp(-e[t]));return this}map(e){return this.clone().map_(e)}map_(e){let t=this.data;for(let s=0;s<t.length;++s)t[s]=e(t[s],s,t);return this}mul(e){return this.clone().mul_(e)}mul_(e){let t=this.data;for(let s=0;s<t.length;++s)t[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let t=this.data;for(let s=0;s<t.length;++s)t[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let t=this.data;for(let s=0;s<t.length;++s)t[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let t=this.data;for(let s=0;s<t.length;++s)t[s]-=e;return this}clone(){return new e(this.type,this.data.slice(),this.dims.slice())}slice(...t){let s=[],n=[];for(let e=0;e<this.dims.length;++e){let r=t[e];if(null==r)n.push([0,this.dims[e]]),s.push(this.dims[e]);else if("number"==typeof r)r=nF(r,this.dims[e],e),n.push([r,r+1]);else if(Array.isArray(r)&&2===r.length){let[t,a]=r;if((t=null===t?0:nF(t,this.dims[e],e,!1))>(a=null===a?this.dims[e]:nF(a,this.dims[e],e,!1)))throw Error(`Invalid slice: ${r}`);let i=[Math.max(t,0),Math.min(a,this.dims[e])];n.push(i),s.push(i[1]-i[0])}else throw Error(`Invalid slice: ${r}`)}let r=n.map(([e,t])=>t-e),a=r.reduce((e,t)=>e*t),i=this.data,o=new i.constructor(a),l=this.stride(),c=!0;for(let e=1;e<r.length;++e)if(0!==n[e][0]||n[e][1]!==this.dims[e]){c=!1;break}if(c){let e=n[0][0]*l[0],t=n[0][1]*l[0];if(ArrayBuffer.isView(i))o.set(i.subarray(e,t));else if(Array.isArray(i)){let s=i.slice(e,t);for(let e=0;e<s.length;++e)o[e]=s[e]}else throw Error("Unsupported data type for slicing")}else for(let e=0;e<a;++e){let t=0;for(let s=r.length-1,a=e;s>=0;--s){let e=r[s];t+=(a%e+n[s][0])*l[s],a=Math.floor(a/e)}o[e]=i[t]}
1return new e(this.type,o,s)}permute(...e){var t=this,s=e;let[n,r]=function(e,t,s){let n=Array(s.length),r=Array(s.length);for(let e=s.length-1,a=1;e>=0;--e)r[e]=a,n[e]=t[s[e]],a*=n[e];let a=s.map((e,t)=>r[s.indexOf(t)]),i=new e.constructor(e.length);for(let s=0;s<e.length;++s){let n=0;for(let e=t.length-1,r=s;e>=0;--e)n+=r%t[e]*a[e],r=Math.floor(r/t[e]);i[n]=e[s]}return[i,n]}(t.data,t.dims,s);return new nx(t.type,n,r)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t="fro",s=null,n=!1){let r,a;if("fro"===t)t=2;else if("string"==typeof t)throw Error(`Unsupported norm: ${t}`);let i=this.data,o=i instanceof BigInt64Array||i instanceof BigUint64Array;if(o&&1!==t)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);if(o?(r=(e,t)=>e+t,a=0n):(r=(e,s)=>e+s**t,a=0),null===s){let s=i.reduce(r,a);return 1!==t&&(s=s**(1/t)),new e(this.type,[s],[])}let[l,c,d]=nP(r,this,s,n);if(1!==t)for(let e=0;e<c.length;++e)c[e]=c[e]**(1/t);return new e(l,c,d)}normalize_(e=2,t=1){t=nF(t,this.dims.length);let s=this.norm(e,t,!0),n=this.data,r=s.data;for(let e=0;e<n.length;++e){let s=0;for(let n=this.dims.length-1,r=e,a=1;n>=0;--n){let e=this.dims[n];n!==t&&(s+=r%e*a,a*=this.dims[n]),r=Math.floor(r/e)}n[e]/=r[s]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return nL(this.dims)}squeeze(t=null){return new e(this.type,this.data,nA(this.dims,t))}squeeze_(e=null){return this.dims=nA(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,nC(this.dims,t))}unsqueeze_(e){return this.dims=nC(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,t+1),r=this.dims.slice(t+1);return this.dims=[...s,n.reduce((e,t)=>e*t,1),...r],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let s=-1;for(let e=0;e<t.length;++e)if(-1===t[e]){if(-1!==s)throw Error("Only one dimension can be inferred");s=e}let n=this.data;if(-1!==s){let e=t.reduce((e,t,n)=>n!==s?e*t:e,1);t[s]=n.length/e}return new e(this.type,n,t)}neg_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=-e[t];return this}neg(){return this.clone().neg_()}gt(t){let s=new Uint8Array(this.data.length),n=this.data;for(let e=0;e<n.length;++e)s[e]=+(n[e]>t);return new e("bool",s,this.dims)}lt(t){let s=new Uint8Array(this.data.length),n=this.data;for(let e=0;e<n.length;++e)s[e]=+(n[e]<t);return new e("bool",s,this.dims)}clamp_(e,t){let s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],e),t);return this}clamp(e,t){return this.clone().clamp_(e,t)}round_(){let e=this.data;for(let t=0;t<e.length;++t)e[t]=Math.round(e[t]);return this}round(){return this.clone().round_()}mean(e=null,t=!1){return nz(this,e,t)}min(t=null,s=!1){if(null===t){let t=sj(this.data)[0];return new e(this.type,[t],[])}let[n,r,a]=nP((e,t)=>Math.min(e,t),this,t,s,1/0);return new e(n,r,a)}max(t=null,s=!1){if(null===t){let t=sR(this.data)[0];return new e(this.type,[t],[])}let[n,r,a]=nP((e,t)=>Math.max(e,t),this,t,s,-1/0);return new e(n,r,a)}argmin(t=null,s=!1){if(null!==t)throw Error("`dim !== null` not yet implemented.");return new e("int64",[BigInt(sj(this.data)[1])],[])}argmax(t=null,s=!1){if(null!==t)throw Error("`dim !== null` not yet implemented.");return new e("int64",[BigInt(sR(this.data)[1])],[])}repeat(...t){if(t.length<this.dims.length)throw Error(`Number of dimensions of repeat dims (${t.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(t.every(e=>1===e)){if(t.length===this.dims.length)return this.clone();let s=Array(t.length-this.dims.length).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),s)}let s=Array(t.length-this.dims.length).fill(1).concat(this.dims),n=s.map((e,s)=>e*t[s]),r=n.reduce((e,t)=>e*t,1),a=this.data,i=new a.constructor(r),o=nL(s),l=nL(n);for(let e=0;e<r;++e){let t=e,r=0;for(let e=0;e<n.length;++e){let n=Math.floor(t/l[e]);t%=l[e],r+=n%s[e]*o[e]}i[e]=a[r]}return new e(this.type,i,n)}tile(...e){return e.length<this.dims.length&&(e=Array(this.dims.length-e.length).fill(1).concat(e)),this.repeat(...e)}to(t){let s;
1if(this.type===t)return this;if(!nw.hasOwnProperty(t))throw Error(`Unsupported type: ${t}`);let n=["int64","uint64"].includes(this.type),r=["int64","uint64"].includes(t);if(n&&!r)s=Number;else if(!n&&r)s=["float16","float32","float64"].includes(this.type)?e=>BigInt(Math.floor(e)):BigInt;else if("float16"===this.type&&"float32"==t&&this.data instanceof Uint16Array)return new e(t,sJ(this.data),this.dims);return new e(t,nw[t].from(this.data,s),this.dims)}};function ny(e,[t,s],n="bilinear",r=!1){let a=e.dims.at(-3)??1,i=e.dims.at(-2),o=e.dims.at(-1),l=function(e,[t,s,n],[r,a],i="bilinear",o=!1){let l=a/n,c=r/s,d=new e.constructor(r*a*t),u=s*n,_=r*a;for(let i=0;i<r;++i)for(let r=0;r<a;++r){let o=i*a+r,h=(r+.5)/l-.5,p=(i+.5)/c-.5,m=Math.floor(h),f=Math.floor(p),g=Math.min(m+1,n-1),w=Math.min(f+1,s-1),x=h-(m=Math.max(m,0)),y=p-(f=Math.max(f,0)),b=(1-x)*(1-y),M=x*(1-y),k=(1-x)*y,v=x*y,E=f*n,A=w*n,C=E+m,F=E+g,S=A+m,T=A+g;for(let s=0;s<t;++s){let t=s*u;d[s*_+o]=b*e[t+C]+M*e[t+F]+k*e[t+S]+v*e[t+T]}}return d}(e.data,[a,i,o],[t,s],n,r);return new nx(e.type,l,[a,t,s])}async function nb(e,{size:t=null,mode:s="bilinear"}={}){let n,r;if(4!==e.dims.length)throw Error("`interpolate_4d` currently only supports 4D input.");if(!t)throw Error("`interpolate_4d` requires a `size` argument.");if(2===t.length)n=[...e.dims.slice(0,2),...t];else if(3===t.length)n=[e.dims[0],...t];else if(4===t.length)n=t;else throw Error("`size` must be of length 2, 3, or 4.");if("nearest"===s)r=await nl.nearest_interpolate_4d;else if("bilinear"===s)r=await nl.bilinear_interpolate_4d;else if("bicubic"===s)r=await nl.bicubic_interpolate_4d;else throw Error(`Unsupported mode: ${s}`);let a=new nx("int64",new BigInt64Array(n.map(BigInt)),[n.length]);return await r({x:e,s:a})}async function nM(e,t){let s=await nl.matmul;return await s({a:e,b:t})}async function nk(e,t){let s=await nl.top_k;return t=null==t?e.dims.at(-1):Math.min(t,e.dims.at(-1)),await s({x:e,k:new nx("int64",[BigInt(t)],[1])})}var nv=e=>new nx("int64",e,[e.length]);async function nE(e,t,s,n,r){let a=await nl.slice;return await a({x:e,s:nv(t),e:nv(s),a:nv(n),t:nv(r??Array(n.length).fill(1))})}function nA(e,t){return e=e.slice(),null===t?e=e.filter(e=>1!==e):"number"==typeof t?1===e[t]&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,s)=>1!==e||!t.includes(s))),e}function nC(e,t){return t=nF(t,e.length+1),(e=e.slice()).splice(t,0,1),e}function nF(e,t,s=null,n=!0){if(e<-t||e>=t)if(!n)return e<-t?0:t;else throw Error(`IndexError: index ${e} is out of bounds for dimension${null===s?"":" "+s} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function nS(e,t=0){t=nF(t,e[0].dims.length);let s=e[0].dims.slice();s[t]=e.reduce((e,s)=>e+s.dims[t],0);let n=s.reduce((e,t)=>e*t,1),r=new e[0].data.constructor(n),a=e[0].type;if(0===t){let t=0;for(let s of e){let e=s.data;r.set(e,t),t+=e.length}}else{let n=0;for(let a=0;a<e.length;++a){let{data:i,dims:o}=e[a];for(let e=0;e<i.length;++e){let a=0;for(let r=o.length-1,i=e,l=1;r>=0;--r){let e=o[r],c=i%e;r===t&&(c+=n),a+=c*l,l*=s[r],i=Math.floor(i/e)}r[a]=i[e]}n+=o[t]}}return new nx(a,r,s)}function nT(e,t=0){return nS(e.map(e=>e.unsqueeze(t)),t)}function nP(e,t,s,n=!1,r=null){let a=t.data,i=t.dims;s=nF(s,i.length);let o=i.slice();o[s]=1;let l=new a.constructor(a.length/i[s]);null!==r&&l.fill(r);for(let t=0;t<a.length;++t){let n=0;for(let e=i.length-1,r=t,a=1;e>=0;--e){let t=i[e];e!==s&&(n+=r%t*a,a*=o[e]),r=Math.floor(r/t)}l[n]=e(l[n],a[t],t,n)}return n||o.splice(s,1),[t.type,l,o]}function nz(e,t=null,s=!1){let n=e.dims,r=e.data;if(null===t){let t=r.reduce((e,t)=>e+t,0);return new nx(e.type,[t/r.length],[])}let[a,i,o]=nP((e,t)=>e+t,e,t=nF(t,n.length),s);if(1!==n[t])for(let e=0;e<i.length;++e)i[e]/=n[t];return new nx(a,i,o)}function nL(e){let t=Array(e.length);for(let s=e.length-1,n=1;s>=0;--s)t[s]=n,n*=e[s];return t}function nO(e,t,s,n){return new nx(s,new n(e.reduce((e,t)=>e*t,1)).fill(t),e)}function nI(e,t){let s,n;if("number"==typeof t)s="float32",n=Float32Array;else if("bigint"==typeof t)s="int64",n=BigInt64Array;else if("boolean"==typeof t)s="bool",n=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return nO(e,t,s,n)}function nN(e,t){return nI(e.dims,t)}function n$(e){return nO(e,1n,"int64",BigInt64Array)}function nB(e){return nO(e,0n,"int64",BigInt64Array)}async function nD(e){if(!e)throw Error("modelId is required for get_tokenizer_files");return(await sT(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function nV(e,t){let s=await nD(e);return await Promise.all(s.map(s=>sq(e,s,!0,t)))}function nq(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(1!==t[0])throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var nG=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function nj(e,...t){for(let s of t){if(!Object.hasOwn(e,s))continue;let t=e[s];if(t)if("object"!=typeof t)return t;else if("AddedToken"===t.__type)return t.content;else throw Error(`Unknown token: ${t}`)}return null}var nR=class extends D{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new ta(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=nj(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_i
1d(this.mask_token),this.pad_token=nj(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=nj(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=nj(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=nj(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=nj(t,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=Object.create(null);for(let{name:t,template:s}of this.chat_template){if("string"!=typeof t||"string"!=typeof s)throw Error('Chat template must be a list of objects with "name" and "template" properties');e[t]=s}this.chat_template=e}this._compiled_template_cache=new Map;let s=function(e){let t=[];for(let s of e.get_added_tokens_decoder().values())s.special&&t.push(s);return t}(this._tokenizer);this.all_special_ids=s.map(e=>e.id),this.all_special_tokens=s.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:r=!1,revision:a="main"}={}){return new this(...await nV(e,{progress_callback:t,config:s,cache_dir:n,local_files_only:r,revision:a}))}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"string"==typeof e?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,t={}){let s,{text_pair:n=null,add_special_tokens:r=!0,padding:a=!1,return_token_type_ids:i=null}=t,{truncation:o=null,max_length:l=null}=t,c=t.return_tensor??!0,d=Array.isArray(e);if(d){if(0===e.length)throw Error("text array must be non-empty");if(null!==n){if(Array.isArray(n)){if(e.length!==n.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");s=e.map((e,t)=>this._encode_plus(e,{text_pair:n[t],add_special_tokens:r,return_token_type_ids:i}))}else s=e.map(e=>this._encode_plus(e,{add_special_tokens:r,return_token_type_ids:i}))}else{if(null==e)throw Error("text may not be null or undefined");if(Array.isArray(n))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");s=[this._encode_plus(e,{text_pair:n,add_special_tokens:r,return_token_type_ids:i})]}if(null===l?l=this.model_max_length:null===o&&(!0===a?(W.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):!1===a&&(W.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)),!0===a&&(l=Math.min(sR(s.map(e=>e.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),a||o)for(let e=0;e<s.length;++e)if(s[e].input_ids.length===l)continue;else s[e].input_ids.length>l?o&&function(e,t){for(let s of Object.keys(e))e[s].length=t}(s[e],l):a&&function(e,t,s,n){for(let r of Object.keys(e)){let a=t-e[r].length,i=s(r),o=Array(a).fill(i);e[r]="right"===n?j(e[r],o):j(o,e[r])}}(s[e],l,e=>"input_ids"===e?this.pad_token_id:0,this.padding_side);let u={};if(c){if(!(a&&o)&&s.some(e=>{for(let t of Object.keys(e))if(e[t].length!==s[0][t]?.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 e=[s.length,s[0].input_ids.length];for(let t of Object.keys(s[0]))u[t]=new nx("int64",BigInt64Array.from(s.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(s[0]))u[e]=s.map(t=>t[e]);if(!d)for(let e of Object.keys(u))u[e]=u[e][0]}return u}_encode_text(e){return null===e?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:r,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:r,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:t=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:s})}encode(e,{text_pair:t=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,t={}){return e instanceof nx&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){var s;if(e instanceof nx&&(e=nq(e)),!Array.isArray(e)||0===e.length||!(Number.isInteger(s=e[0])||"bigint"==typeof s))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:s})}
1get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&"object"==typeof this.chat_template){let s=this.chat_template;if(null!==e&&Object.hasOwn(s,e))e=s[e];else if(null===e)if(null!==t&&"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(null===e)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,t={}){let{tools:s=null,documents:n=null,chat_template:r=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:o=!1,truncation:l=!1,max_length:c=null,return_tensor:d=!0,return_dict:u=!0,tokenizer_kwargs:_={},...h}=t;if("string"!=typeof(r=this.get_chat_template({chat_template:r,tools:s})))throw Error(`chat_template must be a string, but got ${typeof r}`);let p=this._compiled_template_cache.get(r);void 0===p&&(p=new si(r),this._compiled_template_cache.set(r,p));let m=Object.create(null);for(let e of nG){let t=nj(this.config,e);t&&(m[e]=t)}let f=p.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...m,...h});if(i){let e=this._call(f,{add_special_tokens:!1,padding:o,truncation:l,max_length:c,return_tensor:d,..._});return u?e:e.input_ids}return f}};function nU(e,t,s,n){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||"function"!=typeof e.lang_to_token)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let r=n.src_lang,a=n.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(void 0!==r){if(!e.language_codes.includes(r))throw Error(`Source language code "${r}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(let t of e._tokenizer.post_processor.config.single)if("SpecialToken"in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(r);break}}return n.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,s)}var nW={};_(nW,{AlbertTokenizer:()=>nQ,AutoTokenizer:()=>rL,BartTokenizer:()=>nH,BertTokenizer:()=>nX,BlenderbotSmallTokenizer:()=>nJ,BlenderbotTokenizer:()=>nK,BloomTokenizer:()=>nY,CLIPTokenizer:()=>n0,CamembertTokenizer:()=>nZ,CodeGenTokenizer:()=>n2,CodeLlamaTokenizer:()=>n1,CohereAsrTokenizer:()=>n4,CohereTokenizer:()=>n3,ConvBertTokenizer:()=>n8,DebertaTokenizer:()=>n5,DebertaV2Tokenizer:()=>n6,DistilBertTokenizer:()=>n9,ElectraTokenizer:()=>n7,EsmTokenizer:()=>re,FalconTokenizer:()=>rt,GPT2Tokenizer:()=>rr,GPTNeoXTokenizer:()=>rn,GemmaTokenizer:()=>rs,HerbertTokenizer:()=>ra,LlamaTokenizer:()=>ri,M2M100Tokenizer:()=>ro,MBart50Tokenizer:()=>rd,MBartTokenizer:()=>rc,MPNetTokenizer:()=>rh,MarianTokenizer:()=>rl,MgpstrTokenizer:()=>ru,MobileBertTokenizer:()=>r_,NllbTokenizer:()=>rp,NougatTokenizer:()=>rm,PreTrainedTokenizer:()=>nR,Qwen2Tokenizer:()=>rf,RoFormerTokenizer:()=>rw,RobertaTokenizer:()=>rg,SiglipTokenizer:()=>rx,SpeechT5Tokenizer:()=>ry,SqueezeBertTokenizer:()=>rb,T5Tokenizer:()=>rM,TokenizersBackend:()=>nR,VitsTokenizer:()=>rv,Wav2Vec2CTCTokenizer:()=>rE,WhisperTokenizer:()=>rT,XLMRobertaTokenizer:()=>rP,XLMTokenizer:()=>rz});var nQ=class extends nR{return_token_type_ids=!0},nH=class extends nR{},nX=class extends nR{return_token_type_ids=!0},nJ=class extends nR{},nK=class extends nR{},nY=class extends nR{},nZ=class extends nR{},n0=class extends nR{},n1=class extends nR{},n2=class extends nR{},n3=class extends nR{},n4=class extends nR{},n8=class extends nR{return_token_type_ids=!0},n6=class extends nR{return_token_type_ids=!0},n5=class extends nR{return_token_type_ids=!0},n9=class extends nR{},n7=class extends nR{return_token_type_ids=!0},re=class extends nR{},rt=class extends nR{},rs=class extends nR{},rn=class extends nR{},rr=class extends nR{},ra=class extends nR{return_token_type_ids=!0},ri=class extends nR{padding_side="left"},ro=class extends nR{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,s){return nU(this,e,t,s)}},rl=class extends nR{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),W.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(null===e)return null;let[t,...s]=e.trim().split(this.languageRegex);if(0===s.length)return super._encode_text(t);if(2===s.length){let[e,t]=s;return this.supported_language_codes.includes(e)||W.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),j([e],super._encode_text(t))}}},rc=class extends nR{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,s){return nU(this,e,t,s)}},rd=class extends rc{},ru=class extends nR{},r_=class extends nR{return_token_type_ids=!0},rh=class extends nR{},rp=class extends nR{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,s){return nU(this,e,t,s)}},rm=class extends nR{},rf=class extends nR{},rg=class extends nR{},rw=class extends nR{return_token_type_ids=!0},rx=class extends nR{},ry=class extends nR{},rb=class extends nR{return_token_type_ids=!0},rM=class extends nR{},rk=class extends e3{decode_chain(e){let t="";for(let s=1;s<e.length;s+=2)t+=e[s];return[t]}},rv=class extends nR{constructor(e,t){super(e,t),this._tokenizer.decoder=new rk({type:"VitsDecoder"})}},rE=class extends nR{},rA=[["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","swedis
1h"],["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"]],rC=new Map(rA),rF=new Map([...rA.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]),rS=RegExp(`^[\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]+$`,"gu"),rT=class extends nR{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:r=!0}={}){if(null===n)throw Error("Must specify time_precision");let a=null,i="word"===t;function o(){return{language:a,timestamp:[null,null],text:""}}let l=[],c=o(),d=0,u=this.timestamp_begin,_=u+1500,h=[],p=[],m=!1,f=null,g=new Set(this.all_special_ids);for(let s of e){let e=s.tokens,r=i?s.token_timestamps:null,w=null,x=u;if("stride"in s){let[t,r,a]=s.stride;if(d-=r,f=t-a,r&&(x=r/n+u),a)for(let t=e.length-1;t>=0;--t){let s=Number(e[t]);if(s>=u){if(null!==w&&(s-u)*n<f)break;w=s}}}let y=[],b=[];for(let s=0;s<e.length;++s){let f=Number(e[s]);if(g.has(f)){let e=this.decode([f]),s=rC.get(e.slice(2,-2));if(void 0!==s){if(null!==a&&s!==a&&!t){h.push(y);let e=this.findLongestCommonSequence(h)[0],t=this.decode(e);c.text=t,l.push(c),h=[],y=[],c=o()}a=c.language=s}}else if(f>=u&&f<=_){let e=sX((f-u)*n+d,2);if(null!==w&&f>=w)m=!0;else if(m||h.length>0&&f<x)m=!1;else if(null===c.timestamp[0])c.timestamp[0]=e;else if(e===c.timestamp[0]);else{c.timestamp[1]=e,h.push(y),i&&p.push(b);let[t,s]=this.findLongestCommonSequence(h,p),n=this.decode(t);if(c.text=n,i&&(c.words=this.collateWordTimestamps(t,s,a),c.words.length>0&&null!==c.timestamp[1]))for(let e of c.words)e.timestamp[1]>c.timestamp[1]&&c.timestamp[1]>=e.timestamp[0]&&(e.timestamp[1]=c.timestamp[1]);l.push(c),h=[],y=[],p=[],b=[],c=o()}}else if(y.push(f),i){let e,t=sX(r[s]+d,2);if(s+1<r.length){e=sX(r[s+1]+d,2);let a=this.decode([f]);rS.test(a)&&(e=sX(Math.min(t+n,e),2))}else e=null;b.push([t,e])}}if("stride"in s){let[e,t,n]=s.stride;d+=e-n}y.length>0?(h.push(y),i&&p.push(b)):h.every(e=>0===e.length)&&(c=o(),h=[],y=[],p=[],b=[])}if(h.length>0){if(r&&t)throw 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[e,s]=this.findLongestCommonSequence(h,p),n=this.decode(e);c.text=n,i&&(c.words=this.collateWordTimestamps(e,s,a)),l.push(c)}let w=Object.create(null),x=l.map(e=>e.text).join("");if(t||s){for(let e=0;e<l.length;++e){let n=l[e];t||delete n.timestamp,s||delete n.language}if(i){let e=[];for(let t of l)for(let s of t.words)e.push(s);w={chunks:e}}else w={chunks:l}}return[x,w]}findLongestCommonSequence(e,t=null){let s=e[0],n=s.length,r=[],a=Array.isArray(t)&&t.length>0,i=a?[]:null,o=a?t[0]:null;for(let l=1;l<e.length;++l){let c=e[l],d=0,u=[n,n,0,0],_=c.length;for(let e=1;e<n+_;++e){let r,i=Math.max(0,n-e),h=Math.min(n,n+_-e),p=s.slice(i,h),m=Math.max(0,e-n),f=Math.min(_,e),g=c.slice(m,f);if(p.length!==g.length)throw Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");r=a?p.filter((e,s)=>e===g[s]&&o[i+s][0]-.1<=t[l][m+s][0]).length:p.filter((e,t)=>
1e===g[t]).length;let w=e/1e4,x=r/e+w;r>1&&x>d&&(d=x,u=[i,h,m,f])}let[h,p,m,f]=u,g=Math.floor((p+h)/2),w=Math.floor((f+m)/2);if(a&&0===d&&n>0){let e=o[n-1][0],s=t[l].findIndex(t=>t[0]>=e);w=-1===s?c.length:s}r.push(...s.slice(0,g)),n=(s=c.slice(w)).length,a&&(i.push(...o.slice(0,g)),o=t[l].slice(w))}return(r.push(...s),a)?(i.push(...o),[r,i]):[r,[]]}collateWordTimestamps(e,t,s){let[n,r,a]=this.combineTokensIntoWords(e,s),i=[];for(let e=0;e<n.length;++e){let s=a[e];i.push({text:n[e],timestamp:[t[s.at(0)][0],t[s.at(-1)][1]]})}return i}combineTokensIntoWords(e,t,s=`"'\u201C\xa1\xBF([{-`,n=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){let r,a,i;return["chinese","japanese","thai","lao","myanmar"].includes(t=t??"english")?[r,a,i]=this.splitTokensOnUnicode(e):[r,a,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(r,a,i,s,n)}decode(e,t){let s;return t?.decode_with_timestamps?(e instanceof nx&&(e=nq(e)),s=this.decodeWithTimestamps(e,t)):s=super.decode(e,t),s}decodeWithTimestamps(e,t){let s=t?.time_precision??.02,n=this.all_special_ids.at(-1)+1,r=[[]];for(let t of e)if((t=Number(t))>=n){let e=((t-n)*s).toFixed(2);r.push(`<|${e}|>`),r.push([])}else r[r.length-1].push(t);return(r=r.map(e=>"string"==typeof e?e:super.decode(e,t))).join("")}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),s=[],n=[],r=[],a=[],i=[],o=0;for(let l=0;l<e.length;++l){let c=e[l];a.push(c),i.push(l);let d=this.decode(a,{decode_with_timestamps:!0});d.includes("�")&&"�"!==t[o+d.indexOf("�")]||(s.push(d),n.push(a),r.push(i),a=[],i=[],o+=d.length)}return[s,n,r]}splitTokensOnSpaces(e){let[t,s,n]=this.splitTokensOnUnicode(e),r=[],a=[],i=[];for(let e=0;e<t.length;++e){let o=t[e],l=s[e],c=n[e],d=l[0]>=this._tokenizer.token_to_id("<|endoftext|>"),u=o.startsWith(" "),_=o.trim(),h=rS.test(_);if(d||u||h||0===r.length)r.push(o),a.push(l),i.push(c);else{let e=r.length-1;r[e]+=o,a[e].push(...l),i[e].push(...c)}}return[r,a,i]}mergePunctuations(e,t,s,n,r){let a=structuredClone(e),i=structuredClone(t),o=structuredClone(s),l=a.length-2,c=a.length-1;for(;l>=0;)a[l].startsWith(" ")&&n.includes(a[l].trim())?(a[c]=a[l]+a[c],i[c]=j(i[l],i[c]),o[c]=j(o[l],o[c]),a[l]="",i[l]=[],o[l]=[]):c=l,--l;for(l=0,c=1;c<a.length;)!a[l].endsWith(" ")&&r.includes(a[c])?(a[l]+=a[c],i[l]=j(i[l],i[c]),o[l]=j(o[l],o[c]),a[c]="",i[c]=[],o[c]=[]):l=c,++c;return[a.filter(e=>e),i.filter(e=>e.length>0),o.filter(e=>e.length>0)]}},rP=class extends nR{},rz=class extends nR{return_token_type_ids=!0;constructor(e,t){super(e,t),W.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},rL=class{static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:r=!1,revision:a="main"}={}){let[i,o]=await nV(e,{progress_callback:t,config:s,cache_dir:n,local_files_only:r,revision:a}),l=o.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",c=nW[l];return c||(W.warn(`Unknown tokenizer class "${l}", attempting to construct from base class.`),c=nR),new c(i,o)}},rO="https://github.com/huggingface/transformers.js/issues/new/choose",rI="preprocessor_config.json",rN="processor_config.json",r$="chat_template.jinja",rB=class extends D{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,s){super(),this.config=e,this.components=t,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,t={}){if(!this.tokenizer)throw 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,...t})}batch_decode(...e){if(!this.tokenizer)throw Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...t){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...t);throw Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){let[s,n,r]=await Promise.all([this.uses_processor_config?sq(e,rN,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async s=>{let n=await this[s].from_pretrained(e,t);return[s.replace(/_class$/,""),n]})).then(Object.fromEntries),this.uses_chat_template_file?sV(e,r$,!0,t):null]);return new this(s,n,r)}},rD={};_(rD,{ChatterboxProcessor:()=>ah,CohereAsrProcessor:()=>am,Florence2Processor:()=>i$,Gemma3Processor:()=>iB,Gemma3nProcessor:()=>iD,Gemma4Processor:()=>iV,Glm46VProcessor:()=>iG,GraniteSpeechProcessor:()=>ij,GroundingDinoProcessor:()=>iR,Idefics3Processor:()=>iU,JinaCLIPProcessor:()=>iQ,Lfm2VlProcessor:()=>iH,LlavaProcessor:()=>iX,MgpstrProcessor:()=>iK,MoonshineProcessor:()=>iY,OwlViTProcessor:()=>iZ,PaliGemmaProcessor:()=>i1,Phi3VProcessor:()=>i4,PixtralProcessor:()=>i8,Processor:()=>rB,PyAnnoteProcessor:()=>
1i6,Qwen2VLProcessor:()=>iq,Qwen2_5_VLProcessor:()=>i5,Qwen3VLProcessor:()=>i9,Sam2Processor:()=>oe,Sam2VideoProcessor:()=>ot,SamProcessor:()=>i7,SmolVLMProcessor:()=>iU,SpeechT5Processor:()=>os,UltravoxProcessor:()=>on,VLChatProcessor:()=>iW,VoxtralProcessor:()=>oa,VoxtralRealtimeProcessor:()=>oi,Wav2Vec2Processor:()=>oo,Wav2Vec2ProcessorWithLM:()=>ol,WhisperProcessor:()=>oc});var rV=class extends D{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){return new this(await sq(e,rI,!0,t))}};function rq(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} 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 rG={};_(rG,{ASTFeatureExtractor:()=>r3,ChatterboxFeatureExtractor:()=>r8,ClapFeatureExtractor:()=>r6,CohereAsrFeatureExtractor:()=>r9,DacFeatureExtractor:()=>r7,EncodecFeatureExtractor:()=>r4,FeatureExtractor:()=>rV,Gemma3nAudioFeatureExtractor:()=>ae,Gemma4AudioFeatureExtractor:()=>at,GraniteSpeechFeatureExtractor:()=>as,MoonshineFeatureExtractor:()=>an,ParakeetFeatureExtractor:()=>r5,PyAnnoteFeatureExtractor:()=>ar,SeamlessM4TFeatureExtractor:()=>aa,SnacFeatureExtractor:()=>ai,SpeechT5FeatureExtractor:()=>ao,VoxtralRealtimeFeatureExtractor:()=>ad,Wav2Vec2FeatureExtractor:()=>al,WeSpeakerFeatureExtractor:()=>ac,WhisperFeatureExtractor:()=>au});var rj={fromWeb:()=>{}};async function rR(e,t){if(F.IS_BROWSER_ENV){if(F.IS_WEBWORKER_ENV)throw Error("Unable to save a file from a Web Worker.");let s=URL.createObjectURL(t),n=document.createElement("a");n.href=s,n.download=e,n.click(),n.remove(),URL.revokeObjectURL(s)}else if(F.IS_FS_AVAILABLE){let s=t.stream();rj.fromWeb(s),h.createWriteStream(e),await void 0}else throw Error("Unable to save because filesystem is disabled in this environment.")}async function rU(e,t){let s;if("undefined"==typeof AudioContext)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 n=await (await sz(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});void 0===t&&W.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let a=await r.decodeAudioData(n);if(2===a.numberOfChannels){let e=Math.sqrt(2),t=a.getChannelData(0),n=a.getChannelData(1);s=new Float32Array(t.length);for(let r=0;r<a.length;++r)s[r]=e*(t[r]+n[r])/2}else s=a.getChannelData(0);return s}function rW(e,t){if(e<1)return new Float64Array;if(1===e)return new Float64Array([1]);let s=1-t,n=2*Math.PI/(e-1),r=new Float64Array(e);for(let a=0;a<e;++a)r[a]=t-s*Math.cos(a*n);return r}var rQ={htk:e=>2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,s=15,n=27/Math.log(6.4))=>e>=t?s+Math.log(e/t)*n:3*e/200};function rH(e,t="htk"){let s=rQ[t];if(!s)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?s(e):e.map(e=>s(e))}var rX={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,s=15,n=Math.log(6.4)/27)=>e>=s?t*Math.exp(n*(e-s)):200*e/3};function rJ(e,t,s){let n=(t-e)/(s-1);return Float64Array.from({length:s},(t,s)=>e+n*s)}function rK(e,t,s,n,r,a=null,i="htk",o=!1){let l;if(null!==a&&"slaney"!==a)throw Error('norm must be one of null or "slaney"');if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(s>n)throw Error(`Require min_frequency: ${s} <= max_frequency: ${n}`);let c=rJ(rH(s,i),rH(n,i),t+2),d=function(e,t="htk"){let s=rX[t];if(!s)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return"number"==typeof e?s(e):e.map(e=>s(e))}(c,i);if(o){let t=r/((e-1)*2);l=rH(Float64Array.from({length:e},(e,s)=>s*t),i),d=c}else l=rJ(0,Math.floor(r/2),e);let u=function(e,t){let s=Float64Array.from({length:t.length-1},(e,s)=>t[s+1]-t[s]),n=Array.from({length:e.length},()=>Array(t.length));for(let s=0;s<e.length;++s){let r=n[s];for(let n=0;n<t.length;++n)r[n]=t[n]-e[s]}let r=t.length-2,a=Array.from({length:r},()=>Array(e.length));for(let t=0;t<e.length;++t){let e=n[t];for(let n=0;n<r;++n){let r=-e[n]/s[n],i=e[n+2]/s[n+1];a[n][t]=Math.max(0,Math.min(r,i))}}return a}(l,d);if(null!==a&&"slaney"===a)for(let s=0;s<t;++s){let t=u[s],n=2/(d[s+2]-d[s]);for(let s=0;s<e;++s)t[s]*=n}return u}function rY(e,t,s,n,r){if(s<=0)throw Error("reference must be greater than zero");if(n<=0)throw Error("min_value must be greater than zero");let a=Math.log10(s=Math.max(n,s));for(let s=0;s<e.length;++s)e[s]=t*Math.log10(Math.max(n,e[s])-a);if(null!==r){if(r<=0)throw Error("db_range must be greater than zero");let t=sR(e)[0]-r;for(let s=0;s<e.length;++s)e[s]=Math.max(e[s],t)}return e}async function rZ(e,t,s,n,{fft_length:r=null,power:a=1,center:i=!0,pad_mode:o="reflect",onesided:l
1=!0,preemphasis:c=null,preemphasis_htk_flavor:d=!0,mel_filters:u=null,mel_floor:_=1e-10,log_mel:h=null,max_log_mel:p=null,reference:m=1,min_value:f=1e-10,db_range:g=null,remove_dc_offset:w=null,min_num_frames:x=null,max_num_frames:y=null,do_pad:b=!0,transpose:M=!1,mel_offset:k=0,mel_floor_mode:v="clamp"}={}){let E=t.length;if(null===r&&(r=s),s>r)throw Error(`frame_length (${s}) may not be larger than fft_length (${r})`);if(E!==s)throw Error(`Length of the window (${E}) must equal frame_length (${s})`);if(n<=0)throw Error("hop_length must be greater than zero");if(null===a&&null!==u)throw 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(!d)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(i){let t=Math.floor(s/2);switch(o){case"reflect":e=function(e,t,s){let n=new e.constructor(e.length+t+s),r=e.length-1;for(let s=0;s<e.length;++s)n[t+s]=e[s];for(let s=1;s<=t;++s)n[t-s]=e[R(s,r)];for(let a=1;a<=s;++a)n[r+t+a]=e[R(r-a,r)];return n}(e,t,t);break;case"constant":{let s=new e.constructor(e.length+2*t);s.set(e,t),e=s;break}case"semicausal":{let s=new e.constructor(e.length+t);s.set(e,t),e=s;break}default:throw Error(`pad_mode="${o}" not implemented yet.`)}}let A=Math.floor(1+Math.floor((e.length-s)/n));null!==x&&A<x&&(A=x);let C=l?Math.floor(r/2)+1:r,F=A,S=A;null!==y&&(y>A?b&&(S=y):S=F=y);let T=new sH(r),P=new Float64Array(r),z=new Float64Array(T.outputBufferSize),L=new Float32Array(C*S);for(let r=0;r<F;++r){let a=r*n,i=Math.min(e.length-a,s);i!==s&&P.fill(0,0,s);for(let t=0;t<i;++t)P[t]=e[a+t];if(w){let e=0;for(let t=0;t<i;++t)e+=P[t];let t=e/i;for(let e=0;e<i;++e)P[e]-=t}if(null!==c){for(let e=i-1;e>=1;--e)P[e]-=c*P[e-1];P[0]*=1-c}for(let e=0;e<t.length;++e)P[e]*=t[e];T.realTransform(z,P);for(let e=0;e<C;++e){let t=e<<1;L[e*S+r]=z[t]**2+z[t+1]**2}}if(null!==a&&2!==a){let e=a/2;for(let t=0;t<L.length;++t)L[t]**=e}let O=u.length,I=await nM(new nx("float32",u.flat(),[O,C]),new nx("float32",L,[C,S]));M&&(I=I.transpose(1,0));let N=I.data;if("add"===v)for(let e=0;e<N.length;++e)N[e]=k+N[e]+_;else for(let e=0;e<N.length;++e)N[e]=k+Math.max(_,N[e]);if(null!==a&&null!==h){let e=Math.min(N.length,F*O);switch(h){case"log":for(let t=0;t<e;++t)N[t]=Math.log(N[t]);break;case"log10":for(let t=0;t<e;++t)N[t]=Math.log10(N[t]);break;case"log10_max_norm":{for(let t=0;t<e;++t)N[t]=Math.log10(N[t]);let t=(p??sR(N)[0])-8;for(let s=0;s<e;++s)N[s]=(Math.max(N[s],t)+4)/4;break}case"dB":if(1===a)!function(e,t=1,s=1e-5,n=null){rY(e,20,t,s,n)}(N,m,f,g);else if(2===a)!function(e,t=1,s=1e-10,n=null){rY(e,10,t,s,n)}(N,m,f,g);else throw Error(`Cannot use log_mel option '${h}' with power ${a}`);break;default:throw Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${h}'`)}}return I}function r0(e,t,{periodic:s=!0,frame_length:n=null,center:r=!0}={}){let a,i=s?e+1:e;switch(t){case"boxcar":a=new Float64Array(i).fill(1);break;case"hann":case"hann_window":a=rW(i,.5);break;case"hamming":a=rW(i,.54);break;case"povey":a=rW(i,.5).map(e=>Math.pow(e,.85));break;default:throw Error(`Unknown window type ${t}.`)}if(s&&(a=a.subarray(0,e)),null===n||e===n)return a;if(e>n)throw Error(`Length of the window (${e}) may not be larger than frame_length (${n})`);let o=new Float64Array(n),l=r?Math.floor((n-e)/2):0;return o.set(a,l),o}function r1(e,t,s){for(let n=0;n<s.length;++n)e.setUint8(t+n,s.charCodeAt(n))}var r2=class{constructor(e,t){this.audio=e,this.sampling_rate=t}get data(){if(!Array.isArray(this.audio))return this.audio;{if(0===this.audio.length)return new Float32Array(0);if(1===this.audio.length)return this.audio[0];let e=new Float32Array(this.audio.reduce((e,t)=>e+t.length,0)),t=0;for(let s of this.audio)e.set(s,t),t+=s.length;return e}}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),function(e,t){let s=e.reduce((e,t)=>e+t.length,0),n=new ArrayBuffer(44),r=new DataView(n);return r1(r,0,"RIFF"),r.setUint32(4,36+4*s,!0),r1(r,8,"WAVE"),r1(r,12,"fmt "),r.setUint32(16,16,!0),r.setUint16(20,3,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,4*t,!0),r.setUint16(32,4,!0),r.setUint16(34,32,!0),r1(r,36,"data"),r.setUint32(40,4*s,!0),new Blob([n,...e.map(e=>e.buffer)],{type:"audio/wav"})}(e,this.sampling_rate)}async save(e){return rR(e,this.toBlob())}},r3=class extends rV{constructor(e){super(e);let t=this.config.sampling_rate,s=rK(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=r0(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return rZ(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:t,transpose:!0})}async _call(e){rq(e,"ASTFeatureExtractor");let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=2*this.std,s=t.data;for(let t=0;t<s.length;++t)s[t]=(s[t]-this.mean)/e}return{input_values:t.unsqueeze_(0)}}},r4=class extends rV{async _call(e){rq(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=this.config.feature_size;if(e.length%t!=0)throw Error(`The length of the audio data must be a multiple of the number of channels (${t}).`);let s=[1,t,e.length/t];return{input_values:new nx("float32",e,s)}}},r8=class extends rV{async _call(e){rq(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new nx("float32",e,t)}}},r6=class extends rV{constructor(e){super(e),this.mel_filters=rK(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=rK(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=r0(this.config.fft_window_size,"hann")}async _get_input_mel(e,t,s,n){let r,a=e.length-t;if(a>0)if("rand_trunc"===s){let s=Math.floor(s_.random()*(a+1));e=e.subarray(s,s+t),r=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${s}" not implemented`);else{if(a<0){let s=new Float64Array(t);if(s.set(e),"repeat"===n)for(let n=e.length;n<t;n+=e.length)s.set(e.subarray(0,Math.min(e.length,t-n)),n);else if("repeatpad"===n)for(let t=e.length;t<-a;t+=e.length)s.set(e,t);e=s}if("fusion"===s)throw Error(`Truncation strategy "${s}" not implemented`);r=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return r.unsqueeze_(0)}async _extract_fbank_features(e,t,s=null){return rZ(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:t,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:t=null}={}){return rq(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,t??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},r5=class extends rV{constructor(e){super(e),this.config.mel_filters??=rK(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 t=r0(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(t,s)}async _extract_fbank_features(e){let t=this.config.preemphasis;e=new Float64Array(e);for(let s=e.length-1;s>=1;--s)e[s]-=t*e[s-1];return await rZ(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:5960464477539063e-23})}async _call(e){rq(e,"ParakeetFeatureExtractor");let t=await this._extract_fbank_features(e),s=Math.floor((e.length+2*Math.floor(this.config.n_fft/2)-this.config.n_fft)/this.config.hop_length),n=t.data;n.fill(0,s*t.dims[1]);let[r,a]=t.dims,i=new Float64Array(a),o=new Float64Array(a);for(let e=0;e<s;++e){let t=e*a;for(let e=0;e<a;++e){let s=n[t+e];i[e]+=s,o[e]+=s*s}}let l=s>
11?s-1:1;for(let e=0;e<a;++e){let t=i[e]/s,r=1/(Math.sqrt((o[e]-s*t*t)/l)+1e-5);for(let i=0;i<s;++i){let s=i*a+e;n[s]=(n[s]-t)*r}}let c=new BigInt64Array(r);return c.fill(1n,0,s),{input_features:t.unsqueeze_(0),attention_mask:new nx("int64",c,[1,r])}}},r9=class extends r5{_apply_dither(e){let t=this.config.dither??0;if(t<=0)return e;let s=new sc(e.length);for(let n=0;n<e.length;++n)e[n]+=t*s.gauss();return e}split_audio(e){let t=this.config.max_audio_clip_s??35,s=this.config.overlap_chunk_second??5,n=this.config.min_energy_window_samples??1600,r=this.config.sampling_rate,a=Math.max(1,Math.round(t*r)),i=Math.max(1,Math.round(s*r));if(e.length<=a)return[e];let o=[],l=0,c=e.length;for(;l<c;){let t;if(l+a>=c){o.push(e.slice(l,c));break}let s=Math.max(l,l+a-i),r=Math.min(l+a,c);t=r<=s?l+a:this._find_split_point_energy(e,s,r,n),t=Math.max(l+1,Math.min(t,c)),o.push(e.slice(l,t)),l=t}return o}_find_split_point_energy(e,t,s,n){let r=s-t;if(r<=n)return Math.floor((t+s)/2);let a=1/0,i=t,o=r-n;for(let s=0;s<=o;s+=n){let r=0;for(let a=0;a<n;++a){let n=e[t+s+a];r+=n*n}(r=Math.sqrt(r/n))<a&&(a=r,i=t+s)}return i}async _call(e){rq(e,"CohereAsrFeatureExtractor");let t=new Float64Array(e);return this._apply_dither(t),super._call(t)}},r7=class extends r4{},ae=class extends rV{constructor(e){super(e);let{fft_length:t,feature_size:s,min_frequency:n,max_frequency:r,sampling_rate:a,frame_length:i}=this.config,o=rK(Math.floor(1+t/2),s,n,r,a,null,"htk",!1);this.mel_filters=o,this.window=r0(i,"hann")}async _extract_fbank_features(e,t){return rZ(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:t=48e4,truncation:s=!0,padding:n=!0,pad_to_multiple_of:r=128}={}){if(rq(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>t&&(e=e.slice(0,t)),n&&e.length%r!=0){let t=r-e.length%r,s=new Float64Array(e.length+t);s.set(e),0!==this.config.padding_value&&s.fill(this.config.padding_value,e.length),e=s}let a=await this._extract_fbank_features(e,this.config.max_length),i=nI([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}},at=class extends ae{async _extract_fbank_features(e,t){let{frame_length:s,hop_length:n,fft_length:r}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return rZ(e,this.window,s,n,{fft_length:r,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,t={}){rq(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,t),{input_features:r}=n,[,a,i]=r.dims,{frame_length:o,hop_length:l}=this.config,c=Math.floor(o/2),d=o+1,u=new Uint8Array(s+c+(t.pad_to_multiple_of??128));u.fill(1,c,c+s);let _=new Uint8Array(a);for(let e=0;e<a;++e)_[e]=+!!u[e*l+d-1];let h=r.data;for(let e=0;e<a;++e)_[e]||h.fill(0,e*i,(e+1)*i);return n.input_features_mask=new nx("bool",_,[1,a]),n}},as=class extends rV{constructor(e){super(e);let{n_fft:t,win_length:s,n_mels:n,sample_rate:r}=e.melspec_kwargs;this.mel_filters=rK(Math.floor(1+t/2),n,0,r/2,r,null,"htk");let a=r0(s,"hann");this.window=new Float64Array(t);let i=Math.floor((t-s)/2);this.window.set(a,i)}async _call(e){rq(e,"GraniteSpeechFeatureExtractor");let{n_fft:t,hop_length:s,n_mels:n}=this.config.melspec_kwargs,r=1+Math.floor((e.length-1)/s);return{input_features:(await rZ(e,this.window,t,s,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:r-r%2,do_pad:!1})).view(-1,2*n).unsqueeze_(0)}}},an=class extends rV{async _call(e){rq(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new nx("float32",e,t)}}},ar=class extends rV{async _call(e){rq(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,1,e.length];return{input_values:new nx("float32",e,t)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,t){let s=t/this.samples_to_frames(t)/this.config.sampling_rate,n=[];for(let t of e.tolist()){let e=[],r=-1;for(let s=0;s<t.length;++s){let[n,a]=sR(sG(t[s])),[i,o]=[s,s+1];a!==r?(r=a,e.push({id:a,start:i,end:o,score:n}
1)):(e.at(-1).end=o,e.at(-1).score+=n)}n.push(e.map(({id:e,start:t,end:n,score:r})=>({id:e,start:t*s,end:n*s,confidence:r/(n-t)})))}return n}},aa=class extends rV{constructor(e){super(e);let t=this.config.sampling_rate,s=rK(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=r0(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return rZ(e=e.map(e=>32768*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:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:r=!0}={}){let a;rq(e,"SeamlessM4TFeatureExtractor");let i=await this._extract_fbank_features(e,this.config.max_length);if(n){let[e,t]=i.dims,s=i.data;for(let n=0;n<t;++n){let r=0;for(let a=0;a<e;++a)r+=s[a*t+n];let a=r/e,i=0;for(let r=0;r<e;++r)i+=(s[r*t+n]-a)**2;let o=Math.sqrt((i/=e-1)+1e-7);for(let r=0;r<e;++r){let e=r*t+n;s[e]=(s[e]-a)/o}}}if(t){let[e,t]=i.dims,n=i.data,o=e%s;if(o>0){let s=new Float32Array(t*(e+o));s.set(n),s.fill(this.config.padding_value,n.length);let l=e+o;i=new nx(i.type,s,[l,t]),r&&(a=new nx("int64",new BigInt64Array(l),[1,l])).data.fill(1n,0,e)}}let[o,l]=i.dims,c=this.config.stride;if(0!=o%c)throw Error(`The number of frames (${o}) must be a multiple of the stride (${c}).`);let d=i.view(1,Math.floor(o/c),l*c),u={input_features:d};if(r){let e=d.dims[1],t=new BigInt64Array(e);if(a){let e=a.data;for(let s=1,n=0;s<o;s+=c,++n)t[n]=e[s]}else t.fill(1n);u.attention_mask=new nx("int64",t,[1,e])}return u}},ai=class extends r7{},ao=class extends rV{},al=class extends rV{_zero_mean_unit_var_norm(e){let t=e.reduce((e,t)=>e+t,0)/e.length,s=e.reduce((e,s)=>e+(s-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(s+1e-7))}async _call(e){rq(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let s=[1,t.length];return{input_values:new nx("float32",t,s),attention_mask:new nx("int64",new BigInt64Array(t.length).fill(1n),s)}}},ac=class extends rV{constructor(e){super(e);let t=this.config.sampling_rate,s=rK(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=s,this.window=r0(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return rZ(e=e.map(e=>32768*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){rq(e,"WeSpeakerFeatureExtractor");let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(null===this.config.fbank_centering_span){let e=t.mean(1).data,s=t.data,[n,r,a]=t.dims;for(let t=0;t<n;++t){let n=t*r*a,i=t*a;for(let t=0;t<r;++t){let r=n+t*a;for(let t=0;t<a;++t)s[r+t]-=e[i+t]}}}return{input_features:t}}},ad=class extends rV{constructor(e){super(e),this.config.mel_filters??=rK(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=r0(this.config.n_fft,"hann")}async _extract_fbank_features(e,{center:t=!0}={}){let{n_fft:s,hop_length:n,mel_filters:r,global_log_mel_max:a}=this.config,i=t?Math.floor(e.length/n):Math.floor((e.length-s)/n);return await rZ(e,this.window,s,n,{power:2,mel_filters:r,log_mel:"log10_max_norm",max_log_mel:a,center:t,max_num_frames:i,do_pad:!1})}async _call(e,{center:t=!0}={}){return rq(e,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(e,{center:t})).unsqueeze_(0)}}},au=class extends rV{constructor(e){super(e),this.config.mel_filters??=rK(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=r0(this.config.n_fft,"hann")}async _extract_fbank_features(e){return await rZ(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(e,{max_length:t=null}={}){let s;rq(e,"WhisperFeatureExtractor");let n=t??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&W.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)).set(e),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}},a_=class{static async from_pretrained(e,t={}){let s=await sq(e,rI,!0,t),n=s.feature_extractor_type,r=rG[n];if(!r)throw Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${rO}.`);return new r(s)}},ah=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;async _call(e,t=null){let s=this.tokenizer(e),n=t?await this.feature_extractor(t):{};return{...s,...n}}},ap=new Set(["ja","zh"]),am=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let t=["â","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(t)}static join_chunks(e,t="en"){let s=e.filter(e=>e&&e.trim());if(0===s.length)return"";let n=ap.has(t)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(e=>e.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}},af={};if(F.IS_WEB_ENV)a=(e,t)=>{if(!self.OffscreenCanvas)throw Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},o=self.createImageBitmap,i=self.ImageData;else if(af)o=async e=>{let t=(await e.metadata()).channels,{data:s,info:n}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),r=new ax(new Uint8ClampedArray(s),n.width,n.height,n.channels);return void 0!==t&&t!==n.channels&&r.convert(t),r};else throw Error("Unable to load image processing library.");var ag={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},aw=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),ax=class e{constructor(e,t,s,n){this.data=e,this.width=t,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)return t;if("string"==typeof t||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if("undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!F.IS_WEB_ENV)throw Error("fromCanvas() is only supported in browser environments.");return new e(t.getContext("2d").getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}static async fromURL(e){let t=await sz(e);
1if(200!==t.status)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let s=await t.blob();return this.fromBlob(s)}static async fromBlob(e){if(F.IS_WEB_ENV){let t=await o(e),s=a(t.width,t.height).getContext("2d");return s.drawImage(t,0,0),new this(s.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}{let t=af(await e.arrayBuffer());return await o(t)}}static fromTensor(t,s="CHW"){if(3!==t.dims.length)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if("CHW"===s)t=t.transpose(1,2,0);else if("HWC"===s);else throw Error(`Unsupported channel format: ${s}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(1===this.channels)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,s=0;t<this.data.length;t+=this.channels){let n=this.data[t],r=this.data[t+1],a=this.data[t+2];e[s++]=Math.round(.2989*n+.587*r+.114*a)}break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(3===this.channels)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let t=0,s=0;t<this.data.length;++t)e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=this.data[t];break;case 4:for(let t=0,s=0;t<this.data.length;t+=4)e[s++]=this.data[t],e[s++]=this.data[t+1],e[s++]=this.data[t+2];break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(4===this.channels)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let t=0,s=0;t<this.data.length;++t)e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=this.data[t],e[s++]=255;break;case 3:for(let t=0,s=0;t<this.data.length;t+=3)e[s++]=this.data[t],e[s++]=this.data[t+1],e[s++]=this.data[t+2],e[s++]=255;break;default:throw 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 Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(1!==e.channels)throw Error(`Expected mask to have 1 channel, but got ${e.channels}`);let t=this.data,s=e.data,n=this.width*this.height;if(3===this.channels){let e=new Uint8ClampedArray(4*n);for(let r=0,a=0,i=0;r<n;++r)e[i++]=t[a++],e[i++]=t[a++],e[i++]=t[a++],e[i++]=s[r];return this._update(e,this.width,this.height,4)}if(4===this.channels){for(let e=0;e<n;++e)t[4*e+3]=s[e];return this}throw Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(t,s,{resample:n=2}={}){if(this.width===t&&this.height===s)return this;let r=ag[n]??n,i=q(t),l=q(s);if(i&&l)return this;if(i?t=s/this.height*this.width:l&&(s=t/this.width*this.height),F.IS_WEB_ENV){let n=this.channels,r=this.toCanvas(),i=a(t,s).getContext("2d");return i.drawImage(r,0,0,t,s),new e(i.getImageData(0,0,t,s).data,t,s,4).convert(n)}{let e=this.toSharp();switch(r){case"box":case"hamming":("box"===r||"hamming"===r)&&(W.warn(`Resampling method ${r} is not yet supported. Using bilinear instead.`),r="bilinear");case"nearest":case"bilinear":case"bicubic":e=e.affine([t/this.width,0,0,s/this.height],{interpolator:r});break;case"lanczos":e=e.resize({width:t,height:s,fit:"fill",kernel:"lanczos3"});break;default:throw Error(`Resampling method ${r} is not supported.`)}return await o(e)}}async pad([t,s,n,r]){if(t=Math.max(t,0),s=Math.max(s,0),n=Math.max(n,0),r=Math.max(r,0),0===t&&0===s&&0===n&&0===r)return this;if(F.IS_WEB_ENV){let i=this.channels,o=this.toCanvas(),l=this.width+t+s,c=this.height+n+r,d=a(l,c).getContext("2d");return d.drawImage(o,0,0,this.width,this.height,t,n,this.width,this.height),new e(d.getImageData(0,0,l,c).data,l,c,4).convert(i)}{let e=this.toSharp().extend({left:t,right:s,top:n,bottom:r});return await o(e)}}async crop([t,s,n,r]){if(t=Math.max(t,0),s=Math.max(s,0),n=Math.min(n,this.width-1),r=M
1ath.min(r,this.height-1),0===t&&0===s&&n===this.width-1&&r===this.height-1)return this;let i=n-t+1,l=r-s+1;if(F.IS_WEB_ENV){let n=this.channels,r=this.toCanvas(),o=a(i,l).getContext("2d");return o.drawImage(r,t,s,i,l,0,0,i,l),new e(o.getImageData(0,0,i,l).data,i,l,4).convert(n)}{let e=this.toSharp().extract({left:t,top:s,width:i,height:l});return await o(e)}}async center_crop(t,s){if(this.width===t&&this.height===s)return this;let n=(this.width-t)/2,r=(this.height-s)/2;if(F.IS_WEB_ENV){let i=this.channels,o=this.toCanvas(),l=a(t,s).getContext("2d"),c=0,d=0,u=0,_=0;return n>=0?c=n:u=-n,r>=0?d=r:_=-r,l.drawImage(o,c,d,t,s,u,_,t,s),new e(l.getImageData(0,0,t,s).data,t,s,4).convert(i)}{let e=this.toSharp();if(n>=0&&r>=0)e=e.extract({left:Math.floor(n),top:Math.floor(r),width:t,height:s});else if(n<=0&&r<=0){let a=Math.floor(-r),i=Math.floor(-n);e=e.extend({top:a,left:i,right:t-this.width-i,bottom:s-this.height-a})}else{let a=[0,0],i=0;r<0?(a[0]=Math.floor(-r),a[1]=s-this.height-a[0]):i=Math.floor(r);let o=[0,0],l=0;n<0?(o[0]=Math.floor(-n),o[1]=t-this.width-o[0]):l=Math.floor(n),e=e.extend({top:a[0],bottom:a[1],left:o[0],right:o[1]}).extract({left:l,top:i,width:t,height:s})}return await o(e)}}async toBlob(e="image/png",t=1){if(!F.IS_WEB_ENV)throw Error("toBlob() is only supported in browser environments.");let s=this.toCanvas();return await s.convertToBlob({type:e,quality:t})}toTensor(e="CHW"){let t=new nx("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if("HWC"===e);else if("CHW"===e)t=t.permute(2,0,1);else throw Error(`Unsupported channel format: ${e}`);return t}toCanvas(){if(!F.IS_WEB_ENV)throw Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),t=a(e.width,e.height),s=new i(e.data,e.width,e.height);return t.getContext("2d").putImageData(s,0,0),t}split(){let{data:t,width:s,height:n,channels:r}=this,a=t.constructor,i=t.length/r,o=Array.from({length:r},()=>new a(i));for(let e=0;e<i;++e){let s=r*e;for(let n=0;n<r;++n)o[n][e]=t[s+n]}return o.map(t=>new e(t,s,n,1))}_update(e,t,s,n=null){return this.data=e,this.width=t,this.height=s,null!==n&&(this.channels=n),this}clone(){return new e(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 Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(F.IS_WEB_ENV){if(F.IS_WEBWORKER_ENV)throw Error("Unable to save an image from a Web Worker.");let t=e.split(".").pop().toLowerCase(),s=aw.get(t)??"image/png";return rR(e,await this.toBlob(s))}if(F.IS_FS_AVAILABLE){let t=this.toSharp();await t.toFile(e)}else throw Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(F.IS_WEB_ENV)throw Error("toSharp() is only supported in server-side environments.");return af(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};function ay(e,t,s=0,n=null){let r=e/t,a=function(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}(r)*t;return null!==n&&a>n&&(a=Math.floor(r)*t),a<s&&(a=Math.ceil(r)*t),a}function ab([e,t],s){return[Math.max(Math.floor(e/s),1)*s,Math.max(Math.floor(t/s),1)*s]}function aM([e,t,s,n]){return[e-s/2,t-n/2,e+s/2,t+n/2]}function ak(e,t=.5,s=null,n=!1){let r=e.logits,a=e.pred_boxes,[i,o,l]=r.dims;if(null!==s&&s.length!==i)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=[];for(let e=0;e<i;++e){let i=null!==s?s[e]:null,d={boxes:[],classes:[],scores:[]},u=r[e],_=a[e];for(let e=0;e<o;++e){let s,r=u[e],a=[];if(n){s=r.sigmoid().data;for(let e=0;e<s.length;++e)s[e]>t&&a.push(e)}else{let e=sR(r.data)[1];if(e===l-1||(s=sG(r.data))[e]<t)continue;a.push(e)}for(let t of a){let n=_[e].data;n=aM(n),null!==i&&(n=n.map((e,t)=>e*i[(t+1)%2])),d.boxes.push(n),d.classes.push(t),d.scores.push(s[t])}}c.push(d)}return c}function av(e,t=null){let s=e.logits,n=s.dims[0];if(null!==t&&t.length!==n)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let r=[];for(let e=0;e<n;++e){let n=null!==t?t[e]:null,a=s[e];null!==n&&(a=ny(a,n,"bilinear",!1));let[i,o]=n??a.dims.slice(-2),l=new nx("int32",new Int32Array(i*o),[i,o]),c=a[0].data,d=l.data;for(let e=1;e<a.dims[0];++e){let t=a[e].data;for(let s=0;s<t.length;++s)t[s]>c[s]&&(c[s]=t[s],d[s]=e)}let u=Array(a.dims[0]);for(let e=0;e<d.length;++e){let t=d[e];u[t]=t}let _=u.filter(e=>void 0!==e);r.push({segmentation:l,labels:_})}return r}function aE(e,t,s=28,n=3136,r=1003520,a=1){if(e<s||t<s){let n=Math.max(s/e,s/t);e=Math.round(e*n),t=Math.round(t*n)}if(Math.max(e,t)/Math.min(e,t)>200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let i=Math.round(e/s)*s,o=Math.round(t/s)*s;if(a*i*o>r){let n=Math.sqrt(a*e*t/r);i=Math.max(s,Math.floor(e/n/s)*s),o=Math.max(s,Math.floor(t/n/s)*s)}else if(a*i*o<n){let r=Math.sqrt(n/(a*e*t));i=Math.ceil(e*r/s)*s,o=Math.ceil(t*r/s)*s}return[o,i]}function aA(e,t=.5,s=.5,n=.8,r=null,a=null){null===r&&(W.warn("`label_ids_to_fuse` unset. No instance will be fused."),r=new Set);let i=e.class_queries_logits??e.logits,o=(e.masks_queries_logits??e.pred_masks).sigmoid(),[l,c,d]=i.dims;if(d-=1,null!==a&&a.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let e=0;e<l;++e){let l=null!==a?a[e]:null,c=i[e],_=o[e],[h,p,m]=function(e,t,s,n){let r=[],a=[],i=[];for(let o=0;o<e.dims[0];++o){let l=e[o],c=t[o],d=sR(l.data)[1];if(d===n)continue;let u=sG(l.data)[d];u>s&&(r.push(c),a.push(u),i.push(d))}return[r,a,i]}(c,_,t,d);if(0===m.length){let[e,t]=l??_.dims.slice(-2),s=new nx("int32",new Int32Array(e*t).fill(-1),[e,t]);u.push({segmentation:s,segments_info:[]});continue}let[f,g]=function(e,t,s,n,r,a=null,i=null){let[o,l]=i??e[0].dims,c=new nx("int32",new Int32Array(o*l),[o,l]),d=[];if(null!==i)for(let t=0;t<e.length;++t)e[t]=ny(e[t],i,"bilinear",!1);let u=new Int32Array(e[0].data.length),_=new Float32Array(e[0].data.length);for(let s=0;s<e.length;++s){let n=t[s],r=e[s].data;for(let e=0;e<r.length;++e)r[e]*=n,r[e]>_[e]&&(u[e]=s,_[e]=r[e])}let h=0,p=c.data;for(let a=0;a<s.length;++a){let i=s[a],[o,l]=function(e,t,s,n=.5,r=.8){let a=[],i=0,o=0,l=t[s].data;for(let t=0;t<e.length;++t)e[t]===s&&(a.push(t),++i),l[t]>=n&&++o;let c=i>0&&o>0;return c&&(c=i/o>r),[c,a]}(u,e,a,n,r);if(o){for(let e of(++h,l))p[e]=h;d.push({id:h,label_id:i,score:t[a]})}}return[c,d]}(h,p,m,s,n,r,l);u.push({segmentation:f,segments_info:g})}return u}function aC(e,t=.5,s=null){throw Error("`post_process_instance_segmentation` is not yet implemented.")}ax.read.bind(ax);var aF=class extends D{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??void 0!==this.size,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&void 0!==this.size.width&&void 0!==this.size.height&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}
1async thumbnail(e,t,s=2){let n=e.height,r=e.width,a=t.height,i=t.width,o=Math.min(n,a),l=Math.min(r,i);return o===n&&l===r?e:(n>r?l=Math.floor(r*o/n):r>n&&(o=Math.floor(n*l/r)),await e.resize(l,o,{resample:s}))}async crop_margin(e,t=200){let s=e.clone().grayscale(),n=sj(s.data)[0],r=sR(s.data)[0]-n;if(0===r)return e;let a=t/255,i=s.width,o=s.height,l=0,c=0,d=s.data;for(let e=0;e<s.height;++e){let t=e*s.width;for(let u=0;u<s.width;++u)(d[t+u]-n)/r<a&&(i=Math.min(i,u),o=Math.min(o,e),l=Math.max(l,u),c=Math.max(c,e))}return e=await e.crop([i,o,l,c])}pad_image(e,t,s,{mode:n="constant",center:r=!1,constant_values:a=0}={}){let i,o,[l,c,d]=t;if("number"==typeof s?(i=s,o=s):"square"===s?i=o=Math.max(l,c):(i=s.width,o=s.height),i!==c||o!==l){let s=new Float32Array(i*o*d);if(Array.isArray(a))for(let e=0;e<s.length;++e)s[e]=a[e%d];else 0!==a&&s.fill(a);let[u,_]=r?[Math.floor((i-c)/2),Math.floor((o-l)/2)]:[0,0];for(let t=0;t<l;++t){let n=(t+_)*i,r=t*c;for(let t=0;t<c;++t){let a=(n+t+u)*d,i=(r+t)*d;for(let t=0;t<d;++t)s[a+t]=e[i+t]}}if("symmetric"===n){if(r)throw Error("`center` padding is not supported when `mode` is set to `symmetric`.");let t=l-1,n=c-1;for(let r=0;r<o;++r){let a=r*i,o=R(r,t)*c;for(let t=0;t<i;++t){if(r<l&&t<c)continue;let i=(a+t)*d,u=(o+R(t,n))*d;for(let t=0;t<d;++t)s[i+t]=e[u+t]}}}e=s,t=[o,i,d]}return[e,t]}rescale(e){for(let t=0;t<e.length;++t)e[t]=this.rescale_factor*e[t]}get_resize_output_image_size(e,t){let s,n,[r,a]=e.size;if(this.do_thumbnail){let{height:e,width:n}=t;s=Math.min(e,n)}else Number.isInteger(t)?(s=t,n=this.config.max_size??s):void 0!==t&&(s=t.shortest_edge,n=t.longest_edge);if(void 0!==s||void 0!==n){let e=void 0===s?1:Math.max(s/r,s/a),t=r*e,i=a*e,o=void 0===n?1:Math.min(n/t,n/i),l=Math.floor(Number((t*o).toFixed(2))),c=Math.floor(Number((i*o).toFixed(2)));return void 0!==this.size_divisibility&&([l,c]=ab([l,c],this.size_divisibility)),[l,c]}if(void 0!==t&&void 0!==t.width&&void 0!==t.height){let e=t.width,s=t.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let t=s/a,n=e/r;Math.abs(1-n)<Math.abs(1-t)?t=n:n=t,s=ay(t*a,this.config.ensure_multiple_of),e=ay(n*r,this.config.ensure_multiple_of)}return[e,s]}if(void 0!==this.size_divisibility)return ab([r,a],this.size_divisibility);throw Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(t)}`)}async resize(e){let[t,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(t,s,{resample:this.resample})}async preprocess(e,{do_normalize:t=null,do_pad:s=null,do_convert_rgb:n=null,do_convert_grayscale:r=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[i,o]=e.size;if(n??this.do_convert_rgb?e=e.rgb():r&&(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 t,s;Number.isInteger(this.crop_size)?(t=this.crop_size,s=this.crop_size):(t=this.crop_size.width,s=this.crop_size.height),e=await e.center_crop(t,s)}let l=[e.height,e.width],c=Float32Array.from(e.data),d=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(c),t??this.do_normalize){let t=this.image_mean;Array.isArray(this.image_mean)||(t=Array(e.channels).fill(t));let s=this.image_std;if(Array.isArray(this.image_std)||(s=Array(e.channels).fill(s)),t.length!==e.channels||s.length!==e.channels)throw Error(`When set to arrays, the length of \`image_mean\` (${t.length}) and \`image_std\` (${s.length}) must match the number of channels in the image (${e.channels}).`);for(let n=0;n<c.length;n+=e.channels)for(let r=0;r<e.channels;++r)c[n+r]=(c[n+r]-t[r])/s[r]}if(s??this.do_pad){if(this.pad_size){let t=this.pad_image(c,[e.height,e.width,e.channels],this.pad_size);[c,d]=t}else if(this.size_divisibility){let e=Math.ceil(d[1]/this.size_divisibility)*this.size_divisibility,t=Math.ceil(d[0]/this.size_divisibility)*this.size_divisibility;[c,d]=this.pad_image(c,d,{width:e,height:t})}}if(a??this.do_flip_channel_order){if(3!==d[2])throw Error("Flipping channel order is only supported for RGB images.");for(let e=0;e<c.length;e+=3){let t=c[e];c[e]=c[e+2],c[e+2]=t}}return{original_size:[o,i],reshaped_input_size:l,pixel_values:new nx("float32",c,d).permute(2,0,1)}}async _call(e){Array.isArray(e)||(e=[e]);let t=await Promise.all(e.map(e=>this.preprocess(e)));return{pixel_values:nT(t.map(e=>e.pixel_values),0),original_sizes:t.map(e=>e.original_size),reshaped_input_sizes:t.map(e=>e.reshaped_input_size)}}static async from_pretrained(e,t={}){return new this(await sq(e,rI,!0,t))}},aS={};_(aS,{BeitFeatureExtractor:()=>aT,BitImageProcessor:()=>aP,CHMv2ImageProcessor:()=>aL,CLIPFeatureExtractor:()=>aI,CLIPImageProcessor:()=>aO,ChineseCLIPFeatureExtractor:()=>az,ConvNextFeatureExtractor:()=>a$,ConvNextImageProcessor:()=>aN,DINOv3ViTImageProcessor:()=>aG,DPTFeatureExtractor:()=>aW,DPTImageProcessor:()=>aU,DeiTFeatureExtractor:()=>aD,DeiTImageProcessor:()=>aB,DetrFeatureExtractor:()=>aq,DetrImageProcessor:()=>aV,DonutFeatureExtractor:()=>aR,DonutImageProcessor:()=>aj,EfficientNetImageProcessor:()=>aQ,GLPNFeatureExtractor:()=>aY,Gemma3ImageProcessor:()=>aH,Gemma4ImageProcessor:()=>aX,Glm46VImageProcessor:()=>aK,GroundingDinoImageProcessor:()=>aZ,Idefics3ImageProcessor:()=>a0,ImageFeatureExtractor:()=>aF,ImageProcessor:()=>aF,JinaCLIPImageProcessor:()=>a2,Lfm2VlImageProcessor:()=>a4,LlavaOnevisionImageProcessor:()=>a8,Mask2FormerImageProcessor:()=>a9,MaskFormerFeatureExtractor:()=>a5,MaskFormerImageProcessor:()=>a6,MobileNetV1FeatureExtractor:()=>ie,MobileNetV1ImageProcessor:()=>a7,MobileNetV2FeatureExtractor:()=>is,MobileNetV2ImageProcessor:()=>it,MobileNetV3FeatureExtractor:()=>ia,MobileNetV3ImageProcessor:()=>ir,MobileNetV4FeatureExtractor:()=>io,MobileNetV4ImageProcessor:()=>ii,MobileViTFeatureExtractor:()=>ic,MobileViTImageProcessor:()=>il,NougatImageProcessor:()=>id,OwlViTFeatureExtractor:()=>i_,OwlViTImageProcessor:()=>iu,Owlv2ImageProcessor:()=>ih,Phi3VImageProcessor:()=>ix,PixtralImageProcessor:()=>iy,PvtImageProcessor:()=>ib,Qwen2VLImageProcessor:()=>aJ,RTDetrImageProcessor:()=>iM,Sam2ImageProcessor:()=>ik,Sam3ImageProcessor:()=>ik,SamImageProcessor:()=>ik,SapiensFeatureExtractor:()=>iE,SapiensImageProcessor:()=>iv,SegformerFeatureExtractor:()=>iC,SegformerImageProcessor:()=>iA,SiglipImageProcessor:()=>iF,SmolVLMImageProcessor:()=>a0,Swin2SRImageProcessor:()=>
1iS,VLMImageProcessor:()=>a1,ViTFeatureExtractor:()=>iP,ViTImageProcessor:()=>iT,VitMatteImageProcessor:()=>iz,VitPoseImageProcessor:()=>iL,YolosFeatureExtractor:()=>iI,YolosImageProcessor:()=>iO});var aT=class extends aF{},aP=class extends aF{},az=class extends aF{},aL=class extends aF{},aO=class extends aF{},aI=class extends aO{},aN=class extends aF{constructor(e){super(e),this.crop_pct=this.config.crop_pct??.875}async resize(e){let t=this.size?.shortest_edge;if(void 0===t)throw Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){let s=Math.floor(t/this.crop_pct),[n,r]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,r,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},a$=class extends aN{},aB=class extends aF{},aD=class extends aB{},aV=class extends aF{async _call(e){let t=await super._call(e),s=nI([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:s}}post_process_object_detection(...e){return ak(...e)}post_process_panoptic_segmentation(...e){return aA(...e)}post_process_instance_segmentation(...e){return aC(...e)}},aq=class extends aV{},aG=class extends aF{},aj=class extends aF{pad_image(e,t,s,n={}){let[r,a,i]=t,o=this.image_mean;Array.isArray(this.image_mean)||(o=Array(i).fill(o));let l=this.image_std;Array.isArray(l)||(l=Array(i).fill(o));let c=o.map((e,t)=>-e/l[t]);return super.pad_image(e,t,s,{center:!0,constant_values:c,...n})}},aR=class extends aj{},aU=class extends aF{},aW=class extends aU{},aQ=class extends aF{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(e=>e*e))}},aH=class extends aF{},aX=class extends D{constructor(e){super(),this.config=e,this.patch_size=e.patch_size??16,this.max_soft_tokens=e.max_soft_tokens??280,this.pooling_kernel_size=e.pooling_kernel_size??3,this.resample=e.resample??3,this.rescale_factor=e.rescale_factor??1/255,this.do_rescale=e.do_rescale??!0,this.do_resize=e.do_resize??!0,this.do_convert_rgb=e.do_convert_rgb??!0}async _call(e){Array.isArray(e)||(e=[e]);let{patch_size:t,pooling_kernel_size:s}=this,n=this.max_soft_tokens*s**2,r=[],a=[],i=[];for(let o of e){if(this.do_convert_rgb&&(o=o.rgb()),this.do_resize){let[e,r]=function(e,t,s,n,r){let a=Math.sqrt(n*s**2/(e*t)),i=r*s,o=Math.floor(a*e/i)*i,l=Math.floor(a*t/i)*i;if(0===o&&0===l)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let c=Math.floor(n/r**2)*i;return 0===o?(o=i,l=Math.min(Math.floor(t/e)*i,c)):0===l&&(l=i,o=Math.min(Math.floor(e/t)*i,c)),[o,l]}(o.height,o.width,t,n,s);(e!==o.height||r!==o.width)&&(o=await o.resize(r,e,{resample:this.resample}))}let e=Float32Array.from(o.data);if(this.do_rescale)for(let t=0;t<e.length;++t)e[t]*=this.rescale_factor;let{patches:l,positions:c,num_soft_tokens:d}=function(e,t,s,n,r,a,i){let o=Math.floor(t/r),l=Math.floor(s/r),c=r*r*n,d=new Float32Array(a*c),u=0;for(let t=0;t<o;++t)for(let a=0;a<l;++a)for(let i=0;i<r;++i){let o=(t*r+i)*s*n+a*r*n;for(let t=0;t<r;++t){let s=o+t*n;for(let t=0;t<n;++t)d[u++]=e[s+t]}}let _=new BigInt64Array(2*a).fill(-1n),h=0;for(let e=0;e<o;++e)for(let t=0;t<l;++t)_[h++]=BigInt(t),_[h++]=BigInt(e);return{patches:new nx("float32",d,[a,c]),positions:new nx("int64",_,[a,2]),num_soft_tokens:Math.floor(o*l/i**2)}}(e,o.height,o.width,o.channels,t,n,s);r.push(l),a.push(c),i.push(d)}return{pixel_values:nT(r,0),image_position_ids:nT(a,0),num_soft_tokens_per_image:i}}},aJ=class extends aF{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){let s=this.patch_size*this.merge_size;return aE(e.height,e.width,s,this.min_pixels,this.max_pixels)}async _call(e,...t){let{pixel_values:s,original_sizes:n,reshaped_input_sizes:r}=await super._call(e,...t),a=s,{temporal_patch_size:i,merge_size:o,patch_size:l}=this.config;1===a.dims[0]&&(a=nS(Array.from({length:i},()=>a),0));let c=a.dims[0]/i,d=a.dims[1],u=Math.floor(a.dims[2]/l),_=Math.floor(a.dims[3]/l);return{pixel_values:a.view(c,i,d,Math.floor(u/o),o,l,Math.floor(_/o),o,l).permute(0,3,6,4,7,2,1,5,8).view(c*u*_,d*i*l*l),image_grid_thw:new nx("int64",[c,u,_],[1,3]),original_sizes:n,reshaped_input_sizes:r}}},aK=class extends aJ{get_resize_output_image_size(e,t){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return aE(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}},aY=class extends aF{},aZ=class extends aF{async _call(e){let t=await super._call(e),s=t.pixel_values.dims,n=n$([s[0],s[2],s[3]]);return{...t,pixel_mask:n}}},a0=class extends aF{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,t){let[s,n]=e.dims.slice(-2),r=n/s;return n>=s?s=Math.ceil((s=Math.floor((n=Math.ceil(n/t)*t)/r))/t)*t:n=Math.ceil((n=Math.floor((s=Math.ceil(s/t)*t)*r))/t)*t,{height:s,width:n}}async _call(e,{do_image_splitting:t=null,return_row_col_info:s=!1}={}){let n,r,a;if(Array.isArray(e)){if(0===e.length||!e[0])throw Error("No images provided.");n=Array.isArray(e[0])?e:[e]}else n=[[e]];let i=[],o=[],l=[],c=[],d=[];for(let e of n){let s,n=await Promise.all(e.map(e=>this.preprocess(e)));c.push(...n.map(e=>e.original_size)),d.push(...n.map(e=>
1e.reshaped_input_size)),n.forEach(e=>e.pixel_values.unsqueeze_(0));let{longest_edge:r}=this.max_image_size;if(t??this.do_image_splitting){let e=Array(n.length),t=Array(n.length);s=await Promise.all(n.map(async(s,n)=>{let a=this.get_resize_for_vision_encoder(s.pixel_values,r),i=await nb(s.pixel_values,{size:[a.height,a.width]}),{frames:o,num_splits_h:l,num_splits_w:c}=await this.split_image(i,this.max_image_size);return e[n]=l,t[n]=c,nS(o,0)})),o.push(e),l.push(t)}else{let e=[r,r];s=await Promise.all(n.map(t=>nb(t.pixel_values,{size:e}))),o.push(Array(n.length).fill(0)),l.push(Array(n.length).fill(0))}i.push(nS(s,0))}let u=i.length,[_,h,p,m]=i[0].dims;if(1===u)r=i[0].unsqueeze_(0),a=nI([u,_,p,m],!0);else{let e=Math.max(...i.map(e=>e.dims.at(0))),t=(a=nI([u,e,p,m],!0)).data,s=e*p*m;for(let n=0;n<u;++n){let r=i[n].dims[0];if(r<e){i[n]=nS([i[n],nI([e-r,h,p,m],0)],0);let a=n*s+r*p*m,o=(n+1)*s;t.fill(!1,a,o)}}r=nT(i,0)}return{pixel_values:r,pixel_attention_mask:a,original_sizes:c,reshaped_input_sizes:d,...s?{rows:o,cols:l}:{}}}async split_image(e,{longest_edge:t}){let s=[],[n,r]=e.dims.slice(-2),a=0,i=0;if(n>t||r>t){a=Math.ceil(n/t),i=Math.ceil(r/t);let o=Math.ceil(n/a),l=Math.ceil(r/i);for(let t=0;t<a;++t)for(let c=0;c<i;++c){let d,u,_,h;t===a-1?(u=n-o,h=n):(u=t*o,h=(t+1)*o),c===i-1?(d=r-l,_=r):(d=c*l,_=(c+1)*l);let p=[u,d],m=[h,_],f=await nE(e,p,m,[2,3]);s.push(f)}(n!==t||r!==t)&&(e=await nb(e,{size:[t,t]}))}return s.push(e),{frames:s,num_splits_h:a,num_splits_w:i}}},a1=class extends aF{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(e=>e*this.rescale_factor)}pad_image(e,t,s,n){return super.pad_image(e,t,s,{constant_values:this.constant_values,center:!0,...n})}},a2=class extends aF{constructor(e){let{resize_mode:t,fill_color:s,interpolation:n,size:r,...a}=e;super({...a,size:"squash"===t?{width:r,height:r}:"shortest"===t?{shortest_edge:r}:{longest_edge:r},resample:"bicubic"===n?3:2,do_center_crop:!0,crop_size:r,do_normalize:!0})}};function a3(e,t){return Math.round(e/t)*t}var a4=class extends aF{constructor(e){super(e),this.downsample_factor=e.downsample_factor??2,this.do_image_splitting=e.do_image_splitting??!0,this.min_tiles=e.min_tiles??2,this.max_tiles=e.max_tiles??10,this.use_thumbnail=e.use_thumbnail??!0,this.min_image_tokens=e.min_image_tokens??64,this.max_image_tokens=e.max_image_tokens??256,this.encoder_patch_size=e.encoder_patch_size??e.patch_size??16,this.tile_size=e.tile_size??512,this.max_pixels_tolerance=e.max_pixels_tolerance??2,this.return_row_col_info=e.return_row_col_info??!1;let t=this.max_image_tokens*this.downsample_factor**2,s=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(t,s)}_is_image_too_large(e,t){let s=this.encoder_patch_size*this.downsample_factor;return Math.max(this.encoder_patch_size,a3(e,s))*Math.max(this.encoder_patch_size,a3(t,s))>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let[s,n]=function(e,t,s,n,r){let a=1/0,i=[1,1],o=s*n;for(let s of t){let t=Math.abs(e-s[0]/s[1]);t<a?(a=t,i=s):t===a&&o>.5*r*r*s[0]*s[1]&&(i=s)}return i}(t/e,function(e,t){let s=[],n=new Set;for(let r=e;r<=t;++r)for(let a=1;a<=r;++a)for(let i=1;i<=r;++i){let r=a*i;if(r>=e&&r<=t){let e=a<<16|i;n.has(e)||(n.add(e),s.push([a,i]))}}return s.sort((e,t)=>e[0]*e[1]-t[0]*t[1])}(this.min_tiles,this.max_tiles),t,e,this.tile_size);return{grid_width:s,grid_height:n,target_width:this.tile_size*s,target_height:this.tile_size*n}}async _call(e,{return_row_col_info:t=null}={}){let s;s=Array.isArray(e)?Array.isArray(e[0])?e:[e]:[[e]];let n=[],r=[],a=[],i=[],o=[],l=[];for(let e of s)for(let{pixel_values:t}of(await Promise.all(e.map(e=>this.preprocess(e,{do_pad:!1}))))){let e,[,s,c]=t.dims,d=t.unsqueeze_(0),u=this.encoder_patch_size*this.downsample_factor,_=u**2,[h,p]=aE(Math.max(u,s),Math.max(u,c),u,this.min_image_tokens*_,this.max_image_tokens*_).map(e=>Math.max(u,e)),m=1,f=1,g=this._is_image_too_large(s,c),w=this.do_image_splitting&&(1!==this.min_tiles||1!==this.max_tiles);if(g&&w){let{grid_width:t,grid_height:n,target_width:r,target_height:a}=this._get_grid_layout(s,c);m=n,f=t;let i=await nb(d,{size:[a,r]});e=[];for(let s=0;s<n;++s)for(let n=0;n<t;++n){let t=s*this.tile_size,r=n*this.tile_size;e.push(i.slice(null,null,[t,t+this.tile_size],[r,r+this.tile_size]))}this.use_thumbnail&&t*n!=1&&e.push(await nb(d,{size:[p,h]}))}else e=[await nb(d,{size:[p,h]})];for(let t of e){let[,,e,s]=t.dims,{padded:i,mask:o}=function(e,t){let[,s,n]=e.dims,r=new BigInt64Array(t);r.fill(1n,0,s);let a=e;if(s<t){let s=new Float32Array(t*n);s.set(e.data),a=new nx("float32",s,[1,t,n])}return{padded:a,mask:new nx("int64",r,[t])}}(function(e,t){let[s,n,r,a]=e.dims,i=Math.floor(r/t),o=Math.floor(a/t),l=t*t*n,c=e.data,d=new Float32Array(s*i*o*l),u=r*a;for(let e=0;e<s;++e){let s=e*n*u,r=e*i*o*l;for(let e=0;e<i;++e)for(let i=0;i<o;++i){let _=r+(e*o+i)*l;for(let r=0;r<t;++r){let o=(e*t+r)*a+i*t;for(let e=0;e<t;++e){let t=o+e;for(let e=0;e<n;++e)d[_++]=c[s+e*u+t]}}}}return new nx("float32",d,[s,i*o,l])}(t,this.encoder_patch_size),this.max_num_patches);n.push(i),r.push(o),a.push([Math.floor(e/this.encoder_patch_size),Math.floor(s/this.encoder_patch_size)])}i.push(m),o.push(f),l.push([p,h])}let c={pixel_values:nS(n,0),pixel_attention_mask:nT(r,0),spatial_shapes:new nx("int64",BigInt64Array.from(a.flat(),BigInt),[a.length,2])};return(t??this.return_row_col_info)&&(c.image_rows=i,c.image_cols=o,c.image_sizes=l),c}},a8=class extends aF{},a6=class extends aF{post_process_panoptic_segmentation(...e){return aA(...e)}post_process_instance_segmentation(...e){return aC(...e)}},a5=class extends a6{},a9=class extends a6{},a7=class extends aF{}
1,ie=class extends a7{},it=class extends aF{},is=class extends it{},ir=class extends aF{},ia=class extends ir{},ii=class extends aF{},io=class extends ii{},il=class extends aF{},ic=class extends il{},id=class extends aj{},iu=class extends aF{post_process_object_detection(...e){return ak(...e)}},i_=class extends iu{},ih=class extends iu{},ip=[2,3],{ceil:im,floor:ig,sqrt:iw}=Math,ix=class extends aF{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,t){let{num_img_tokens:s}=this.config;return ig((ig(t/336)*ig(e/336)+1)*s+1+(ig(t/336)+1)*iw(s))}get_resize_output_image_size(e,t){let s=this._num_crops,[n,r]=e.size,a=n/r,i=1;for(;i*Math.ceil(i/a)<=s;)i+=1;let o=Math.floor(336*(i-=1)),l=Math.floor(o/a);return[o,l]}pad_image(e,t,s,n={}){let[r,a]=t,i=336*im(r/336),o=336*im(a/336),l=[1,1,1].map((e,t)=>(e-this.image_mean[t])/this.image_std[t]);return super.pad_image(e,t,{width:o,height:i},{center:!0,constant_values:l,...n})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||iw(t)%1!=0)throw Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(e=>this.preprocess(e))),r=n.map(e=>e.original_size),a=n.map(e=>e.reshaped_input_size),i=[];for(let{pixel_values:e}of n){e.unsqueeze_(0);let[s,n]=e.dims.slice(-2),r=await nb(e,{size:[336,336],mode:"bicubic"});if(t>0){let a=[],o=iw(t),l=ig(n/o),c=ig(s/o);for(let t=0;t<o;++t)for(let r=0;r<o;++r){let i,d,u,_;t===o-1?(d=s-c,_=s):(d=t*c,_=(t+1)*c),r===o-1?(i=n-l,u=n):(i=r*l,u=(r+1)*l);let h=[d,i],p=[_,u],m=await nE(e,h,p,ip);a.push(m)}let d=await nb(nS(a,0),{size:[336,336],mode:"bicubic"});i.push(nS([r,d],0))}else i.push(r)}let o=nT(i,0),l=a.map(e=>e.map(e=>336*im(e/336)));return{pixel_values:o,original_sizes:r,reshaped_input_sizes:a,image_sizes:new nx("int64",l.flat(),[s,2]),num_img_tokens:l.map(([e,t])=>this.calc_num_image_tokens_from_image_size(t,e))}}},iy=class extends aF{get_resize_output_image_size(e,t){let{longest_edge:s}=t;if(void 0===s)throw Error("size must contain 'longest_edge'");
1let[n,r]=e.size,a=Math.max(n,r)/s,i=n,o=r;a>1&&(i=Math.floor(n/a),o=Math.floor(r/a));let{patch_size:l,spatial_merge_size:c}=this.config;if(!c)throw Error("config must contain 'spatial_merge_size'");let d=l*c,u=Math.floor((i-1)/d)+1,_=Math.floor((o-1)/d)+1;return[u*d,_*d]}},ib=class extends aF{},iM=class extends aF{post_process_object_detection(...e){return ak(...e)}},ik=class extends aF{reshape_input_points(e,t,s,n=!1){let r=G(e=structuredClone(e));if(3===r.length)n||(r=[1,...r]),e=[e];else if(4!==r.length)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let n=0;n<e.length;++n){let[r,a]=t[n],[i,o]=s[n],l=[o/a,i/r];for(let t=0;t<e[n].length;++t)for(let s=0;s<e[n][t].length;++s)for(let r=0;r<e[n][t][s].length;++r)e[n][t][s][r]*=l[r%2]}return new nx("float32",Float32Array.from(e.flat(1/0)),r)}add_input_labels(e,t){let s=G(e);if(2===s.length)s=[1,...s],e=[e];else if(3!==s.length)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((e,s)=>e!==t.dims[s]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new nx("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:t=null,input_labels:s=null,input_boxes:n=null}={}){let r=await super._call(e);if(t&&(r.input_points=this.reshape_input_points(t,r.original_sizes,r.reshaped_input_sizes)),s){if(!r.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");r.input_labels=this.add_input_labels(s,r.input_points)}return n&&(r.input_boxes=this.reshape_input_points(n,r.original_sizes,r.reshaped_input_sizes,!0)),r}async post_process_masks(e,t,s,{mask_threshold:n=0,binarize:r=!0,pad_size:a=null}={}){let i=[],o=[(a=a??this.pad_size??this.size).height,a.width];for(let a=0;a<t.length;++a){let l=t[a],c=s[a],d=await nb(e[a],{mode:"bilinear",size:o});if(d=d.slice(null,null,[0,c[0]],[0,c[1]]),d=await nb(d,{mode:"bilinear",size:l}),r){let e=d.data,t=new Uint8Array(e.length);for(let s=0;s<e.length;++s)e[s]>n&&(t[s]=1);d=new nx("bool",t,d.dims)}i.push(d)}return i}generate_crop_boxes(e,t,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:r=32,crop_n_points_downscale_factor:a=1}={}){}},iv=class extends aF{post_process_semantic_segmentation(...e){return av(...e)}},iE=class extends iv{},iA=class extends aF{post_process_semantic_segmentation(...e){return av(...e)}},iC=class extends iA{},iF=class extends aF{},iS=class extends aF{pad_image(e,t,s,n={}){let[r,a,i]=t;return super.pad_image(e,t,{width:a+(s-a%s)%s,height:r+(s-r%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}},iT=class extends aF{},iP=class extends iT{},iz=class extends aF{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let s=await Promise.all(e.map(e=>this.preprocess(e))),n=await Promise.all(t.map(e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:nT(s.map((e,t)=>nS([e.pixel_values,n[t].pixel_values],0)),0),original_sizes:s.map(e=>e.original_size),reshaped_input_sizes:s.map(e=>e.reshaped_input_size)}}},iL=class extends aF{post_process_pose_estimation(e,t,{threshold:s=null}={}){let n=e.tolist(),[r,a,i,o]=e.dims,l=[];for(let e=0;e<r;++e){let r=n[e],a=t[e],c=[];for(let e=0;e<a.length;++e){let t=a[e],n=[],l=[],d=[],u=t.at(-2)/o,_=t.at(-1)/i;for(let e=0;e<r.length;++e){let[t,a]=[0,0],i=0,o=-1/0,c=r[e];for(let e=0;e<c.length;++e){let s=c[e];for(let n=0;n<s.length;++n){let r=s[n];i+=r,o=Math.max(o,r),t+=(n+.5)*r,a+=e*r}}if(null!=s&&o<s)continue;let h=[u*t/i,_*a/i];n.push(h),d.push(e),l.push(o)}c.push({bbox:t,scores:l,labels:d,keypoints:n})}l.push(c)}return l}},iO=class extends aF{post_process_object_detection(...e){return ak(...e)}},iI=class extends iO{},iN=class{static async from_pretrained(e,t={}){let s=await sq(e,rI,!0,t),n=s.image_processor_type??s.feature_extractor_type,r=aS[n?.replace(/Fast$/,"")];return r||(void 0!==n&&W.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${rO}.`),r=aF),new r(s)}},i$=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;constructor(e,t,s){super(e,t,s);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:r,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(r??{})),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){"string"==typeof e&&(e=[e]);let t=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))t.push(this.task_prompts_without_inputs.get(s));else{for(let[e,n]of this.task_prompts_with_input)if(s.includes(e)){t.push(n.replaceAll("{input}",s).replaceAll(e,""));break}t.length!==e.length&&t.push(s)}return t}post_process_generation(e,t,s){let n,r=this.tasks_answer_post_processing_type.get(t)??"pure_text";switch(e=e.replaceAll("<s>","").replaceAll("</s>",""),r){case"pure_text":n=e;break;
1case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a="ocr"===r?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),o=[],l=[];for(let[e,t,...n]of i)o.push(t?t.trim():o.at(-1)??""),l.push(n.map((e,t)=>(Number(e)+.5)/this.size_per_bin*s[t%2]));n={labels:o,[a]:l};break;default:throw Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:n}}async _call(e,t=null,s={}){if(!e&&!t)throw Error("Either text or images must be provided");let n=await this.image_processor(e,s),r=t?this.tokenizer(this.construct_prompts(t),s):{};return{...n,...r}}},iB=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,s){super(e,t,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:r,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=r,this.eoi_token=a;let i=r.repeat(this.image_seq_length);this.full_image_sequence=` 2 3${n}${i}${a} 4 5`}async _call(e,t=null,s={}){let n;return"string"==typeof e&&(e=[e]),t&&(n=await this.image_processor(t,s),e=e.map(e=>e.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,s),...n}}},iD=class extends rB{static image_processor_class=iN;static feature_extractor_class=a_;static tokenizer_class=rL;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,s){super(e,t,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:r,audio_token:a,eoa_token:i,image_token_id:o,boi_token:l,image_token:c,eoi_token:d}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=r,this.audio_token=a;let u=a.repeat(this.audio_seq_length);this.full_audio_sequence=` 6 7${r}${u}${i} 8 9`,this.image_token_id=o,this.boi_token=l,this.image_token=c;let _=c.repeat(this.image_seq_length);this.full_image_sequence=` 10 11${l}${_}${d} 12 13`}async _call(e,t=null,s=null,n={}){let r,a;return"string"==typeof e&&(e=[e]),s&&(r=await this.feature_extractor(s,n),e=e.map(e=>e.replaceAll(this.audio_token,this.full_audio_sequence))),t&&(a=await this.image_processor(t,n),e=e.map(e=>e.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...r}}},iV=class extends rB{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,s){super(e,t,s),this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:n,boa_token:r,eoa_token:a,image_token:i,boi_token:o,eoi_token:l}=this.tokenizer.config;this.audio_token=n,this.boa_token=r,this.eoa_token=a,this.image_token=i,this.boi_token=o,this.eoi_token=l}static async from_pretrained(e,t={}){let[s,n,r]=await Promise.all([sq(e,rN,!0,t),rL.from_pretrained(e,t),sV(e,r$,!1,t)]),a={tokenizer:n};return s.image_processor&&(a.image_processor=new aX(s.image_processor)),s.feature_extractor&&(a.feature_extractor=new at(s.feature_extractor)),new this(s,a,r)}_compute_audio_num_tokens(e,t){let s=Math.round(20*t/1e3),n=Math.floor((e+Math.floor(s/2)-s-1)/Math.round(10*t/1e3))+1;if(n<=0)return 0;for(let e=0;e<2;++e)n=Math.floor((n-1)/2)+1;return Math.min(n,this.audio_seq_length)}async _call(e,t=null,s=null,n={}){let r,a;if("string"==typeof e&&(e=[e]),t){let s=(r=await this.image_processor(t,n)).num_soft_tokens_per_image,a=0;e=e.map(e=>e.replaceAll(this.image_token,()=>` 14 15${this.boi_token}${this.image_token.repeat(s[a++])}${this.eoi_token} 16 17`))}if(s){let t=Array.isArray(s)?s:[s];a=await this.feature_extractor(t[0],n);let r=this.feature_extractor.config.sampling_rate??16e3,i=0;e=e.map(e=>e.replaceAll(this.audio_token,()=>` 18 19${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(t[i++].length,r))}${this.eoa_token} 20 21`))}return{...this.tokenizer(e,n),...r,...a}}},iq=class extends rB{static image_processor_class=iN;static tokenizer_class=rL;static image_token="<|image_pad|>";async _call(e,t=null){let s,n;if(Array.isArray(e)||(e=[e]),t&&(n=(s=await this.image_processor(t)).image_grid_thw),n){let t=this.image_processor.config.merge_size**2,s=0,r=this.constructor.image_token,a=n.tolist();e=e.map(e=>{for(;e.includes(r);){let n=Number(a[s++].reduce((e,t)=>
21e*t,1n));e=e.replace(r,"<|placeholder|>".repeat(Math.floor(n/t)))}return e.replaceAll("<|placeholder|>",r)})}return{...this.tokenizer(e),...s}}},iG=class extends iq{static image_token="<|image|>"},ij=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:n}=this.feature_extractor.config,r=Math.floor(s/n);return Math.ceil(Math.floor((Math.floor(e/t)+1)/2)/s)*r}async _call(e,t=null,s={}){if(Array.isArray(e))throw Error("Batched inputs are not supported yet.");let n={};if(t){let{input_features:s}=await this.feature_extractor(t);n.input_features=s;let r=this._get_num_audio_features(t.length);n.input_features_mask=new nx("bool",new Uint8Array(r).fill(1),[1,r]);let a=this.config.audio_token??"<|audio|>";if(!e.includes(a))throw Error(`The input text does not contain the audio token ${a}.`);e=e.replaceAll(a,a.repeat(r))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}},iR=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;async _call(e,t,s={}){let n=e?await this.image_processor(e,s):{};return{...t?this.tokenizer(t,s):{},...n}}post_process_grounded_object_detection(e,t,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:r=null}={}){let{logits:a,pred_boxes:i}=e,o=a.dims[0];if(null!==r&&r.length!==o)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let l=a.dims.at(1),c=a.sigmoid(),d=c.max(-1).tolist(),u=i.tolist().map(e=>e.map(e=>aM(e))),_=[];for(let e=0;e<o;++e){let a=null!==r?r[e]:null;null!==a&&(u[e]=u[e].map(e=>e.map((e,t)=>e*a[(t+1)%2])));let i=d[e],o=[],h=[],p=[];for(let r=0;r<l;++r){let a=i[r];if(a<=s)continue;let l=u[e][r],d=c[e][r];o.push(a),p.push(l);let _=function(e,t){let s=e.dims.at(-1)-1,n=e.tolist();n.fill(!1,0,1),n.fill(!1,s);let r=t.tolist();return n.map((e,t)=>e?t:null).filter(e=>null!==e).map(e=>r[e])}(d.gt(n),t[e]);h.push(_)}_.push({scores:o,boxes:p,labels:this.batch_decode(h)})}return _}},iU=class extends rB{static image_processor_class=iN;static tokenizer_class=rL;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(e,t=null,s={}){let n;s.return_row_col_info??=!0,t&&(n=await this.image_processor(t,s)),Array.isArray(e)||(e=[e]);let r=n.rows??[Array(e.length).fill(0)],a=n.cols??[Array(e.length).fill(0)],i=this.config.image_seq_len,o=[],l=[];for(let t=0;t<e.length;++t){let s=e[t],n=r[t],c=a[t];o.push(function(e,t){let s=0;for(let n of e)n===t&&++s;return s}(s,this.image_token));let d=n.map((e,t)=>(function(e,t,s,n,r,a){if(0===e&&0===t)return`${n}${a}`+r.repeat(s)+`${n}`;let i="";for(let a=0;a<e;++a){for(let e=0;e<t;++e)i+=n+`<row_${a+1}_col_${e+1}>`+r.repeat(s);i+="\n"}return i+(` 22${n}${a}`+r.repeat(s)+`${n}`)})(e,c[t],i,this.fake_image_token,this.image_token,this.global_img_token)),u=s.split(this.image_token);if(0===u.length)throw Error("The image token should be present in the text.");let _=u[0];for(let e=0;e<d.length;++e)_+=d[e]+u[e+1];l.push(_)}return{...this.tokenizer(l),...n}}},iW=class extends rB{static image_processor_class=iN;static tokenizer_class=rL;static uses_processor_config=!0;constructor(e,t,s){super(e,t,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:t=null,chat_template:s="default"}={}){t?Array.isArray(t)||(t=[t]):t=await Promise.all(e.filter(e=>e.images).flatMap(e=>e.images).map(e=>ax.read(e)));let n=this.tokenizer,r=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=e=>n.encode(e,{add_special_tokens:!1}),i=r.split(this.image_tag),o=i.length-1;if(t.length!==o)throw Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${o})`);let[l,c,d]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),u=a(i[0]),_=Array(u.length).fill(!1);for(let e=1;e<i.length;++e){let t=Array(this.num_image_tokens).fill(l),s=a(i[e]);u=j(u,[c],t,[d],s),_=j(_,[!1],Array(this.num_image_tokens).fill(!0),[!1],Array(s.length).fill(!1))}let h=[1,u.length],p={input_ids:new nx("int64",u,h),attention_mask:new nx("int64",Array(u.length).fill(1),h),images_seq_mask:new nx("bool",_,h),images_emb_mask:new nx("bool",Array(o*this.num_image_tokens).fill(!0),[1,o,this.num_image_tokens])};if(t&&t.length>0){let e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...p,...e}}return p}},iQ=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;async _call(e=null,t=null,s={}){if(!e&&!t)throw Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},r=t?await this.image_processor(t,s):{};return{...n,...r}}},iH=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;async _call(e,t=null,s={}){let{image_rows:n,image_cols:r,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(t){let e=this.config.image_token??"<image>",{tile_size:s=512,downsample_factor:i=2,encoder_patch_size:o=16,use_thumbnail:l=!0}=this.image_processor.config,c=e=>Math.ceil(Math.floor(e/o)/i),d=c(s)**2,u=this.config.image_start_token??"<|image_start|>",_=this.config.image_end_token??"<|image_end|>",h=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let p=0;t=t.map(t=>{let s=t.split(e);return s[0]+s.slice(1).map(t=>{let s=p++,[i,o]=a[s],m=n[s],f=r[s],g=c(i)*c(o),w=u;if(m>1||f>1){let t=e.repeat(d);for(let e=0;e<m;++e)for(let s=0;s<f;
22++s)w+=`<|img_row_${e+1}_col_${s+1}|>`+t;l&&(w+=h+e.repeat(g))}else w+=e.repeat(g);return w+_+t}).join("")})}return{...i,...t?this.tokenizer(t,s):{}}}},iX=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;static uses_processor_config=!0;async _call(e,t=null,s={}){let n=await this.image_processor(e,s);if(t){let[e,s]=n.pixel_values.dims.slice(-2),{image_token:r,patch_size:a,num_additional_image_tokens:i}=this.config,o=Math.floor(e/a)*Math.floor(s/a)+i;Array.isArray(t=structuredClone(t))||(t=[t]);for(let e=0;e<t.length;++e)t[e]=t[e].replace(r,r.repeat(o))}let r=t?this.tokenizer(t,s):{};return{...n,...r}}},iJ={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},iK=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;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,t){if(!iJ.hasOwnProperty(t))throw Error(`Format ${t} is not supported.`);let[s,n]=iJ[t],r=this[s].bind(this),[a,i]=e.dims,o=[],l=[],c=e.tolist();for(let e=0;e<a;++e){let t=c[e],s=[],r=[];for(let e=1;e<i;++e){let[a,i]=sR(sG(t[e]));if(r.push(a),i==n)break;s.push(i)}let a=r.length>0?r.reduce((e,t)=>e*t,1):0;l.push(s),o.push(a)}return[r(l),o]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(e=>e.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(e=>e.replaceAll(" ",""))}batch_decode([e,t,s]){let[n,r]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(t,"bpe"),[o,l]=this._decode_helper(s,"wp"),c=[],d=[];for(let e=0;e<n.length;++e){let[t,s]=sR([r[e],i[e],l[e]]);c.push([n[e],a[e],o[e]][s]),d.push(t)}return{generated_text:c,scores:d,char_preds:n,bpe_preds:a,wp_preds:o}}static async from_pretrained(...e){let t=await super.from_pretrained(...e),s=await rL.from_pretrained("Xenova/gpt2"),n=await rL.from_pretrained("Xenova/bert-base-uncased");return t.components={image_processor:t.image_processor,char_tokenizer:t.tokenizer,bpe_tokenizer:s,wp_tokenizer:n},t}async _call(e,t=null){let s=await this.image_processor(e);return t&&(s.labels=this.tokenizer(t).input_ids),s}},iY=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;async _call(e){return await this.feature_extractor(e)}},iZ=class extends rB{static tokenizer_class=rL;static image_processor_class=iN},i0="<image>",i1=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;static uses_processor_config=!1;async _call(e,t=null,s={}){let n;t||(W.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=this.tokenizer.bos_token,a=this.image_processor.config.image_seq_length;t.some(e=>e.includes(i0))?n=t.map(e=>{let t=e.replaceAll(i0,i0.repeat(a)),s=t.lastIndexOf(i0),n=-1===s?0:s+i0.length;return t.slice(0,n)+r+t.slice(n)+"\n"}):(W.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."),n=t.map(t=>{var s;return s=e.length,`${i0.repeat(a*s)}${r}${t} 23`}));let i=this.tokenizer(n,s);return{...await this.image_processor(e,s),...i}}},i2="<|image|>",i3=/<\|image_\d+\|>/g,i4=class extends rB{static image_processor_class=iN;static tokenizer_class=rL;async _call(e,t=null,{padding:s=!0,truncation:n=!0,num_crops:r=null}={}){let a,i;if(Array.isArray(e)||(e=[e]),t){let{num_img_tokens:o}=i=await this.image_processor(t,{num_crops:r}),l=e.map((e,t)=>e.split(i3).join(i2.repeat(o[t])));a=this.tokenizer(l,{padding:s,truncation:n});let c=this.tokenizer._tokenizer.token_to_id(i2);a.input_ids.map_(e=>e==c?-e:e)}else a=this.tokenizer(e);return{...a,...i}}},i8=class extends rB{static tokenizer_class=rL;static image_processor_class=iN;static uses_processor_config=!0;async _call(e,t=null,s={}){let n=await this.image_processor(e,s);if(t){let[e,s]=n.pixel_values.dims.slice(-2),{image_token:r,image_break_token:a,image_end_token:i,patch_size:o,spatial_merge_size:l}
23=this.config,c=o*l,d=Math.floor(e/c),u=Math.floor(s/c);Array.isArray(t=structuredClone(t))||(t=[t]);for(let e=0;e<t.length;++e){let s=r.repeat(u),n=s+a,o=s+i,l=n.repeat(d-1)+o;t[e]=t[e].replace(r,l)}}let r=t?this.tokenizer(t,s):{};return{...n,...r}}},i6=class extends rB{static feature_extractor_class=ar;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}},i5=class extends iq{},i9=class extends i5{},i7=class extends rB{static image_processor_class=iN;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)}},oe=class extends i7{},ot=class extends oe{},os=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;async _call(e){return await this.feature_extractor(e)}},on=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;static uses_processor_config=!0;async _call(e,t=null,s={}){if(Array.isArray(e))throw Error("Batched inputs are not supported yet.");let n={};if(t){let r=t.length,{input_features:a}=await this.feature_extractor(t,{...s,max_length:r}),i=1+Math.ceil(Math.round(r/this.config.encoder_ds_factor+1e-4)/this.config.stack_factor);n.audio_token_len=[i],n.audio_values=a;let o=this.config.audio_placeholder;if(!e.includes(o))throw Error(`The input text does not contain the image token ${o}.`);e=e.replaceAll(o,o.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}},or="[AUDIO]",oa=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;static uses_processor_config=!1;async _call(e,t=null,s={}){if(Array.isArray(e))throw Error("Batched inputs are not supported yet.");let n={};if(t){if(!e.includes(or))throw Error(`The input text does not contain the audio token ${or}.`);Array.isArray(t)||(t=[t]);let r=e.split(or),a=r.length-1;if(a!==t.length)throw Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${a}).`);let i=this.feature_extractor.config.n_samples,o=t.map(e=>(function(e,t){let s=[];for(let n=0;n<e.length;n+=t)s.push(e.subarray(n,Math.min(n+t,e.length)));return s})(e,i)),l=o.map(e=>e.length),c=o.flat(),d=(await Promise.all(c.map(e=>this.feature_extractor(e,s)))).map(e=>e.input_features);n.audio_values=d.length>1?nS(d,0):d[0];let u=r[0];for(let e=0;e<l.length;++e){u+="[BEGIN_AUDIO]";for(let t=0;t<l[e];++t)u+=or.repeat(375);u+=r[e+1]}e=u}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}},oi=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return 56}get num_samples_first_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return 8*e+t}get num_right_pad_tokens(){return 17}get audio_length_per_tok(){return 8}get raw_audio_length_per_tok(){return 8*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:s=!0}={}){if(rq(e,"VoxtralRealtimeProcessor"),!t&&!s)throw Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(!s)return await this.feature_extractor(e,{center:!1});if(t){let t=32*this.raw_audio_length_per_tok,s=new Float32Array(t+e.length);s.set(e,t);let n=await this.feature_extractor(s,{center:!0}),r=new BigInt64Array(39).fill(BigInt(32));return r[0]=1n,{input_ids:new nx("int64",r,[1,39]),...n}}{let t=this.num_right_pad_tokens*this.raw_audio_length_per_tok,s=new Float32Array(e.length+t);return s.set(e),await this.feature_extractor(s,{center:!0})}}},oo=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;async _call(e){return await this.feature_extractor(e)}},ol=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;async _call(e){return await this.feature_extractor(e)}},oc=class extends rB{static tokenizer_class=rL;static feature_extractor_class=a_;async _call(e){return await this.feature_extractor(e)}},od=class{static async from_pretrained(e,t={}){let s=await sq(e,rI,!0,t),{image_processor_type:n,feature_extractor_type:r,processor_class:a}=s;if(a&&rD[a])return rD[a].from_pretrained(e,t);if(!n&&!r)throw Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let i={};if(n){let e=aS[n.replace(/Fast$/,"")];if(!e)throw Error(`Unknown image_processor_type: '${n}'.`);i.image_processor=new e(s)}if(r){let e=aS[r];if(e)i.image_processor=new e(s);else{let e=rG[r];if(!e)throw Error(`Unknown feature_extractor_type: '${r}'.`);i.feature_extractor=new e(s)}}return new rB({},i,null)}};async function ou(e,t){return await sq(e,"config.json",!0,t)}function o_(e,t){e instanceof oh||(e=new oh(e));let s=t?.prefix??"past_key_values",n="present"===s?"present":"past",r=new Set;if(["lfm2","lfm2_moe"].includes(e.model_type)){let{layer_types:t}=e;for(let e=0;e<t.length;++e)if("full_attention"===t[e])r.add(`${s}.${e}.key`),r.add(`${s}.${e}.value`);else if("conv"===t[e])r.add(`${n}_conv.${e}`);else throw Error(`Unsupported layer type: ${t[e]}`);return r}if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(e.model_type)){let t=e,a=t.layer_types??t.layers_block_type,i=t.num_hidden_layers??a?.length;for(let e=0;e<i;++e)a&&"mamba"!==a[e]||(r.add(`${n}_conv.${e}`),r.add(`${n}_ssm.${e}`)),a&&"attention"!==a[e]||(r.add(`${s}.${e}.key`),r.add(`${s}.${e}.value`));return r}if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(e.model_type)){let{layer_types:t}=e;for(let a=0;a<t.length;++a)if("full_attention"===t[a])r.add(`${s}.${a}.key`),r.add(`${s}.${a}.value`);else if("linear_attention"===t[a])"olmo_hybrid"===e.model_type?(r.add(`${n}_conv.${a}.key`),r.add(`${n}_conv.${a}.value`),r.add(`${n}_conv.${a}.query`)):r.add(`${n}_conv.${a}`),r.add(`${n}_recurrent.${a}`);else throw Error(`Unsupported layer type: ${t[a]}`);return r}if(["gemma4","gemma4_text"].includes(e.model_type)){let t="gemma4"===e.model_type?e.text_config:e,n=t.num_hidden_layers-(t.num_kv_shared_layers??0);for(let e=0;e<n;++e)r.add(`${s}.${e}.key`),r.add(`${s}.${e}.value`);return r}if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(e.model_type))return o_("voxtral_realtime"===e.model_type&&t?.session_name==="audio_encoder"?e.audio_config:e.text_config,t);return function(e,{prefix:t="past_key_values"}={}){let s=new Set,n=e.normalized_config;if(n.is_encoder_decoder&&"num_encoder_heads"in n&&"num_decoder_heads"in n)for(let e=0;e<n.num_decoder_layers;++e)s.add(`${t}.${e}.encoder.key`),s.add(`${t}.${e}.encoder.value`),s.add(`${t}.${e}.decoder.key`),s.add(`${t}.${e}.decoder.value`);else if(n.multi_query)for(let e=0;e<n.num_layers;++e)s.add(`${t}.${e}.key_value`);else for(let e=0;e<n.num_layers;++e)s.add(`${t}.${e}.key`),s.add(`${t}.${e}.value`);return s}(e,{prefix:s})}var oh=class e{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=function e(t){let s={},n={};switch(t.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"gemma4":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":n=e(t.text_config);break;case"moondream1":n=e(t.phi_config);break;case"musicgen":n=e(t.decoder);break;case"multi_modality":n=e(t.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":s.num_heads="n_head",s.num_layers="n_layer",s.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":s.num_heads="num_attention_heads",s.num_layers="num_hidden_layers",s.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":s.num_heads="num_key_value_heads",s.num_layers="num_hidden_layers",s.hidden_size="hidden_size",s.num_attention_heads="num_attention_heads",s.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"gemma4_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":s.num_heads="num_key_value_heads",s.num_layers="num_hidden_layers",s.dim_kv="head_dim";break;case"openelm":s.num_heads="num_kv_heads",s.num_layers="num_transformer_layers",s.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":s.num_heads="num_heads",s.num_layers="num_layers",s.hidden_size="hidden_size";break;case"bloom":s.num_heads="n_head",s.num_layers="n_layer",s.hidden_size="hidden_size";break;case"mpt":s.num_heads="n_heads",s.num_layers="n_layers",s.hidden_size="d_model";break;case"exaone":s.num_heads="num_key_value_heads",s.num_layers="num_layers",s.dim_kv="head_dim",s.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"glm_moe_dsa":case"mistral4":s.num_heads="num_key_value_heads",s.num_layers="num_hidden_layers",s.dim_kv="qk_head_dim",s.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":s.num_decoder_layers="num_decoder_layers",s.num_decoder_heads="num_heads",s.decoder_dim_kv="d_kv",s.num_encoder_layers="num_layers",s.num_encoder_heads="num_heads",s.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":s.num_decoder_layers="decoder_layers",s.num_decoder_heads="decoder_attention_heads",s.decoder_hidden_size="d_model",s.num_encoder_layers="encoder_layers",s.num_encoder_heads="encoder_attention_heads",s.encoder_hidden_size="d_model";break;case"speecht5":s.num_decoder_layers="decoder_layers",s.num_decoder_heads="decoder_attention_heads",s.decoder_hidden_size="hidden_size",s.num_encoder_layers="encoder_layers",s.num_encoder_heads="encoder_attention_heads",s.encoder_hidden_size="hidden_size";break;case"trocr":s.num_encoder_layers=s.num_decoder_layers="decoder_layers",s.num_encoder_heads=s.num_decoder_heads="decoder_attention_heads",s.encoder_hidden_size=s.decoder_hidden_size="d_model";break;case"musicgen_decoder":s.num_encoder_layers=s.num_decoder_layers="num_hidden_layers",s.num_encoder_heads=s.num_decoder_heads="num_attention_heads",s.encoder_hidden_size=s.decoder_hidden_size="hidden_size";break;case"moonshine":s.num_decoder_layers="decoder_num_hidden_layers",s.num_decoder_heads="decoder_num_key_value_heads",s.num_encoder_layers="encoder_num_hidden_layers",s.num_encoder_heads="encoder_num_key_value_heads",s.encoder_hidden_size=s.decoder_hidden_size="hidden_size";break;case"cohere_asr":s.num_decoder_layers="num_hidden_layers",s.num_decoder_heads="num_key_value_heads",s.decoder_hidden_size="hidden_size",s.decoder_dim_kv="head_dim";let{num_hidden_layers:r,num_attention_heads:a,hidden_size:i}=t.encoder_config;n={num_encoder_layers:r,num_encoder_heads:a,encoder_hidden_size:i,encoder_dim_kv:t.head_dim};break;case"vision-encoder-decoder":let o=e(t.decoder),l="num_decoder_layers"in o,c=U(t,["model_type","is_encoder_decoder"]);return l?(c.num_decoder_layers=o.num_decoder_layers,c.num_decoder_heads=o.num_decoder_heads,c.decoder_hidden_size=o.decoder_hidden_size,c.num_encoder_layers=o.num_encoder_layers,c.num_encoder_heads=o.num_encoder_heads,c.encoder_hidden_size=o.encoder_hidden_size):(c.num_layers=o.num_layers,c.num_heads=o.num_heads,c.hidden_size=o.hidden_size),c}let d={...n,...U(t,["model_type","multi_query","is_encoder_decoder"])};for(let e in s)d[e]=t[s[e]];return d}(this)}static async from_pretrained(t,{progress_callback:s=null,config:n=null,cache_dir:r=null,local_files_only:a=!1,revision:i="main"}={}){return!n||n instanceof e||(n=new e(n)),new this(n??await ou(t,{progress_callback:s,config:n,cache_dir:r,local_files_only:a,revision:i}))}},op=class{static async from_pretrained(...e){return oh.from_pretrained(...e)}
23};function om(e,t,s){return e?"object"==typeof e&&null!==e?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(s)?+e[s]:0:+e:0}function of(e,t){let s=[];for(let n=0;n<t;++n)s.push(`${e}_data${0===n?"":"_"+n}`);return s}async function og(e,t,s,n){let r=`${t}${n}.onnx`,a=`${s.subfolder??""}/${r}`;return await sD(e,a,!0,s,F.IS_NODE_ENV)}async function ow(e,t,s,n,r,a={}){let i=`${t}${s}.onnx`,o=F.IS_NODE_ENV,l=[],c=om(r,i,t);if(c>0){if(c>100)throw Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (100).`);for(let t of of(i,c)){let s=`${n.subfolder??""}/${t}`;l.push(new Promise(async(r,a)=>{let i=await sD(e,s,!0,n,o);r(i instanceof Uint8Array?{path:t,data:i}:t)}))}}else void 0!==a.externalData&&(l=a.externalData.map(async t=>{if("string"==typeof t.data){let s=await sD(e,t.data,!0,n);return{...t,data:s}}return t}));return Promise.all(l)}async function ox(e,t,s,r=!1,a){let i=s.config?.["transformers.js_config"]??{},o=nu(s.device??i.device,t,{warn:e=>W.info(e)}),l=function(e=null){if(!e)return n;switch(e){case"auto":return s8;case"gpu":return s8.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(s8.includes(e))return[s2[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${s8.join(", ")}.`)}(o),c=i.device_config??{};c.hasOwnProperty(o)&&(i={...i,...c[o]});let d=ng(s.dtype??i.dtype,t,o,{configDtype:i.dtype,warn:e=>W.info(e)});if(nf.hasOwnProperty(d)){if("webgpu"===o&&!F.IS_NODE_ENV&&d===nh.fp16&&!await n_())throw Error(`The device (${o}) does not support fp16.`)}else throw Error(`Invalid dtype: ${d}. Should be one of: ${Object.keys(nh).join(", ")}`);let u=nf[d],_={...s.session_options};_.executionProviders??=l;let h=i.free_dimension_overrides;h?_.freeDimensionOverrides??=h:o.startsWith("webnn")&&!_.freeDimensionOverrides&&W.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"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let p=og(e,t,s,u),m=s.use_external_data_format??i.use_external_data_format,f=await ow(e,t,u,s,m,_);if(f.length>0&&(!F.IS_NODE_ENV||f.some(e=>"string"!=typeof e))&&(_.externalData=f),r&&"webgpu"===o){let e=o_(s.config,{prefix:"present",session_name:a});if(e.size>0&&!ni()){let t={};for(let s of e)t[s]="gpu-buffer";_.preferredOutputLocation=t}}return{buffer_or_path:await p,session_options:_,session_config:{dtype:d,device:o}}}async function oy(e,t,s,n){return Object.fromEntries(await Promise.all(Object.keys(t).map(async r=>{let a=n?.[r]??!1,{buffer_or_path:i,session_options:o,session_config:l}=await ox(e,t[r],s,a,r);return[r,await nt(i,o,l)]})))}async function ob(e,t){let s=function(e,t){let s=Object.create(null),n=[];for(let r of e.inputNames){let e=t[r];if(!(e instanceof nx)){n.push(r);continue}s[r]=ni()?e.clone():e}if(n.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${n.join(", ")}.`);let r=Object.keys(t).length,a=e.inputNames.length;if(r>a){let s=Object.keys(t).filter(t=>!e.inputNames.includes(t));W.warn(`WARNING: Too many inputs were provided (${r} > ${a}). The following inputs will be ignored: "${s.join(", ")}".`)}return s}(e,t);try{let t=Object.fromEntries(Object.entries(s).map(([e,t])=>{let s=t.ort_tensor;return F.IS_NODE_ENV&&"undefined"!=typeof Float16Array&&s.cpuData instanceof Float16Array&&(s.cpuData=new Uint16Array(s.cpuData.buffer)),[e,s]})),n=await nn(e,t);return function e(t){for(let s in t)nr(t[s])?t[s]=new nx(t[s]):"object"==typeof t[s]&&e(t[s]);return t}(n)}catch(t){let e=Object.fromEntries(Object.entries(s).map(([e,t])=>{let s={type:t.type,dims:t.dims,location:t.location};return"gpu-buffer"!==s.location&&(s.data=t.data),[e,s]}));throw W.error(`An error occurred during model execution: "${t}".`),W.error("Inputs given to model:",e),t}}var oM=class{},ok=class extends oM{constructor({logits:e,...t}){super(),this.logits=e;let s=Object.values(t);s.length>0&&(this.attentions=s)}},ov=class extends oM{constructor({logits:e}){super(),this.logits=e}},oE=class extends oM{constructor({logits:e}){super(),this.logits=e}},oA=class extends oM{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},oC=class extends oM{constructor({logits:e}){super(),this.logits=e}},oF=class extends oM{constructor({alphas:e}){super(),this.alphas=e}},oS=class extends D{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},oT=class extends D{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},oP=class extends D{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let s=t;for(let t of this.processors)s=t(e,s);return s}[Symbol.iterator](){return this.processors.values()}},oz=class extends oS{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let s=0;s<e.length;++s)if(1===e[s].length){let e=t[s].data;e.fill(-1/0),e[this.bos_token_id]=0}return t}},oL=class extends oS{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.max_length-1){let e=t[s].data;for(let t of(e.fill(-1/0),this.eos_token_id))e[t]=0}return t}},oO=class extends oS{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let s=0;s<e.length;++s){let e=t[s].data;for(let t of this.suppress_tokens)e[t]=-1/0}return t}},oI=class extends oS{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length===this.begin_index){let e=t[s].data;for(let t of this.begin_suppress_tokens)e[t]=-1/0}return t}},oN=class extends oS{constructor(e,t){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=t.length,t.at(-1)===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let s=0;s<e.length;++s){let n=t[s].data;if(n[this.no_timestamps_token_id]=-1/0,e[s].length===this.begin_index){n.subarray(0,this.timestamp_begin).fill(-1/0);continue}let r=e[s].slice(this.begin_index),a=r.length>=1&&r[r.length-1]>=this.timestamp_begin,i=r.length<2||r[r.length-2]>=this.timestamp_begin;
23if(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&&null!==this.max_initial_timestamp_index){let e=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(e+1).fill(-1/0)}let o=function(e){let t=sR(e)[0],s=0;for(let n=0;n<e.length;++n)s+=Math.exp(e[n]-t);let n=Math.log(s);return e.map(e=>e-t-n)}(n);Math.log(o.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>sR(o.subarray(0,this.timestamp_begin))[0]&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},o$=class extends oS{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,s=[];for(let n=0;n<t+1-this.no_repeat_ngram_size;++n){let t=[];for(let s=0;s<this.no_repeat_ngram_size;++s)t.push(e[n+s]);s.push(t.map(Number))}let n=new Map;for(let e of s){let t=JSON.stringify(e.slice(0,e.length-1)),s=n.get(t)??[];s.push(e[e.length-1]),n.set(t,s)}return n}getGeneratedNgrams(e,t){let s=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(s.map(Number)))??[]}calcBannedNgramTokens(e){if(e.length+1<this.no_repeat_ngram_size)return[];{let t=this.getNgrams(e);return this.getGeneratedNgrams(t,e)}}_call(e,t){for(let s=0;s<e.length;++s){let n=t[s].data;for(let t of this.calcBannedNgramTokens(e[s]))n[t]=-1/0}return t}},oB=class extends oS{constructor(e){super(),this.penalty=e}_call(e,t){for(let s=0;s<e.length;++s){let n=t[s].data;for(let t of new Set(e[s])){let e=Number(t);n[e]<0?n[e]*=this.penalty:n[e]/=this.penalty}}return t}},oD=class extends oS{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length<this.min_length){let e=t[s].data;for(let t of this.eos_token_id)e[t]=-1/0}return t}},oV=class extends oS{constructor(e,t,s){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(s)?s:[s]}_call(e,t){for(let s=0;s<e.length;++s)if(e[s].length-this.prompt_length_to_skip<this.min_new_tokens){let e=t[s].data;for(let t of this.eos_token_id)e[t]=-1/0}return t}},oq=class extends oS{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let s=0;s<e.length;++s){let n=t[s].data,r=e[s];for(let e of this.bad_words_ids){if(r.length<e.length-1)continue;let t=!0;for(let s=1;s<=e.length-1;++s)if(e.at(-s-1)!=r.at(-s)){t=!1;break}t&&(n[e.at(-1)]=-1/0)}}return t}},oG=class extends oS{constructor(e){if(super(),e<=1)throw Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw 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 ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let s=e.length,n=t.slice([0,s],null),r=t.slice([s,t.dims[0]],null);for(let e=0;e<r.data.length;++e)r.data[e]+=(n.data[e]-r.data[e])*this.guidance_scale;return r}},oj=class extends oT{constructor(e){super(),"number"!=typeof e||e<=0,this.temperature=e}_call(e,t){let s=t.data;for(let e=0;e<s.length;++e)s[e]/=this.temperature;return t}},oR=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,U(e,Object.getOwnPropertyNames(this)))}},oU=class extends D{_call(e,t){throw Error("StoppingCriteria needs to be subclassed")}},oW=class e extends D{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(t){t instanceof e?t=t.criteria:t instanceof oU&&(t=[t]),this.criteria.push(...t)}_call(e,t){let s=Array(e.length).fill(!1);for(let n of this.criteria){let r=n(e,t);for(let e=0;e<s.length;++e)s[e]||=r[e]}return s}[Symbol.iterator](){return this.criteria.values()}},oQ=class extends oU{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(e=>e.length>=this.max_length)}},oH=class extends oU{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(e=>{let t=e.at(-1);return this.eos_token_id.some(e=>t==e)})}},oX=class extends D{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}
23async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,t){let s=e.dims.at(-1),n=e.data;if(-1===t)n=n.slice(-s);else{let e=t*s;n=n.slice(e,e+s)}return n}randomSelect(e){return sd(s_.random,e)}static getSampler(e){if(e.do_sample)return new oK(e);if(e.num_beams>1)return new oY(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 oJ(e)}},oJ=class extends oX{async sample(e){return[[BigInt(sR(e.data)[1]),0]]}},oK=class extends oX{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[s,n]=await nk(e,t),r=sG(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(r);return[n.data[e],Math.log(r[e])]})}},oY=class extends oX{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[s,n]=await nk(e,t),r=sG(s.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[n.data[t],Math.log(r[t])])}},oZ=class{constructor(e){if(!e)return;for(let t in e){if(t in this)throw TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let s=e[t];if(!(s instanceof nx))throw TypeError(`Expected a Tensor for key "${t}", got ${typeof s}`);this[t]=s}}get_seq_length(){if(0===Object.keys(this).length)return 0;for(let e in this)if(e.startsWith("past_key_values."))return this[e].dims.at(-2);throw Error("Unable to determine sequence length from the cache.")}update(e){for(let t in e){let s=this[t],n=e[t];s&&s!==n&&"gpu-buffer"===s.location&&s.dispose(),this[t]=n}}async dispose(){let e=[];for(let t of Object.values(this))"gpu-buffer"===t.location&&e.push(t.dispose());await Promise.all(e)}},o0={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},o1={[o0.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??"model"})},[o0.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[o0.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[o0.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,s)=>{let n={...o1[o0.ImageTextToText].text_only_sessions};return s||(n.vision_encoder="vision_encoder"),e.is_encoder_decoder&&(n.model="encoder_model"),n},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,s)=>{let n={...o1[o0.AudioTextToText].text_only_sessions};return s||(n.audio_encoder="audio_encoder"),n},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,s)=>{let n={...o1[o0.ImageAudioTextToText].text_only_sessions};return s||(n.audio_encoder="audio_encoder",n.vision_encoder="vision_encoder"),n},optional_configs:{generation_config:"generation_config.json"}},[o0.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[o0.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[o0.Chatterbox]:{sessions:()=>
23({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[o0.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(e,t,s)=>{let n={...o1[o0.VoxtralRealtime].text_only_sessions};return s||(n.audio_encoder="audio_encoder"),n},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(e,t)=>({model:t.model_file_name??"model"})}};async function o2(e,{config:t=null,dtype:s=null,device:n=null,model_file_name:r=null}={}){t=await function(e,{config:t=null,cache_dir:s=null,local_files_only:n=!1,revision:r="main"}={}){return null!==t?op.from_pretrained(e,{config:t,cache_dir:s,local_files_only:n,revision:r}):sF(JSON.stringify([e,s,n,r]),()=>op.from_pretrained(e,{config:t,cache_dir:s,local_files_only:n,revision:r}))}(e,{config:t});let a=["config.json"],i=t["transformers.js_config"]??{},o=i.use_external_data_format,l="onnx",c=n??i.device,d=s??i.dtype,u=function(e,{warn:t=!0}={}){let s=e.architectures||[];for(let e of s){let t=o9.get(e);if(void 0!==t)return t}if(e.model_type){let t=o9.get(e.model_type);if(void 0!==t)return t;for(let t of Object.values(o3))if(t.has(e.model_type)){let s=o9.get(t.get(e.model_type));if(void 0!==s)return s}}if(t){let t=s.length>0?s.join(", "):"(none)";W.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${t}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${rO}`)}return o0.EncoderOnly}(t),_=(e,t=null)=>{t=t??e;let s=nu(c,e),n=nf[ng(d,e,s)]??"",r=`${t}${n}.onnx`,i=l?`${l}/${r}`:r;a.push(i);let u=om(o,r,e);for(let e of of(r,u)){let t=l?`${l}/${e}`:e;a.push(t)}},{sessions:h,optional_configs:p}=function(e,t,s={}){let n=o1[e]??o1.default;return{sessions:n.sessions(t,s,s.textOnly??!1),cache_sessions:n.cache_sessions,optional_configs:n.optional_configs}}(u,t,{model_file_name:r});for(let[e,t]of Object.entries(h))_(e,t);if(p)for(let e of Object.values(p))a.push(e);return a}var o3=null;function o4(e){if(e instanceof nx)return e;if(0===e.length)throw Error("items must be non-empty");if(!Array.isArray(e[0]))return new nx("int64",BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length]);if(e.some(t=>t.length!==e[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 nx("int64",BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}function o8(e){return new nx("bool",[e],[1])}var o6={[o0.DecoderOnly]:{can_generate:!0,forward:ll,prepare_inputs:lh},[o0.DecoderOnlyWithoutHead]:{can_generate:!1,forward:ll,prepare_inputs:lh},[o0.Seq2Seq]:{can_generate:!0,forward:ls,prepare_inputs:lp},[o0.Vision2Seq]:{can_generate:!0,forward:ls,prepare_inputs:lp},[o0.Musicgen]:{can_generate:!0,forward:ls},[o0.EncoderDecoder]:{can_generate:!1,forward:ls},[o0.ImageTextToText]:{can_generate:!0,forward:lu,prepare_inputs:lm},[o0.AudioTextToText]:{can_generate:!0,forward:ld,prepare_inputs:lm},[o0.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:lm},[o0.Phi3V]:{can_generate:!0,prepare_inputs:lm},[o0.MultiModality]:{can_generate:!0},[o0.AutoEncoder]:{can_generate:!1,forward:lr},[o0.Chatterbox]:{can_generate:!0,forward:ln},[o0.VoxtralRealtime]:{can_generate:!0,prepare_inputs:lh},default:{can_generate:!1,forward:ln}};function o5(e,t){let s=o9.get(e),n=!1,r=t?.architectures?.[0];if(r&&r!==e&&e?.endsWith("ForCausalLM")&&r.endsWith("ForConditionalGeneration")){let e=o9.get(r);void 0!==e&&(s=e,n=!0)}let a=o6[s]??o6.default,i=o1[s]??o1.default;return{typeConfig:{...a,...i},textOnly:n,modelType:s}}var o9=new Map,o7=new Map,le=new Map,lt=class extends D{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,t,s){super(),this.config=e,this.sessions=t,this.configs=s;let{typeConfig:n}=o5(le.get(this.constructor),e);this.can_generate=n.can_generate,this._forward=n.forward,this._prepare_inputs_for_generation=n.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 t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:r=!1,revision:a="main",model_file_name:i=null,subfolder:o="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,
23session_options:u={}}={}){let _={progress_callback:t,config:s,cache_dir:n,local_files_only:r,revision:a,model_file_name:i,subfolder:o,device:l,dtype:c,use_external_data_format:d,session_options:u},h=le.get(this),{typeConfig:p,textOnly:m,modelType:f}=o5(h,s=_.config=await op.from_pretrained(e,_));if(void 0===f){let e=h??s?.model_type;"custom"!==e&&W.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${rO}.`)}if(t&&!(t instanceof V)){let n={};try{let t=await o2(e,{config:s,dtype:c,device:l,model_file_name:i});(await Promise.all(t.map(t=>sT(e,t,_)))).forEach((e,s)=>{if(e.exists){let r="config.json"===t[s];n[t[s]]={loaded:r?e.size??0:0,total:e.size??0}}})}catch(e){W.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}Object.keys(n).length>0&&(_.progress_callback=new V(t,n))}let g=[oy(e,p.sessions(s,_,m),_,p.cache_sessions)];p.optional_configs&&g.push(lx(e,p.optional_configs,_));let w=await Promise.all(g);return new this(s,...w)}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,t,s=null){let n=new oP;if(null!==e.repetition_penalty&&1!==e.repetition_penalty&&n.push(new oB(e.repetition_penalty)),null!==e.no_repeat_ngram_size&&e.no_repeat_ngram_size>0&&n.push(new o$(e.no_repeat_ngram_size)),null!==e.bad_words_ids&&n.push(new oq(e.bad_words_ids,e.eos_token_id)),null!==e.min_length&&null!==e.eos_token_id&&e.min_length>0&&n.push(new oD(e.min_length,e.eos_token_id)),null!==e.min_new_tokens&&null!==e.eos_token_id&&e.min_new_tokens>0&&n.push(new oV(t,e.min_new_tokens,e.eos_token_id)),null!==e.forced_bos_token_id&&n.push(new oz(e.forced_bos_token_id)),null!==e.forced_eos_token_id&&n.push(new oL(e.max_length,e.forced_eos_token_id)),null!==e.suppress_tokens&&n.push(new oO(e.suppress_tokens)),null!==e.begin_suppress_tokens){let s=t>1||null===e.forced_bos_token_id?t:t+1;n.push(new oI(e.begin_suppress_tokens,s))}return null!==e.guidance_scale&&e.guidance_scale>1&&n.push(new oG(e.guidance_scale)),0===e.temperature&&e.do_sample&&(W.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&&null!==e.temperature&&1!==e.temperature&&n.push(new oj(e.temperature)),null!==s&&n.extend(s),n}_prepare_generation_config(e,t,s=oR){let n={...this.config};for(let e of["decoder","generator","text_config"])e in n&&Object.assign(n,n[e]);let r=new s(n);return Object.assign(r,this.generation_config??{}),e&&Object.assign(r,e),t&&Object.assign(r,U(t,Object.getOwnPropertyNames(r))),r}_get_stopping_criteria(e,t=null){let s=new oW;return null!==e.max_length&&s.push(new oQ(e.max_length,this.config.max_position_embeddings??null)),null!==e.eos_token_id&&s.push(new oH(e.eos_token_id)),t&&s.extend(t),s}_validate_model_class(){if(!this.can_generate){let e=[o3.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,o3.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,o3.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,o3.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=le.get(this.constructor),s=new Set,n=this.config.model_type;for(let t of e){let e=t?.get(n);e&&s.add(e)}let r=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(r+=` Please use the following class instead: ${[...s].join(", ")}`),Error(r)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw 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:t,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=la(t,s.past_key_values),s.input_ids=new nx("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=nS([s.decoder_attention_mask,n$([s.decoder_attention_mask.dims[
230],1])],1)):s.attention_mask=nS([s.attention_mask,n$([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:s}){let n=U(s,this.forward_params),r=this.main_input_name;if(r in n){if(e)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[r]=e;return{inputs_tensor:n[r],model_inputs:n,model_input_name:r}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:e,pixel_values:s,attention_mask:n,...r}=t,a=await this._prepare_inputs_embeds(t);t={...r,...U(a,["inputs_embeds","attention_mask"])}}let{last_hidden_state:r}=await ln(this,t);if(null!==n.guidance_scale&&n.guidance_scale>1)r=nS([r,nN(r,0)],0),"attention_mask"in t&&(t.attention_mask=nS([t.attention_mask,nB(t.attention_mask.dims)],0));else if(t.decoder_input_ids){let e=o4(t.decoder_input_ids).dims[0];if(e!==r.dims[0]){if(1!==r.dims[0])throw Error(`The encoder outputs have a different batch size (${r.dims[0]}) than the decoder inputs (${e}).`);r=nS(Array.from({length:e},()=>r),0)}}return t.encoder_outputs=r,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:s,decoder_start_token_id:n,bos_token_id:r,generation_config:a}){let{decoder_input_ids:i,...o}=s;if(!(i instanceof nx)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=r,"musicgen"===this.config.model_type)i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${n.length}`);i=n}else i=Array.from({length:e},()=>[n]);i=o4(i)}return o.decoder_attention_mask=n$(i.dims),{input_ids:i,model_inputs:o}}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:n=null,streamer:r=null,...a}){let i,o;this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:l,model_inputs:c,model_input_name:d}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),u=this.config.is_encoder_decoder;u&&("encoder_outputs"in c||(c=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:l,model_inputs:c,model_input_name:d,generation_config:t}))),u?{input_ids:i,model_inputs:c}=this._prepare_decoder_input_ids_for_generation({batch_size:c[d].dims.at(0),model_input_name:d,model_kwargs:c,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):i=c[d];let _=i.dims.at(-1);null!==t.max_new_tokens&&(t.max_length=_+t.max_new_tokens);let h=this._get_logits_processor(t,_,s),p=this._get_stopping_criteria(t,n),m=c[d].dims.at(0),f=oX.getSampler(t),g=Array(m).fill(0),w=i.tolist();r&&r.put(w);let x={},y={};for(;;){if(c=this.prepare_inputs_for_generation(w,c,t),o=await this.forward(c),t.return_dict_in_generate)if(t.output_attentions){let e=function(e){let t={};for(let s of["cross_attentions","encoder_attentions","decoder_attentions"])for(let n in e)n.startsWith(s)&&(s in t||(t[s]=[]),t[s].push(e[n]));return t}(o);for(let t in e)t in x||(x[t]=[]),x[t].push(e[t])}else this._return_dict_in_generate_keys&&Object.assign(y,U(o,this._return_dict_in_generate_keys));let e=h(w,o.logits.slice(null,-1,null).to("float32")),s=[];for(let t=0;t<e.dims.at(0);++t){let n=e[t];for(let[e,r]of(await f(n))){let n=BigInt(e);g[t]+=r,w[t].push(n),s.push([n]);break}}if(r&&r.put(s),p(w).every(e=>e))break;c=this._update_model_kwargs_for_generation({generated_input_ids:s,outputs:o,model_inputs:c,is_encoder_decoder:u})}r&&r.end();let b=new nx("int64",w.flat(),[w.length,w[0].length]),M=la(o,c.past_key_values),k=new Set(Object.values(M));for(let e of Object.values(o))"gpu-buffer"!==e.location||k.has(e)||e.dispose();return("past_key_values"in a||t.return_dict_in_generate||await M.dispose(),t.return_dict_in_generate)?{sequences:b,past_key_values:M,...x,...y}:b}async _encode_input(e,t,s){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let n=this.sessions[e];
23return(await ob(n,U(t,n.inputNames)))[s]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function ls(e,t){let{encoder_outputs:s,input_ids:n,decoder_input_ids:r,decoder_attention_mask:a,...i}=t;if(!s){let n=U(t,e.sessions.model.inputNames);s=(await ln(e,n)).last_hidden_state}return i.input_ids=r,i.encoder_hidden_states=s,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(i.encoder_attention_mask=t.attention_mask),a&&!i.attention_mask&&(i.attention_mask=a),await ll(e,i,!0)}async function ln(e,t){let s=e.sessions.model,n=U(t,s.inputNames);if(s.inputNames.includes("inputs_embeds")&&!n.inputs_embeds){if(!t.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");n.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(s.inputNames.includes("token_type_ids")&&!n.token_type_ids){if(!n.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");n.token_type_ids=nB(n.input_ids.dims)}if(s.inputNames.includes("pixel_mask")&&!n.pixel_mask){if(!n.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let e=n.pixel_values.dims;n.pixel_mask=n$([e[0],e[2],e[3]])}return await ob(s,n)}async function lr(e,t){let s=await e.encode(t);return await e.decode(s)}function la(e,t){let s=Object.create(null);for(let n in e)if(n.startsWith("present")){let r=n.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");n.includes("encoder")&&t?s[r]=t[r]:s[r]=e[n]}return t?(t.update(s),t):new oZ(s)}function li(e,t){return e.map(e=>"number"==typeof e?e:t[e]??0)}function lo(e,t,s){if(s&&Object.keys(s).length>0)return Object.assign(t,s),s;let n=e.sessions.decoder_model_merged??e.sessions.model,r=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=o_(e.config),i=e.config?.normalized_config?.num_heads,o={batch_size:r};"number"==typeof i&&(o["batch_size x num_heads"]=r*i);let l=Object.create(null);for(let e of n.inputMetadata){if(!a.has(e.name))continue;let s=li(e.shape,o),n=s.reduce((e,t)=>e*t,1),r=nw[e.type],i=new nx(e.type,new r(n),s);t[e.name]=i,l[e.name]=i}return s?(s.update(l),s):new oZ(l)}async function ll(e,t,s=!1){let n=e.sessions[s?"decoder_model_merged":"model"],{past_key_values:r,...a}=t;n.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=o8(null!=r&&Object.keys(r).length>0)),n.inputNames.includes("position_ids")&&a.attention_mask&&!a.position_ids&&(a.position_ids=function(e,t=null,s=0){let{input_ids:n,inputs_embeds:r,attention_mask:a}=e,{data:i,dims:o}=l_(a,s),l=new nx("int64",i,o);if(t){let e=-(n??r).dims.at(1);l=l.slice(null,[e,null])}return l}(a,r,+!!["paligemma","gemma3_text","gemma3"].includes(e.config.model_type))),n.inputNames.includes("num_logits_to_keep")&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new nx("int64",[0n],[])),lo(e,a,r);let i=U(a,n.inputNames);return await ob(n,i)}async function lc(e,{encode_function:t,merge_function:s,modality_input_names:n,modality_output_name:r,input_ids:a=null,attention_mask:i=null,position_ids:o=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:d=null,logits_processor:u=null,..._}){if(!l){l=await e.encode_text({input_ids:a,..._});let o=U(_,n);if(Object.keys(o).length>0){if(1!==a.dims[1]){let e=await t({...o,..._});({inputs_embeds:l,attention_mask:i}
vendor: 7,573 bytes, line 23
23=s({[r]:e,inputs_embeds:l,input_ids:a,attention_mask:i}))}else if(c&&1===a.dims[1]){let e=a.dims[1],t=c.get_seq_length();i=nS([n$([a.dims[0],t]),i.slice(null,[i.dims[1]-e,i.dims[1]])],1)}}}if(!o&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(e.config.model_type)){let{image_grid_thw:t,video_grid_thw:s}=_;[o]=e.get_rope_index(a,t,s,i)}return await ll(e,{inputs_embeds:l,past_key_values:c,attention_mask:i,position_ids:o,generation_config:d,logits_processor:u},!0)}async function ld(e,t){return await lc(e,{...t,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function lu(e,t){return await lc(e,{...t,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function l_(e,t=0){let[s,n]=e.dims,r=e.data,a=new BigInt64Array(r.length);for(let e=0;e<s;++e){let s=e*n,i=BigInt(t);for(let e=0;e<n;++e){let t=s+e;0n===r[t]?a[t]=BigInt(1):(a[t]=i,i+=r[t])}}return{data:a,dims:e.dims}}function lh(e,t,s,n){let r=s.past_key_values?s.past_key_values.get_seq_length():0,a=e.sessions.decoder_model_merged??e.sessions.model;if(a?.inputNames.includes("num_logits_to_keep")&&!s.num_logits_to_keep&&(s.num_logits_to_keep=new nx("int64",[1n],[])),!s.attention_mask){let e;for(let t of["input_ids","inputs_embeds","position_ids"])if(s[t]){e=s[t].dims;break}if(!e)throw Error("attention_mask is not provided, and unable to infer its shape from model inputs.");s.attention_mask=n$([e[0],r+e[1]])}if(s.past_key_values){let{input_ids:e,attention_mask:t}=s;t&&t.dims[1]>e.dims[1]||r<e.dims[1]&&(s.input_ids=e.slice(null,[r,null]))}return s}function lp(e,t,s,n){return s.past_key_values&&(t=t.map(e=>[e.at(-1)])),{...s,decoder_input_ids:o4(t)}}function lm(e,...t){return e.config.is_encoder_decoder?lp(e,...t):lh(e,...t)}function lf({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:n,attention_mask:r}){let a=n.tolist().map(t=>t.reduce((t,s,n)=>(s==e&&t.push(n),t),[])),i=a.reduce((e,t)=>e+t.length,0),o=s.dims[0];if(i!==o)throw Error(`Number of tokens and features do not match: tokens: ${i}, features ${o}`);let l=0;for(let e=0;e<a.length;++e){let n=a[e],r=t[e];for(let e=0;e<n.length;++e)r[n[e]].data.set(s[l++].data)}return{inputs_embeds:t,attention_mask:r}}function lg({image_token_id:e,inputs_embeds:t,image_features:s,input_ids:n,attention_mask:r}){return lf({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:n,attention_mask:r})}function lw({audio_token_id:e,inputs_embeds:t,audio_features:s,input_ids:n,attention_mask:r}){return lf({modality_token_id:e,inputs_embeds:t,modality_features:s,input_ids:n,attention_mask:r})}async function lx(e,t,s){return Object.fromEntries(await Promise.all(Object.keys(t).map(async n=>{let r=await sq(e,t[n],!1,s);return[n,r]})))}var ly={};_(ly,{ASTForAudioClassification:()=>l$,ASTModel:()=>lN,ASTPreTrainedModel:()=>lI,AfmoeForCausalLM:()=>lP,AfmoeModel:()=>lT,AfmoePreTrainedModel:()=>lS,AlbertForMaskedLM:()=>lE,AlbertForQuestionAnswering:()=>lv,AlbertForSequenceClassification:()=>lk,AlbertModel:()=>lM,AlbertPreTrainedModel:()=>lb,ApertusForCausalLM:()=>lF,ApertusModel:()=>lC,ApertusPreTrainedModel:()=>lA,ArceeForCausalLM:()=>lO,ArceeModel:()=>lL,ArceePreTrainedModel:()=>lz,BartForConditionalGeneration:()=>lV,BartForSequenceClassification:()=>lq,BartModel:()=>lD,BartPretrainedModel:()=>lB,BeitForImageClassification:()=>lR,BeitModel:()=>lj,BeitPreTrainedModel:()=>lG,BertForMaskedLM:()=>lQ,BertForQuestionAnswering:()=>lJ,BertForSequenceClassification:()=>lH,BertForTokenClassification:()=>lX,BertModel:()=>lW,BertPreTrainedModel:()=>lU,BlenderbotForConditionalGeneration:()=>lZ,BlenderbotModel:()=>lY,BlenderbotPreTrainedModel:()=>lK,BlenderbotSmallForConditionalGeneration:()=>l2,BlenderbotSmallModel:()=>l1,BlenderbotSmallPreTrainedModel:()=>l0,BloomForCausalLM:()=>l8,BloomModel:()=>l4,BloomPreTrainedModel:()=>l3,CHMv2ForDepthEstimation:()=>co,CHMv2PreTrainedModel:()=>ci,CLIPModel:()=>ch,CLIPPreTrainedModel:()=>c_,CLIPSegForImageSegmentation:()=>cy,CLIPSegModel:()=>cx,CLIPSegPreTrainedModel:()=>cw,CLIPTextModel:()=>cp,CLIPTextModelWithProjection:()=>cm,CLIPVisionModel:()=>cf,CLIPVisionModelWithProjection:()=>cg,CamembertForMaskedLM:()=>l9,CamembertForQuestionAnswering:()=>ct,CamembertForSequenceClassification:()=>l7,CamembertForTokenClassification:()=>ce,CamembertModel:()=>l5,CamembertPreTrainedModel:()=>l6,ChatterboxModel:()=>cn,ChatterboxPreTrainedModel:()=>cs,ChineseCLIPModel:()=>ca,ChineseCLIPPreTrainedModel:()=>cr,ClapAudioModelWithProjection:()=>cu,ClapModel:()=>cc,ClapPreTrainedModel:()=>cl,ClapTextModelWithProjection:()=>cd,CodeGenForCausalLM:()=>ck,CodeGenModel:()=>cM,CodeGenPreTrainedModel:()=>cb,Cohere2ForCausalLM:()=>cS,Cohere2Model:()=>cF,Cohere2PreTrainedModel:()=>cC,CohereAsrForConditionalGeneration:()=>cz,CohereAsrModel:()=>cP,CohereAsrPreTrainedModel:()=>cT,CohereForCausalLM:()=>cA,CohereModel:()=>cE,CoherePreTrainedModel:()=>cv,ConvBertForMaskedLM:()=>cI,ConvBertForQuestionAnswering:()=>cB,ConvBertForSequenceClassification:()=>cN,ConvBertForTokenClassification:()=>c$,ConvBertModel:()=>cO,ConvBertPreTrainedModel:()=>cL,ConvNextForImageClassification:()=>cq,ConvNextModel:()=>cV,ConvNextPreTrainedModel:()=>cD,ConvNextV2ForImageClassification:()=>cR,ConvNextV2Model:()=>cj,ConvNextV2PreTrainedModel:()=>cG,DFineForObjectDetection:()=>cK,DFineModel:()=>cJ,DFinePreTrainedModel:()=>cX,DINOv3ConvNextModel:()=>dz,DINOv3ConvNextPreTrainedModel:()=>dP,DINOv3ViTModel:()=>dO,DINOv3ViTPreTrainedModel:()=>dL,DPTForDepthEstimation:()=>dU,DPTModel:()=>dR,DPTPreTrainedModel:()=>dj,DacDecoderModel:()=>c3,DacDecoderOutput:()=>cZ,DacEncoderModel:()=>c2,DacEncoderOutput:()=>cY,DacModel:()=>c1,DacPreTrainedModel:()=>c0,DebertaForMaskedLM:()=>c6,DebertaForQuestionAnswering:()=>c7,DebertaForSequenceClassification:()=>c5,DebertaForTokenClassification:()=>c9,DebertaModel:()=>c8,DebertaPreTrainedModel:()=>c4,DebertaV2ForMaskedLM:()=>da,DebertaV2ForQuestionAnswering:()=>dc,DebertaV2ForSequenceClassification:()=>di,DebertaV2ForTokenClassification:()=>dl,DebertaV2Model:()=>dr,DebertaV2PreTrainedModel:()=>dn,DecisionTransformerModel:()=>du,DecisionTransformerPreTrainedModel:()=>dd,DeepseekV3ForCausalLM:()=>ds,DeepseekV3Model:()=>dt,DeepseekV3PreTrainedModel:()=>de,DeiTForImageClassification:()=>dp,DeiTModel:()=>dh,DeiTPreTrainedModel:()=>d_,DepthAnythingForDepthEstimation:()=>df,DepthAnythingPreTrainedModel:()=>dm,DepthProForDepthEstimation:()=>dw,DepthProPreTrainedModel:()=>dg,DetrForObjectDetection:()=>db,DetrForSegmentation:()=>dM,DetrModel:()=>dy,DetrObjectDetectionOutput:()=>dk,DetrPreTrainedModel:()=>dx,DetrSegmentationOutput:()=>dv,Dinov2ForImageClassification:()=>dC,Dinov2Model:()=>dA,Dinov2PreTrainedModel:()=>dE,Dinov2WithRegistersForImageClassification:()=>dT,Dinov2WithRegistersModel:()=>dS,Dinov2WithRegistersPreTrainedModel:()=>dF,DistilBertForMaskedLM:()=>dV,DistilBertForQuestionAnswering:()=>dD,DistilBertForSequenceClassification:()=>d$,DistilBertForTokenClassification:()=>dB,DistilBertModel:()=>dN,DistilBertPreTrainedModel:()=>dI,DonutSwinModel:()=>dG,DonutSwinPreTrainedModel:()=>dq,EdgeTamModel:()=>ff,EfficientNetForImageClassification:()=>dH,EfficientNetModel:()=>dQ,EfficientNetPreTrainedModel:()=>
23dW,ElectraForMaskedLM:()=>dK,ElectraForQuestionAnswering:()=>d0,ElectraForSequenceClassification:()=>dY,ElectraForTokenClassification:()=>dZ,ElectraModel:()=>dJ,ElectraPreTrainedModel:()=>dX,Ernie4_5ForCausalLM:()=>d3,Ernie4_5Model:()=>d2,Ernie4_5PretrainedModel:()=>d1,EsmForMaskedLM:()=>d6,EsmForSequenceClassification:()=>d5,EsmForTokenClassification:()=>d9,EsmModel:()=>d8,EsmPreTrainedModel:()=>d4,EuroBertForMaskedLM:()=>ut,EuroBertForSequenceClassification:()=>us,EuroBertForTokenClassification:()=>un,EuroBertModel:()=>ue,EuroBertPreTrainedModel:()=>d7,ExaoneForCausalLM:()=>ui,ExaoneModel:()=>ua,ExaonePreTrainedModel:()=>ur,FalconForCausalLM:()=>uc,FalconH1ForCausalLM:()=>u_,FalconH1Model:()=>uu,FalconH1PreTrainedModel:()=>ud,FalconModel:()=>ul,FalconPreTrainedModel:()=>uo,FastViTForImageClassification:()=>um,FastViTModel:()=>up,FastViTPreTrainedModel:()=>uh,Florence2ForConditionalGeneration:()=>ug,Florence2PreTrainedModel:()=>uf,GLPNForDepthEstimation:()=>uK,GLPNModel:()=>uJ,GLPNPreTrainedModel:()=>uX,GPT2LMHeadModel:()=>_s,GPT2Model:()=>_t,GPT2PreTrainedModel:()=>_e,GPTBigCodeForCausalLM:()=>u0,GPTBigCodeModel:()=>uZ,GPTBigCodePreTrainedModel:()=>uY,GPTJForCausalLM:()=>_a,GPTJModel:()=>_r,GPTJPreTrainedModel:()=>_n,GPTNeoForCausalLM:()=>u3,GPTNeoModel:()=>u2,GPTNeoPreTrainedModel:()=>u1,GPTNeoXForCausalLM:()=>u6,GPTNeoXModel:()=>u8,GPTNeoXPreTrainedModel:()=>u4,Gemma2ForCausalLM:()=>uk,Gemma2Model:()=>uM,Gemma2PreTrainedModel:()=>ub,Gemma3ForCausalLM:()=>uP,Gemma3ForConditionalGeneration:()=>uT,Gemma3Model:()=>uS,Gemma3PreTrainedModel:()=>uF,Gemma3nForCausalLM:()=>uO,Gemma3nForConditionalGeneration:()=>uL,Gemma3nPreTrainedModel:()=>uz,Gemma4ForCausalLM:()=>uN,Gemma4ForConditionalGeneration:()=>
23uI,GemmaForCausalLM:()=>uy,GemmaModel:()=>ux,GemmaPreTrainedModel:()=>uw,GlmForCausalLM:()=>uD,GlmModel:()=>uB,GlmMoeDsaForCausalLM:()=>uG,GlmMoeDsaModel:()=>uq,GlmMoeDsaPreTrainedModel:()=>uV,GlmOcrForConditionalGeneration:()=>uH,GlmPreTrainedModel:()=>u$,GptOssForCausalLM:()=>u7,GptOssModel:()=>u9,GptOssPreTrainedModel:()=>u5,GraniteForCausalLM:()=>_l,GraniteModel:()=>_o,GraniteMoeHybridForCausalLM:()=>_u,GraniteMoeHybridModel:()=>_d,GraniteMoeHybridPreTrainedModel:()=>_c,GranitePreTrainedModel:()=>_i,GraniteSpeechForConditionalGeneration:()=>_p,GroundingDinoForObjectDetection:()=>_f,GroundingDinoPreTrainedModel:()=>_m,GroupViTModel:()=>_w,GroupViTPreTrainedModel:()=>_g,HeliumForCausalLM:()=>_b,HeliumModel:()=>_y,HeliumPreTrainedModel:()=>_x,HieraForImageClassification:()=>_v,HieraModel:()=>_k,HieraPreTrainedModel:()=>_M,HubertForCTC:()=>_z,HubertForSequenceClassification:()=>_L,HubertModel:()=>_P,HubertPreTrainedModel:()=>_T,HunYuanDenseV1ForCausalLM:()=>_N,HunYuanDenseV1Model:()=>_I,HunYuanDenseV1PreTrainedModel:()=>_O,IJepaForImageClassification:()=>_V,IJepaModel:()=>_D,IJepaPreTrainedModel:()=>_B,Idefics3ForConditionalGeneration:()=>_$,JAISLMHeadModel:()=>_j,JAISModel:()=>_G,JAISPreTrainedModel:()=>_q,JinaCLIPModel:()=>_U,JinaCLIPPreTrainedModel:()=>_R,JinaCLIPTextModel:()=>_W,JinaCLIPVisionModel:()=>_Q,Lfm2ForCausalLM:()=>_J,Lfm2Model:()=>_X,Lfm2MoeForCausalLM:()=>_0,Lfm2MoeModel:()=>_Z,Lfm2MoePreTrainedModel:()=>_Y,Lfm2PreTrainedModel:()=>_H,Lfm2VlForConditionalGeneration:()=>_1,LightOnOcrForConditionalGeneration:()=>_K,LiteWhisperForConditionalGeneration:()=>wt,Llama4ForCausalLM:()=>_6,Llama4PreTrainedModel:()=>_8,LlamaForCausalLM:()=>_4,LlamaModel:()=>_3,LlamaPreTrainedModel:()=>_2,LlavaForConditionalGeneration:()=>uE,LlavaOnevisionForConditionalGeneration:()=>uE,LlavaPreTrainedModel:()=>uv,LlavaQwen2ForCausalLM:()=>uC,LongT5ForConditionalGeneration:()=>_7,LongT5Model:()=>_9,LongT5PreTrainedModel:()=>_5,M2M100ForConditionalGeneration:()=>hs,M2M100Model:()=>ht,M2M100PreTrainedModel:()=>he,MBartForCausalLM:()=>hh,MBartForConditionalGeneration:()=>hu,MBartForSequenceClassification:()=>h_,MBartModel:()=>hd,MBartPreTrainedModel:()=>hc,MPNetForMaskedLM:()=>p_,MPNetForQuestionAnswering:()=>pm,MPNetForSequenceClassification:()=>ph,MPNetForTokenClassification:()=>pp,MPNetModel:()=>pu,MPNetPreTrainedModel:()=>pd,MT5ForConditionalGeneration:()=>pb,MT5Model:()=>py,MT5PreTrainedModel:()=>px,MarianMTModel:()=>ha,MarianModel:()=>hr,MarianPreTrainedModel:()=>hn,MaskFormerForInstanceSegmentation:()=>hl,MaskFormerModel:()=>ho,MaskFormerPreTrainedModel:()=>hi,Metric3DForDepthEstimation:()=>hm,Metric3DPreTrainedModel:()=>hp,Metric3Dv2ForDepthEstimation:()=>hg,Metric3Dv2PreTrainedModel:()=>hf,MgpstrForSceneTextRecognition:()=>hy,MgpstrModelOutput:()=>hw,MgpstrPreTrainedModel:()=>hx,MimiDecoderModel:()=>hA,MimiDecoderOutput:()=>hM,MimiEncoderModel:()=>hE,MimiEncoderOutput:()=>hb,MimiModel:()=>hv,MimiPreTrainedModel:()=>hk,Mistral4ForCausalLM:()=>hz,Mistral4Model:()=>hP,Mistral4PreTrainedModel:()=>hT,MistralForCausalLM:()=>hS,MistralModel:()=>hF,MistralPreTrainedModel:()=>hC,MobileBertForMaskedLM:()=>hI,MobileBertForQuestionAnswering:()=>h$,MobileBertForSequenceClassification:()=>hN,MobileBertModel:()=>hO,MobileBertPreTrainedModel:()=>hL,MobileLLMForCausalLM:()=>hV,MobileLLMModel:()=>hD,MobileLLMPreTrainedModel:()=>hB,MobileNetV1ForImageClassification:()=>hj,MobileNetV1ForSemanticSegmentation:()=>hR,MobileNetV1Model:()=>hG,MobileNetV1PreTrainedModel:()=>hq,MobileNetV2ForImageClassification:()=>hQ,MobileNetV2ForSemanticSegmentation:()=>hH,MobileNetV2Model:()=>hW,MobileNetV2PreTrainedModel:()=>hU,MobileNetV3ForImageClassification:()=>hK,MobileNetV3ForSemanticSegmentation:()=>hY,MobileNetV3Model:()=>hJ,MobileNetV3PreTrainedModel:()=>hX,MobileNetV4ForImageClassification:()=>h1,MobileNetV4ForSemanticSegmentation:()=>h2,MobileNetV4Model:()=>h0,MobileNetV4PreTrainedModel:()=>hZ,MobileViTForImageClassification:()=>h8,MobileViTModel:()=>h4,MobileViTPreTrainedModel:()=>h3,MobileViTV2ForImageClassification:()=>h9,MobileViTV2Model:()=>h5,MobileViTV2PreTrainedModel:()=>h6,ModernBertDecoderForCausalLM:()=>pi,ModernBertDecoderModel:()=>pa,ModernBertDecoderPreTrainedModel:()=>pr,ModernBertForMaskedLM:()=>pt,ModernBertForSequenceClassification:()=>ps,ModernBertForTokenClassification:()=>pn,ModernBertModel:()=>pe,ModernBertPreTrainedModel:()=>h7,Moondream1ForConditionalGeneration:()=>uA,MoonshineForConditionalGeneration:()=>pc,MoonshineModel:()=>pl,MoonshinePreTrainedModel:()=>po,MptForCausalLM:()=>pw,MptModel:()=>pg,MptPreTrainedModel:()=>
23pf,MultiModalityCausalLM:()=>pk,MultiModalityPreTrainedModel:()=>pM,MusicgenForCausalLM:()=>pA,MusicgenForConditionalGeneration:()=>pC,MusicgenModel:()=>pE,MusicgenPreTrainedModel:()=>pv,NanoChatForCausalLM:()=>pT,NanoChatModel:()=>pS,NanoChatPreTrainedModel:()=>pF,NemotronHForCausalLM:()=>pL,NemotronHModel:()=>pz,NemotronHPreTrainedModel:()=>pP,NeoBertForMaskedLM:()=>pN,NeoBertForQuestionAnswering:()=>pD,NeoBertForSequenceClassification:()=>p$,NeoBertForTokenClassification:()=>pB,NeoBertModel:()=>pI,NeoBertPreTrainedModel:()=>pO,NomicBertModel:()=>pq,NomicBertPreTrainedModel:()=>pV,OPTForCausalLM:()=>p9,OPTModel:()=>p5,OPTPreTrainedModel:()=>p6,Olmo2ForCausalLM:()=>pQ,Olmo2Model:()=>pW,Olmo2PreTrainedModel:()=>pU,Olmo3ForCausalLM:()=>pJ,Olmo3Model:()=>pX,Olmo3PreTrainedModel:()=>pH,OlmoForCausalLM:()=>pR,OlmoHybridForCausalLM:()=>pZ,OlmoHybridModel:()=>pY,OlmoHybridPreTrainedModel:()=>pK,OlmoModel:()=>pj,OlmoPreTrainedModel:()=>pG,OpenAIPrivacyFilterForTokenClassification:()=>p2,OpenAIPrivacyFilterModel:()=>p1,OpenAIPrivacyFilterPreTrainedModel:()=>p0,OpenELMForCausalLM:()=>p8,OpenELMModel:()=>p4,OpenELMPreTrainedModel:()=>p3,OwlViTForObjectDetection:()=>mr,OwlViTModel:()=>mn,OwlViTPreTrainedModel:()=>ms,Owlv2ForObjectDetection:()=>mt,Owlv2Model:()=>me,Owlv2PreTrainedModel:()=>p7,PaliGemmaForConditionalGeneration:()=>ma,ParakeetForCTC:()=>mo,ParakeetPreTrainedModel:()=>mi,PatchTSMixerForPrediction:()=>md,PatchTSMixerModel:()=>mc,PatchTSMixerPreTrainedModel:()=>ml,PatchTSTForPrediction:()=>mh,PatchTSTModel:()=>m_,PatchTSTPreTrainedModel:()=>mu,Phi3ForCausalLM:()=>mx,Phi3Model:()=>mw,Phi3PreTrainedModel:()=>mg,Phi3VForCausalLM:()=>mb,Phi3VPreTrainedModel:()=>my,PhiForCausalLM:()=>mf,PhiModel:()=>mm,PhiPreTrainedModel:()=>mp,PreTrainedModel:()=>lt,PvtForImageClassification:()=>mv,PvtModel:()=>mk,PvtPreTrainedModel:()=>mM,PyAnnoteForAudioFrameClassification:()=>mC,PyAnnoteModel:()=>mA,PyAnnotePreTrainedModel:()=>mE,Qwen2ForCausalLM:()=>mT,Qwen2Model:()=>mS,Qwen2MoeForCausalLM:()=>mL,Qwen2MoeModel:()=>mz,Qwen2MoePreTrainedModel:()=>mP,Qwen2PreTrainedModel:()=>mF,Qwen2VLForCausalLM:()=>uU,Qwen2VLForConditionalGeneration:()=>uR,Qwen2VLPreTrainedModel:()=>uj,Qwen2_5_VLForCausalLM:()=>uQ,Qwen2_5_VLForConditionalGeneration:()=>uW,Qwen3ForCausalLM:()=>mN,Qwen3Model:()=>mI,Qwen3MoeForCausalLM:()=>mD,Qwen3MoeModel:()=>mB,Qwen3MoePreTrainedModel:()=>m$,Qwen3NextForCausalLM:()=>mG,Qwen3NextModel:()=>mq,Qwen3NextPreTrainedModel:()=>mV,Qwen3PreTrainedModel:()=>mO,Qwen3VLForCausalLM:()=>mR,Qwen3VLForConditionalGeneration:()=>mj,Qwen3VLMoeForCausalLM:()=>mW,Qwen3VLMoeForConditionalGeneration:()=>mU,Qwen3_5ForCausalLM:()=>mH,Qwen3_5ForConditionalGeneration:()=>mQ,Qwen3_5MoeForCausalLM:()=>mJ,Qwen3_5MoeForConditionalGeneration:()=>mX,RFDetrForObjectDetection:()=>m2,RFDetrModel:()=>m1,RFDetrObjectDetectionOutput:()=>m3,RFDetrPreTrainedModel:()=>m0,RTDetrForObjectDetection:()=>cQ,RTDetrModel:()=>cW,RTDetrObjectDetectionOutput:()=>cH,RTDetrPreTrainedModel:()=>cU,RTDetrV2ForObjectDetection:()=>fl,RTDetrV2Model:()=>fo,RTDetrV2ObjectDetectionOutput:()=>fc,RTDetrV2PreTrainedModel:()=>fi,ResNetForImageClassification:()=>mZ,ResNetModel:()=>mY,ResNetPreTrainedModel:()=>mK,RoFormerForMaskedLM:()=>fs,RoFormerForQuestionAnswering:()=>fa,RoFormerForSequenceClassification:()=>fn,RoFormerForTokenClassification:()=>fr,RoFormerModel:()=>ft,RoFormerPreTrainedModel:()=>fe,RobertaForMaskedLM:()=>m6,RobertaForQuestionAnswering:()=>m7,RobertaForSequenceClassification:()=>m5,RobertaForTokenClassification:()=>m9,RobertaModel:()=>m8,RobertaPreTrainedModel:()=>m4,Sam2ImageSegmentationOutput:()=>fh,Sam2Model:()=>fm,Sam2PreTrainedModel:()=>fp,Sam3TrackerModel:()=>fg,SamImageSegmentationOutput:()=>fd,SamModel:()=>f_,SamPreTrainedModel:()=>fu,SapiensForDepthEstimation:()=>fy,SapiensForNormalEstimation:()=>fb,SapiensForSemanticSegmentation:()=>fx,SapiensPreTrainedModel:()=>fw,SegformerForImageClassification:()=>fv,SegformerForSemanticSegmentation:()=>fE,SegformerModel:()=>fk,SegformerPreTrainedModel:()=>fM,SiglipModel:()=>fC,SiglipPreTrainedModel:()=>fA,SiglipTextModel:()=>fF,SiglipVisionModel:()=>fS,SmolLM3ForCausalLM:()=>fz,SmolLM3Model:()=>fP,SmolLM3PreTrainedModel:()=>fT,SmolVLMForConditionalGeneration:()=>fL,SnacDecoderModel:()=>f$,SnacEncoderModel:()=>fN,SnacModel:()=>fI,SnacPreTrainedModel:()=>fO,SolarOpenForCausalLM:()=>fV,SolarOpenModel:()=>fD,SolarOpenPreTrainedModel:()=>fB,SpeechT5ForSpeechToText:()=>fj,SpeechT5ForTextToSpeech:()=>fR,SpeechT5HifiGan:()=>fU,SpeechT5Model:()=>fG,SpeechT5PreTrainedModel:()=>fq,SqueezeBertForMaskedLM:()=>fH,SqueezeBertForQuestionAnswering:()=>fJ,SqueezeBertForSequenceClassification:()=>fX,SqueezeBertModel:()=>fQ,SqueezeBertPreTrainedModel:()=>fW,StableLmForCausalLM:()=>fZ,StableLmModel:()=>fY,StableLmPreTrainedModel:()=>fK,Starcoder2ForCausalLM:()=>f2,Starcoder2Model:()=>f1,Starcoder2PreTrainedModel:()=>f0,StyleTextToSpeech2Model:()=>f4,StyleTextToSpeech2PreTrainedModel:()=>f3,SupertonicForConditionalGeneration:()=>f6,SupertonicPreTrainedModel:()=>f8,Swin2SRForImageSuperResolution:()=>gn,Swin2SRModel:()=>gs,Swin2SRPreTrainedModel:()=>gt,SwinForImageClassification:()=>f7,SwinForSemanticSegmentation:()=>ge,SwinModel:()=>f9,SwinPreTrainedModel:()=>f5,T5ForConditionalGeneration:()=>gi,T5Model:()=>ga,T5PreTrainedModel:()=>gr,TableTransformerForObjectDetection:()=>gc,TableTransformerModel:()=>gl,TableTransformerObjectDetectionOutput:()=>gd,TableTransformerPreTrainedModel:()=>go,TrOCRForCausalLM:()=>g_,TrOCRPreTrainedModel:()=>gu,UltravoxModel:()=>_h,UltravoxPreTrainedModel:()=>__,UniSpeechForCTC:()=>gm,UniSpeechForSequenceClassification:()=>gf,UniSpeechModel:()=>gp,UniSpeechPreTrainedModel:()=>gh,UniSpeechSatForAudioFrameClassification:()=>gb,UniSpeechSatForCTC:()=>gx,UniSpeechSatForSequenceClassification:()=>gy,UniSpeechSatModel:()=>gw,UniSpeechSatPreTrainedModel:()=>
23gg,VaultGemmaForCausalLM:()=>gv,VaultGemmaModel:()=>gk,VaultGemmaPreTrainedModel:()=>gM,ViTForImageClassification:()=>gF,ViTMAEModel:()=>gT,ViTMAEPreTrainedModel:()=>gS,ViTMSNForImageClassification:()=>gL,ViTMSNModel:()=>gz,ViTMSNPreTrainedModel:()=>gP,ViTModel:()=>gC,ViTPreTrainedModel:()=>gA,VisionEncoderDecoderModel:()=>gE,VitMatteForImageMatting:()=>gI,VitMattePreTrainedModel:()=>gO,VitPoseForPoseEstimation:()=>g$,VitPosePreTrainedModel:()=>gN,VitsModel:()=>gV,VitsModelOutput:()=>gB,VitsPreTrainedModel:()=>gD,VoxtralForConditionalGeneration:()=>gq,VoxtralRealtimeForConditionalGeneration:()=>gQ,VoxtralRealtimePreTrainedModel:()=>gW,Wav2Vec2BertForCTC:()=>gJ,Wav2Vec2BertForSequenceClassification:()=>gK,Wav2Vec2BertModel:()=>gX,Wav2Vec2BertPreTrainedModel:()=>gH,Wav2Vec2ForAudioFrameClassification:()=>_S,Wav2Vec2ForCTC:()=>_C,Wav2Vec2ForSequenceClassification:()=>_F,Wav2Vec2Model:()=>_A,Wav2Vec2PreTrainedModel:()=>_E,WavLMForAudioFrameClassification:()=>g4,WavLMForCTC:()=>g1,WavLMForSequenceClassification:()=>g2,WavLMForXVector:()=>g3,WavLMModel:()=>g0,WavLMPreTrainedModel:()=>gZ,WeSpeakerResNetModel:()=>g6,WeSpeakerResNetPreTrainedModel:()=>g8,WhisperForConditionalGeneration:()=>we,WhisperModel:()=>g7,WhisperPreTrainedModel:()=>g9,XLMForQuestionAnswering:()=>wo,XLMForSequenceClassification:()=>wa,XLMForTokenClassification:()=>wi,XLMModel:()=>wn,XLMPreTrainedModel:()=>ws,XLMRobertaForMaskedLM:()=>wd,XLMRobertaForQuestionAnswering:()=>wh,XLMRobertaForSequenceClassification:()=>wu,XLMRobertaForTokenClassification:()=>w_,XLMRobertaModel:()=>wc,XLMRobertaPreTrainedModel:()=>wl,XLMWithLMHeadModel:()=>wr,XVectorOutput:()=>gY,YolosForObjectDetection:()=>wf,YolosModel:()=>wm,YolosObjectDetectionOutput:()=>wg,YolosPreTrainedModel:()=>wp,YoutuForCausalLM:()=>wy,YoutuModel:()=>wx,YoutuPreTrainedModel:()=>ww});var lb=class extends lt{},lM=class extends lb{},lk=class extends lb{async _call(e){return new ok(await super._call(e))}},lv=class extends lb{async _call(e){return new oA(await super._call(e))}},lE=class extends lb{async _call(e){return new oE(await super._call(e))}},lA=class extends lt{},lC=class extends lA{},lF=class extends lA{},lS=class extends lt{},lT=class extends lS{},lP=class extends lS{},lz=class extends lt{},lL=class extends lz{},lO=class extends lz{},lI=class extends lt{},lN=class extends lI{},l$=class extends lI{},lB=class extends lt{},lD=class extends lB{},lV=class extends lB{},lq=class extends lB{async _call(e){return new ok(await super._call(e))}},lG=class extends lt{},lj=class extends lG{},lR=class extends lG{async _call(e){return new ok(await super._call(e))}},lU=class extends lt{},lW=class extends lU{},lQ=class extends lU{async _call(e){return new oE(await super._call(e))}},lH=class extends lU{async _call(e){return new ok(await super._call(e))}},lX=class extends lU{async _call(e){return new ov(await super._call(e))}},lJ=class extends lU{async _call(e){return new oA(await super._call(e))}},lK=class extends lt{},lY=class extends lK{},lZ=class extends lK{},l0=class extends lt{},l1=class extends l0{},l2=class extends l0{},l3=class extends lt{},l4=class extends l3{},l8=class extends l3{},l6=class extends lt{},l5=class extends l6{},l9=class extends l6{async _call(e){return new oE(await super._call(e))}},l7=class extends l6{async _call(e){return new ok(await super._call(e))}},ce=class extends l6{async _call(e){return new ov(await super._call(e))}},ct=class extends l6{async _call(e){return new oA(await super._call(e))}},cs=class extends lt{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"]},cn=class extends cs{async encode_speech(e){return ob(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:s=null,exaggeration:n=null,position_ids:r=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:o=null,logits_processor:l=null,audio_features:c=null,audio_tokens:d=null,speaker_embeddings:u=null,speaker_features:_=null,...h}){let p;if(!a){let o=this.sessions.embed_tokens.inputNames,l={input_ids:e};if(o.includes("exaggeration")){if(!(n instanceof nx)){let t=e.dims[0];if(null==n)n=nI([t],.5);else if("number"==typeof n)n=nI([t],n);else if(Array.isArray(n))n=new nx("float32",n,[t]);else throw Error("Unsupported type for `exaggeration` input")}l.exaggeration=n}if(o.includes("position_ids")&&(l.position_ids=r),{inputs_embeds:a}=await ob(this.sessions.embed_tokens,l),c&&d&&u&&_&&(p={audio_features:c,audio_tokens:d,speaker_embeddings:u,speaker_features:_}),p||s)p??=await this.encode_speech(s),t=n$([(a=nS([p.audio_features,a],1)).dims[0],a.dims[1]]);else{let e=a.dims[1];if(!i||1!==e)throw Error("Incorrect state encountered during generation.");let s=i.get_seq_length();
23t=n$([a.dims[0],s+e])}}return{...await ll(this,{inputs_embeds:a,past_key_values:i,attention_mask:t,generation_config:o,logits_processor:l},!1),...p}}prepare_inputs_for_generation(e,t,s){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(1===t.input_ids.dims[1])t.position_ids=new nx("int64",Array.from({length:e.length},(t,s)=>e[s].length-e[s].findLastIndex(e=>6561n==e)-1),[e.length,1]);else{let e=t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=6561n?0:t++)});t.position_ids=new nx("int64",e.flat(),t.input_ids.dims)}return 1===t.input_ids.dims[1]&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),lh(this,e,t,s)}async generate(e){let{sequences:t,audio_tokens:s,speaker_embeddings:n,speaker_features:r}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),i=nI([a.dims[0],3],4299n),o=nS([s,a,i],1),{waveform:l}=await ob(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:r,speaker_embeddings:n});return l}},cr=class extends lt{},ca=class extends cr{},ci=class extends lt{},co=class extends ci{},cl=class extends lt{},cc=class extends cl{},cd=class extends cl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},cu=class extends cl{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},c_=class extends lt{},ch=class extends c_{},cp=class extends c_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},cm=class extends c_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},cf=class extends c_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},cg=class extends c_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},cw=class extends lt{},cx=class extends cw{},cy=class extends cw{},cb=class extends lt{},cM=class extends cb{},ck=class extends cb{},cv=class extends lt{},cE=class extends cv{},cA=class extends cv{},cC=class extends lt{},cF=class extends cC{},cS=class extends cC{},cT=class extends lt{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},cP=class extends cT{},cz=class extends cT{},cL=class extends lt{},cO=class extends cL{},cI=class extends cL{async _call(e){return new oE(await super._call(e))}},cN=class extends cL{async _call(e){return new ok(await super._call(e))}},c$=class extends cL{async _call(e){return new ov(await super._call(e))}},cB=class extends cL{async _call(e){return new oA(await super._call(e))}},cD=class extends lt{},cV=class extends cD{},cq=class extends cD{async _call(e){return new ok(await super._call(e))}},cG=class extends lt{},cj=class extends cG{},cR=class extends cG{async _call(e){return new ok(await super._call(e))}},cU=class extends lt{},cW=class extends cU{},cQ=class extends cU{async _call(e){return new cH(await super._call(e))}},cH=class extends oM{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},cX=class extends lt{},cJ=class extends cX{},cK=class extends cX{async _call(e){return new cH(await super._call(e))}},cY=class extends oM{constructor({audio_codes:e}){super(),this.audio_codes=e}},cZ=class extends oM{constructor({audio_values:e}){super(),this.audio_values=e}},c0=class extends lt{main_input_name="input_values";forward_params=["input_values"]},c1=class extends c0{async encode(e){return new cY(await ob(this.sessions.encoder_model,e))}async decode(e){return new cZ(await ob(this.sessions.decoder_model,e))}},c2=class extends c0{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},c3=class extends c0{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},c4=class extends lt{},c8=class extends c4{},c6=class extends c4{async _call(e){return new oE(await super._call(e))}},c5=class extends c4{async _call(e){return new ok(await super._call(e))}},c9=class extends c4{async _call(e){return new ov(await super._call(e))}},c7=class extends c4{async _call(e){return new oA(await super._call(e))}},de=class extends lt{},dt=class extends de{},ds=class extends de{},dn=class extends lt{},dr=class extends dn{},da=class extends dn{async _call(e){return new oE(await super._call(e))}},di=class extends dn{async _call(e){return new ok(await super._call(e))}},dl=class extends dn{async _call(e){return new ov(await super._call(e))}},dc=class extends dn{async _call(e){return new oA(await super._call(e))}},dd=class extends lt{},du=class extends dd{},d_=class extends lt{},dh=class extends d_{},dp=class extends d_{async _call(e){return new ok(await super._call(e))}},dm=class extends lt{},df=class extends dm{},dg=class extends lt{},dw=class extends dg{},dx=class extends lt{},dy=class extends dx{},db=class extends dx{async _call(e){return new dk(await super._call(e))}},dM=class extends dx{async _call(e){return new dv(await super._call(e))}},dk=class extends oM{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},dv=class extends oM{constructor({logits:e,pred_boxes:t,pred_masks:s}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=s}},dE=class extends lt{},dA=class extends dE{},dC=class extends dE{async _call(e){return new ok(await super._call(e))}},dF=class extends lt{},dS=class extends dF{},dT=class extends dF{async _call(e){return new ok(await super._call(e))}},dP=class extends lt{},dz=class extends dP{},dL=class extends lt{},dO=class extends dL{},dI=class extends lt{},dN=class extends dI{},d$=class extends dI{async _call(e){return new ok(await super._call(e))}},dB=class extends dI{async _call(e){return new ov(await super._call(e))}},dD=class extends dI{async _call(e){return new oA(await super._call(e))}},dV=class extends dI{async _call(e){return new oE(await super._call(e))}},dq=class extends lt{},dG=class extends dq{},dj=class extends lt{},dR=class extends dj{},dU=class extends dj{},dW=class extends lt{},dQ=class extends dW{},dH=class extends dW{async _call(e){return new ok(await super._call(e))}},dX=class extends lt{},dJ=class extends dX{},dK=class extends dX{async _call(e){return new oE(await super._call(e))}},dY=class extends dX{async _call(e){return new ok(await super._call(e))}},dZ=class extends dX{async _call(e){return new ov(await super._call(e))}},d0=class extends dX{async _call(e){return new oA(await super._call(e))}},d1=class extends lt{},d2=class extends d1{},d3=class extends d1{},d4=class extends lt{},d8=class extends d4{},d6=class extends d4{async _call(e){return new oE(await super._call(e))}},d5=class extends d4{async _call(e){return new ok(await super._call(e))}},d9=class extends d4{async _call(e){return new ov(await super._call(e))}},d7=class extends lt{},ue=class extends d7{},ut=class extends d7{async _call(e){return new oE(await super._call(e))}},us=class extends d7{async _call(e){return new ok(await super._call(e))}},un=class extends d7{async _call(e){return new ov(await super._call(e))}},ur=class extends lt{},ua=class extends ur{},ui=class extends ur{},uo=class extends lt{},ul=class extends uo{},uc=class extends uo{},ud=class extends lt{},uu=class extends ud{},u_=class extends ud{},uh=class extends lt{},up=class extends uh{},um=class extends uh{async _call(e){return new ok(await super._call(e))}},uf=class extends lt{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"},ug=class extends uf{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:s,attention_mask:n}){return{inputs_embeds:nS([t,e],1),attention_mask:nS([n$(t.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n}){let r,a;
23if(!e&&!t)throw Error("Either `input_ids` or `pixel_values` should be provided.");return e&&(r=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),r&&a?{inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:r,image_features:a,input_ids:e,attention_mask:n}):s=r||a,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:t,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:r,encoder_outputs:a,past_key_values:i,inputs_embeds:o,decoder_inputs_embeds:l}){if(o||({inputs_embeds:o,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:o,attention_mask:s})),!a){let{last_hidden_state:e}=await ln(this,{inputs_embeds:o,attention_mask:s});a=e}if(!l){if(!n)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");l=await this.encode_text({input_ids:n})}let c={inputs_embeds:l,attention_mask:r,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i};return await ll(this,c,!0)}},uw=class extends lt{},ux=class extends uw{},uy=class extends uw{},ub=class extends lt{},uM=class extends ub{},uk=class extends ub{},uv=class extends lt{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},uE=class extends uv{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),s=e.image_features.view(-1,t);return lg({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},uA=class extends uE{},uC=class extends uE{},uF=class extends lt{},uS=class extends uF{},uT=class extends uE{},uP=class extends uT{},uz=class extends lt{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},uL=class extends uz{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:s=null,input_features:n=null,input_features_mask:r=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:o=null,past_key_values:l=null,generation_config:c=null,logits_processor:d=null,...u}){if((!i||!o)&&({inputs_embeds:i,per_layer_inputs:o}=await ob(this.sessions.embed_tokens,{input_ids:e}),1!==e.dims[1])){if(s){let{image_features:n}=await this._encode_vision({pixel_values:s,...u});({inputs_embeds:i,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:n,inputs_embeds:i,input_ids:e,attention_mask:t}))}if(n){let{audio_features:s}=await ob(this.sessions.audio_encoder,{input_features:n,input_features_mask:r});({inputs_embeds:i,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:s,inputs_embeds:i,input_ids:e,attention_mask:t}))}}return await ll(this,{inputs_embeds:i,per_layer_inputs:o,past_key_values:l,attention_mask:t,position_ids:a,generation_config:c,logits_processor:d},!0)}_encode_vision(e){return ob(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),s=e.image_features.view(-1,t);return lg({image_token_id:this.config.image_token_id,...e,image_features:s})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,t);return lw({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},uO=class extends uL{},uI=class extends uL{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(e){return ob(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},uN=class extends uI{},u$=class extends lt{},uB=class extends u${},uD=class extends u${},uV=class extends lt{},uq=class extends uV{},uG=class extends uV{},uj=class extends lt{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},uR=class extends uj{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,t){if(t){let{data:e,dims:s}=l_(t),n=BigInt64Array.from({length:3*e.length},(t,s)=>e[s%e.length]),r=Array.from({length:s[0]},(t,n)=>sR(e.subarray(s[1]*n,s[1]*(n+1)))[0]+1n+BigInt(s[1]));return[new nx("int64",n,[3,...s]),new nx("int64",r,[r.length,1])]}{let[t,s]=e.dims;return[new nx("int64",BigInt64Array.from({length:3*t*s},(e,n)=>BigInt(Math.floor(n%s/t))),[3,...e.dims]),nB([t,1])]}}_reorder_and_write_positions(e,t,s,n){let r=e.reduce((e,t)=>
23e+t.length,0),a=Array(r),i=0;for(let t=0;t<3;++t)for(let s of e){let e=s.length/3;for(let n=t*e;n<(t+1)*e;++n)a[i++]=s[n]}let o=0;for(let e=0;e<t.length;++e)if(1==t[e]){for(let t=0;t<3;++t)s[t][n][e]=a[t*r/3+o];++o}return a}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:s,spatial_merge_size:n,state:r}){let{image_token_id:a,video_token_id:i,vision_start_token_id:o}=this.config,l=e.reduce((e,t,s)=>(t==o&&e.push(s),e),[]).map(t=>e[t+1]),c=l.filter(e=>e==a).length,d=l.filter(e=>e==i).length,u=[],_=0,h=c,p=d;for(let o=0;o<l.length;++o){let o,l,c,d,m=e.findIndex((e,t)=>t>_&&e==a),f=e.findIndex((e,t)=>t>_&&e==i),g=h>0&&-1!==m?m:e.length+1,w=p>0&&-1!==f?f:e.length+1;g<w?([l,c,d]=t[r.image_index],++r.image_index,--h,o=g):([l,c,d]=s[r.video_index],++r.video_index,--p,o=w);let[x,y,b]=[Number(l),Math.floor(Number(c)/n),Math.floor(Number(d)/n)],M=o-_,k=u.length>0?sR(u.at(-1))[0]+1:0;u.push(Array.from({length:3*M},(e,t)=>k+t%M));let v=M+k,E=x*y*b,A=Array.from({length:E},(e,t)=>v+Math.floor(t/(y*b))),C=Array.from({length:E},(e,t)=>v+Math.floor(t/b)%y),F=Array.from({length:E},(e,t)=>v+t%b);u.push([A,C,F].flat()),_=o+E}if(_<e.length){let t=u.length>0?sR(u.at(-1))[0]+1:0,s=e.length-_;u.push(Array.from({length:3*s},(e,n)=>t+n%s))}return u}get_rope_index(e,t,s,n){let{vision_config:r}
23=this.config,a=r.spatial_merge_size??2;if(!t&&!s)return this._get_text_only_rope_index(e,n);{let r=e.tolist();n||(n=n$(e.dims));let i=n.tolist(),o=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),l=t?t.tolist():[],c=s?s.tolist():[],d={image_index:0,video_index:0},u=[];for(let e=0;e<r.length;++e){let t=r[e].filter((t,s)=>1==i[e][s]),s=this._get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:l,video_grid_thw_list:c,spatial_merge_size:a,state:d}),n=this._reorder_and_write_positions(s,i[e],o,e);u.push(sR(n)[0]+1-r[e].length)}return[new nx("int64",o.flat(1/0),[3,e.dims[0],e.dims[1]]),new nx("int64",u,[u.length,1])]}}async encode_image({pixel_values:e,image_grid_thw:t}){return(await ob(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return lg({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,s){if(!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return t;if(t.past_key_values){t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(e<t.input_ids.dims[1]){let[s,n]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);t.rope_deltas=n,t.position_ids=s.slice(null,null,[e,null]),t.input_ids=t.input_ids.slice(null,[e,null])}else{t.rope_deltas||([,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask));let s=BigInt(e),n=t.rope_deltas.map(e=>s+e);t.position_ids=nT([n,n,n],0)}}else[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);return t}},uU=class extends uR{},uW=class extends uR{image_grid_thw_name="image_grid_thw"},uQ=class extends uU{image_grid_thw_name="image_grid_thw"},uH=class extends uW{get_vision_position_ids(e,t,s,n){let r=Math.floor(t[0]/s),a=Math.floor(t[1]/n),i=Math.floor(t[2]/n),o=a*i*r,l=Array.from({length:o},()=>e);return[...l,...Array.from({length:o},(t,s)=>e+Math.floor(s/(i*r))),...Array.from({length:o},(t,s)=>e+s%i)]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:s,spatial_merge_size:n,state:r}){let{image_token_id:a}=this.config,i=[],o=0,l=+(e[0]==a);for(let t=1;t<=e.length;++t){let s=t<e.length?+(e[t]==a):-1;s!==l&&(i.push([l,o,t]),o=t,l=s)}let c=0,d=[];for(let[e,s,a]of i)if(0===e){let e=a-s;d.push(Array.from({length:3*e},(t,s)=>c+s%e)),c+=e}else{let e=t[r.image_index++].map(Number),s=e[0];d.push(this.get_vision_position_ids(c,e,s,n)),c+=Math.max(e[1],e[2])/n}return d}},uX=class extends lt{},uJ=class extends uX{},uK=class extends uX{},uY=class extends lt{},uZ=class extends uY{},u0=class extends uY{},u1=class extends lt{},u2=class extends u1{},u3=class extends u1{},u4=class extends lt{},u8=class extends u4{},u6=class extends u4{},u5=class extends lt{},u9=class extends u5{},u7=class extends u5{},_e=class extends lt{},_t=class extends _e{},_s=class extends _e{},_n=class extends lt{},_r=class extends _n{},_a=class extends _n{},_i=class extends lt{},_o=class extends _i{},_l=class extends _i{},_c=class extends lt{},_d=class extends _c{},_u=class extends _c{},__=class extends lt{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},_h=class extends __{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,t);return lw({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}},_p=class extends _h{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},_m=class extends lt{},_f=class extends _m{},_g=class extends lt{},_w=class extends _g{},_x=class extends lt{},_y=class extends _x{},_b=class extends _x{},_M=class extends lt{},_k=class extends _M{},_v=class extends _M{async _call(e){return new ok(await super._call(e))}},_E=class extends lt{},_A=class extends _E{},_C=class extends _E{async _call(e){return new oC(await super._call(e))}},_F=class extends _E{async _call(e){return new ok(await super._call(e))}},_S=class extends _E{async _call(e){return new ov(await super._call(e))}},_T=class extends lt{},_P=class extends _E{},_z=class extends _E{async _call(e){return new oC(await super._call(e))}},_L=class extends _E{async _call(e){return new ok(await super._call(e))}},_O=class extends lt{},_I=class extends _O{},_N=class extends _O{},_$=class extends uE{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},_B=class extends lt{},_D=class extends _B{},_V=class extends _B{async _call(e){return new ok(await super._call(e))}},_q=class extends lt{},_G=class extends _q{},_j=class extends _q{},_R=class extends lt{},_U=class extends _R{async forward(e){let t=!e.input_ids,s=!e.pixel_values;if(t&&s)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=n$([e.pixel_values.dims[0],1])),s){let{image_size:t}=this.config.vision_config;
vendor: 6,846 bytes, line 23
23e.pixel_values=nI([0,3,t,t],0)}let{text_embeddings:n,image_embeddings:r,l2norm_text_embeddings:a,l2norm_image_embeddings:i}=await super.forward(e),o={};return t||(o.text_embeddings=n,o.l2norm_text_embeddings=a),s||(o.image_embeddings=r,o.l2norm_image_embeddings=i),o}},_W=class extends _R{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},_Q=class extends _R{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},_H=class extends lt{},_X=class extends _H{},_J=class extends _H{},_K=class extends uE{},_Y=class extends lt{},_Z=class extends _Y{},_0=class extends _Y{},_1=class extends uE{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},_2=class extends lt{},_3=class extends _2{},_4=class extends _2{},_8=class extends lt{},_6=class extends _8{},_5=class extends lt{},_9=class extends _5{},_7=class extends _5{},he=class extends lt{},ht=class extends he{},hs=class extends he{},hn=class extends lt{},hr=class extends hn{},ha=class extends hn{},hi=class extends lt{},ho=class extends hi{},hl=class extends hi{},hc=class extends lt{},hd=class extends hc{},hu=class extends hc{},h_=class extends hc{async _call(e){return new ok(await super._call(e))}},hh=class extends hc{},hp=class extends lt{},hm=class extends hp{},hf=class extends lt{},hg=class extends hf{},hw=class extends oM{constructor({char_logits:e,bpe_logits:t,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},hx=class extends lt{},hy=class extends hx{async _call(e){return new hw(await super._call(e))}},hb=class extends oM{constructor({audio_codes:e}){super(),this.audio_codes=e}},hM=class extends oM{constructor({audio_values:e}){super(),this.audio_values=e}},hk=class extends lt{main_input_name="input_values";forward_params=["input_values"]},hv=class extends hk{async encode(e){return new hb(await ob(this.sessions.encoder_model,e))}async decode(e){return new hM(await ob(this.sessions.decoder_model,e))}},hE=class extends hk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},hA=class extends hk{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},hC=class extends lt{},hF=class extends hC{},hS=class extends hC{},hT=class extends lt{},hP=class extends hT{},hz=class extends hT{},hL=class extends lt{},hO=class extends hL{},hI=class extends hL{async _call(e){return new oE(await super._call(e))}},hN=class extends hL{async _call(e){return new ok(await super._call(e))}},h$=class extends hL{async _call(e){return new oA(await super._call(e))}},hB=class extends lt{},hD=class extends hB{},hV=class extends hB{},hq=class extends lt{},hG=class extends hq{},hj=class extends hq{async _call(e){return new ok(await super._call(e))}},hR=class extends hq{},hU=class extends lt{},hW=class extends hU{},hQ=class extends hU{async _call(e){return new ok(await super._call(e))}},hH=class extends hU{},hX=class extends lt{},hJ=class extends hX{},hK=class extends hX{async _call(e){return new ok(await super._call(e))}},hY=class extends hX{},hZ=class extends lt{},h0=class extends hZ{},h1=class extends hZ{async _call(e){return new ok(await super._call(e))}},h2=class extends hZ{},h3=class extends lt{},h4=class extends h3{},h8=class extends h3{async _call(e){return new ok(await super._call(e))}},h6=class extends lt{},h5=class extends h6{},h9=class extends h6{async _call(e){return new ok(await super._call(e))}},h7=class extends lt{},pe=class extends h7{},pt=class extends h7{async _call(e){return new oE(await super._call(e))}},ps=class extends h7{async _call(e){return new ok(await super._call(e))}},pn=class extends h7{async _call(e){return new ov(await super._call(e))}},pr=class extends lt{},pa=class extends pr{},pi=class extends pr{},po=class extends lt{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},pl=class extends po{},pc=class extends po{},pd=class extends lt{},pu=class extends pd{},p_=class extends pd{async _call(e){return new oE(await super._call(e))}},ph=class extends pd{async _call(e){return new ok(await super._call(e))}},pp=class extends pd{async _call(e){return new ov(await super._call(e))}},pm=class extends pd{async _call(e){return new oA(await super._call(e))}},pf=class extends lt{},pg=class extends pf{},pw=class extends pf{},px=class extends lt{},py=class extends px{},pb=class extends px{},pM=class extends lt{},pk=class extends pM{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 t,s=this._generation_mode??"text";if("text"!==s&&e.past_key_values){let s=this.sessions.gen_img_embeds,n=U({image_ids:e.input_ids},s.inputNames);t=await ob(s,n)}else{let s=this.sessions.prepare_inputs_embeds,n=U(e,s.inputNames);t=await ob(s,n)}let n={...e,...t},r=await ll(this,n),a=this.sessions["text"===s?"lm_head":"gen_head"];if(!a)throw Error(`Unable to find "${a}" generation head`);let i=await ob(a,U(r,a.inputNames));return{...t,...r,...i}}prepare_inputs_for_generation(e,t,s){let n=!!t.past_key_values;return null!==s.guidance_scale&&s.guidance_scale>1&&(n?t.input_ids=nS([t.input_ids,t.input_ids],0):(t.input_ids=nS([t.input_ids,nN(t.input_ids,BigInt(s.pad_token_id))],0),t.attention_mask=nS([t.attention_mask,nN(t.attention_mask,0n)],0))),(n||!t.pixel_values)&&(t.pixel_values=nI([0,0,3,384,384],1)),n&&(t.images_seq_mask=new nx("bool",[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new nx("bool",[].fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let t=(e.inputs??e[this.main_input_name]).dims[1],s=(await super.generate(e)).slice(null,[t,null]),n=this.sessions.image_decode,{decoded_image:r}=await ob(n,{generated_tokens:s}),a=r.add_(1).mul_(127.5).clamp_(0,255).to("uint8"),i=[];for(let e of a){let t=ax.fromTensor(e);i.push(t)}return i}},pv=class extends lt{},pE=class extends pv{},pA=class extends pv{},pC=class extends lt{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[t,s]=e.dims,n=this.config.decoder.num_codebooks,r=s-n,a=0;for(let t=0;t<e.size;++t){if(e.data[t]==this.config.decoder.pad_token_id)continue;let i=t%s-Math.floor(t/s)%n;i>0&&i<=r&&(e.data[a++]=e.data[t])}let i=Math.floor(t/n),o=a/(i*n);
23return new nx(e.type,e.data.slice(0,a),[i,n,o])}prepare_inputs_for_generation(e,t,s){let n=BigInt(this.config.decoder.pad_token_id),r=structuredClone(e);for(let e=0;e<r.length;++e)for(let t=0;t<r[e].length;++t)e%this.config.decoder.num_codebooks>=t&&(r[e][t]=n);return null!==s.guidance_scale&&s.guidance_scale>1&&(r=r.concat(r)),lp(this,r,t,s)}async generate(e){let t=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:n}=await ob(this.sessions.encodec_decode,{audio_codes:s});return n}},pF=class extends lt{},pS=class extends pF{},pT=class extends pF{},pP=class extends lt{},pz=class extends pP{},pL=class extends pP{},pO=class extends lt{},pI=class extends pO{},pN=class extends pO{async _call(e){return new oE(await super._call(e))}},p$=class extends pO{async _call(e){return new ok(await super._call(e))}},pB=class extends pO{async _call(e){return new ov(await super._call(e))}},pD=class extends pO{async _call(e){return new oA(await super._call(e))}},pV=class extends lt{},pq=class extends pV{},pG=class extends lt{},pj=class extends pG{},pR=class extends pG{},pU=class extends lt{},pW=class extends pU{},pQ=class extends pU{},pH=class extends lt{},pX=class extends pH{},pJ=class extends pH{},pK=class extends lt{},pY=class extends pK{},pZ=class extends pK{},p0=class extends lt{},p1=class extends p0{},p2=class extends p0{async _call(e){return new ok(await super._call(e))}},p3=class extends lt{},p4=class extends p3{},p8=class extends p3{},p6=class extends lt{},p5=class extends p6{},p9=class extends p6{},p7=class extends lt{},me=class extends p7{},mt=class extends p7{},ms=class extends lt{},mn=class extends ms{},mr=class extends ms{},ma=class extends uE{},mi=class extends lt{},mo=class extends mi{async _call(e){return new oC(await super._call(e))}},ml=class extends lt{},mc=class extends ml{},md=class extends ml{},mu=class extends lt{},m_=class extends mu{},mh=class extends mu{},mp=class extends lt{},mm=class extends mp{},mf=class extends mp{},mg=class extends lt{},mw=class extends mg{},mx=class extends mg{},my=class extends lt{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},mb=class extends my{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:s=null,image_sizes:n=null,position_ids:r=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:o=null,logits_processor:l=null,...c}){if(!a){let t;if(s&&1!==e.dims[1]){if(!n)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:t}=await ob(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else t=new nx("float32",[],[0,this.config.normalized_config.hidden_size]);({inputs_embeds:a}=await ob(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await ll(this,{inputs_embeds:a,past_key_values:i,attention_mask:t,position_ids:r,generation_config:o,logits_processor:l},!1)}},mM=class extends lt{},mk=class extends mM{},mv=class extends mM{async _call(e){return new ok(await super._call(e))}},mE=class extends lt{},mA=class extends mE{},mC=class extends mE{async _call(e){return new ov(await super._call(e))}},mF=class extends lt{},mS=class extends mF{},mT=class extends mF{},mP=class extends lt{},mz=class extends mP{},mL=class extends mP{},mO=class extends lt{},mI=class extends mO{},mN=class extends mO{},m$=class extends lt{},mB=class extends m${},mD=class extends m${},mV=class extends lt{},mq=class extends mV{},mG=class extends mV{},mj=class extends uW{},mR=class extends uQ{},mU=class extends mj{},mW=class extends mR{},mQ=class extends mj{},mH=class extends mQ{},mX=class extends mQ{},mJ=class extends mH{},mK=class extends lt{},mY=class extends mK{},mZ=class extends mK{async _call(e){return new ok(await super._call(e))}},m0=class extends lt{},m1=class extends m0{},m2=class extends m0{async _call(e){return new m3(await super._call(e))}},m3=class extends cH{},m4=class extends lt{},m8=class extends m4{},m6=class extends m4{async _call(e){return new oE(await super._call(e))}},m5=class extends m4{async _call(e){return new ok(await super._call(e))}},m9=class extends m4{async _call(e){return new ov(await super._call(e))}},m7=class extends m4{async _call(e){return new oA(await super._call(e))}},fe=class extends lt{},ft=class extends fe{},fs=class extends fe{async _call(e){return new oE(await super._call(e))}},fn=class extends fe{async _call(e){return new ok(await super._call(e))}},fr=class extends fe{async _call(e){return new ov(await super._call(e))}},fa=class extends fe{async _call(e){return new oA(await super._call(e))}},fi=class extends lt{},fo=class extends fi{},fl=class extends fi{async _call(e){return new fc(await super._call(e))}},fc=class extends cH{},fd=class extends oM{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},fu=class extends lt{},f_=class extends fu{async get_image_embeddings({pixel_values:e}){return await ln(this,{pixel_values:e})}async forward(e){e=e.image_embeddings&&e.image_positional_embeddings?{...e}:{...e,...await this.get_image_embeddings(e)},e.input_labels??=n$(e.input_points.dims.slice(0,-1));let t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.
23input_boxes&&(t.input_boxes=e.input_boxes),await ob(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new fd(await super._call(e))}},fh=class extends oM{constructor({iou_scores:e,pred_masks:t,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=s}},fp=class extends lt{},fm=class extends fp{async get_image_embeddings({pixel_values:e}){return await ln(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if((e=Array.from({length:t},(e,t)=>`image_embeddings.${t}`).some(t=>!e[t])?{...e,...await this.get_image_embeddings(e)}:{...e}).input_points){if(e.input_boxes&&1!==e.input_boxes.dims[1])throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let t=e.input_points.dims;e.input_labels??=n$(t.slice(0,-1)),e.input_boxes??=nI([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=nI([t[0],t[1],0],-1n),e.input_points=nI([t[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let s=this.sessions.prompt_encoder_mask_decoder,n=U(e,s.inputNames);return await ob(s,n)}async _call(e){return new fh(await super._call(e))}},ff=class extends fm{},fg=class extends fm{},fw=class extends lt{},fx=class extends fw{},fy=class extends fw{},fb=class extends fw{},fM=class extends lt{},fk=class extends fM{},fv=class extends fM{},fE=class extends fM{},fA=class extends lt{},fC=class extends fA{},fF=class extends fA{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},fS=class extends c_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},fT=class extends lt{},fP=class extends fT{},fz=class extends fT{},fL=class extends _${},fO=class extends lt{main_input_name="input_values";forward_params=["input_values"]},fI=class extends fO{async encode(e){return await ob(this.sessions.encoder_model,e)}async decode(e){return await ob(this.sessions.decoder_model,e)}},fN=class extends fO{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},f$=class extends fO{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},fB=class extends lt{},fD=class extends fB{},fV=class extends fB{},fq=class extends lt{},fG=class extends fq{},fj=class extends fq{},fR=class extends fq{async generate_speech(e,t,{threshold:s=.5,minlenratio:n=0,maxlenratio:r=20,vocoder:a=null}={}){let{encoder_outputs:i,encoder_attention_mask:o}=await ln(this,{input_ids:e}),l=i.dims[1]/this.config.reduction_factor,c=Math.floor(l*r),d=Math.floor(l*n),u=this.config.num_mel_bins,_=[],h=null,p=null,m=0;for(;;){++m;let e={use_cache_branch:o8(!!p),output_sequence:p?p.output_sequence_out:new nx("float32",new Float32Array(u),[1,1,u]),encoder_attention_mask:o,speaker_embeddings:t,encoder_hidden_states:i};lo(this,e,h),h=la(p=await ob(this.sessions.decoder_model_merged,e),h);let{prob:n,spectrum:r}=p;if(_.push(r),m>=d&&(Array.from(n.data).filter(e=>e>=s).length>0||m>=c))break}let f=nS(_),{waveform:g}=await ob(a.sessions.model,{spectrogram:f});return{spectrogram:f,waveform:g}}},fU=class extends lt{main_input_name="spectrogram"},fW=class extends lt{},fQ=class extends fW{},fH=class extends fW{async _call(e){return new oE(await super._call(e))}},fX=class extends fW{async _call(e){return new ok(await super._call(e))}},fJ=class extends fW{async _call(e){return new oA(await super._call(e))}},fK=class extends lt{},fY=class extends fK{},fZ=class extends fK{},f0=class extends lt{},f1=class extends f0{},f2=class extends f0{},f3=class extends lt{},f4=class extends f3{},f8=class extends lt{},f6=class extends f8{async generate_speech({input_ids:e,attention_mask:t,style:s,num_inference_steps:n=5,speed:r=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:o,latent_dim:l}=this.config,{last_hidden_state:c,durations:d}=await ob(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:s}),u=d.div(r).mul_(a),_=o*i,h=u.data,p=Int32Array.from(h,e=>Math.ceil(e/_)),m=Math.max(...p),f=e.dims[0],g=new BigInt64Array(f*m);for(let e=0;e<f;++e)g.fill(1n,e*m,e*m+p[e]);let w=new nx("int64",g,[f,m]),x=l*i,y=x*m,b=function(e){let t=e.reduce((e,t)=>
23e*t,1);return new nx("float32",Float32Array.from({length:t},()=>s_.gauss()),e)}([f,x,m]),M=b.data;for(let e=0;e<f;++e)if(p[e]!==m)for(let t=0;t<x;++t)M.fill(0,e*y+t*m+p[e],e*y+(t+1)*m);let k=nI([f],n);for(let e=0;e<n;++e){let n=nI([f],e);({denoised_latents:b}=await ob(this.sessions.latent_denoiser,{style:s,noisy_latents:b,latent_mask:w,encoder_outputs:c,attention_mask:t,timestep:n,num_inference_steps:k}))}let{waveform:v}=await ob(this.sessions.voice_decoder,{latents:b});return{waveform:v,durations:u}}},f5=class extends lt{},f9=class extends f5{},f7=class extends f5{async _call(e){return new ok(await super._call(e))}},ge=class extends f5{},gt=class extends lt{},gs=class extends gt{},gn=class extends gt{},gr=class extends lt{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},ga=class extends gr{},gi=class extends gr{},go=class extends lt{},gl=class extends go{},gc=class extends go{async _call(e){return new gd(await super._call(e))}},gd=class extends dk{},gu=class extends lt{},g_=class extends gu{},gh=class extends lt{},gp=class extends gh{},gm=class extends gh{async _call(e){return new oC(await super._call(e))}},gf=class extends gh{async _call(e){return new ok(await super._call(e))}},gg=class extends lt{},gw=class extends gg{},gx=class extends gg{async _call(e){return new oC(await super._call(e))}},gy=class extends gg{async _call(e){return new ok(await super._call(e))}},gb=class extends gg{async _call(e){return new ov(await super._call(e))}},gM=class extends lt{},gk=class extends gM{},gv=class extends gM{},gE=class extends lt{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},gA=class extends lt{},gC=class extends gA{},gF=class extends gA{async _call(e){return new ok(await super._call(e))}},gS=class extends lt{},gT=class extends gS{},gP=class extends lt{},gz=class extends gP{},gL=class extends gP{async _call(e){return new ok(await super._call(e))}},gO=class extends lt{},gI=class extends gO{async _call(e){return new oF(await super._call(e))}},gN=class extends lt{},g$=class extends gN{},gB=class extends oM{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},gD=class extends lt{},gV=class extends gD{async _call(e){return new gB(await super._call(e))}},gq=class extends _h{},gG=new WeakMap;async function gj(e,t){let s=Math.floor((1+t.dims[2]-3)/2)+1,n=new nx("int64",BigInt64Array.from({length:s},(t,s)=>BigInt(e.enc_past_seq_len+s)),[1,s]),r=e.enc_past_seq_len+s,a=n$([1,r]),{audio_embeds:i,present_padding_cache:o,...l}=await ob(e.encoder_session,{input_features:t,attention_mask:a,position_ids:n,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});for(let t in"gpu-buffer"===e.enc_padding_cache.location&&e.enc_padding_cache.dispose(),e.enc_padding_cache=o,l)if(t.startsWith("present.")){let s=t.replace("present","past_key_values"),n=e.enc_kv_cache[s];n?.location==="gpu-buffer"&&n.dispose(),e.enc_kv_cache[s]=l[t]}return e.enc_past_seq_len=r,i}async function gR(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){let t=await e.chunks_iter.next();if(t.done){e.stream_exhausted=!0;break}let s=await gj(e,t.value);e.audio_embed_queue.push({data:s.data,tokens:s.dims[1]}),e.audio_embed_total_tokens+=s.dims[1]}}var gU=class extends oU{constructor(e){super(),this._s=e}_call(e){let t=this._s.stream_exhausted&&0===this._s.audio_embed_queue.length;return e.map(()=>t)}},gW=class extends lt{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},gQ=class extends gW{async forward({input_ids:e,past_key_values:t,...s}){let n=e.dims[1],r=gG.get(this);r&&await gR(r,r.audio_consumed+n);let{inputs_embeds:a}=await ob(this.sessions.embed_tokens,{input_ids:e});r&&function(e,t,s){if(0===e.audio_embed_queue.length)return;let n=t.data,r=0,a=s;for(;a>0&&e.audio_embed_queue.length>0;){let t=e.audio_embed_queue[0],s=Math.min(a,t.tokens-e.audio_queue_offset),i=e.audio_queue_offset*e.text_hidden_size;for(let a=0;a<s*e.text_hidden_size;++a)n[r*e.text_hidden_size+a]+=t.data[i+a];r+=s,a-=s,e.audio_queue_offset+=s,e.audio_queue_offset>=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=s-a}(r,a,n);
23let i={inputs_embeds:a,...s};lo(this,i,t);let o=this.sessions.decoder_model_merged,l=U(i,o.inputNames);return await ob(o,l)}async generate({input_features:e,stopping_criteria:t,...s}){if(!e)throw Error("input_features (generator/iterable) must be provided");let n=function(e,t){let{text_config:s,audio_config:n}=e.config,r=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:i}=n,o=a+i,l=new oZ,c=o_(n),d={batch_size:1},u="float32";for(let e of r.inputMetadata){if("past_padding_cache"===e.name){u=e.type;continue}if(!c.has(e.name))continue;let t=li(e.shape,d),s=t.reduce((e,t)=>e*t,1),n=nw[e.type];l[e.name]=new nx(e.type,new n(s),t)}let _=nw[u],h=new nx(u,new _(2*o),[1,o,2]),p=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!p)throw Error("input_features must be iterable or async iterable");return{encoder_session:r,enc_kv_cache:l,enc_padding_cache:h,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:p,text_hidden_size:s.hidden_size}}(this,e);gG.set(this,n);let r=new oW;r.push(new gU(n)),t&&r.extend(t);try{return await super.generate({...s,stopping_criteria:r})}finally{n.enc_kv_cache.dispose(),gG.delete(this)}}},gH=class extends lt{},gX=class extends gH{},gJ=class extends gH{async _call(e){return new oC(await super._call(e))}},gK=class extends gH{async _call(e){return new ok(await super._call(e))}},gY=class extends oM{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},gZ=class extends lt{},g0=class extends gZ{},g1=class extends gZ{async _call(e){return new oC(await super._call(e))}},g2=class extends gZ{async _call(e){return new ok(await super._call(e))}},g3=class extends gZ{async _call(e){return new gY(await super._call(e))}},g4=class extends gZ{async _call(e){return new ov(await super._call(e))}},g8=class extends lt{},g6=class extends g8{},g5=class extends oR{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},g9=class extends lt{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},g7=class extends g9{},we=class extends g9{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,g5)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(W.warn("No language specified - defaulting to English (en)."),s="en");let r=function(e){e=e.toLowerCase();let t=rF.get(e);if(void 0===t){let s=e.match(/^<\|([a-z]{2})\|>$/);if(s&&(e=s[1]),rC.has(e))t=e;else{let t=2===e.length?rC.keys():rC.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}(s),a=`<|${r}|>`;t.push(e.lang_to_id[a]),t.push(e.task_to_id[n??"transcribe"])}else if(s||n)throw 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&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(W.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(e=>null!=e)}async generate({inputs:e=null,generation_config:t=null,logits_processor:s=null,stopping_criteria:n=null,...r}){t=this._prepare_generation_config(t,r);let a=r.decoder_input_ids instanceof nx?nq(r.decoder_input_ids):r.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(s??=new oP).push(new oN(t,a)),t.begin_suppress_tokens&&(s??=new oP).push(new oI(t.begin_suppress_tokens,a.length)),t.return_token_timestamps){if(!t.alignment_heads)throw 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.");"translate"===t.task&&W.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!r.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:s,init_tokens:a,kwargs:r});let i=await super.generate({inputs:e,generation_config:t,logits_processor:s,decoder_input_ids:a,...r});return t.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,t.alignment_heads,t.num_frames,.02,a.length)),i}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:s,init_tokens:n,kwargs:r}){let a=t.no_timestamps_token_id+1,i=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,o=t.return_token_timestamps,l=e.dims[2],c=2*this.config.max_source_positions,d=0,u=[],_=[];for(;d<l;){let h,p,m,f=Math.min(d+c,l),g=e.slice(null,null,[d,f]),w=g.dims[2];if(w<c){let t=e.dims[1],s=new Float32Array(t*c),n=g.data;for(let e=0;e<t;++e)s.set(n.subarray(e*w,(e+1)*w),e*c);h=new nx("float32",s,[1,t,c])}else h=g;if(s)for(let e of s)"begin_index"in e&&(e.begin_index=n.length);let x=await super.generate({inputs:h,generation_config:t,logits_processor:s,decoder_input_ids:n,...r}),y=(o?x.sequences:x)[0].tolist().map(Number).slice(n.length);if(o){x.token_timestamps=this._extract_token_timestamps(x,t.alignment_heads,Math.floor((f-d)/2),.02,n.length);let e=d/2*.02;p=x.token_timestamps[0].tolist().slice(n.length).map(t=>t+e)}if(y.length>0&&y.at(-1)===i&&y.pop(),0===y.length)break;let b=y.map(e=>e>=a),M=y.length>=2&&b[y.length-1]&&!b[y.length-2],k=[];for(let e=0;e<y.length-1;++e)b[e]&&b[e+1]&&k.push(e+1);let v=y.length;if(k.length>0)if(M)m=f-d;else{let e=k.at(-1);m=(y[e-1]-a)*2,v=e}else m=f-d;let E=Math.floor(d/2),A=a+1500;for(let e=0;e<v;++e)y[e]>=a&&(y[e]=Math.min(y[e]+E,A));u.push(...y.slice(0,v)),p&&_.push(...p.slice(0,v)),d+=m}u.push(i);let h=[...n,...u];
23if(o){let e=new nx("int64",h.map(BigInt),[1,h.length]),t=[...Array(n.length).fill(0),..._,0];return{sequences:e,token_timestamps:new nx("float32",new Float32Array(t),[1,t.length])}}return new nx("int64",h.map(BigInt),[1,h.length])}_extract_token_timestamps(e,t,s=null,n=.02,r=0){if(!e.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");null==s&&W.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;void 0===a&&(W.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let i=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(e,t)=>nS(i.map(e=>e[t]),2)),l=nT(t.map(([e,t])=>{if(e>=o.length)throw Error(`Layer index ${e} is out of bounds for cross attentions (length ${o.length}).`);return s?o[e].slice(null,t,null,[0,s]):o[e].slice(null,t)})).transpose(1,0,2,3),[c,d]=function(e,t=null,s=1,n=!1){let r=e.data,a=e.dims;if(null===t){let t=r.reduce((e,t)=>e+t,0)/r.length,n=Math.sqrt(r.reduce((e,s)=>e+(s-t)**2,0)/(r.length-s)),a=new nx(e.type,[t],[]);return[new nx(e.type,[n],[]),a]}let i=nz(e,t=nF(t,a.length),n),o=i.data,[l,c,d]=nP((e,t,s,n)=>e+(t-o[n])**2,e,t,n);for(let e=0;e<c.length;++e)c[e]=Math.sqrt(c[e]/(a[t]-s));return[new nx(l,c,d),i]}(l,-2,0,!0),u=l.clone();for(let e=0;e<u.dims[0];++e){let t=u[e];for(let s=0;s<t.dims[0];++s){let n=t[s],r=c[e][s][0].data,i=d[e][s][0].data;for(let e=0;e<n.dims[0];++e){let t=n[e].data;for(let e=0;e<t.length;++e)t[e]=(t[e]-i[e])/r[e];t.set(function(e,t){if(t%2==0||t<=0)throw Error("Window size must be a positive odd number");let s=new e.constructor(e.length),n=new e.constructor(t),r=Math.floor(t/2);for(let t=0;t<e.length;++t){let a=0;for(let s=-r;s<=r;++s){let r=t+s;r<0?r=Math.abs(r):r>=e.length&&(r=2*(e.length-1)-r),n[a++]=e[r]}n.sort(),s[t]=n[r]}return s}(t,a))}}}let _=[nz(r>0?u.slice(null,null,[r,u.dims[2]],null):u,1)],h=e.sequences.dims,p=new nx("float32",new Float32Array(h[0]*h[1]),h);for(let e=0;e<h[0];++e){let[t,s]=function(e){let t=e.length,s=e[0].length,n=[t+1,s+1],r=Array.from({length:n[0]},()=>Array(n[1]).fill(1/0));r[0][0]=0;let a=Array.from({length:n[0]},()=>Array(n[1]).fill(-1));for(let t=1;t<n[1];++t)for(let s=1;s<n[0];++s){let n,i,o=r[s-1][t-1],l=r[s-1][t],c=r[s][t-1];o<l&&o<c?(n=o,i=0):l<o&&l<c?(n=l,i=1):(n=c,i=2),r[s][t]=e[s-1][t-1]+n,a[s][t]=i}for(let e=0;e<n[1];++e)a[0][e]=2;for(let e=0;e<n[0];++e)a[e][0]=1;let i=t,o=s,l=[],c=[];for(;i>0||o>0;)switch(l.push(i-1),c.push(o-1),a[i][o]){case 0:--i,--o;break;case 1:--i;break;case 2:--o;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${i}, ${o}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}(_[e].neg().squeeze_(0).tolist()),a=j([1],Array.from({length:t.length-1},(e,s)=>t[s+1]-t[s])).map(e=>!!e),i=[];for(let e=0;e<a.length;++e)a[e]&&i.push(s[e]*n);let o=Array(r).fill(0);o.push(...i),i.length>0&&o.push(i.at(-1)),p[e].data.set(o)}return p}},wt=class extends we{},ws=class extends lt{},wn=class extends ws{},wr=class extends ws{async _call(e){return new oE(await super._call(e))}},wa=class extends ws{async _call(e){return new ok(await super._call(e))}},wi=class extends ws{async _call(e){return new ov(await super._call(e))}},wo=class extends ws{async _call(e){return new oA(await super._call(e))}},wl=class extends lt{},wc=class extends wl{},wd=class extends wl{async _call(e){return new oE(await super._call(e))}},wu=class extends wl{async _call(e){return new ok(await super._call(e))}},w_=class extends wl{async _call(e){return new ov(await super._call(e))}},wh=class extends wl{async _call(e){return new oA(await super._call(e))}},wp=class extends lt{},wm=class extends wp{},wf=class extends wp{async _call(e){return new wg(await super._call(e))}},wg=class extends oM{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},ww=class extends lt{},wx=class extends ww{},wy=class extends ww{},wb=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","
23EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"]]),wM=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["cohere_asr","CohereAsrModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),wk=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),wv=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),wE=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),wA=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),wC=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),wF=new Map([["bert","BertForSequenceClassification"],["eurobert","EuroBertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraF
23orSequenceClassification"],["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"]]),wS=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),wT=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),wP=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),wz=new Map([["multi_modality","MultiM
23odalityCausalLM"]]),wL=new Map([["bert","BertForMaskedLM"],["eurobert","EuroBertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),wO=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"]]),wI=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),wN=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),w$=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),wB=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),wD=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"]]),wV=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),wq=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),wG=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),wj=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),wR=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),wU=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),wW=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),wQ=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),wH=new Map([["wavlm","WavLMForXVector"]]),wX=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),wJ=new Map([["vitmatte","VitMatteForImageMatting"]]),wK=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),wY=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),wZ=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),w0=new Map([["sapiens","SapiensForNormalEstimation"]]),w1=new Map([["vitpose","VitPoseForPoseEstimation"]]),w2=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),w3=[[wb,o0.EncoderOnly],[wM,o0.EncoderDecoder],[wv,o0.DecoderOnlyWithoutHead],[wk,o0.AutoEncoder],[wF,o0.EncoderOnly],[wS,o0.EncoderOnly],[wT,o0.Seq2Seq],[wE,o0.Seq2Seq],[wP,o0.DecoderOnly],[wz,o0.MultiModality],[wL,o0.EncoderOnly],[wO,o0.EncoderOnly],[wI,o0.
23Vision2Seq],[wN,o0.ImageTextToText],[w$,o0.AudioTextToText],[wD,o0.EncoderOnly],[wG,o0.EncoderOnly],[wR,o0.EncoderOnly],[wj,o0.EncoderOnly],[wJ,o0.EncoderOnly],[wK,o0.EncoderOnly],[wY,o0.EncoderOnly],[wZ,o0.EncoderOnly],[w0,o0.EncoderOnly],[w1,o0.EncoderOnly],[wV,o0.EncoderOnly],[wq,o0.EncoderOnly],[wU,o0.MaskGeneration],[wW,o0.EncoderOnly],[wQ,o0.EncoderOnly],[wA,o0.Seq2Seq],[wC,o0.EncoderOnly],[wH,o0.EncoderOnly],[wX,o0.EncoderOnly],[w2,o0.EncoderOnly]];for(let[e,t]of w3)for(let s of e.values()){o9.set(s,t);let e=ly[s];le.set(e,s),o7.set(s,e)}for(let[e,t,s]of[["MusicgenForConditionalGeneration",pC,o0.Musicgen],["Phi3VForCausalLM",mb,o0.Phi3V],["CLIPTextModelWithProjection",cm,o0.EncoderOnly],["SiglipTextModel",fF,o0.EncoderOnly],["JinaCLIPTextModel",_W,o0.EncoderOnly],["ClapTextModelWithProjection",cd,o0.EncoderOnly],["ClapAudioModelWithProjection",cu,o0.EncoderOnly],["DacEncoderModel",c2,o0.EncoderOnly],["DacDecoderModel",c3,o0.EncoderOnly],["MimiEncoderModel",hE,o0.EncoderOnly],["MimiDecoderModel",hA,o0.EncoderOnly],["SnacEncoderModel",fN,o0.EncoderOnly],["SnacDecoderModel",f$,o0.EncoderOnly],["Gemma3nForConditionalGeneration",uL,o0.ImageAudioTextToText],["Gemma4ForConditionalGeneration",uI,o0.ImageAudioTextToText],["SupertonicForConditionalGeneration",f6,o0.Supertonic],["ChatterboxModel",cn,o0.Chatterbox],["VoxtralRealtimeForConditionalGeneration",gQ,o0.VoxtralRealtime]])o9.set(e,s),le.set(t,e),o7.set(e,t);var w4=new Map([["modnet",wG],["birefnet",wG],["isnet",wG],["ben",wG]]);for(let[e,t]of w4.entries())t.set(e,"PreTrainedModel"),o9.set(e,o0.EncoderOnly),o7.set(e,lt);var w8=new Set(w4.keys());o9.set("PreTrainedModel",o0.EncoderOnly),le.set(lt,"PreTrainedModel");var w6={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:wF,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:wS,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:wA,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:wC,MODEL_FOR_MASKED_LM_MAPPING_NAMES:wL,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:wO,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:wD,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:wG,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:wj,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:wR,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:wV,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:wq,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:wU,MODEL_FOR_CTC_MAPPING_NAMES:wW,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:wQ,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:wH,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:wX,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:wB,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:wJ,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:wY,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:wZ,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:w0,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:w1,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:w2,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:wN,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:w$,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:wT,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:wE,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:wP,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:wI};o3=w6;var w5=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:s=null,cache_dir:n=null,local_files_only:r=!1,revision:a="main",model_file_name:i=null,subfolder:o="onnx",device:l=null,dtype:c=null,use_external_data_format:d=null,
23session_options:u={}}={}){let _={progress_callback:t,config:s,cache_dir:n,local_files_only:r,revision:a,model_file_name:i,subfolder:o,device:l,dtype:c,use_external_data_format:d,session_options:u};if(_.config=await op.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:h}=_.config;for(let t of this.MODEL_CLASS_MAPPINGS){let s=t.get(h);if(!s){for(let e of t.values())if(e[0]===h){s=e;break}if(!s)continue}return await ly[s].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return w8.has(h)||W.warn(`Unknown model class "${h}", attempting to construct from base class.`),await lt.from_pretrained(e,_);throw Error(`Unsupported model type: ${h}`)}},w9=class extends w5{static MODEL_CLASS_MAPPINGS=w3.map(e=>e[0]);static BASE_IF_FAIL=!0},w7=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},xe=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},xt=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},xs=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},xn=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},xr=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},xa=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},xi=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},xo=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},xl=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},xc=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},xd=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},xu=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},x_=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},xh=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},xp=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};w6.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES;var xm=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_CTC_MAPPING_NAMES]},xf=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};w6.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES,w6.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES;var xg=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};w6.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES;var xw=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},xx=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};w6.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES,w6.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES;var xy=class extends w5{static MODEL_CLASS_MAPPINGS=[w6.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};async function xb(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>ax.read(e)))}async function xM(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>"string"==typeof e||e instanceof URL?rU(e,t):e instanceof Float64Array?new Float32Array(e):e))}function xk(e,t){t&&(e=e.map(e=>0|e));let[s,n,r,a]=e;return{xmin:s,ymin:n,xmax:r,ymax:a}}w6.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES,w6.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES;var xv=class extends D{constructor({task:e,model:t,tokenizer:s=null,processor:n=null}){super(),this.task=e,this.model=t,this.tokenizer=s,this.processor=n}async dispose(){await this.model.dispose()}},xE=class extends xv{async _call(e,{top_k:t=1}={}){let s=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(s),{problem_type:r,id2label:a}=this.model.config,i="multi_label_classification"===r?e=>e.sigmoid():e=>new nx("float32",sG(e.data),e.dims),o=[];for(let e of n.logits){let s=i(e),n=await nk(s,t),r=n[0].tolist(),l=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));1===t?o.push(...l):o.push(l)}return Array.isArray(e)||1===t?o:o[0]}},xA=class extends xv{async _call(e,{ignore_labels:t=["O"],aggregation_strategy:s="none"}={}){if("none"!==s&&"simple"!==s)throw Error(`Invalid aggregation_strategy: "${s}". Must be one of "none" or "simple".`);let n=Array.isArray(e),r=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}
23),a=(await this.model(r)).logits,i=this.model.config.id2label,o=[];for(let e=0;e<a.dims[0];++e){let n=r.input_ids[e].tolist(),l=a[e],c=[];for(let e=0;e<l.dims[0];++e){let s=l[e],r=sR(s.data)[1],a=i?i[r]:`LABEL_${r}`;if(t.includes(a))continue;let o=this.tokenizer.decode([n[e]],{skip_special_tokens:!0});if(""===o)continue;let d=sG(s.data);c.push({entity:a,score:d[r],index:e,word:o})}o.push("simple"===s?function(e,t,s){let n=[],r=null;for(let t=0;t<e.length;++t){let[s,a]=function(e){let t=e[0];return"-"===e[1]&&("B"===t||"I"===t||"E"===t||"S"===t)?[t,e.slice(2)]:["I",e]}(e[t].entity);r===a&&"B"!==s&&"S"!==s?(n[n.length-1].end=t+1,"E"===s&&(r=null)):(n.push({tag:a,start:t,end:t+1}),r="S"===s?null:a)}return n.map(({tag:n,start:r,end:a})=>{let i=0,o=[];for(let s=r;s<a;++s)i+=e[s].score,o.push(t[e[s].index]);return{entity_group:n,score:i/(a-r),word:s.decode(o,{skip_special_tokens:!0})}})}(c,n,this.tokenizer):c)}return n?o:o[0]}},xC=class extends xv{async _call(e,t,{top_k:s=1}={}){let n=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),r=Array.isArray(e),{start_logits:a,end_logits:i}=await this.model(n),o=n.input_ids.tolist(),l=n.attention_mask.tolist(),{all_special_ids:c,sep_token_id:d}=this.tokenizer,u=[];for(let e=0;e<a.dims[0];++e){let t=o[e],n=t.findIndex(e=>e==d),r=a[e].tolist(),_=i[e].tolist();for(let s=1;s<r.length;++s)(0==l[e]||s<=n||-1!==c.findIndex(e=>e==t[s]))&&(r[s]=-1/0,_[s]=-1/0);let h=sG(r).map((e,t)=>[e,t]),p=sG(_).map((e,t)=>[e,t]);h[0][0]=0,p[0][0]=0;let m=(function(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))})(h,p).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]),f=[];for(let e=0;e<Math.min(m.length,s);++e){let[s,n,r]=m[e],a=t.slice(s,n+1),i=this.tokenizer.decode(a,{skip_special_tokens:!0});f.push({answer:i,score:r})}1===s?u.push(...f):u.push(f)}return r?u:u[0]}},xF=class extends xv{async _call(e,{top_k:t=5}={}){let{mask_token_id:s,mask_token:n}=this.tokenizer,r=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(r),i=[],o=r.input_ids.tolist();for(let e=0;e<o.length;++e){let r=o[e],l=r.findIndex(e=>e==s);if(-1===l)throw Error(`Mask token (${n}) not found in text.`);let c=a[e][l],d=await nk(new nx("float32",sG(c.data),c.dims),t),u=d[0].tolist(),_=d[1].tolist();i.push(_.map((e,t)=>{let s=r.slice();return s[l]=e,{score:u[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(s,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}},xS=class extends xv{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,t={}){let s;Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let r=this.tokenizer,a={padding:!0,truncation:!0};s="translation"===this.task&&"_build_translation_inputs"in r?r._build_translation_inputs(e,a,t):r(e,a);let i=await this.model.generate({...s,...this._default_generation_config,...t});return r.batch_decode(i,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},xT=class extends xS{_key="summary_text"},xP=class extends xS{_key="translation_text"};function xz(e){return Array.isArray(e)&&e.every(e=>"role"in e&&"content"in e)}var xL=class extends xv{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let s,n,{add_special_tokens:r,return_full_text:a,tools:i,documents:o,chat_template:l,tokenizer_encode_kwargs:c,...d}=t,u=!1,_=!1,h=r??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,p=c;if("string"==typeof e)s=e=[e];else if(Array.isArray(e)&&e.every(e=>"string"==typeof e))u=!0,s=e;else{if(xz(e))e=[e];else if(Array.isArray(e)&&e.every(xz))u=!0;else throw Error("Input must be a string, an array of strings, a Chat, or an array of Chats");_=!0;let t={tokenize:!1,add_generation_prompt:!0,...U({tools:i,documents:o,chat_template:l},["tools","documents","chat_template"]),...p};s=e.map(e=>this.tokenizer.apply_chat_template(e,t)),h=!1,p=void 0}let m=!_&&(a??!0);this.tokenizer.padding_side="left";let f=this.tokenizer(s,{add_special_tokens:h,padding:!0,truncation:!0,...p}),g=await this.model.generate({...f,...this._default_generation_config,...d}),w=this.tokenizer.batch_decode(g,{skip_special_tokens:!0});!m&&f.input_ids.dims.at(-1)>0&&(n=this.tokenizer.batch_decode(f.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let x=Array.from({length:e.length},e=>[]);for(let t=0;t<w.length;++t){let s=Math.floor(t/g.dims[0]*e.length);n&&(w[t]=w[t].slice(n[s])),x[s].push({generated_text:_?[...e[s],{role:"assistant",content:w[t]}]:w[t]})}return u||1!==x.length?x:x[0]}},xO=class extends xv{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([e,t])=>[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,void 0===this.entailment_id&&(W.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,void 0===this.contradiction_id&&(W.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let r=Array.isArray(e);r||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(e=>s.replace("{}",e)),i=n||1===t.length,o=[];for(let s of e){let e=[];for(let t of a){let n=this.tokenizer(s,{text_pair:t,padding:!0,truncation:!0}
23),r=await this.model(n);i?e.push([r.logits.data[this.contradiction_id],r.logits.data[this.entailment_id]]):e.push(r.logits.data[this.entailment_id])}let n=(i?e.map(e=>sG(e)[1]):sG(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);o.push({sequence:s,labels:n.map(e=>t[e[1]]),scores:n.map(e=>e[0])})}return r?o:o[0]}},xI=class extends xv{async _call(e,{top_k:t=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await xM(e,s),r=this.model.config.id2label,a=[];for(let e of n){let s=await this.processor(e),n=(await this.model(s)).logits[0],i=await nk(new nx("float32",sG(n.data),n.dims),t),o=i[0].tolist(),l=i[1].tolist().map((e,t)=>({label:r?r[e]:`LABEL_${e}`,score:o[t]}));a.push(l)}return Array.isArray(e)?a:a[0]}},xN=class extends xv{async _call(e,t,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let r=t.map(e=>s.replace("{}",e)),a=this.tokenizer(r,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,o=await xM(e,i),l=[];for(let e of o){let s=await this.processor(e),n=sG((await this.model({...a,...s})).logits_per_audio.data);l.push([...n].map((e,s)=>({score:e,label:t[s]})))}return n?l[0]:l}},x$=class extends xv{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,t);case"moonshine":return this._call_moonshine(e,t);case"cohere_asr":return this._call_cohere_asr(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&W.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&W.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=this.processor.feature_extractor.config.sampling_rate,r=await xM(s?[e]:e,n),a=[];for(let e of r){let t=await this.processor(e),s=(await this.model(t)).logits[0],n=[];for(let e of s)n.push(sR(e.data)[1]);let r=this.tokenizer.decode(n,{skip_special_tokens:!0}).trim();a.push({text:r})}return s?a[0]:a}async _call_whisper(e,t){let s=t.return_timestamps??!1,n=t.chunk_length_s??0,r=t.force_full_sequences??!1,a=t.stride_length_s??null,i={...t};"word"===s&&(i.return_token_timestamps=!0,i.return_timestamps=!0);let o=!Array.isArray(e),l=this.processor.feature_extractor.config,c=l.chunk_length/this.model.config.max_source_positions,d=l.hop_length,u=l.sampling_rate,_=await xM(o?[e]:e,u),h=[];for(let e of _){let t=[];if(n>0){if(null===a)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let s=u*n,r=u*a,i=s-2*r,o=0;for(;;){let n=o+s,a=e.subarray(o,n),l=await this.processor(a),c=0===o,d=n>=e.length;if(t.push({stride:[a.length,c?0:r,d?0:r],input_features:l.input_features,is_last:d}),d)break;o+=i}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of t){i.num_frames=Math.floor(e.stride[0]/d);let t=await this.model.generate({inputs:e.input_features,...i});if("word"===s){let s=t.sequences.tolist()[0],n=t.token_timestamps.tolist()[0],r=this.tokenizer.timestamp_begin,a=Math.max(s.findIndex(e=>Number(e)>=r),0);e.tokens=s.slice(a),e.token_timestamps=n.slice(a).map(e=>sX(e,2))}else e.tokens=t[0].tolist();e.stride=e.stride.map(e=>e/u)}let[o,l]=this.tokenizer._decode_asr(t,{time_precision:c,return_timestamps:s,force_full_sequences:r});h.push({text:o,...l})}return o?h[0]:h}async _call_moonshine(e,t){let s=!Array.isArray(e),n=this.processor.feature_extractor.config.sampling_rate,r=await xM(s?[e]:e,n),a=[];for(let e of r){let s=await this.processor(e),r=6*Math.floor(e.length/n),i=await this.model.generate({max_new_tokens:r,...t,...s}),o=this.processor.batch_decode(i,{skip_special_tokens:!0})[0];a.push({text:o})}return s?a[0]:a}async _call_cohere_asr(e,t){let s=!Array.isArray(e),n=this.processor.feature_extractor,r=n.config.sampling_rate,a=await xM(s?[e]:e,r),i=t.language??"en",o=this.processor.get_decoder_prompt_ids(i),l=[];for(let e of a){let s=n.split_audio(e),r=[];for(let e of s){let s=await this.processor(e),n=await this.model.generate({...s,decoder_input_ids:o,...t}),a=this.tokenizer.decode(n[0].tolist(),{skip_special_tokens:!0}).trim();r.push(a)}let a=this.processor.constructor.join_chunks(r,i);l.push({text:a})}return s?l[0]:l}},xB=class extends xv{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if(("string"==typeof e||e instanceof URL)&&(e=new Float32Array(await (await $.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new nx("float32",e,[e.length]);else if(!(e instanceof nx))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(1===e.dims[0])e=e.repeat(t,1);else if(e.dims[0]!==t)throw Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,s,n=null){let r=t.data,[a,i]=t.dims,o=n?n.data:null,l=[];for(let e=0;e<a;++e){let t=o?Math.min(Math.ceil(o[e]),i):i,n=e*i;l.push(new r2(r.slice(n,n+t),s))}return Array.isArray(e)?l:l[0]}async _call(e,t){return this.processor?this._call_text_to_spectrogram(e,t):"supertonic"===this.model.config.model_type?this._call_supertonic(e,t):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:s,speed:n}){if(!t)throw Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:r,style_dim:a}=this.model.config,i=this.tokenizer(e,{padding:!0,truncation:!0}
23),o=i.input_ids.dims[0];t=(t=await this._prepare_speaker_embeddings(t,o)).view(o,-1,a);let{waveform:l,durations:c}=await this.model.generate_speech({...i,style:t,num_inference_steps:s,speed:n});return this._postprocess_waveform(e,l,r,c)}async _call_text_to_waveform(e){let t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:s}=await this.model(t),n=this.model.config.sampling_rate;return this._postprocess_waveform(e,s,n)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){this.vocoder||(W.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await w9.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));let{input_ids:s}=this.tokenizer(e,{padding:!0,truncation:!0}),n=s.dims[0];t=(t=await this._prepare_speaker_embeddings(t,n)).view(n,-1);let{waveform:r}=await this.model.generate_speech(s,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,r,a)}},xD=class extends xv{async _call(e,t={}){let s=Array.isArray(e),n=await xb(e),{pixel_values:r}=await this.processor(n),a=[];for(let e of r){e.dims=[1,...e.dims];let s=await this.model.generate({inputs:e,...t}),n=this.tokenizer.batch_decode(s,{skip_special_tokens:!0}).map(e=>({generated_text:e.trim()}));a.push(n)}return s?a:a[0]}},xV=class extends xv{async _call(e,{top_k:t=5}={}){let s=await xb(e),{pixel_values:n}=await this.processor(s),r=await this.model({pixel_values:n}),{id2label:a}=this.model.config,i=[];for(let e of r.logits){let s=await nk(new nx("float32",sG(e.data),e.dims),t),n=s[0].tolist(),r=s[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:n[t]}));i.push(r)}return Array.isArray(e)?i:i[0]}},xq={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},xG=class extends xv{async _call(e,{threshold:t=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:r=null,target_sizes:a=null,subtask:i=null}={}){if(Array.isArray(e)&&1!==e.length)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let o=await xb(e),l=o.map(e=>[e.height,e.width]),c=await this.processor(o),{inputNames:d,outputNames:u}=this.model.sessions.model;if(!d.includes("pixel_values")){if(1!==d.length)throw Error(`Expected a single input name, but got ${d.length} inputs: ${d}.`);let e=d[0];if(e in c)throw Error(`Input name ${e} already exists in the inputs.`);c[e]=c.pixel_values}let _=await this.model(c),h=null;if(null!==i)h=xq[i];else if(this.processor.image_processor){for(let[e,t]of Object.entries(xq))if(t in this.processor.image_processor){h=this.processor.image_processor[t].bind(this.processor.image_processor),i=e;break}}let p=this.model.config.id2label,m=[];if(i)if("panoptic"===i||"instance"===i){let e=h(_,t,s,n,r,a??l)[0],i=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(i.data.length);for(let s=0;s<i.data.length;++s)i.data[s]===t.id&&(e[s]=255);let s=new ax(e,i.dims[1],i.dims[0],1);m.push({score:t.score,label:p[t.label_id],mask:s})}}else if("semantic"===i){let{segmentation:e,labels:t}=h(_,a??l)[0];for(let s of t){let t=new Uint8ClampedArray(e.data.length);for(let n=0;n<e.data.length;++n)e.data[n]===s&&(t[n]=255);let n=new ax(t,e.dims[1],e.dims[0],1);m.push({score:null,label:p[s],mask:n})}}else throw Error(`Subtask ${i} not supported.`);else{let e=_[u[0]];for(let t=0;t<l.length;++t){let s=l[t],n=e[t];n.data.some(e=>e<-1e-5||e>1.00001)&&n.sigmoid_();let r=await ax.fromTensor(n.mul_(255).to("uint8")).resize(s[1],s[0]);m.push({label:null,score:null,mask:r})}}return m}},xj=class extends xG{async _call(e,t={}){let s=await xb(e),n=await super._call(e,t),r=s.map((e,t)=>{let s=e.clone();return s.putAlpha(n[t].mask),s});return Array.isArray(e)?r:r[0]}};Object.freeze({"text-classification":{pipeline:xE,model:w7,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:xA,model:xe,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:xC,model:xo,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:xF,model:xi,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:xT,model:xt,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:xP,model:xt,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:xS,model:xt,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:xL,model:xa,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:xO,model:w7,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:xI,model:xf,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:xN,model:w9,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:x$,model:[xs,xm],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:xB,model:[xr,xn],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:xD,model:xl,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:xV,model:xc,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:xG,model:[xd,xu,x_],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:xj,model:[xd,xu,x_],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:class extends xv{async _call(e,t,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),r=await xb(e),a=t.map(e=>s.replace("{}",e)),i=this.tokenizer(a,{padding:"siglip"!==this.model.config.model_type||"max_length",truncation:!0}
23),{pixel_values:o}=await this.processor(r),l=await this.model({...i,pixel_values:o}),c="siglip"===this.model.config.model_type?e=>e.sigmoid().data:e=>sG(e.data),d=[];for(let e of l.logits_per_image){let s=[...c(e)].map((e,s)=>({score:e,label:t[s]}));s.sort((e,t)=>t.score-e.score),d.push(s)}return n?d:d[0]}},model:w9,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:class extends xv{async _call(e,{threshold:t=.9,percentage:s=!1}={}){let n=Array.isArray(e);if(n&&1!==e.length)throw Error("Object detection pipeline currently only supports a batch size of 1.");let r=await xb(e),a=s?null:r.map(e=>[e.height,e.width]),{pixel_values:i,pixel_mask:o}=await this.processor(r),l=await this.model({pixel_values:i,pixel_mask:o}),c=this.processor.image_processor.post_process_object_detection(l,t,a),{id2label:d}=this.model.config,u=c.map(e=>e.boxes.map((t,n)=>({score:e.scores[n],label:d[e.classes[n]],box:xk(t,!s)})));return n?u:u[0]}},model:xh,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:class extends xv{async _call(e,t,{threshold:s=.1,top_k:n=null,percentage:r=!1}={}){let a=Array.isArray(e),i=await xb(e),o=this.tokenizer(t,{padding:!0,truncation:!0}),l=await this.processor(i),c=[];for(let e=0;e<i.length;++e){let a,d=i[e],u=r?null:[[d.height,d.width]],_=l.pixel_values[e].unsqueeze_(0),h=await this.model({...o,pixel_values:_});if("post_process_grounded_object_detection"in this.processor){let e=this.processor.post_process_grounded_object_detection(h,o.input_ids,{box_threshold:s,text_threshold:s,target_sizes:u})[0];a=e.boxes.map((t,s)=>({score:e.scores[s],label:e.labels[s],box:xk(t,!r)}))}else{let e=this.processor.image_processor.post_process_object_detection(h,s,u,!0)[0];a=e.boxes.map((s,n)=>({score:e.scores[n],label:t[e.classes[n]],box:xk(s,!r)}))}a.sort((e,t)=>t.score-e.score),null!==n&&(a=a.slice(0,n)),c.push(a)}return a?c:c[0]}},model:xp,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:class extends xv{_default_generation_config={max_new_tokens:256};async _call(e,t,s={}){if(Array.isArray(e)){if(1!==e.length)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await xb(e))[0],{pixel_values:r}=await this.processor(n),a=`<s_docvqa><s_question>${t}</s_question><s_answer>`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,o=await this.model.generate({inputs:r,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...s}),l=this.tokenizer.batch_decode(o)[0].match(/<s_answer>(.*?)<\/s_answer>/),c=null;return l&&l.length>=2&&(c=l[1].trim()),[{answer:c}]}},model:xg,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:class extends xv{async _call(e){let t=await xb(e),s=await this.processor(t),n=await this.model(s),r=[];for(let e of n.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");r.push(ax.fromTensor(t))}return Array.isArray(e)?r:r[0]}},model:xw,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:class extends xv{async _call(e){let t=await xb(e),s=await this.processor(t),{predicted_depth:n}=await this.model(s),r=[];for(let e=0;e<t.length;++e){let s=n[e],[a,i]=s.dims.slice(-2),[o,l]=t[e].size,c=(await nb(s.view(1,1,a,i),{size:[l,o],mode:"bilinear"})).view(l,o),d=c.min().item(),u=c.max().item(),_=c.sub(d).div_(u-d).mul_(255).to("uint8").unsqueeze(0),h=ax.fromTensor(_);r.push({predicted_depth:c,depth:h})}return Array.isArray(e)?r:r[0]}},model:xx,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:class extends xv{async _call(e,{pooling:t="none",normalize:s=!1,quantize:n=!1,precision:r="binary"}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),i=await this.model(a),o=i.last_hidden_state??i.logits??i.token_embeddings;switch(t){case"none":break;case"mean":o=function(e,t){let s=e.data,n=t.data,r=[e.dims[0],e.dims[2]],a=new s.constructor(r[0]*r[1]),[i,o,l]=e.dims,c=0;for(let e=0;e<i;++e){let t=e*l*o;for(let r=0;r<l;++r){let i=0,d=0,u=e*o,_=t+r;for(let e=0;e<o;++e){let t=Number(n[u+e]);d+=t,i+=s[_+e*l]*t}let h=i/d;a[c++]=h}}return new nx(e.type,a,r)}(o,a.attention_mask);break;case"first_token":case"cls":o=o.slice(null,0);break;case"last_token":case"eos":o=o.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return s&&(o=o.normalize(2,-1)),n&&(o=function(e,t){if(2!==e.dims.length)throw Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!=0)throw Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw Error("The precision must be either 'binary' or 'ubinary'");
23let s="binary"===t,n=s?Int8Array:Uint8Array,r=e.data,a=new n(r.length/8);for(let e=0;e<r.length;++e){let t=+(r[e]>0),n=Math.floor(e/8),i=e%8;a[n]|=t<<7-i,s&&0===i&&(a[n]-=128)}return new nx(s?"int8":"uint8",a,[e.dims[0],e.dims[1]/8])}(o,r)),o}},model:w9,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:class extends xv{async _call(e,{pool:t=null}={}){let s,n=await xb(e),{pixel_values:r}=await this.processor(n),a=await this.model({pixel_values:r});if(t){if(!("pooler_output"in a))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");s=a.pooler_output}else s=a.last_hidden_state??a.logits??a.image_embeds;return s}},model:[xy,w9],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"}),F.IS_PROCESS_AVAILABLE||(e=>console.log(e)),Object.keys(nf)}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.