var OP=Object.defineProperty;var Ts=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var yn=(t,e)=>{for(var r in e)OP(t,r,{get:e[r],enumerable:!0})};var xt={};var Gt={};var kA={};var IP="4.3.2",ld=typeof self<"u",bn=!OA(xt),TA=!OA(Gt),Oc=ld&&"caches"in self,CP=typeof globalThis.Deno<"u",C3=typeof globalThis.Bun<"u",Cc=CP&&Oc&&!bn,SA=typeof process<"u",MA=SA&&process?.release?.name==="node"&&!Cc,cd=typeof window<"u"&&typeof window.document<"u",ud=ld&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),PP=cd||ud||Cc,NP=MA||typeof navigator<"u"&&"gpu"in navigator,LP=typeof navigator<"u"&&"ml"in navigator,zP=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",$P=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",RP=typeof ServiceWorkerGlobalScope<"u"&&ld&&self instanceof ServiceWorkerGlobalScope,BP=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent;if(!((navigator.vendor||"").indexOf("Apple")>-1&&!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android")))return!1;let r=t.match(/Version\/(\d+)/);return r?parseInt(r[1],10)<26:!1},DP=BP(),le=Object.freeze({IS_BROWSER_ENV:cd,IS_WEBWORKER_ENV:ud,IS_WEB_ENV:PP,IS_SERVICE_WORKER_ENV:RP,IS_DENO_WEB_RUNTIME:Cc,IS_WEB_CACHE_AVAILABLE:Oc,IS_WEBGPU_AVAILABLE:NP,IS_WEBNN_AVAILABLE:LP,IS_SAFARI_BELOW_26:DP,IS_PROCESS_AVAILABLE:SA,IS_NODE_ENV:MA,IS_FS_AVAILABLE:bn,IS_PATH_AVAILABLE:TA,IS_CRYPTO_AVAILABLE:zP,IS_CHROME_AVAILABLE:$P}),pd=bn&&TA,Ic="./";if(pd){let t=import.meta.url;t?Ic=Gt.dirname(Gt.dirname(kA.fileURLToPath(t))):typeof __dirname<"u"&&(Ic=Gt.dirname(__dirname))}var UP=pd?Gt.join(Ic,"/.cache/"):null,EA="/models/",FP=pd?Gt.join(Ic,EA):EA,GP=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,It=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),AA=It.WARNING,he={version:IP,backends:{onnx:{}},get logLevel(){return AA},set logLevel(t){AA=t,he.backends.onnx?.setLogLevel?.(t)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(cd||ud||Cc),localModelPath:FP,useFS:bn,useBrowserCache:Oc,useFSCache:bn,cacheDir:UP,useCustomCache:!1,customCache:null,useWasmCache:Oc||bn,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:GP};function OA(t){return Object.keys(t).length===0}var We=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function fr(t,e){t&&t(e)}var Ar=class extends We{constructor(e,r){super(),this.callback=e,this.files_loading=r,this.loads=new Map}_call(e){if(e.status==="progress"){this.files_loading[e.file]={loaded:e.loaded,total:e.total};let r=Object.values(this.files_loading).reduce((o,a)=>o+a.loaded,0),s=Object.values(this.files_loading).reduce((o,a)=>o+a.total,0),n=s>0?r/s*100:0;this.callback({status:"progress_total",name:e.name,progress:n,loaded:r,total:s,files:structuredClone(this.files_loading)})}this.callback(e)}};function IA(t){return Number.isInteger(t)||typeof t=="bigint"}function fd(t){return t==null||t===-1}function dd(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function yt(...t){return Array.prototype.concat.apply([],t)}function CA(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function vn(t,e){return Math.abs((t+e)%(2*e)-e)}function He(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function PA(t,e){let r=0;for(let s of t)s===e&&++r;return r}var te={error(...t){he.logLevel<=It.ERROR&&console.error(...t)},warn(...t){he.logLevel<=It.WARNING&&console.warn(...t)},info(...t){he.logLevel<=It.INFO&&console.log(...t)},debug(...t){he.logLevel<=It.DEBUG&&console.log(...t)},log(...t){this.info(...t)}};var jP=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;ns&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s{try{return new RegExp(t,e)}catch(r){if(!(r instanceof SyntaxError))throw r;let s=new Map,n=t.replace(/(\\[pP])\{([^}=]+)\}/g,(o,a,i,l)=>{let c=0;for(let f=l-1;f>=0&&t[f]==="\\";--f)++c;if(c%2===1)return o;let u=s.get(i);if(u===void 0){try{new RegExp(`\\p{${i}}`,"u"),u=i}catch{u=`Script=${i}`}s.set(i,u)}return`${a}{${u}}`});if(n===t)throw r;try{return new RegExp(n,e)}catch{throw r}}},_d=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),zc=(t,e=!0)=>{if(t.Regex!==void 0){let r=lN(oN(t.Regex));return jA(r,"gu")}else if(t.String!==void 0){let r=cN(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},kn="\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}",qA=`${kn}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`,dr=`[${qA}]`,WA=`[^${qA}]`,VP=`(?:(?|[:=!>])/,XA=/^\\([pPxu])\{([^}]*)\}/,tN=/^\{(\d+(?:,\d*)?|,\d+)\}/,rN=/^\[:(\^?)(\p{Alphabetic}+):\]/u,sN=/^\[:\^:\]/,nN=/^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/,KA=/^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/,YA=t=>t>="A"&&t<="Z"||t>="a"&&t<="z",Pc=(t,e)=>String.fromCodePoint(t.codePointAt(e)),LA=t=>{if(!/^[0-9A-Fa-f]{1,8}$/.test(t))return null;let e=Number.parseInt(t,16);if(e>127)return null;let r=String.fromCharCode(e);return YA(r)?`[${r.toLowerCase()}${r.toUpperCase()}]`:null},oN=t=>t.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g,"[^()|\\s$1]"),QA="[\\s\\S]",zA=256,$A=()=>({fragment:"",alternatives:[],tail:null,contains_complex_set:!1}),hd=t=>{throw new SyntaxError(`Unsupported range with a set-valued character-class operand at index ${t}`)},Nc=(t,e,r,s=!0)=>{t.tail==="range"&&hd(r),t.alternatives.push(e),t.tail="set",t.contains_complex_set=t.contains_complex_set||s},Rr=(t,e,r=!1,s=-1)=>{if(r&&t.tail==="range"&&hd(s),t.tail==="range"){t.fragment+=e,t.tail="complete_range";return}t.fragment+=e,t.tail=r?"set":"scalar",t.contains_complex_set=t.contains_complex_set||r},aN=(t,e,r)=>{let s=XA.exec(t.slice(e));if(s){let[m,_,w]=s;if(_==="P"&&w==="Word")Nc(r,`[^${kn}]`,e);else{let x=_==="x"?`\\u{${w}}`:_==="p"&&w==="Word"?kn:m;Rr(r,x,_==="p"||_==="P",e)}return e+m.length}let n=KA.exec(t.slice(e));if(n)return Rr(r,n[0]),e+n[0].length;if(e+1>=t.length)throw new SyntaxError(`Unterminated escape in character class at index ${e}`);let o=Pc(t,e+1),a=e+1+o.length,i=VA.get(o);if(i!==void 0)return Rr(r,i),a;let l=JP.get(o);if(l!==void 0)return Nc(r,l,e),a;let c=QP.get(o),u,f=!1;return c!==void 0?(u=c,f=o!=="a"&&o!=="e"):/[A-Za-z0-9]/.test(o)?u=`\\${o}`:HA.includes(o)||o==="-"?u=`\\${o}`:u=o,Rr(r,u,f,e),a},JA=t=>t.length===1?t[0]:`(?:(?=(?:${t.join("|")}))${QA})`,RA=t=>{let e=t.fragment.length===0?t.alternatives:[`[${t.fragment}]`,...t.alternatives];return JA(e)},iN=t=>{let e=jA(`^(?:${t})$`,"u"),r="";for(let s=0;s<26;++s){let n=String.fromCharCode(65+s),o=String.fromCharCode(97+s),a=e.test(n),i=e.test(o);a!==i&&(r+=a?o:n)}return r},ZA=(t,e,r,s=!0,n=1)=>{if(n>zA)throw new SyntaxError(`Maximum character-class nesting depth of ${zA} exceeded at index ${e}`);let o=e+1,a=t[o]==="^";a&&++o;let i=o,l=[$A()],c=l[0],u=!1;for(;o1?new SyntaxError(`Malformed character-class intersection with an empty operand at index ${o}`):new SyntaxError(`Empty character class at index ${e}`);let m=l.some(k=>k.contains_complex_set);if(a&&l.length>1&&u)throw new SyntaxError(`Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${e}`);let _=RA(l[0]),w=_;if(l.length>1){let k="";for(let M=1;M0&&(x?(b+=k,w=`[${b}]`):w=JA([w,`[${k}]`]))}return{atom:a?x?`[^${b}]`:`(?:(?!${w})${QA})`:w,end:o+1,negated:a,contains_complex_set:m,contains_nested_negated_complex_set:u}}if(t.startsWith("&&",o)){if(c.tail===null)throw new SyntaxError(`Malformed character-class intersection with an empty operand at index ${o}`);c=$A(),l.push(c),o+=2;continue}if(f==="["){let m=t.slice(o);if(sN.test(m))throw new SyntaxError(`Malformed empty negated POSIX character class at index ${o}`);let _=rN.exec(m);if(_){let[,x,b]=_,A=ZP.get(b);if(A===void 0)throw new SyntaxError(`Unsupported POSIX character class "${b}" at index ${o}`);if(r&&x&&(b==="lower"||b==="upper"))throw new SyntaxError(`Unsupported negated POSIX ${b} class inside an inline case-insensitive group`);x?Nc(c,`[^${A}]`,o):Rr(c,A,!0,o),o+=_[0].length;continue}if(nN.test(m))throw new SyntaxError(`Unsupported POSIX collating or equivalence bracket expression at index ${o}`);let w=ZA(t,o,r,!1,n+1);Nc(c,w.atom,o,w.contains_complex_set),u||=w.contains_nested_negated_complex_set||w.negated&&w.contains_complex_set,o=w.end;continue}if(f==="-"){let m=t[o+1]==="]"||t.startsWith("&&",o+1);c.tail==="set"&&!m&&hd(o),c.tail===null||c.tail==="range"||c.tail==="complete_range"||m?Rr(c,"\\-"):(c.fragment+="-",c.tail="range"),++o;continue}Rr(c,f==="^"&&c.fragment.length===0?"\\^":f),o+=f.length}throw new SyntaxError(`${l.length>1?"Unterminated character-class intersection":"Unterminated character class"} at index ${e}`)},lN=t=>{let e="",r=-1,s=!1,n=!1,o=[],a=i=>{r=e.length,e+=i,s=!1};for(let i=0;i=t.length){e+=l;break}let f=Pc(t,i+1);if(i+=1+f.length,f==="G")continue;let m=VA.get(f);if(m!==void 0){a(m);continue}let _=YP.get(f),w;_!==void 0?w=_:/[A-Za-z0-9]/.test(f)?w=`\\${f}`:HA.includes(f)?w=`\\${f}`:w=f,a(w);continue}switch(l){case"[":{let c=ZA(t,i,n);a(c.atom),i=c.end;continue}case"]":a("\\]"),++i;continue;case".":a("[^\\n]"),++i;continue;case"^":a(XP),++i;continue;case"$":a(KP),++i;continue;case"(":{let c=t.startsWith("(?i:",i),u=c?"(?i:":eN.exec(t.slice(i))?.[0]??"(",f=c||u==="(?>"?"(?:":u;o.push([e.length,n]),c&&(n=!0),e+=f,s=!1,i+=u.length;continue}case")":e+=l,[r,n]=o.pop()??[-1,!1],s=!1,++i;continue;case"|":e+=l,r=-1,s=!1,++i;continue;case"{":{let c=tN.exec(t.slice(i));if(!c||r<0){a("\\{"),++i;continue}let u=c[1].startsWith(",")?`0${c[1]}`:c[1];i+=c[0].length;let f=t[i];f==="+"||f==="*"?(e=`${e.slice(0,r)}(?:${e.slice(r)}{${u}})${f}`,++i):e+=`{${u}}`,s=!0;continue}case"}":a("\\}"),++i;continue;case"+":if(s){++i;continue}e+=l,s=!0,++i;continue;case"*":case"?":e+=l,s=!0,++i;continue;default:a(n&&YA(l)?`[${l.toLowerCase()}${l.toUpperCase()}]`:l),i+=l.length;continue}}return e},cN=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),uN=(t,e,r)=>{let s=[],n=0;for(;nt>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,fN=t=>Number.isInteger(t)||typeof t=="bigint",dN=t=>{let e=0;for(let r of t)++e;return e},mN=t=>e2(t.toLowerCase()),Qt=(...t)=>Array.prototype.concat.apply([],t),gd=t=>new Map(Object.entries(t)),_N=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s0&&r.push(o),s=n.index+o.length}return st.replace(/\p{M}/gu,""),BA=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},hN=t=>t.match(/\S+/g)||[],gN=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},Io=gN,wN=class extends Io{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Tr=wN,xN=class extends Tr{tokenize_chinese_chars(t){let e=[];for(let r=0;rr.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},vN=bN,kN=class extends Tr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>t2(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},EN=kN,AN=class extends Tr{constructor(t){super(t),this.pattern=zc(this.config.pattern??{})}normalize(t){return this.pattern===null?t:t.replaceAll(this.pattern,this.config.content??"")}},TN=AN,SN=class extends Tr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},$c=SN,MN=class extends $c{constructor(){super(...arguments),this.form="NFC"}},ON=MN,IN=class extends $c{constructor(){super(...arguments),this.form="NFD"}},CN=IN,PN=class extends $c{constructor(){super(...arguments),this.form="NFKC"}},NN=PN,LN=class extends $c{constructor(){super(...arguments),this.form="NFKD"}},zN=LN,$N=class extends Tr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},RN=$N,BN=class extends Tr{normalize(t){return e2(t)}},DN=BN,UN=class extends Tr{normalize(t){return t.toLowerCase()}},FN=UN,GN=class extends Tr{normalize(t){return t=this.config.prepend+t,t}},jN=GN;function qN(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new yN(t);case"Precompiled":return new vN(t);case"Sequence":return new EN(t);case"Replace":return new TN(t);case"NFC":return new ON(t);case"NFD":return new CN(t);case"NFKC":return new NN(t);case"NFKD":return new zN(t);case"Strip":return new RN(t);case"StripAccents":return new DN(t);case"Lowercase":return new FN(t);case"Prepend":return new jN(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var t2=qN,WN=class extends Io{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Jt=WN,r2=(()=>{let t=[...Array.from({length:94},(n,o)=>o+33),...Array.from({length:12},(n,o)=>o+161),...Array.from({length:82},(n,o)=>o+174)],e=t.slice(),r=0;for(let n=0;n<256;++n)t.includes(n)||(t.push(n),e.push(256+r),r+=1);let s=e.map(n=>String.fromCharCode(n));return Object.fromEntries(t.map((n,o)=>[n,s[o]]))})(),VN=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),HN=VN(r2),Lc="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",XN=class extends Jt{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=r2,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(s=>Array.from(this.text_encoder.encode(s),n=>this.byte_encoder[n]).join(""))}},KN=XN,YN=class extends Jt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},QN=YN,JN=class extends Jt{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:r=void 0}=e??{},s=t.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},ZN=JN,eL=class extends Jt{constructor(t){super(),this.config=t,this.pattern=zc(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?(t.match(this.pattern)||[]).filter(e=>e):this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):_N(t,this.pattern)}},tL=eL,rL=class extends Jt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Lc}]+|[${Lc}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},sL=rL,nL=class extends Jt{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},oL=nL,aL=class extends Jt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Lc}]+|[${Lc}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},iL=aL,lL=class extends Jt{constructor(t){super(),this.config=t,this.pattern=zc(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},cL=lL,uL=class extends Jt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>s2(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},pL=uL,fL=class extends Jt{pre_tokenize_text(t){return hN(t)}},dL=fL,mL=class extends Jt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;rthis.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){l=c;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},DA=wL,UA=class n2{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new n2(!1,new Map)}},xL=class{constructor(){this.root=UA.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let r of t){let s=e.children.get(r);s===void 0&&(s=UA.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t,e=0){let r=this.root;if(r===void 0)return;let s="";for(let n=e;n[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new md(this.bos_token_id??0,0,0,0,0),n=new md(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(n.clone()),this.begin_nodes[this.len].push(n),this.end_nodes[0].push(s)}insert(t,e,r,s){let n=this.nodes.length,o=new md(s,n,t,e,r);this.begin_nodes[t].push(o),this.end_nodes[t+e].push(o),this.nodes.push(o)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let a of this.begin_nodes[e]){a.prev=null;let i=0,l=null;for(let c of this.end_nodes[e]){let u=c.backtrace_score+a.score;(l===null||u>i)&&(l=c.clone(),i=u)}if(l!==null)a.prev=l,a.backtrace_score=i;else return[]}++e}let r=[],n=this.begin_nodes[t][0].prev;if(n===null)return[];let o=n.clone();for(;o.prev!==null;)r.push(o.clone()),o=o.clone().prev.clone();return r.reverse(),r}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},vL=bL;function kL(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=kL(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new yL,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;sr>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},ML=SL,OL=class extends Rc{constructor(t){super(t),this.tokens_to_ids=gd(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[r,s]of this.tokens_to_ids)this.vocab[s]=r;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(r=>r.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((r,s)=>[JSON.stringify(r),s])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new ML(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){let n=new TL((i,l)=>i.score`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},GA=OL,IL=class extends Rc{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=gd(e.target_lang?r[e.target_lang]:r),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[s,n]of this.tokens_to_ids)this.vocab[n]=s}encode(t){return t}},CL=IL;function PL(t,e){switch(t.type){case"WordPiece":return new DA(t);case"Unigram":return new FA(t,e.eos_token);case"BPE":return new GA(t);default:if(t.vocab)return Array.isArray(t.vocab)?new FA(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new GA(t):new DA(t):new CL(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var NL=PL,LL=class extends Io{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Co=LL,zL=class extends Co{post_process(t,e=null,r=!0){let s=e===null?this.config.single:this.config.pair,n=[],o=[];for(let a of s)"SpecialToken"in a?r&&(n.push(a.SpecialToken.id),o.push(a.SpecialToken.type_id)):"Sequence"in a&&(a.Sequence.id==="A"?(n=Qt(n,t),o=Qt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Qt(n,e),o=Qt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},$L=zL,RL=class extends Co{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},BL=RL,DL=class extends Co{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Qt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=[],o=r?[this.sep[0]]:[];t=Qt(t,n,e,o),s=Qt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},UL=DL,FL=class extends Co{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Qt([this.cls[0]],t,[this.sep[0]]));let s=new Array(t.length).fill(0);if(e){let n=r?[this.sep[0]]:[],o=r?[this.sep[0]]:[];t=Qt(t,n,e,o),s=Qt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},GL=FL,jL=class extends Co{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>a2(e))}post_process(t,e=null,r=!0){let s={tokens:t,tokens_pair:e};for(let n of this.processors)s=n.post_process(s.tokens,s.tokens_pair,r);return s}},qL=jL;function WL(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new $L(t);case"ByteLevel":return new BL(t);case"BertProcessing":return new UL(t);case"RobertaProcessing":return new GL(t);case"Sequence":return new qL(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var a2=WL,VL=class extends Io{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},jt=VL,HL=class extends jt{constructor(t){super(t),this.byte_decoder=HN,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),r=new Uint8Array([...e].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(t){let e=[],r=[];for(let s of t)this.added_tokens.find(n=>n.content===s)!==void 0?(r.length>0&&(e.push(this.convert_tokens_to_string(r)),r=[]),e.push(s)):r.push(s);return r.length>0&&e.push(this.convert_tokens_to_string(r)),e}},XL=HL,KL=class extends jt{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,r)=>{if(r!==0){let s=this.config.prefix;s&&e.startsWith(s)?e=e.replace(s,""):e=" "+e}return this.cleanup&&(e=_d(e)),e})}},YL=KL,QL=class extends jt{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;re.replaceAll(this.suffix,r===t.length-1?"":" "))}},ez=ZL,tz=class extends jt{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;nn!==this.pad_token).join("");return this.cleanup&&(s=_d(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},rz=tz,sz=class extends jt{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>i2(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},nz=sz,oz=class extends jt{constructor(t){super(t),this.pattern=zc(this.config.pattern)}decode_chain(t){let e=this.config.content??"",r=this.pattern;return r===null?t:t.map(s=>s.replaceAll(r,e))}},az=oz,iz=class extends jt{decode_chain(t){return[t.join("")]}},lz=iz,cz=class extends jt{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},fz=pz;function dz(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new XL(t);case"WordPiece":return new YL(t);case"Metaspace":return new JL(t);case"BPEDecoder":return new ez(t);case"CTC":return new rz(t);case"Sequence":return new nz(t);case"Replace":return new az(t);case"Fuse":return new lz(t);case"Strip":return new uz(t);case"ByteFallback":return new fz(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var i2=dz,mz=class{constructor(t,e){let r=BA(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=BA(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=t2(this.tokenizer.normalizer),this.pre_tokenizer=s2(this.tokenizer.pre_tokenizer),this.model=NL(this.tokenizer.model,this.config),this.post_processor=a2(this.tokenizer.post_processor),this.decoder=i2(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let n=[],o=[];this.added_tokens_map=new Map;for(let a of this.tokenizer.added_tokens){let i=new WP(a);if(this.added_tokens.push(i),this.model.tokens_to_ids.set(i.content,i.id),this.model.vocab[i.id]=i.content,i.special&&(this.special_tokens.push(i.content),this.all_special_ids.push(i.id)),this.added_tokens_map.set(i.content,i),i.normalized&&this.normalizer!==null){let l=this.normalizer(i.content);o.push(l),this.added_tokens_map.set(l,i)}else n.push(i.content)}(this.config.additional_special_tokens??[]).forEach(a=>{this.special_tokens.includes(a)||this.special_tokens.push(a)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new NA(n),this.splitter_normalized=new NA(o),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){let{tokens:n,token_type_ids:o}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}),a=n.map(l=>this.added_tokens_map.get(l)?.id??this.model.tokens_to_ids.get(l)??this.model.unk_token_id),i={ids:a,tokens:n,attention_mask:new Array(a.length).fill(1)};return s&&o&&(i.token_type_ids=o),i}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!fN(t[0]))throw Error("token_ids must be a non-empty array of integers.");let r=t.map(n=>this.model.vocab[Number(n)]??this.model.unk_token);e.skip_special_tokens&&(r=r.filter(n=>!this.special_tokens.includes(n)));let s=this.decoder?this.decoder(r):r.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(s=s.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=_d(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=mN(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Qt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;re in t?_z(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gz=(t,e,r)=>(hz(t,typeof e!="symbol"?e+"":e,r),r),D=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ExponentiationBinaryOperator:"ExponentiationBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),qt=class{constructor(t,e){this.value=t,this.type=e}};function c2(t){return/\w/.test(t)}function Ss(t){return/[0-9]/.test(t)}function u2(t){return/\s/.test(t)}var wz=[["{%",D.OpenStatement],["%}",D.CloseStatement],["{{",D.OpenExpression],["}}",D.CloseExpression],["(",D.OpenParen],[")",D.CloseParen],["{",D.OpenCurlyBracket],["}",D.CloseCurlyBracket],["[",D.OpenSquareBracket],["]",D.CloseSquareBracket],[",",D.Comma],[".",D.Dot],[":",D.Colon],["|",D.Pipe],["<=",D.ComparisonBinaryOperator],[">=",D.ComparisonBinaryOperator],["==",D.ComparisonBinaryOperator],["!=",D.ComparisonBinaryOperator],["<",D.ComparisonBinaryOperator],[">",D.ComparisonBinaryOperator],["+",D.AdditiveBinaryOperator],["-",D.AdditiveBinaryOperator],["~",D.AdditiveBinaryOperator],["**",D.ExponentiationBinaryOperator],["*",D.MultiplicativeBinaryOperator],["//",D.MultiplicativeBinaryOperator],["/",D.MultiplicativeBinaryOperator],["%",D.MultiplicativeBinaryOperator],["=",D.Equals]],xz=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function yz(t,e={}){return t.endsWith(` `)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs,(r,s,n,o,a)=>(n?"":s)+(o?"":a))}function bz(t,e={}){let r=[],s=yz(t,e),n=0,o=0,a=c=>{let u="";for(;c(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=xz.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);u+=m;continue}if(u+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return u},i=()=>{let c=r.at(-1);c&&c.type===D.Text&&(c.value=c.value.trimEnd(),c.value===""&&r.pop())},l=()=>{for(;n0){r.push(new qt(f,D.Text));continue}}if(s[n]==="{"&&s[n+1]==="#"){n+=2;let f=s[n]==="-";f&&++n;let m="";for(;s[n]!=="#"||s[n+1]!=="}";){if(n+2>=s.length)throw new SyntaxError("Missing end of comment tag");m+=s[n++]}let _=m.endsWith("-");_&&(m=m.slice(0,-1)),f&&i(),r.push(new qt(m,D.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new qt("{%",D.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new qt("{{",D.OpenExpression)),o=0,n+=3;continue}if(a(u2),s.slice(n,n+3)==="-%}"){r.push(new qt("%}",D.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new qt("}}",D.CloseExpression)),n+=3,l();continue}let u=s[n];if(u==="-"||u==="+"){let f=r.at(-1)?.type;if(f===D.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${u}`);switch(f){case D.Identifier:case D.NumericLiteral:case D.StringLiteral:case D.CloseParen:case D.CloseSquareBracket:break;default:{++n;let m=a(Ss);if(m.length>0&&s[n]==="."&&Ss(s[n+1])){++n;let _=a(Ss);m=`${m}.${_}`}r.push(new qt(`${u}${m}`,m.length>0?D.NumericLiteral:D.UnaryOperator));continue}}}for(let[f,m]of wz){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new qt(f,m)),m===D.OpenExpression?o=0:m===D.OpenCurlyBracket?++o:m===D.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(u==="'"||u==='"'){++n;let f=a(m=>m!==u);r.push(new qt(f,D.StringLiteral)),++n;continue}if(Ss(u)){let f=a(Ss);if(r.at(-1)?.type!==D.Dot&&s[n]==="."&&Ss(s[n+1])){++n;let m=a(Ss);f=`${f}.${m}`}r.push(new qt(f,D.NumericLiteral));continue}if(c2(u)){let f=a(c2);r.push(new qt(f,D.Identifier));continue}throw new SyntaxError(`Unexpected character: ${u}`)}return r}var Wt=class{type="Statement"},vz=class extends Wt{constructor(t){super(),this.body=t}type="Program"},kz=class extends Wt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},Ez=class extends Wt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},Az=class extends Wt{type="Break"},Tz=class extends Wt{type="Continue"},Sz=class extends Wt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},Mz=class extends Wt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},Oz=class extends Wt{constructor(t){super(),this.value=t}type="Comment"},Ct=class extends Wt{type="Expression"},Iz=class extends Ct{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},p2=class extends Ct{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Br=class extends Ct{constructor(t){super(),this.value=t}type="Identifier"},An=class extends Ct{constructor(t){super(),this.value=t}type="Literal"},Cz=class extends An{type="IntegerLiteral"},Pz=class extends An{type="FloatLiteral"},f2=class extends An{type="StringLiteral"},Nz=class extends An{type="ArrayLiteral"},d2=class extends An{type="TupleLiteral"},Lz=class extends An{type="ObjectLiteral"},En=class extends Ct{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},zz=class extends Ct{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},$z=class extends Wt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},Rz=class extends Ct{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},Bz=class extends Ct{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},m2=class extends Ct{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},Dz=class extends Ct{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},wd=class extends Ct{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},Uz=class extends Ct{constructor(t){super(),this.argument=t}type="SpreadExpression"},Fz=class extends Ct{constructor(t){super(),this.argument=t}type="KeywordSpreadExpression"},Gz=class extends Wt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},jz=class extends Ct{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function qz(t){let e=new vz([]),r=0;function s(L,z){let G=t[r++];if(!G||G.type!==L)throw new Error(`Parser Error: ${z}. ${G.type} !== ${L}.`);return G}function n(L){if(!l(L))throw new SyntaxError(`Expected ${L}`);++r}function o(){switch(t[r].type){case D.Comment:return new Oz(t[r++].value);case D.Text:return c();case D.OpenStatement:return u();case D.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...L){return r+L.length<=t.length&&L.every((z,G)=>z===t[r+G].type)}function i(...L){return t[r]?.type===D.OpenStatement&&t[r+1]?.type===D.Identifier&&L.includes(t[r+1]?.value)}function l(...L){return r+L.length<=t.length&&L.every((z,G)=>t[r+G].type==="Identifier"&&z===t[r+G].value)}function c(){return new f2(s(D.Text,"Expected text token").value)}function u(){if(s(D.OpenStatement,"Expected opening statement token"),t[r].type!==D.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let L=t[r].value,z;switch(L){case"set":++r,z=m();break;case"if":++r,z=_(),s(D.OpenStatement,"Expected {% token"),n("endif"),s(D.CloseStatement,"Expected %} token");break;case"macro":++r,z=w(),s(D.OpenStatement,"Expected {% token"),n("endmacro"),s(D.CloseStatement,"Expected %} token");break;case"for":++r,z=b(),s(D.OpenStatement,"Expected {% token"),n("endfor"),s(D.CloseStatement,"Expected %} token");break;case"call":{++r;let G=null;a(D.OpenParen)&&(G=F("parameters"));let ge=me();if(ge.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let ie=F("call");s(D.CloseStatement,"Expected closing statement token");let ot=[];for(;!i("endcall");)ot.push(o());s(D.OpenStatement,"Expected '{%'"),n("endcall"),s(D.CloseStatement,"Expected closing statement token");let Fe=new p2(ge,ie);z=new Gz(Fe,G,ot);break}case"break":++r,s(D.CloseStatement,"Expected closing statement token"),z=new Az;break;case"continue":++r,s(D.CloseStatement,"Expected closing statement token"),z=new Tz;break;case"filter":{++r;let G=me();G instanceof Br&&a(D.OpenParen)&&(G=j(G)),s(D.CloseStatement,"Expected closing statement token");let ge=[];for(;!i("endfilter");)ge.push(o());s(D.OpenStatement,"Expected '{%'"),n("endfilter"),s(D.CloseStatement,"Expected '%}'"),z=new $z(G,ge);break}default:throw new SyntaxError(`Unknown statement type: ${L}`)}return z}function f(){s(D.OpenExpression,"Expected opening expression token");let L=A();return s(D.CloseExpression,"Expected closing expression token"),L}function m(){let L=x(),z=null,G=[];if(a(D.Equals))++r,z=x();else{for(s(D.CloseStatement,"Expected %} token");!i("endset");)G.push(o());s(D.OpenStatement,"Expected {% token"),n("endset")}return s(D.CloseStatement,"Expected closing statement token"),new Sz(L,z,G)}function _(){let L=A();s(D.CloseStatement,"Expected closing statement token");let z=[],G=[];for(;!i("elif","else","endif");)z.push(o());if(i("elif")){++r,++r;let ge=_();G.push(ge)}else if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endif");)G.push(o());return new kz(L,z,G)}function w(){let L=me();if(L.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let z=F("parameters");s(D.CloseStatement,"Expected closing statement token");let G=[];for(;!i("endmacro");)G.push(o());return new Mz(L,z,G)}function x(L=!1){let z=L?me:A,G=[z()],ge=a(D.Comma);for(;ge&&(++r,G.push(z()),!!a(D.Comma)););return ge?new d2(G):G[0]}function b(){let L=x(!0);if(!(L instanceof Br||L instanceof d2))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${L.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let z=A();s(D.CloseStatement,"Expected closing statement token");let G=[];for(;!i("endfor","else");)G.push(o());let ge=[];if(i("else"))for(++r,++r,s(D.CloseStatement,"Expected closing statement token");!i("endfor");)ge.push(o());return new Ez(L,z,G,ge)}function A(){return k()}function k(){let L=M();if(l("if")){++r;let z=M();if(l("else")){++r;let G=k();return new jz(z,L,G)}else return new Rz(L,z)}return L}function M(){let L=S();for(;l("or");){let z=t[r];++r;let G=S();L=new En(z,L,G)}return L}function S(){let L=O();for(;l("and");){let z=t[r];++r;let G=O();L=new En(z,L,G)}return L}function O(){let L;for(;l("not");){let z=t[r];++r;let G=O();L=new m2(z,G)}return L??C()}function C(){let L=v();for(;;){let z;if(l("not","in"))z=new qt("not in",D.Identifier),r+=2;else if(l("in"))z=t[r++];else if(a(D.ComparisonBinaryOperator))z=t[r++];else break;let G=v();L=new En(z,L,G)}return L}function v(){let L=B();for(;a(D.AdditiveBinaryOperator);){let z=t[r];++r;let G=B();L=new En(z,L,G)}return L}function U(){let L=Q(me());return a(D.OpenParen)?j(L):L}function j(L){let z=new p2(L,F("call"));return z=Q(z),a(D.OpenParen)&&(z=j(z)),z}function F(L){s(D.OpenParen,"Expected opening parenthesis for arguments list");let z=K(L);return s(D.CloseParen,"Expected closing parenthesis for arguments list"),z}function K(L){let z=[],G=new Set,ge=!1,ie=!1;for(;!a(D.CloseParen);){let ot=a(D.ExponentiationBinaryOperator),Fe=a(D.MultiplicativeBinaryOperator)&&t[r].value==="*";if(L==="parameters"&&(ot||Fe))throw new SyntaxError("Argument unpacking is not allowed in parameter declarations");if(ot){if(++r,z.push(new Fz(A())),a(D.Comma)&&++r,!a(D.CloseParen))throw new SyntaxError("Expected closing parenthesis: `**` must be applied to the final argument");break}let Re;if(Fe){if(ie)throw new SyntaxError("Only one `*` argument unpacking is allowed");ie=!0,++r;let et=A();Re=new Uz(et)}else{if(Re=A(),a(D.Equals)){if(++r,!(Re instanceof Br))throw new SyntaxError(L==="parameters"?"Expected identifier for parameter declaration":"Expected identifier for keyword argument");let et=A();Re=new wd(Re,et)}if(L==="parameters"){if(!(Re instanceof Br||Re instanceof wd))throw new SyntaxError("Expected identifier for parameter declaration");let et=Re instanceof Br?Re.value:Re.key.value;if(G.has(et))throw new SyntaxError(`Duplicate parameter name: ${et}`);G.add(et)}if(Re instanceof wd)ge=!0;else{if(ge)throw new SyntaxError(L==="call"?"Positional arguments must come before keyword arguments":"Non-default argument follows default argument");if(ie)throw new SyntaxError("Positional arguments must not follow `*` argument unpacking")}}z.push(Re),a(D.Comma)&&++r}return z}function Y(){let L=[],z=!1;for(;!a(D.CloseSquareBracket);)a(D.Colon)?(L.push(void 0),++r,z=!0):(L.push(A()),a(D.Colon)&&(++r,z=!0));if(L.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(z){if(L.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Dz(...L)}return L[0]}function Q(L){for(;a(D.Dot)||a(D.OpenSquareBracket);){let z=t[r];++r;let G,ge=z.type===D.OpenSquareBracket;if(ge)G=Y(),s(D.CloseSquareBracket,"Expected closing square bracket");else if(G=me(),G.type!=="Identifier"&&G.type!=="IntegerLiteral")throw new SyntaxError("Expected identifier or integer following dot operator");L=new Iz(L,G,ge)}return L}function B(){let L=I();for(;a(D.MultiplicativeBinaryOperator);){let z=t[r++],G=I();L=new En(z,L,G)}return L}function I(){let L=oe();for(;a(D.ExponentiationBinaryOperator);){let z=t[r++],G=oe();L=new En(z,L,G)}return L}function oe(){let L=J();for(;l("is");){++r;let z=l("not");z&&++r;let G=me();if(!(G instanceof Br))throw new SyntaxError("Expected identifier for the test");L=new Bz(L,z,G)}return L}function J(){let L=Z();for(;a(D.Pipe);){++r;let z=me();if(!(z instanceof Br))throw new SyntaxError("Expected identifier for the filter");a(D.OpenParen)&&(z=j(z)),L=new zz(L,z)}return L}function Z(){let L=t[r];if(L&&(L.type===D.UnaryOperator||L.type===D.AdditiveBinaryOperator)&&(L.value==="-"||L.value==="+")){let z=t[r++],G=Z();return new m2(z,G)}return U()}function me(){let L=t[r++];switch(L.type){case D.NumericLiteral:{let z=L.value;return z.includes(".")?new Pz(Number(z)):new Cz(Number(z))}case D.StringLiteral:{let z=L.value;for(;a(D.StringLiteral);)z+=t[r++].value;return new f2(z)}case D.Identifier:return new Br(L.value);case D.OpenParen:{let z=x();return s(D.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),z}case D.OpenSquareBracket:{let z=[];for(;!a(D.CloseSquareBracket);)z.push(A()),a(D.Comma)&&++r;return++r,new Nz(z)}case D.OpenCurlyBracket:{let z=new Map;for(;!a(D.CloseCurlyBracket);){let G=A();s(D.Colon,"Expected colon between key and value in object literal");let ge=A();z.set(G,ge),a(D.Comma)&&++r}return++r,new Lz(z)}default:throw new SyntaxError(`Unexpected token: ${L.type}`)}}for(;r0)for(let n=t;ne;n+=r)s.push(n);return s}function _2(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*ae.toUpperCase())}function Hz(t){return Xz(new Date,t)}function Xz(t,e){let r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),n=o=>o<10?"0"+o:o.toString();return e.replace(/%[YmdbBHM%]/g,o=>{switch(o){case"%Y":return t.getFullYear().toString();case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%b":return s.format(t);case"%B":return r.format(t);case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%%":return"%";default:return o}})}function Kz(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yz(t,e,r,s){if(s===0)return t;let n=s==null||s<0?1/0:s,o=e.length===0?new RegExp("(?=)","gu"):new RegExp(Kz(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var h2=class extends Error{},g2=class extends Error{},Qz=new Map,tr=class{type="RuntimeValue";value;get builtins(){return Qz}constructor(t=void 0){this.value=t}__bool__(){return new fe(!!this.value)}toString(){return String(this.value)}},de=class extends tr{type="IntegerValue"},De=class extends tr{type="FloatValue";toString(){return Object.is(this.value,-0)?"-0.0":this.value%1===0?this.value.toFixed(1):this.value.toString()}},re=class extends tr{type="StringValue";_builtins;get builtins(){return this._builtins??=new Map([["upper",new Ke(()=>new re(this.value.toUpperCase()))],["lower",new Ke(()=>new re(this.value.toLowerCase()))],["strip",new Ke(()=>new re(this.value.trim()))],["title",new Ke(()=>new re(Vz(this.value)))],["capitalize",new Ke(()=>new re(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new de(this.value.length)],["rstrip",new Ke(()=>new re(this.value.trimEnd()))],["lstrip",new Ke(()=>new re(this.value.trimStart()))],["startswith",new Ke(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof re)return new fe(this.value.startsWith(e.value));if(e instanceof ke){for(let r of e.value){if(!(r instanceof re))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new fe(!0)}return new fe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ke(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof re)return new fe(this.value.endsWith(e.value));if(e instanceof ke){for(let r of e.value){if(!(r instanceof re))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new fe(!0)}return new fe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ke(t=>{let e=t[0]??new Ye;if(!(e instanceof re||e instanceof Ye))throw new Error("sep argument must be a string or null");let r=t[1]??new de(-1);if(!(r instanceof de))throw new Error("maxsplit argument must be a number");let s=[];if(e instanceof Ye){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ke(s.map(n=>new re(n)))})],["replace",new Ke(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof re&&r instanceof re))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new Ye:s=t[2]:s=new Ye,!(s instanceof de||s instanceof Ye))throw new Error("replace() count argument must be a number or null");return new re(Yz(this.value,e.value,r.value,s.value))})]])}},fe=class extends tr{type="BooleanValue"},Jz=/[\x7f-\uffff]/g;function w2(t){return t.replace(Jz,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function Ur(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,c;switch(a?[l,c]=a:n?(l=",",c=": "):(l=", ",c=": "),t.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(t.value);case"StringValue":{let u=JSON.stringify(t.value);return o&&(u=w2(u)),u}case"ArrayValue":case"NamespaceValue":case"ObjectValue":{let u=n?" ".repeat(n):"",f=` `+u.repeat(r),m=f+u;if(t.type==="ArrayValue"){let _=t.value.map(w=>Ur(w,e,r+1,s));return n?`[${m}${_.join(`${l}${m}`)}${f}]`:`[${_.join(l)}]`}else{let _=Array.from(t.value.entries());i&&(_=_.sort(([x],[b])=>x.localeCompare(b)));let w=_.map(([x,b])=>{let A=JSON.stringify(x);o&&(A=w2(A));let k=`${A}${c}${Ur(b,e,r+1,s)}`;return n?`${m}${k}`:k});return n?`{${w.join(l)}${f}}`:`{${w.join(l)}}`}}default:throw new Error(`Cannot convert to JSON: ${t.type}`)}}var At=class extends tr{type="ObjectValue";_builtins;__bool__(){return new fe(this.value.size>0)}get builtins(){return this._builtins??=new Map([["get",new Ke(([t,e])=>{if(!(t instanceof re))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??e??new Ye})],["items",new Ke(()=>this.items())],["keys",new Ke(()=>this.keys())],["values",new Ke(()=>this.values())],["dictsort",new Ke(t=>{let e=new Map,r=t.filter(i=>i instanceof Ms?(e=i.value,!1):!0),s=r.at(0)??e.get("case_sensitive")??new fe(!1);if(!(s instanceof fe))throw new Error("case_sensitive must be a boolean");let n=r.at(1)??e.get("by")??new re("key");if(!(n instanceof re))throw new Error("by must be a string");if(!["key","value"].includes(n.value))throw new Error("by must be either 'key' or 'value'");let o=r.at(2)??e.get("reverse")??new fe(!1);if(!(o instanceof fe))throw new Error("reverse must be a boolean");let a=Array.from(this.value.entries()).map(([i,l])=>new ke([new re(i),l])).sort((i,l)=>{let c=n.value==="key"?0:1,u=i.value[c],f=l.value[c],m=xd(u,f,s.value);return o.value?-m:m});return new ke(a)})]])}items(){return new ke(Array.from(this.value.entries()).map(([t,e])=>new ke([new re(t),e])))}keys(){return new ke(Array.from(this.value.keys()).map(t=>new re(t)))}values(){return new ke(Array.from(this.value.values()))}toString(){return Ur(this,{},0,!1)}},Ms=class extends At{type="KeywordArgumentsValue"},bd=class extends tr{type="NamespaceValue";toString(){return Ur(this,{},0,!1)}},ke=class extends tr{type="ArrayValue";_builtins;get builtins(){return this._builtins??=new Map([["length",new de(this.value.length)]])}__bool__(){return new fe(this.value.length>0)}toString(){return Ur(this,{},0,!1)}},x2=class extends ke{type="TupleValue"},Ke=class extends tr{type="FunctionValue"},Ye=class extends tr{type="NullValue"},Xe=class extends tr{type="UndefinedValue"};function Zz(t){let e;if(t instanceof ke?e=t.value:t instanceof re&&(e=Array.from(t.value,n=>new re(n))),!e||e.length!==2)throw new Error("namespace expected an object or an iterable of [key, value] pairs");let[r,s]=e;if(!(r instanceof re))throw new Error("namespace keys must be strings");return[r,s]}var k2=class{constructor(t){this.parent=t}variables=new Map([["namespace",new Ke(t=>{let e=t.slice(),r;if(e.at(-1)instanceof Ms&&(r=e.pop()),e.length>1)throw new Error(`namespace expected at most 1 argument, got ${e.length}`);let s=new Map;if(e.length===1){let n=e[0];if(n instanceof At)for(let[o,a]of n.value)s.set(o,a);else if(n instanceof ke)for(let o of n.value){let[a,i]=Zz(o);s.set(a.value,i)}else throw new Error(`'${n.type}' object is not iterable`)}if(r)for(let[n,o]of r.value)s.set(n,o);return new bd(s)})]]);tests=k2.TESTS;set(t,e){return this.declareVariable(t,Dc(e))}declareVariable(t,e){if(this.variables.has(t))throw new SyntaxError(`Variable already declared: ${t}`);return this.variables.set(t,e),e}setVariable(t,e){return this.variables.set(t,e),e}resolve(t){if(this.variables.has(t))return this;if(this.parent)return this.parent.resolve(t);throw new Error(`Unknown variable: ${t}`)}lookupVariable(t){try{return this.resolve(t).variables.get(t)??new Xe}catch{return new Xe}}},Dr=k2;gz(Dr,"TESTS",new Map([["boolean",t=>t.type==="BooleanValue"],["callable",t=>t instanceof Ke],["odd",t=>{if(!(t instanceof de))throw new Error(`cannot odd on ${t.type}`);return t.value%2!==0}],["even",t=>{if(!(t instanceof de))throw new Error(`cannot even on ${t.type}`);return t.value%2===0}],["false",t=>t.type==="BooleanValue"&&!t.value],["true",t=>t.type==="BooleanValue"&&t.value],["none",t=>t.type==="NullValue"],["string",t=>t.type==="StringValue"],["number",t=>t instanceof de||t instanceof De],["integer",t=>t instanceof de],["iterable",t=>t.type==="ArrayValue"||t.type==="StringValue"],["mapping",t=>t instanceof At],["sequence",t=>t instanceof ke||t instanceof At||t instanceof re],["lower",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toLowerCase()}],["upper",t=>{let e=t.value;return t.type==="StringValue"&&e===e.toUpperCase()}],["none",t=>t.type==="NullValue"],["defined",t=>t.type!=="UndefinedValue"],["undefined",t=>t.type==="UndefinedValue"],["equalto",(t,e)=>t.value===e.value],["eq",(t,e)=>t.value===e.value]]));function e$(t){t.set("false",!1),t.set("true",!0),t.set("none",null),t.set("raise_exception",e=>{throw new Error(e)}),t.set("range",Wz),t.set("strftime_now",Hz),t.set("True",!0),t.set("False",!1),t.set("None",null)}function Bc(t){return t instanceof At||t instanceof bd}function Uc(t){return t instanceof de||t instanceof De||t instanceof fe}function Fc(t){return t instanceof fe?Number(t.value):t.value}function y2(t,e){let r=e.split("."),s=t;for(let n of r)if(Bc(s))s=s.value.get(n)??new Xe;else if(s instanceof ke){let o=parseInt(n,10);if(!isNaN(o)&&o>=0&&on?1:0}if(t.type!==e.type)throw new Error(`Cannot compare different types: ${t.type} and ${e.type}`);if(t.type==="StringValue"){let s=t.value,n=e.value;return r||(s=s.toLowerCase(),n=n.toLowerCase()),sn?1:0}else throw new Error(`Cannot compare type: ${t.type}`)}function yd(t){if(t.type==="Identifier")return{name:t.value};let e=t;return{name:e.key.value,defaultValue:e.value}}function b2(t){return t==="kwargs"||t==="varargs"}function v2(t,e){let r=new Set,s=new Set,n=u=>{b2(u)&&r.add(u)},o=u=>{if(u.type==="Identifier")n(u.value);else if(u.type==="TupleLiteral")for(let f of u.value)o(f)},a=u=>{n(yd(u).name)},i=u=>{for(let f of u){let m=yd(f);m.defaultValue&&c(m.defaultValue)}},l=u=>{u.type==="CallExpression"&&c(u.args)},c=u=>{if(Array.isArray(u)){for(let f of u)c(f);return}if(u instanceof Map){for(let[f,m]of u)c(f),c(m);return}if(u instanceof Wt)switch(u.type){case"For":{let f=u;if(o(f.loopvar),f.iterable.type==="SelectExpression"){let m=f.iterable;c(m.lhs),c(f.body),c(f.defaultBlock),c(m.test);return}c(f.iterable),c(f.body),c(f.defaultBlock);return}case"Set":{let f=u;o(f.assignee),c(f.value),c(f.body);return}case"Macro":{let f=u;for(let m of f.args)a(m);i(f.args),c(f.body);return}case"CallStatement":{let f=u;c(f.call);for(let m of f.callerArgs??[])a(m);i(f.callerArgs??[]),c(f.body);return}case"FilterStatement":{let f=u;c(f.body),l(f.filter);return}case"Identifier":{let f=u.value;b2(f)&&!r.has(f)&&s.add(f);return}case"MemberExpression":{let f=u;c(f.object),f.computed&&c(f.property);return}case"FilterExpression":{let f=u;c(f.operand),l(f.filter);return}case"TestExpression":c(u.operand);return;case"SelectExpression":{let f=u;c(f.test),c(f.lhs);return}case"KeywordArgumentExpression":c(u.value);return;default:for(let f of Object.values(u))c(f)}};for(let u of t)a(u);return c(e),s}var t$=class{global;constructor(t){this.global=t??new Dr}run(t){return this.evaluate(t,this.global)}evaluateBinaryExpression(t,e){let r=this.evaluate(t.left,e);switch(t.operator.value){case"and":return r.__bool__().value?this.evaluate(t.right,e):r;case"or":return r.__bool__().value?r:this.evaluate(t.right,e)}let s=this.evaluate(t.right,e);switch(t.operator.value){case"==":return new fe(r.value==s.value);case"!=":return new fe(r.value!=s.value)}if(r instanceof Xe||s instanceof Xe){if(s instanceof Xe&&["in","not in"].includes(t.operator.value))return new fe(t.operator.value==="not in");throw new Error(`Cannot perform operation ${t.operator.value} on undefined values`)}else{if(r instanceof Ye||s instanceof Ye)throw new Error("Cannot perform operation on null values");if(t.operator.value==="~")return new re(r.value.toString()+s.value.toString());if(t.operator.value==="**"&&Uc(r)&&Uc(s)){let n=Fc(r),o=Fc(s);if(n===0&&o<0)throw new Error("0.0 cannot be raised to a negative power");let a=n**o;if(!Number.isFinite(a))throw new Error("Exponentiation result is not a finite real number");return r instanceof De||s instanceof De||o<0?new De(a):new de(a)}else if((r instanceof de||r instanceof De)&&(s instanceof de||s instanceof De)){let n=r.value,o=s.value;switch(t.operator.value){case"+":case"-":case"*":{let a=t.operator.value==="+"?n+o:t.operator.value==="-"?n-o:n*o;return r instanceof De||s instanceof De?new De(a):new de(a)}case"/":return new De(n/o);case"//":{let a=Math.floor(n/o);return r instanceof De||s instanceof De?new De(a):new de(a)}case"%":{let a=n%o;return r instanceof De||s instanceof De?new De(a):new de(a)}case"<":return new fe(n":return new fe(n>o);case">=":return new fe(n>=o);case"<=":return new fe(n<=o)}}else if(r instanceof ke&&s instanceof ke){if(t.operator.value==="+")return new ke(r.value.concat(s.value))}else if(s instanceof ke){let n=s.value.find(o=>o.value===r.value)!==void 0;switch(t.operator.value){case"in":return new fe(n);case"not in":return new fe(!n)}}}if((r instanceof re||s instanceof re)&&t.operator.value==="+")return new re(r.value.toString()+s.value.toString());if(r instanceof re&&s instanceof re)switch(t.operator.value){case"in":return new fe(s.value.includes(r.value));case"not in":return new fe(!s.value.includes(r.value))}if(r instanceof re&&s instanceof At)switch(t.operator.value){case"in":return new fe(s.value.has(r.value));case"not in":return new fe(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${t.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(t,e){let r=[],s=new Map,n=(o,a)=>{if(s.has(o))throw new Error(`Got multiple values for keyword argument '${o}'`);s.set(o,a)};for(let o of t)if(o.type==="SpreadExpression"){let a=o,i=this.evaluate(a.argument,e);if(!(i instanceof ke))throw new Error(`Cannot unpack non-iterable type: ${i.type}`);for(let l of i.value)r.push(l)}else o.type!=="KeywordArgumentExpression"&&o.type!=="KeywordSpreadExpression"&&r.push(this.evaluate(o,e));for(let o of t)if(o.type==="KeywordArgumentExpression"){let a=o;n(a.key.value,this.evaluate(a.value,e))}else if(o.type==="KeywordSpreadExpression"){let a=o,i=this.evaluate(a.argument,e);if(!(i instanceof At))throw new Error(`Argument after ** must be a mapping, not ${i.type}`);for(let[l,c]of i.value)n(l,c)}return[r,s]}applyFilter(t,e,r){if(e.type==="Identifier"){let s=e;if(s.value==="safe")return t;if(s.value==="tojson")return new re(Ur(t,{}));if(t instanceof ke)switch(s.value){case"list":return t;case"first":return t.value[0];case"last":return t.value[t.value.length-1];case"length":return new de(t.value.length);case"reverse":return new ke(t.value.slice().reverse());case"sort":return new ke(t.value.slice().sort((n,o)=>xd(n,o,!1)));case"join":return new re(t.value.map(n=>n.value).join(""));case"string":return new re(Ur(t,{},0,!1));case"unique":{let n=new Set,o=[];for(let a of t.value)n.has(a.value)||(n.add(a.value),o.push(a));return new ke(o)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(t instanceof re)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let n=t.builtins.get(s.value);if(n instanceof Ke)return n.value([],r);if(n instanceof de)return n;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new re(t.value.trim());case"indent":return new re(t.value.split(` `).map((n,o)=>o===0||n.length===0?n:" "+n).join(` `));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new de(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new De(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof de||t instanceof De)switch(s.value){case"abs":return t instanceof de?new de(Math.abs(t.value)):new De(Math.abs(t.value));case"int":return new de(Math.floor(t.value));case"float":return new De(t.value);case"string":return new re(t.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof At)switch(s.value){case"items":return new ke(Array.from(t.value.entries()).map(([n,o])=>new ke([new re(n),o])));case"length":return new de(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof Ke?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof fe)switch(s.value){case"bool":return new fe(t.value);case"int":return new de(t.value?1:0);case"float":return new De(t.value?1:0);case"string":return new re(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new Ye;if(!(a instanceof de||a instanceof Ye))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new fe(!1);if(!(i instanceof fe))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new fe(!1);if(!(l instanceof fe))throw new Error("If set, sort_keys must be a boolean");let c=o.get("separators")??new Ye,u=null;if(c instanceof ke||c instanceof x2){if(c.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=c.value;if(!(f instanceof re)||!(m instanceof re))throw new Error("separators must be a tuple of two strings");u=[f.value,m.value]}else if(!(c instanceof Ye))throw new Error("If set, separators must be a tuple of two strings");return new re(Ur(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:u}))}else if(n==="join"){let o;if(t instanceof re)o=Array.from(t.value);else if(t instanceof ke)o=t.value.map(c=>c.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new re("");if(!(l instanceof re))throw new Error("separator must be a string");return new re(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new de(0):new De(0));if(t instanceof re){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new de(l):new De(l)}else{if(t instanceof de||t instanceof De)return t;if(t instanceof fe)return n==="int"?new de(t.value?1:0):new De(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new re(""),l=o[1]??a.get("boolean")??new fe(!1);if(!(l instanceof fe))throw new Error("`default` filter flag must be a boolean");return t instanceof Xe||l.value&&!t.__bool__().value?i:t}if(t instanceof ke){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new fe(!1);if(!(i instanceof fe))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new fe(!1);if(!(l instanceof fe))throw new Error("case_sensitive must be a boolean");let c=o.at(2)??a.get("attribute")??new Ye;if(!(c instanceof re||c instanceof de||c instanceof Ye))throw new Error("attribute must be a string, integer, or null");let u=f=>{if(c instanceof Ye)return f;let m=c instanceof de?String(c.value):c.value;return y2(f,m)};return new ke(t.value.slice().sort((f,m)=>{let _=u(f),w=u(m),x=xd(_,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!Bc(f)))throw new Error(`\`${n}\` can only be applied to array of objects`);if(s.args.some(f=>f.type!=="StringLiteral"))throw new Error(`arguments of \`${n}\` must be strings`);let[a,i,l]=s.args.map(f=>this.evaluate(f,r)),c;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);c=f}else c=(...f)=>f[0].__bool__().value;let u=t.value.filter(f=>{let m=f.value.get(a.value),_=m?c(m,l):!1;return o?_:!_});return new ke(u)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof re))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(c=>{if(!Bc(c))throw new Error("items in map must be an object");let u=y2(c,a.value);return u instanceof Xe?i??new Xe:u});return new ke(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof re){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new de(4);if(!(i instanceof de))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new fe(!1),c=o.at(2)??a.get("blank")??new fe(!1),u=t.value.split(` `),f=" ".repeat(i.value),m=u.map((_,w)=>!l.value&&w===0||!c.value&&_.length===0?_:f+_);return new re(m.join(` `))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof Ke))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new Ms(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof At){let o=t.builtins.get(n);if(o&&o instanceof Ke){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new Ms(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new fe(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new Xe}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);switch(t.operator.value){case"not":return new fe(!r.value);case"+":case"-":{let s=t.operator.value==="-"?-1:1;if(r instanceof de||r instanceof De||r instanceof fe){let n=r instanceof fe?r.value?1:0:r.value,o=s*n;return r instanceof De?new De(o):new de(o)}throw new SyntaxError(`Unknown operator "${t.operator.value}" for ${r.type}`)}default:throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new re(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new Ms(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ke||t instanceof re))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof de||s instanceof Xe))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof de||n instanceof Xe))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof de||o instanceof Xe))throw new Error("Slice step must be numeric or undefined");return t instanceof ke?new ke(_2(t.value,s.value,n.value,o.value)):new re(_2(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else t.property.type==="IntegerLiteral"?s=new de(t.property.value):s=new re(t.property.value);let n;if(Bc(r)){if(!(s instanceof re))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??(r instanceof At?r.builtins.get(s.value):void 0)}else if(r instanceof ke||r instanceof re)if(s instanceof de)n=r.value.at(s.value),r instanceof re&&(n=new re(r.value.at(s.value)));else if(s instanceof re)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof re))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof tr?n:new Xe}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ke))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o_.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let _=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(_.value.length!==w.value.length)throw new Error(`Too ${_.value.length>w.value.length?"few":"many"} items to unpack`);m=x=>{for(let b=0;b<_.value.length;++b){if(_.value[b].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_.value[b].type}`);x.setVariable(_.value[b].value,w.value[b])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(u),!this.evaluate(s,u).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let c=0;c0?o[c-1]:new Xe],["nextitem",c0)throw new Error(`macro ${t} takes no keyword argument '${a.keys().next().value}'`);if(r.has("varargs"))n.setVariable("varargs",new ke(o.slice(e.length)));else if(o.length>e.length)throw new Error(`macro ${t} takes not more than ${e.length} argument(s)`);for(let[l,c]of i)n.setVariable(l,this.evaluate(c,n))}evaluateMacro(t,e){let r=v2(t.args,t.body);return e.setVariable(t.name.value,new Ke((s,n)=>{let o=new Dr(n);return this.bindMacroArguments(`'${t.name.value}'`,t.args,r,s,o),this.evaluateBlock(t.body,o)})),new Ye}evaluateCallStatement(t,e){let r=t.callerArgs??[],s=v2(r,t.body),n=new Ke(c=>{let u=new Dr(e);return this.bindMacroArguments("None",r,s,c,u),this.evaluateBlock(t.body,u)}),[o,a]=this.evaluateArguments(t.call.args,e);o.push(new Ms(a));let i=this.evaluate(t.call.callee,e);if(i.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${i.type}`);let l=new Dr(e);return l.setVariable("caller",n),i.value(o,l)}evaluateFilterStatement(t,e){let r=this.evaluateBlock(t.body,e);return this.applyFilter(r,t.filter,e)}evaluate(t,e){if(!t)return new Xe;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"CallStatement":return this.evaluateCallStatement(t,e);case"Break":throw new h2;case"Continue":throw new g2;case"IntegerLiteral":return new de(t.value);case"FloatLiteral":return new De(t.value);case"StringLiteral":return new re(t.value);case"ArrayLiteral":return new ke(t.value.map(r=>this.evaluate(r,e)));case"TupleLiteral":return new x2(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof re))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new At(r)}case"Identifier":return this.evaluateIdentifier(t,e);case"CallExpression":return this.evaluateCallExpression(t,e);case"MemberExpression":return this.evaluateMemberExpression(t,e);case"UnaryExpression":return this.evaluateUnaryExpression(t,e);case"BinaryExpression":return this.evaluateBinaryExpression(t,e);case"FilterExpression":return this.evaluateFilterExpression(t,e);case"FilterStatement":return this.evaluateFilterStatement(t,e);case"TestExpression":return this.evaluateTestExpression(t,e);case"SelectExpression":return this.evaluateSelectExpression(t,e);case"Ternary":return this.evaluateTernaryExpression(t,e);case"Comment":return new Ye;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Dc(t){switch(typeof t){case"number":return Number.isInteger(t)?new de(t):new De(t);case"string":return new re(t);case"boolean":return new fe(t);case"undefined":return new Xe;case"object":return t===null?new Ye:Array.isArray(t)?new ke(t.map(Dc)):new At(new Map(Object.entries(t).map(([e,r])=>[e,Dc(r)])));case"function":return new Ke((e,r)=>{let s=t(...e.map(n=>n.value))??null;return Dc(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var pt=` `,r$="{%- ",s$=" -%}",tt=Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});function E2(t){switch(t.operator.type){case"ExponentiationBinaryOperator":return tt.EXPONENTIATION;case"MultiplicativeBinaryOperator":return tt.MULTIPLICATIVE;case"AdditiveBinaryOperator":return tt.ADDITIVE;case"ComparisonBinaryOperator":return tt.COMPARISON;case"Identifier":return t.operator.value==="and"?tt.LOGICAL_AND:t.operator.value==="in"||t.operator.value==="not in"?tt.COMPARISON:tt.LOGICAL_OR}return tt.LOGICAL_OR}function A2(t){switch(t.type){case"SelectExpression":case"Ternary":return tt.CONDITIONAL;case"BinaryExpression":return E2(t);case"UnaryExpression":return t.operator.value==="not"?tt.LOGICAL_NOT:tt.UNARY_SIGN;case"TestExpression":return tt.TEST;case"FilterExpression":return tt.FILTER;default:return tt.ATOM}}function Zt(t,e){let r=Qe(t);return A2(t)o$(s,e,r)).join(pt)}function Gc(t){return t.map(e=>Qe(e)).join(", ")}function o$(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return er(t.body,e,r);case"If":return a$(t,e,r);case"For":return i$(t,e,r);case"Set":return l$(t,e,r);case"Macro":return c$(t,e,r);case"Break":return s+bt("break");case"Continue":return s+bt("continue");case"CallStatement":return u$(t,e,r);case"FilterStatement":return p$(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+Qe(t)+" -}}"}}function a$(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+bt("if",Qe(n[0].test))+pt+er(n[0].body,e+1,r);for(let i=1;i0&&(a+=pt+s+bt("else")+pt+er(o.alternate,e+1,r)),a+=pt+s+bt("endif"),a}function i$(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${Qe(a.lhs)} if ${Qe(a.test)}`}else n=Qe(t.iterable);let o=s+bt("for",Qe(t.loopvar),"in",n)+pt+er(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=pt+s+bt("else")+pt+er(t.defaultBlock,e+1,r)),o+=pt+s+bt("endfor"),o}function l$(t,e,r){let s=r.repeat(e),n=Qe(t.assignee),o=t.value?Qe(t.value):"",a=s+bt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+pt+er(t.body,e+1,r)+pt+s+bt("endset")}function c$(t,e,r){let s=r.repeat(e),n=Gc(t.args);return s+bt("macro",`${t.name.value}(${n})`)+pt+er(t.body,e+1,r)+pt+s+bt("endmacro")}function u$(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${Gc(t.callerArgs)})`:"",o=Qe(t.call),a=s+bt(`call${n}`,o)+pt;return a+=er(t.body,e+1,r)+pt,a+=s+bt("endcall"),a}function p$(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:Qe(t.filter),o=s+bt("filter",n)+pt;return o+=er(t.body,e+1,r)+pt,o+=s+bt("endfilter"),o}function Qe(t){switch(t.type){case"SpreadExpression":return`*${Qe(t.argument)}`;case"KeywordSpreadExpression":return`**${Qe(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":{let e=t.value;return Object.is(e,-0)?"-0.0":e%1===0?e.toFixed(1):e.toString()}case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let e=t,r=E2(e),s=Zt(e.left,r),n=Zt(e.right,r+1);return`${s} ${e.operator.value} ${n}`}case"UnaryExpression":{let e=t,r=e.argument.type==="UnaryExpression"?A2(e):tt.ATOM;return e.operator.value+(e.operator.value==="not"?" ":"")+Zt(e.argument,r)}case"CallExpression":{let e=t,r=Gc(e.args);return`${Qe(e.callee)}(${r})`}case"MemberExpression":{let e=t,r=Zt(e.object,tt.ATOM),s=Qe(e.property);return!e.computed&&e.property.type!=="Identifier"&&e.property.type!=="IntegerLiteral"&&(s=`(${s})`),e.computed?`${r}[${s}]`:`${r}.${s}`}case"FilterExpression":{let e=t,r=Zt(e.operand,tt.FILTER);return e.filter.type==="CallExpression"?`${r} | ${Qe(e.filter)}`:`${r} | ${e.filter.value}`}case"SelectExpression":{let e=t;return`${Zt(e.lhs,tt.LOGICAL_OR)} if ${Zt(e.test,tt.LOGICAL_OR)}`}case"TestExpression":{let e=t;return`${Zt(e.operand,tt.TEST)} is${e.negate?" not":""} ${e.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let e=Gc(t.value),r=t.type==="ArrayLiteral"?"[]":"()";return`${r[0]}${e}${r[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([r,s])=>`${Qe(r)}: ${Qe(s)}`).join(", ")}}`;case"SliceExpression":{let e=t,r=e.start?Qe(e.start):"",s=e.stop?Qe(e.stop):"",n=e.step?`:${Qe(e.step)}`:"";return`${r}:${s}${n}`}case"KeywordArgumentExpression":{let e=t;return`${e.key.value}=${Qe(e.value)}`}case"Ternary":{let e=t;return`${Zt(e.trueExpr,tt.LOGICAL_OR)} if ${Zt(e.condition,tt.LOGICAL_OR)} else ${Zt(e.falseExpr,tt.CONDITIONAL)}`}default:throw new Error(`Unknown expression type: ${t.type}`)}}var T2=class{parsed;constructor(t){let e=bz(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=qz(e)}render(t){let e=new Dr;if(e$(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new t$(e).run(this.parsed).value}format(t){return n$(this.parsed,t?.indent||" ")}};var f$={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"},Fr=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=xt.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=xt.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=xt.createReadStream(e);this.body=new ReadableStream({start(n){s.on("data",o=>n.enqueue(o)),s.on("end",()=>n.close()),s.on("error",o=>n.error(o))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let e=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",f$[e]??"application/octet-stream")}clone(){let e=new t(this.filePath);return e.exists=this.exists,e.status=this.status,e.statusText=this.statusText,e.headers=new Headers(this.headers),e}async arrayBuffer(){return(await xt.promises.readFile(this.filePath)).buffer}async blob(){let e=await xt.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await xt.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}};var Gr=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(le.IS_CRYPTO_AVAILABLE){let i=new Uint32Array(1);crypto.getRandomValues(i),e=i[0]}else e=Date.now()>>>0;Number.isSafeInteger(e)&&(e=Math.abs(e));let r=this._mt,s=(i,l)=>Math.imul(i,l)>>>0,n=[];for(let i=e||0;i>0;i=Math.floor(i/4294967296))n.push(i&4294967295);n.length||n.push(0),r[0]=19650218;for(let i=1;i<624;++i)r[i]=s(1812433253,r[i-1]^r[i-1]>>>30)+i>>>0;let o=1,a=0;for(let i=Math.max(624,n.length);i>0;--i,++o,++a)o>=624&&(r[0]=r[623],o=1),a>=n.length&&(a=0),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1664525))+n[a]+a>>>0;for(let i=623;i>0;--i,++o)o>=624&&(r[0]=r[623],o=1),r[o]=(r[o]^s(r[o-1]^r[o-1]>>>30,1566083941))-o>>>0;r[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let s=0;s<624;++s){let n=e[s]&2147483648|e[(s+1)%624]&2147483647;e[s]=(e[(s+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let r=e[this._idx++];return r^=r>>>11,r^=r<<7&2636928640,r^=r<<15&4022730752,r^=r>>>18,r>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,r=1){let s=this._gauss_next;if(this._gauss_next=null,s===null){let n=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));s=Math.cos(n)*o,this._gauss_next=Math.sin(n)*o}return e+s*r}shuffle(e){for(let r=e.length-1;r>0;--r){let s=32-Math.clz32(r+1),n=this._int32()>>>32-s;for(;n>r;)n=this._int32()>>>32-s;let o=e[r];e[r]=e[n],e[n]=o}}choices(e,r){return e[S2(this._random_fn,r)]}};function S2(t,e){let r=0;for(let n=0;nS2(Os.random,t);var d$=new Gr,Tn=class{constructor(e){this.path=e}async match(e){let r=Gt.join(this.path,e),s=new Fr(r);if(s.exists)return s}async put(e,r,s=void 0){let n=Gt.join(this.path,e),o=le.IS_PROCESS_AVAILABLE?process.pid:Date.now(),a=d$._int32().toString(36),i=n+`.tmp.${o}.${a}`;try{let l=r.headers.get("Content-Length"),c=parseInt(l??"0"),u=0;await xt.promises.mkdir(Gt.dirname(n),{recursive:!0});let f=xt.createWriteStream(i),m=r.body.getReader();for(;;){let{done:_,value:w}=await m.read();if(_)break;await new Promise((b,A)=>{f.write(w,k=>{if(k){A(k);return}b()})}),u+=w.length;let x=c?u/c*100:0;s?.({progress:x,loaded:u,total:c})}await new Promise((_,w)=>{f.close(x=>x?w(x):_())}),await xt.promises.rename(i,n)}catch(l){try{await xt.promises.unlink(i)}catch{}throw l}}async delete(e){let r=Gt.join(this.path,e);try{return await xt.promises.unlink(r),!0}catch{return!1}}};var O2={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"},jc=100,I2=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Po(...t){return t=t.map((e,r)=>(r&&(e=e.replace(new RegExp("^/"),"")),r!==t.length-1&&(e=e.replace(new RegExp("/$"),"")),e)),t.join("/")}function Sr(t,e=null,r=null){let s;try{s=new URL(t)}catch{return!1}return!(e&&!e.includes(s.protocol)||r&&!r.includes(s.hostname))}function C2(t){return!(!I2.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function Sn(t,e={},...r){return JSON.stringify([t,e.revision??"main",e.cache_dir??null,e.local_files_only??!1,...r])}var Is=class extends Error{constructor(e,{status:r=null}={}){super(e),this.name="ModelFileNotFoundError",this.status=r}},m$=new Set([401,403,404]);function qc(t,e,r){if(!r)return null;let n=`${O2[t]??`Error (${t}) occurred while trying to load file`}: "${e}".`;throw m$.has(t)?new Is(n,{status:t}):Error(n)}async function P2(t,e,r){let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):r??0;s===null&&!r&&te.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let o=new Uint8Array(n),a=0,i=t.body.getReader();async function l(){let{done:c,value:u}=await i.read();if(c)return;let f=a+u.length;if(f>n){n=f;let _=new Uint8Array(n);_.set(o),o=_}o.set(u,a),a=f;let m=a/n*100;return e({progress:m,loaded:a,total:n}),l()}return await l(),o}function vd(t){return Sr(t,["blob:"])}function No(t,{allowUnresolved:e=!1}={}){let r;if(typeof location<"u"&&location.href)r=location.href;else if(typeof import.meta<"u"&&import.meta.url)r=import.meta.url;else return t;try{return new URL(t,r).href}catch(s){if(!e)throw s;return t}}var L2="SHA-256",_$="experimental_transformers-hash-cache",N2=t=>({algorithm:L2,value:t}),Lo=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(_$),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{let r=await this._getFileHash(e);if(r)try{let n=await(await navigator.crossOriginStorage.requestFileHandle(N2(r))).getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,r)=>{let s=await this._getFileHash(e);if(s){let n=await r.blob();await this._storeBlobInCOS(n,s)}else this._processAndStore(e,r.body)};_storeBlobInCOS=async(e,r)=>{let n=await(await navigator.crossOriginStorage.requestFileHandle(N2(r),{create:!0,origins:"*"})).createWritable();await n.write(e),await n.close()};_processAndStore=async(e,r)=>{try{let s=[];for await(let a of r)s.push(a);let n=new Blob(s),o=await this._getBlobHash(n);await this._storeBlobInCOS(n,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let r=await this._getHashCache(),s=await r.match(e);if(s)return s.text();let n=await this._getLfsFileHash(e);return n?(await r.put(e,new Response(n)),n):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;let r=e.replace("/resolve/","/raw/");try{let n=(await fetch(r).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return n?n[1]:null}catch{return null}};_getBlobHash=async e=>{let r=await e.arrayBuffer(),s=await crypto.subtle.digest(L2,r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function rr(t=null){let e=null;if(he.useCustomCache){if(!he.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!he.customCache.match||!he.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=he.customCache}if(!e&&he.experimental_useCrossOriginStorage&&Lo.isAvailable()&&(e=new Lo),!e&&he.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(he.cacheKey)}catch(r){te.warn("An error occurred while opening the browser cache:",r)}}if(!e&&he.useFSCache){if(!le.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Tn(t??he.cacheDir)}return e}async function z2(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}var Wc=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;let r=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,r),r}put(e,r){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,r),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}};var h$=100,kd=new Wc(h$);function Vc(t,e){let r=kd.get(t);if(r!==void 0)return r;let s=e().then(n=>n,n=>(kd.delete(t),Promise.reject(n)));return kd.put(t,s),s}async function g$(t){if(!Sr(t,["http:","https:"]))return null;let e=Ed(t);return e.set("Range","bytes=0-0"),he.fetch(t,{method:"GET",headers:e,cache:"no-store"})}function Pt(t,e,r={}){let s=Sn(t,r,e);return Vc(s,()=>w$(t,e,r))}async function w$(t,e,r){let s=await rr(r?.cache_dir),{localPath:n,remoteURL:o,proposedCacheKey:a,validModelId:i}=qr(t,e,r,s),l=await Wr(s,n,a);if(l!==void 0&&typeof l!="string"){let c=l.headers.get("content-length"),u=l.headers.get("content-type");return{exists:!0,size:c?parseInt(c,10):void 0,contentType:u||void 0,fromCache:!0}}if(he.allowLocalModels&&!Sr(n,["http:","https:"]))try{let u=await jr(n);if(typeof u!="string"&&u.status!==404){let f=u.headers.get("content-length"),m=u.headers.get("content-type");return{exists:!0,size:f?parseInt(f,10):void 0,contentType:m||void 0,fromCache:!1}}}catch{}if(he.allowRemoteModels&&!r.local_files_only&&i){let c=await g$(o);if(c&&c.status>=200&&c.status<300){let u,f=c.headers.get("content-type");if(c.status===206){let m=c.headers.get("content-range");if(m){let _=m.match(/bytes \d+-\d+\/(\d+)/);_&&(u=parseInt(_[1],10))}}else if(c.status===200)try{await c.body?.cancel()}catch{}if(u===void 0){let m=c.headers.get("content-length");u=m?parseInt(m,10):void 0}return{exists:!0,size:u,contentType:f||void 0,fromCache:!1}}c&&c.status!==404&&c.status!==416&&qc(c.status,o,!0)}return{exists:!1,fromCache:!1}}async function jr(t){return he.useFS&&!Sr(t,["http:","https:","blob:"])?new Fr(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t):he.fetch(t,{headers:Ed(t)})}function Ed(t){let e=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(e){let s=!!process.env?.TESTING_REMOTELY,n=he.version;if(r.set("User-Agent",`transformers.js/${n}; is_ci/${s};`),Sr(t,["http:","https:"],["huggingface.co","hf.co"])){let a=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;a&&r.set("Authorization",`Bearer ${a}`)}}return r}function qr(t,e,r={},s=null){let n=r.revision??"main",o=Po(t,e),a=C2(t),i=a?Po(he.localModelPath,o):o,l=Po(he.remoteHost,he.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),c=s instanceof Tn?n==="main"?o:Po(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:a}}async function Wr(t,e,r){if(t)return await z2(t,e,r)}async function x$(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0&&!(typeof Cache<"u"&&r instanceof Cache&&!Sr(No(s,{allowUnresolved:!0}),["http:","https:"])))if(o){if(typeof n!="string"){let i=new Headers(n.headers);i.set("content-length",o.byteLength.toString()),await r.put(s,new Response(o,{headers:i})).catch(l=>{te.warn(`Unable to add response to browser cache: ${l}.`)})}}else{let i=a.progress_callback?l=>fr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function y$(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:c,validModelId:u}=qr(t,e,s,o),f,m=!1,_;_=await Wr(o,i,c);let w=_!==void 0;if(w)f=c;else{if(he.allowLocalModels)if(Sr(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!he.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{_=await jr(i),f=i}catch(k){te.warn(`Unable to load from local path "${i}": "${k}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!he.allowRemoteModels){if(r)throw new Is(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!u)throw new Is(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await jr(l),_.status!==200)return qc(_.status,l,r);f=c}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}fr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(le.IS_NODE_ENV&&n)){let A;if(typeof _!="string")if(!s.progress_callback)A=new Uint8Array(await _.arrayBuffer());else if(w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))A=new Uint8Array(await _.arrayBuffer()),fr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A.length,total:A.length});else{let k,M=_.headers.get("content-length");if(M)k=parseInt(M,10);else try{let S=await Pt(t,e,s);S.size&&(k=S.size)}catch{}A=await P2(_,S=>{fr(s.progress_callback,{status:"progress",name:t,file:e,...S})},k)}x=A}if(m&&f&&typeof _!="string"&&await x$(t,e,o,f,_,x,s),le.IS_NODE_ENV&&n&&s.progress_callback&&typeof _!="string"){let A=parseInt(_.headers.get("content-length"),10)||0;fr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:A,total:A})}if(fr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!le.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof Fr)return _.filePath;let b=await o?.match(f);if(b instanceof Fr)return b.filePath;if(b instanceof Response)return new Uint8Array(await b.arrayBuffer());if(typeof b=="string")return b;throw new Error("Unable to get model file path or buffer.")}var Ad=new Map;async function zo(t,e,r=!0,s={},n=!1){if(!he.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!he.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}let o=Sn(t,s,e,r,n),{progress_callback:a}=s,i=a instanceof Ar?a.loads:Ad,l=i.get(o);return l||(fr(a,{status:"initiate",name:t,file:e}),l=rr(s.cache_dir).then(c=>y$(t,e,r,s,n,c)),i===Ad&&(l=l.finally(()=>Ad.delete(o))),i.set(o,l)),await l}async function $o(t,e,r=!0,s={}){let n=await zo(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function lt(t,e,r=!0,s={}){let n=await $o(t,e,r,s);return n===null?{}:JSON.parse(n)}function R2(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,c=n/r,u=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i=0;--c)l+=u%e[c]*o[c],u=Math.floor(u/e[c]);a[l]=t[i]}return[a,s]}function Ue(t){let e=Le(t)[0],r=t.map(o=>Math.exp(o-e)),s=r.reduce((o,a)=>o+a,0);return r.map(o=>o/s)}function Sd(t){let e=Le(t)[0],r=0;for(let o=0;oo-e-s)}function D2(t,e){let r=0;for(let s=0;se+r*r,0))}function Ro(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;se&&(e=t[s],r=s);return[e,r]}function U2(t){return t>0&&(t&t-1)===0}var Hc=class{constructor(e){if(this.size=e|0,this.size<=1||!U2(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;ss;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<>>n&3)<>>1);for(let n=0;n>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l>>1,a>>>1)}else for(l=0,c=0;l>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l>>1;for(let _=2;_>1;++u){let f=(u+1-e)**2/2,m=Math.sqrt(l**2+c**2)**f,_=f*Math.atan2(c,l),w=2*u;o[w]=m*Math.cos(_),o[w+1]=m*Math.sin(_),a[w]=o[w],a[w+1]=-o[w+1]}this._slicedChirpBuffer=o.subarray(r,s),this._f=new Hc(n>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,r,s){let n=this._buffer1,o=this._buffer2,a=this._outBuffer1,i=this._outBuffer2,l=this._chirpBuffer,c=this._slicedChirpBuffer,u=this._a;if(s)for(let f=0;f>1,w=r[_];n[f]=w*c[f],n[m]=w*c[m]}else for(let f=0;f=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function Cs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function G2(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function j2(t){let e=t.length,r=t[0].length,s=[e+1,r+1],n=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));n[0][0]=0;let o=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let u=1;u0||i>0;)switch(l.push(a-1),c.push(i-1),o[a][i]){case 0:--a,--i;break;case 1:--a;break;case 2:--i;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${a}, ${i}]. Please file a bug report.`)}return l.reverse(),c.reverse(),[l,c]}var q2=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l>10,m=l&1023;if(f===31)c=u|2139095040|m<<13;else if(f===0)if(m===0)c=u;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,c=u|_<<23|m<<13}else c=u|f+112<<23|m<<13;a[0]=c,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;otm,TRACE:()=>ru,TRACE_EVENT_BEGIN:()=>Kr,TRACE_EVENT_END:()=>Yr,TRACE_FUNC_BEGIN:()=>Rs,TRACE_FUNC_END:()=>Bs,Tensor:()=>sr,default:()=>Y$,env:()=>Je,registerBackend:()=>$s});var Zd=Object.defineProperty,v$=Object.getOwnPropertyDescriptor,k$=Object.getOwnPropertyNames,E$=Object.prototype.hasOwnProperty,A$=(t=>typeof Ts<"u"?Ts:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Ts<"u"?Ts:e)[r]}):t)(function(t){if(typeof Ts<"u")return Ts.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),Ae=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(s){throw r=[s],s}},Wo=(t,e)=>{for(var r in e)Zd(t,r,{get:e[r],enumerable:!0})},T$=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of k$(e))!E$.call(t,n)&&n!==r&&Zd(t,n,{get:()=>e[n],enumerable:!(s=v$(e,n))||s.enumerable});return t},tu=t=>T$(Zd({},"__esModule",{value:!0}),t),Bo,Vr,$s,V2,yT,bT=Ae(()=>{"use strict";Bo=new Map,Vr=[],$s=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Bo.get(t);if(s===void 0)Bo.set(t,{backend:e,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${r}`)}if(r>=0){let n=Vr.indexOf(t);n!==-1&&Vr.splice(n,1);for(let o=0;o{let e=Bo.get(t);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init(t)),await e.initPromise,e.initialized=!0,e.backend}catch(s){return r||(e.error=`${s}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},yT=async t=>{let e=t.executionProviders||[],r=e.map(l=>typeof l=="string"?l:l.name),s=r.length===0?Vr:r,n,o=[],a=new Set;for(let l of s){let c=await V2(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),S$=Ae(()=>{"use strict";bT()}),vT,M$=Ae(()=>{"use strict";vT="1.31.0-dev.20260911-2a43ec07e"}),Md,mt,kT=Ae(()=>{"use strict";M$(),Md="warning",mt={wasm:{},webgl:{},webgpu:{},versions:{common:vT},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);Md=t}},get logLevel(){return Md}},Object.defineProperty(mt,"logLevel",{enumerable:!0})}),Je,O$=Ae(()=>{"use strict";kT(),Je=mt}),ET,AT,I$=Ae(()=>{"use strict";ET=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,A=0,k=f,M=f*2,S=-1;i==="RGBA"?(A=0,k=f,M=f*2,S=f*3):i==="RGB"?(A=0,k=f,M=f*2):i==="RBG"&&(A=0,M=f,k=f*2),s=r.createImageData(n,o);for(let O=0;O{"use strict";em(),Kc=(t,e)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,A=c,k=c*2,M=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?M=c*3:l==="RBG"?(b=0,k=c,A=c*2):l==="BGR"&&(k=0,A=c,b=c*2);for(let S=0;S{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,Kc(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(Kc(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Kc(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},ST=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new $t({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},MT=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new $t({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},OT=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new $t({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},IT=(t,e,r)=>new $t({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),Ls,jo,Od,CT,P$=Ae(()=>{"use strict";Ls=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),jo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Od=!1,CT=()=>{if(!Od){Od=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Ls.set("int64",BigInt64Array),jo.set(BigInt64Array,"int64")),e&&(Ls.set("uint64",BigUint64Array),jo.set(BigUint64Array,"uint64")),s?(Ls.set("float16",r),jo.set(r,"float16")):Ls.set("float16",Uint16Array)}}}),PT,NT,N$=Ae(()=>{"use strict";em(),PT=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new $t(t.type,t.data,e);case"cpu-pinned":return new $t({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new $t({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new $t({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new $t({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),$t,em=Ae(()=>{"use strict";I$(),C$(),P$(),N$(),$t=class{constructor(t,e,r){CT();let s,n;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,s=t.type,n=t.dims,t.location){case"cpu-pinned":{let a=Ls.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(t.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=t.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,i;if(typeof t=="string")if(s=t,i=r,t==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");a=e}else{let l=Ls.get(t);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e)){if(t==="float16"&&l===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${l.name} as data.`);t==="uint64"||t==="int64"?a=l.from(e,BigInt):a=l.from(e)}else if(e instanceof l)a=e;else if(e instanceof Uint8ClampedArray)if(t==="uint8")a=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&e instanceof Uint16Array&&l!==Uint16Array)a=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(i=e,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof t[0];if(l==="string")s="string",a=t;else if(l==="boolean")s="bool",a=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(t instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(t);else{let l=jo.get(t.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);s=l,a=t}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=PT(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(t,e){return TT(t,e)}static fromTexture(t,e){return ST(t,e)}static fromGpuBuffer(t,e){return MT(t,e)}static fromMLTensor(t,e){return OT(t,e)}static fromPinnedBuffer(t,e,r){return IT(t,e,r)}toDataURL(t){return ET(this,t)}toImageData(t){return AT(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,t&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return NT(this,t)}}}),sr,LT=Ae(()=>{"use strict";em(),sr=$t}),ru,Id,Rs,Bs,Kr,Yr,zT=Ae(()=>{"use strict";kT(),ru=(t,e)=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.timeStamp(`${t}::ORT::${e}`)},Id=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||Id("BEGIN",t)},Bs=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||Id("END",t)},Kr=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.time(`ORT::${t}`)},Yr=t=>{(typeof mt.trace>"u"?!mt.wasm.trace:!mt.trace)||console.timeEnd(`ORT::${t}`)}}),$T,L$=Ae(()=>{"use strict";bT(),LT(),zT(),$T=class RT{constructor(e){this.handler=e}async run(e,r,s){Rs(),Kr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof sr||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof sr)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,u=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(u.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof sr)&&(c=!0,a=!1,n[f]=m)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof e[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(e,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let u=i[c];u instanceof sr?l[c]=u:l[c]=new sr(u.type,u.data,u.dims)}return Yr("InferenceSession.run"),Bs(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){Rs(),Kr("InferenceSession.create");let o,a={};if(typeof e=="string"){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let u=e,f=0,m=e.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(f=r,!Number.isSafeInteger(f))throw new RangeError("'byteOffset' must be an integer.");if(f<0||f>=u.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${u.byteLength}).`);if(m=e.byteLength-f,typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteLength' must be an integer.");if(m<=0||f+m>u.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${u.byteLength-f}].`);if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(u,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await yT(a),c=await i.createInferenceSessionHandler(o,l);return Yr("InferenceSession.create"),Bs(),new RT(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),tm,z$=Ae(()=>{"use strict";L$(),tm=$T}),$$=Ae(()=>{"use strict"}),R$=Ae(()=>{"use strict"}),B$=Ae(()=>{"use strict"}),D$=Ae(()=>{"use strict"}),BT={};Wo(BT,{InferenceSession:()=>tm,TRACE:()=>ru,TRACE_EVENT_BEGIN:()=>Kr,TRACE_EVENT_END:()=>Yr,TRACE_FUNC_BEGIN:()=>Rs,TRACE_FUNC_END:()=>Bs,Tensor:()=>sr,env:()=>Je,registerBackend:()=>$s});var Ds=Ae(()=>{"use strict";S$(),O$(),z$(),LT(),$$(),R$(),zT(),B$(),D$()}),rm=Ae(()=>{"use strict"}),DT={};Wo(DT,{default:()=>UT});var Cd,Pd,UT,U$=Ae(()=>{"use strict";tS(),Us(),sm(),Cd="ort-wasm-proxy-worker",Pd=globalThis.self?.name===Cd,Pd&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":nm(r.wasm).then(()=>{cm(r).then(()=>{postMessage({type:e})},s=>{postMessage({type:e,err:s})})},s=>{postMessage({type:e,err:s})});break;case"init-ep":{let{epName:s,env:n}=r;um(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=ou(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;pm(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":fm(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;dm(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},_m([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":mm(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),UT=Pd?null:t=>new Worker(t??Lt,{type:"module",name:Cd})}),FT={};Wo(FT,{default:()=>GT});async function H2(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(p,d)=>{p.startsWith("./")&&(p=p.substring(2)),(e.ed||(e.ed=new Map)).set(p,d)},e.unmountExternalData=()=>{delete e.ed,delete e.Te,delete e.Se,delete e.Ue},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let o=()=>{let p=d=>(...h)=>{let g=ur;return h=d(...h),ur!=g?new Promise((E,T)=>{qf={resolve:E,reject:T}}):h};(()=>{for(let d of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[d]=p(e[d])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(p,d)=>{throw d},c=import.meta.url,u="";if(r||s){try{u=new URL(".",c).href}catch{}s&&(i=p=>{var d=new XMLHttpRequest;return d.open("GET",p,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),a=async p=>{if(C(p))return new Promise((h,g)=>{var E=new XMLHttpRequest;E.open("GET",p,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?h(E.response):g(E.status)},E.onerror=g,E.send(null)});var d=await fetch(p,{credentials:"same-origin"});if(d.ok)return d.arrayBuffer();throw Error(d.status+" : "+d.url)}}var f,m,_,w,x,b,A=console.log.bind(console),k=console.error.bind(console),M=A,S=k,O=!1,C=p=>p.startsWith("file://");function v(){zr.buffer!=F.buffer&&G()}if(n){let p=function(d){try{var h=d.data,g=h.$c;if(g==="load"){let E=[];self.onmessage=T=>E.push(T),b=()=>{postMessage({$c:"loaded"});for(let T of E)p(T);self.onmessage=p};for(let T of h.ue)e[T]&&!e[T].proxy||(e[T]=(...N)=>{postMessage({$c:"callHandler",te:T,args:N})},T=="print"&&(M=e[T]),T=="printErr"&&(S=e[T]));zr=h.Me,G(),m=h.Ne,Fe(),Mc()}else if(g==="run"){(function(E){var T=(v(),I)[E+52>>>2>>>0];E=(v(),I)[E+56>>>2>>>0],CE(T,T-E),ce(T)})(h.Xc),rd(h.Xc,0,0,1,0,0),pk(),Ff(h.Xc),j||(fE(),j=!0);try{xO(h.ze,h.kd)}catch(E){if(E!="unwind")throw E}}else h.target!=="setimmediate"&&(g==="checkMailbox"?j&&wc():g&&(S(`worker: received unknown command ${g}`),S(h)))}catch(E){throw TE(),E}};var U=p,j=!1;self.onunhandledrejection=d=>{throw d.reason||d},self.onmessage=p}var F,K,Y,Q,B,I,oe,J,Z,me,L,z=!1;function G(){var p=zr.buffer;e.HEAP8=F=new Int8Array(p),Y=new Int16Array(p),e.HEAPU8=K=new Uint8Array(p),Q=new Uint16Array(p),e.HEAP32=B=new Int32Array(p),e.HEAPU32=I=new Uint32Array(p),oe=new Float32Array(p),J=new Float64Array(p),Z=new BigInt64Array(p),me=new BigUint64Array(p)}function ge(){z=!0,n?b():Er.hc()}function ie(p){throw S(p="Aborted("+p+")"),O=!0,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),x?.(p),p}function ot(){return{a:{qa:jC,f:yO,K:bO,k:vO,p:kO,l:EO,fa:AO,b:TO,da:SO,gc:gk,q:MO,ea:bk,Ua:vk,cc:kk,ec:Ek,Va:Ak,Sa:Tk,La:Sk,Ra:Mk,oa:Ok,dc:Ik,ac:Ck,Ta:Pk,bc:Nk,_a:OO,Ba:CO,Xb:PO,Vb:LO,Aa:$O,O:RO,J:BO,Wb:DO,ka:VO,Yb:HO,Oa:XO,_b:YO,Ea:QO,Tb:JO,Ca:ZO,Na:Ff,Xa:eI,U:nI,n:cI,c:Df,qb:uI,w:pI,N:fI,A:dI,j:mI,o:Fk,rb:_I,H:hI,T:gI,g:wI,u:xI,m:yI,i:bI,Ia:vI,Ja:kI,Ka:EI,Ga:Wk,Ha:Vk,Ub:Hk,ab:TI,Za:OI,Z:II,pb:CI,Da:PI,Ya:SI,X:NI,Wa:LI,$b:zI,G:AI,db:$I,_:RI,pa:kc,Zb:DI,cb:BI,bb:UI,lb:ZI,z:eC,sa:tC,ra:rC,nb:sC,Y:nC,v:oC,kb:aC,jb:iC,ib:lC,mb:cC,gb:uC,fb:pC,eb:fC,Pa:nE,Qa:oE,fc:mn,W:aE,Fa:iE,ma:lE,Ma:cE,la:uE,Fb:SP,va:bP,Gb:TP,wa:yP,E:iP,e:HC,r:WC,x:qC,C:sP,Ib:gP,ca:hP,D:YC,xa:wP,aa:vP,ha:_P,Jb:mP,Kb:dP,za:cP,Lb:pP,ya:fP,Mb:uP,ua:AP,ba:xP,d:VC,B:KC,s:XC,Eb:MP,t:JC,y:oP,F:QC,I:ZC,L:aP,Nb:lP,R:kP,ia:rP,$:EP,Pb:tP,Rb:eP,Ob:nP,h:mC,a:zr,$a:dn,Hb:_C,V:hC,M:gC,na:wC,Db:xC,ja:yC,S:bC,Ab:vC,Bb:kC,vb:EC,wb:AC,P:TC,xb:SC,yb:MC,ta:OC,Sb:IC,ob:CC,Q:PC,hb:NC,Cb:LC,sb:zC,tb:RC,ub:BC,ga:DC,zb:UC,Qb:FC}}}async function Fe(){function p(g,E){var T=Er=g.exports;g={};for(let[N,P]of Object.entries(T))typeof P=="function"?(T=tI(P),g[N]=T):g[N]=P;return Er=g,Er=(function(){var N=Er,P=H=>xe=>H(xe)>>>0,R=H=>()=>H()>>>0;return(N=Object.assign({},N)).ic=P(N.ic),N.Nc=R(N.Nc),N.Pc=P(N.Pc),N.Bd=(H=>(xe,ve)=>H(xe,ve)>>>0)(N.Bd),N.Gd=P(N.Gd),N.Hd=R(N.Hd),N.Ld=P(N.Ld),N})(),ck.push(Er.sd),pE=(g=Er).ic,fE=g.jc,e._OrtInit=g.kc,e._OrtGetLastError=g.lc,e._OrtCreateSessionOptions=g.mc,e._OrtAppendExecutionProvider=g.nc,e._OrtAddFreeDimensionOverride=g.oc,e._OrtAddSessionConfigEntry=g.pc,e._OrtReleaseSessionOptions=g.qc,e._OrtCreateSession=g.rc,e._OrtReleaseSession=g.sc,e._OrtGetInputOutputCount=g.tc,e._OrtGetInputOutputMetadata=g.uc,e._OrtFree=g.vc,e._OrtCreateTensor=g.wc,e._OrtGetTensorData=g.xc,e._OrtReleaseTensor=g.yc,e._OrtCreateRunOptions=g.zc,e._OrtAddRunConfigEntry=g.Ac,e._OrtReleaseRunOptions=g.Bc,e._OrtCreateBinding=g.Cc,e._OrtBindInput=g.Dc,e._OrtBindOutput=g.Ec,e._OrtClearBoundOutputs=g.Fc,e._OrtReleaseBinding=g.Gc,e._OrtRunWithBinding=g.Hc,e._OrtRun=g.Ic,e._OrtEndProfiling=g.Jc,dE=e._OrtCreateWebGpuInstance=g.Kc,e._wgpuCreateInstance=g.Lc,Yf=e._OrtGetWebGpuDevice=g.Mc,Tc=g.Nc,Ft=e._free=g.Oc,ks=e._malloc=g.Pc,mE=e._wgpuBufferRelease=g.Qc,_E=g.Rc,hE=g.Sc,gE=g.Tc,wE=g.Uc,xE=g.Vc,yE=g.Yc,bE=g.Zc,vE=g.hd,kE=g.id,EE=g.jd,Qf=g.ld,Jf=g.md,Zf=g.nd,ed=g.od,So=g.pd,td=g.qd,AE=g.rd,rd=g.ud,TE=g.vd,SE=g.wd,ME=g.xd,sd=g.yd,OE=g.zd,IE=g.Ad,nd=g.Bd,be=g.Cd,Mo=g.Dd,CE=g.Ed,ce=g.Fd,Sc=g.Gd,ue=g.Hd,PE=g.Id,od=g.Jd,NE=g.Kd,LE=g.Ld,zE=g.Md,ad=g.Nd,$E=g.Od,RE=g.Pd,BE=g.Qd,DE=g.Rd,UE=g.Sd,FE=g.Td,GE=g.Ud,jE=g.Vd,qE=g.Wd,WE=g.Xd,VE=g.Yd,HE=g.Zd,XE=g._d,KE=g.$d,YE=g.ae,QE=g.be,JE=g.ce,ZE=g.de,eA=g.fe,tA=g.ge,rA=g.he,sA=g.ie,nA=g.je,oA=g.ke,aA=g.le,iA=g.me,lA=g.Ae,cA=g.Be,uA=g.Ce,pA=g.De,fA=g.Ee,dA=g.Fe,mA=g.Ge,_A=g.He,hA=g.Ie,gA=g.Je,wA=g.Ke,xA=g.nf,yA=g.of,bA=g.pf,vA=g.qf,m=E,Er}var d,h=ot();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(E,T)=>{g(p(E,T))})}):n?p(new WebAssembly.Instance(m,ot()),m):(L??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",u):u+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,d=await(async function(g){var E=L;if(!f&&!C(E))try{var T=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(T,g)}catch(N){S(`wasm streaming compile failed: ${N}`),S("falling back to ArrayBuffer instantiation")}return(async function(N,P){try{var R=await(async function(H){if(!f)try{var xe=await a(H);return new Uint8Array(xe)}catch{}if(H==L&&f)H=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";H=i(H)}return H})(N);return await WebAssembly.instantiate(R,P)}catch(H){S(`failed to asynchronously prepare wasm: ${H}`),ie(H)}})(E,g)})(h),p(d.instance,d.module))}class Re{name="ExitStatus";constructor(d){this.message=`Program terminated with exit(${d})`,this.status=d}}var et=p=>{p.terminate(),p.onmessage=()=>{}},qe=[],Ce=0,at=null,lr=p=>{Lr.length==0&&(dk(),fk(Lr[0]));var d=Lr.pop();if(!d)return 6;Ao.push(d),ys[p.Xc]=d,d.Xc=p.Xc;var h={$c:"run",ze:p.ye,kd:p.kd,Xc:p.Xc};return d.postMessage(h,p.oe),0},Pe=0,Ge=(p,d,...h)=>{var g,E=16*h.length,T=ue(),N=Sc(E),P=N>>>3;for(g of h)typeof g=="bigint"?((v(),Z)[P++>>>0]=1n,(v(),Z)[P++>>>0]=g):((v(),Z)[P++>>>0]=0n,(v(),J)[P++>>>0]=g);return p=SE(p,0,E,N,d),ce(T),p};function dn(p){if(n)return Ge(0,1,p);if(_=p,!(0{if(_=p,n)throw Eo(p),"unwind";dn(p)},Lr=[],Ao=[],ck=[],ys={},uk=p=>{var d=p.Xc;delete ys[d],Lr.push(p),Ao.splice(Ao.indexOf(p),1),p.Xc=0,ME(d)};function pk(){ck.forEach(p=>p())}var fk=p=>new Promise(d=>{p.onmessage=E=>{var T=E.data;if(E=T.$c,T.gd&&T.gd!=Tc()){var N=ys[T.gd];N?N.postMessage(T,T.oe):S(`Internal error! Worker sent a message "${E}" to target pthread ${T.gd}, but that thread no longer exists!`)}else E==="checkMailbox"?wc():E==="spawnThread"?lr(T):E==="cleanupThread"?St(()=>{uk(ys[T.Le])}):E==="loaded"?(p.loaded=!0,d(p)):T.target==="setimmediate"?p.postMessage(T):E==="uncaughtException"?p.onerror(T.error):E==="callHandler"?e[T.te](...T.args):E&&S(`worker sent an unknown command ${E}`)},p.onerror=E=>{throw S(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);p.postMessage({$c:"load",ue:g,Me:zr,Ne:m})});function dk(){var p=new Worker((()=>{let d=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new d("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Lr.push(p)}var zr,xO=(p,d)=>{Pe=0,p=ad(p,d),0-9007199254740992>p||9007199254740992>>=0);return(v(),F)[d.ad+12>>>0]==0&&(mk(d,!0),gc--),_k(d,!1),hc.push(d),LE(p)}var _n=0,bO=()=>{be(0,0);var p=hc.pop();PE(p.td),_n=0};function mk(p,d){d=d?1:0,(v(),F)[p.ad+12>>>0]=d}function _k(p,d){d=d?1:0,(v(),F)[p.ad+13>>>0]=d}class zf{constructor(d){this.td=d,this.ad=d-24}}var $f=p=>{var d=_n;if(!d)return Mo(0),0;var h=new zf(d);(v(),I)[h.ad+16>>>2>>>0]=d;var g=(v(),I)[h.ad+4>>>2>>>0];if(!g)return Mo(0),d;for(var E of p){if(E===0||E===g)break;if(NE(E,g,h.ad+16))return Mo(E),d}return Mo(g),d};function vO(){return $f([])}function kO(p){return $f([p>>>0])}function EO(p,d,h,g){return $f([p>>>0,d>>>0,h>>>0,g>>>0])}var AO=()=>{var p=hc.pop();p||ie("no exception to throw");var d=p.td;throw(v(),F)[p.ad+13>>>0]==0&&(hc.push(p),_k(p,!0),mk(p,!1),gc++),od(d),_n=d};function TO(p,d,h){var g=new zf(p>>>=0);throw d>>>=0,h>>>=0,(v(),I)[g.ad+16>>>2>>>0]=0,(v(),I)[g.ad+4>>>2>>>0]=d,(v(),I)[g.ad+8>>>2>>>0]=h,od(p),gc++,_n=p}var SO=()=>gc;function hk(p,d,h,g){return n?Ge(2,1,p,d,h,g):gk(p,d,h,g)}function gk(p,d,h,g){if(p>>>=0,d>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return n&&E.length===0?hk(p,d,h,g):(p={ye:h,Xc:p,kd:g,oe:E},n?(p.$c="spawnThread",postMessage(p,E),0):lr(p))}function MO(p){throw _n||=p>>>0,_n}var wk=globalThis.TextDecoder&&new TextDecoder,xk=(p,d,h,g)=>{if(h=d+h,g)return h;for(;p[d]&&!(d>=h);)++d;return d},yk=(p,d=0,h,g)=>{if(16<(h=xk(p,d>>>=0,h,g))-d&&p.buffer&&wk)return wk.decode(p.buffer instanceof ArrayBuffer?p.subarray(d,h):p.slice(d,h));for(g="";d(E=(240&E)==224?(15&E)<<12|T<<6|N:(7&E)<<18|T<<12|N<<6|63&p[d++])?g+=String.fromCharCode(E):(E-=65536,g+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else g+=String.fromCharCode(E)}return g},hn=(p,d,h)=>(p>>>=0)?yk((v(),K),p,d,h):"";function bk(p,d,h){return n?Ge(3,1,p,d,h):0}function vk(p,d){if(n)return Ge(4,1,p,d)}function kk(p,d){if(n)return Ge(5,1,p,d)}function Ek(p,d,h){if(n)return Ge(6,1,p,d,h)}function Ak(p,d,h){return n?Ge(7,1,p,d,h):0}function Tk(p,d){if(n)return Ge(8,1,p,d)}function Sk(p,d,h){if(n)return Ge(9,1,p,d,h)}function Mk(p,d,h,g){if(n)return Ge(10,1,p,d,h,g)}function Ok(p,d,h,g){if(n)return Ge(11,1,p,d,h,g)}function Ik(p,d,h,g){if(n)return Ge(12,1,p,d,h,g)}function Ck(p){if(n)return Ge(13,1,p)}function Pk(p,d){if(n)return Ge(14,1,p,d)}function Nk(p,d,h){if(n)return Ge(15,1,p,d,h)}var OO=()=>ie(""),cr=p=>{p>>>=0;for(var d="";;){var h=(v(),K)[p++>>>0];if(!h)return d;d+=String.fromCharCode(h)}},Rf={},Bf={},IO={},gn=class extends Error{constructor(p){super(p),this.name="BindingError"}};function yr(p,d,h={}){return(function(g,E,T={}){var N=E.name;if(!g)throw new gn(`type "${N}" must have a positive integer typeid pointer`);if(Bf.hasOwnProperty(g)){if(T.ve)return;throw new gn(`Cannot register type '${N}' twice`)}Bf[g]=E,delete IO[g],Rf.hasOwnProperty(g)&&(E=Rf[g],delete Rf[g],E.forEach(P=>P()))})(p,d,h)}var Lk=(p,d,h)=>{switch(d){case 1:return h?g=>(v(),F)[g>>>0]:g=>(v(),K)[g>>>0];case 2:return h?g=>(v(),Y)[g>>>1>>>0]:g=>(v(),Q)[g>>>1>>>0];case 4:return h?g=>(v(),B)[g>>>2>>>0]:g=>(v(),I)[g>>>2>>>0];case 8:return h?g=>(v(),Z)[g>>>3>>>0]:g=>(v(),me)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${d}): ${p}`)}};function CO(p,d,h,g,E){p>>>=0,h>>>=0,d=cr(d>>>0);let T=N=>N;if(g=g===0n){let N=8*h;T=P=>BigInt.asUintN(N,P),E=T(E)}yr(p,{name:d,Wc:T,cd:(N,P)=>(typeof P=="number"&&(P=BigInt(P)),P),bd:Lk(d,h,!g),dd:null})}function PO(p,d,h,g){yr(p>>>=0,{name:d=cr(d>>>0),Wc:function(E){return!!E},cd:function(E,T){return T?h:g},bd:function(E){return this.Wc((v(),K)[E>>>0])},dd:null})}var zk=[],bs=[0,1,,1,null,1,!0,1,!1,1];function Df(p){9<(p>>>=0)&&--bs[p+1]===0&&(bs[p]=void 0,zk.push(p))}var Ut=p=>{if(!p)throw new gn(`Cannot use deleted val. handle = ${p}`);return bs[p]},Kt=p=>{switch(p){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let d=zk.pop()||bs.length;return bs[d]=p,bs[d+1]=1,d}};function Uf(p){return this.Wc((v(),I)[p>>>2>>>0])}var NO={name:"emscripten::val",Wc:p=>{var d=Ut(p);return Df(p),d},cd:(p,d)=>Kt(d),bd:Uf,dd:null};function LO(p){return yr(p>>>0,NO)}var zO=(p,d)=>{switch(d){case 4:return function(h){return this.Wc((v(),oe)[h>>>2>>>0])};case 8:return function(h){return this.Wc((v(),J)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${d}): ${p}`)}};function $O(p,d,h){h>>>=0,yr(p>>>=0,{name:d=cr(d>>>0),Wc:g=>g,cd:(g,E)=>E,bd:zO(d,h),dd:null})}function RO(p,d,h,g,E){p>>>=0,h>>>=0,d=cr(d>>>0);let T=P=>P;if(g===0){var N=32-8*h;T=P=>P<>>N,E=T(E)}yr(p,{name:d,Wc:T,cd:(P,R)=>R,bd:Lk(d,h,g!==0),dd:null})}function BO(p,d,h){function g(T){var N=(v(),I)[T>>>2>>>0];return T=(v(),I)[T+4>>>2>>>0],new E((v(),F).buffer,T,N)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][d];yr(p>>>=0,{name:h=cr(h>>>0),Wc:g,bd:g},{ve:!0})}var br=(p,d,h)=>{var g=(v(),K);if(d>>>=0,0=N){if(d>=h)break;g[d++>>>0]=N}else if(2047>=N){if(d+1>=h)break;g[d++>>>0]=192|N>>6,g[d++>>>0]=128|63&N}else if(65535>=N){if(d+2>=h)break;g[d++>>>0]=224|N>>12,g[d++>>>0]=128|N>>6&63,g[d++>>>0]=128|63&N}else{if(d+3>=h)break;g[d++>>>0]=240|N>>18,g[d++>>>0]=128|N>>12&63,g[d++>>>0]=128|N>>6&63,g[d++>>>0]=128|63&N,T++}}g[d>>>0]=0,p=d-E}else p=0;return p},vr=p=>{for(var d=0,h=0;h=g?d++:2047>=g?d+=2:55296<=g&&57343>=g?(d+=4,++h):d+=3}return d};function DO(p,d){yr(p>>>=0,{name:d=cr(d>>>0),Wc(h){var g=(v(),I)[h>>>2>>>0];return g=hn(h+4,g,!0),Ft(h),g},cd(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var E=typeof g=="string";if(!(E||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new gn("Cannot pass non-string to std::string");var T=E?vr(g):g.length,N=ks(4+T+1),P=N+4;return(v(),I)[N>>>2>>>0]=T,E?br(g,P,T+1):(v(),K).set(g,P>>>0),h!==null&&h.push(Ft,N),N},bd:Uf,dd(h){Ft(h)}})}var $k=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,UO=(p,d,h)=>{if(p>>>=1,16<(d=xk((v(),Q),p,d/2,h))-p&&$k)return $k.decode((v(),Q).slice(p,d));for(h="";p>>0];h+=String.fromCharCode(g)}return h},FO=(p,d,h)=>{if(h??=2147483647,2>h)return 0;var g=d;h=(h-=2)<2*p.length?h/2:p.length;for(var E=0;E>>1>>>0]=T,d+=2}return(v(),Y)[d>>>1>>>0]=0,d-g},GO=p=>2*p.length,jO=(p,d,h)=>{var g="";p>>>=2;for(var E=0;!(E>=d/4);E++){var T=(v(),I)[p+E>>>0];if(!T&&!h)break;g+=String.fromCodePoint(T)}return g},qO=(p,d,h)=>{if(d>>>=0,h??=2147483647,4>h)return 0;var g=d;h=g+h-4;for(var E=0;E>>2>>>0]=T,(d+=4)+4>h)break}return(v(),B)[d>>>2>>>0]=0,d-g},WO=p=>{for(var d=0,h=0;h>>=0,d>>>=0,h=cr(h>>>=0),d===2)var g=UO,E=FO,T=GO;else g=jO,E=qO,T=WO;yr(p,{name:h,Wc:N=>{var P=(v(),I)[N>>>2>>>0];return P=g(N+4,P*d,!0),Ft(N),P},cd:(N,P)=>{if(typeof P!="string")throw new gn(`Cannot pass non-string to C++ string type ${h}`);var R=T(P),H=ks(4+R+d);return(v(),I)[H>>>2>>>0]=R/d,E(P,H+4,R+d),N!==null&&N.push(Ft,H),H},bd:Uf,dd(N){Ft(N)}})}function HO(p,d){yr(p>>>=0,{we:!0,name:d=cr(d>>>0),Wc:()=>{},cd:()=>{}})}function XO(p){rd(p>>>0,!s,1,!r,131072,!1),pk()}var St=p=>{if(!O)try{if(p(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ff(p){p>>>=0,KO||(Atomics.waitAsync((v(),B),p>>>2,p).value.then(wc),p+=128,Atomics.store((v(),B),p>>>2,1))}var wc=()=>St(()=>{var p=Tc();p&&(Ff(p),IE())});function YO(p,d){(p>>>=0)==d>>>0?setTimeout(wc):n?postMessage({gd:p,$c:"checkMailbox"}):(p=ys[p])&&p.postMessage({$c:"checkMailbox"})}var Gf=[];function QO(p,d,h,g,E){for(d>>>=0,E>>>=0,Gf.length=0,h=E>>>3,g=E+g>>>3;h>>0]?(v(),Z)[h++>>>0]:(v(),J)[h++>>>0],Gf.push(T)}return(d?id[d]:GC[p])(...Gf)}var JO=()=>{Pe=0};function ZO(p){p>>>=0,n?postMessage({$c:"cleanupThread",Le:p}):uk(ys[p])}function eI(p){}var xc=p=>{try{p()}catch(d){ie(d)}};function tI(p){var d=(...h)=>{yc.push(p);try{return p(...h)}finally{O||(yc.pop(),ur&&$r===1&&yc.length===0&&($r=0,Pe+=1,xc(yA),typeof Fibers<"u"&&Fibers.We()))}};return Dk.set(p,d),d}var $r=0,ur=null,Rk=0,yc=[],jf=new Map,Bk=new Map,Dk=new Map,rI=0,qf=null,sI=[],Uk=p=>(function(d){if(!O){if($r===0){var h=!1,g=!1;d((E=0)=>{if(!O&&(Rk=E,h=!0,g)){$r=2,xc(()=>bA(ur)),typeof MainLoop<"u"&&MainLoop.se&&MainLoop.resume(),E=!1;try{var T=(function(){var R=(v(),B)[ur+8>>>2>>>0];return R=Bk.get(R),R=Dk.get(R),--Pe,R()})()}catch(R){T=R,E=!0}var N=!1;if(!ur){var P=qf;P&&(qf=null,(E?P.reject:P.resolve)(T),N=!0)}if(E&&!N)throw T}}),g=!0,h||($r=1,ur=(function(){var E=ks(65548),T=E+12;if((v(),I)[E>>>2>>>0]=T,(v(),I)[E+4>>>2>>>0]=T+65536,T=yc[0],!jf.has(T)){var N=rI++;jf.set(T,N),Bk.set(N,T)}return T=jf.get(T),(v(),B)[E+8>>>2>>>0]=T,E})(),typeof MainLoop<"u"&&MainLoop.se&&MainLoop.pause(),xc(()=>xA(ur)))}else $r===2?($r=0,xc(vA),Ft(ur),ur=null,sI.forEach(St)):ie(`invalid state: ${$r}`);return Rk}})(d=>{p().then(d)});function nI(p){return p>>>=0,Uk(async()=>{var d=await Ut(p);return Kt(d)})}var Wf=[],oI=p=>{var d=Wf.length;return Wf.push(p),d},aI=(p,d)=>{for(var h=Array(p),g=0;g>>2>>>0],N=Bf[T];if(N===void 0)throw p=`parameter ${g}`,T=pE(T),d=cr(T),Ft(T),new gn(`${p} has unknown type ${d}`);h[E]=N}return h},iI=(p,d,h)=>{var g=[];return p=p(g,h),g.length&&((v(),I)[d>>>2>>>0]=Kt(g)),p},lI={},bc=p=>{var d=lI[p];return d===void 0?cr(p):d};function cI(p,d,h){var[g,...E]=aI(p,d>>>0);d=g.cd.bind(g);var T=E.map(R=>R.bd.bind(R));p--;var N={toValue:Ut};switch(p=T.map((R,H)=>{var xe=`argFromPtr${H}`;return N[xe]=R,`${xe}(args${H?"+"+8*H:""})`}),h){case 0:var P="toValue(handle)";break;case 2:P="new (toValue(handle))";break;case 3:P="";break;case 1:N.getStringOrSymbol=bc,P="toValue(handle)[getStringOrSymbol(methodName)]"}return P+=`(${p})`,g.we||(N.toReturnWire=d,N.emval_returnValue=iI,P=`return emval_returnValue(toReturnWire, destructorsRef, ${P})`),P=`return function (handle, methodName, destructorsRef, args) { ${P} }`,h=new Function(Object.keys(N),P)(...Object.values(N)),P=`methodCaller<(${E.map(R=>R.name)}) => ${g.name}>`,oI(Object.defineProperty(h,"name",{value:P}))}function uI(p,d){return d>>>=0,(p=Ut(p>>>0))==Ut(d)}function pI(p){return(p>>>=0)?(p=bc(p),Kt(globalThis[p])):Kt(globalThis)}function fI(p){return p=bc(p>>>0),Kt(e[p])}function dI(p,d){return d>>>=0,p=Ut(p>>>0),d=Ut(d),Kt(p[d])}function mI(p){9<(p>>>=0)&&(bs[p+1]+=1)}function Fk(p,d,h,g,E){return Wf[p>>>0](d>>>0,h>>>0,g>>>0,E>>>0)}function _I(p,d,h,g,E){return Fk(p>>>0,d>>>0,h>>>0,g>>>0,E>>>0)}function hI(){return Kt([])}function gI(p){p=Ut(p>>>0);for(var d=Array(p.length),h=0;h>>0))}function xI(){return Kt({})}function yI(p){for(var d=Ut(p>>>=0);d.length;){var h=d.pop();d.pop()(h)}Df(p)}function bI(p,d,h){d>>>=0,h>>>=0,p=Ut(p>>>0),d=Ut(d),h=Ut(h),p[d]=h}function vI(p,d){p=gt(p),d>>>=0,p=new Date(1e3*p),(v(),B)[d>>>2>>>0]=p.getUTCSeconds(),(v(),B)[d+4>>>2>>>0]=p.getUTCMinutes(),(v(),B)[d+8>>>2>>>0]=p.getUTCHours(),(v(),B)[d+12>>>2>>>0]=p.getUTCDate(),(v(),B)[d+16>>>2>>>0]=p.getUTCMonth(),(v(),B)[d+20>>>2>>>0]=p.getUTCFullYear()-1900,(v(),B)[d+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),B)[d+28>>>2>>>0]=p}var Gk=p=>p%4==0&&(p%100!=0||p%400==0),jk=[0,31,60,91,121,152,182,213,244,274,305,335],qk=[0,31,59,90,120,151,181,212,243,273,304,334];function kI(p,d){p=gt(p),d>>>=0,p=new Date(1e3*p),(v(),B)[d>>>2>>>0]=p.getSeconds(),(v(),B)[d+4>>>2>>>0]=p.getMinutes(),(v(),B)[d+8>>>2>>>0]=p.getHours(),(v(),B)[d+12>>>2>>>0]=p.getDate(),(v(),B)[d+16>>>2>>>0]=p.getMonth(),(v(),B)[d+20>>>2>>>0]=p.getFullYear()-1900,(v(),B)[d+24>>>2>>>0]=p.getDay();var h=(Gk(p.getFullYear())?jk:qk)[p.getMonth()]+p.getDate()-1|0;(v(),B)[d+28>>>2>>>0]=h,(v(),B)[d+36>>>2>>>0]=-60*p.getTimezoneOffset(),h=new Date(p.getFullYear(),6,1).getTimezoneOffset();var g=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=0|(h!=g&&p.getTimezoneOffset()==Math.min(g,h)),(v(),B)[d+32>>>2>>>0]=p}function EI(p){p>>>=0;var d=new Date((v(),B)[p+20>>>2>>>0]+1900,(v(),B)[p+16>>>2>>>0],(v(),B)[p+12>>>2>>>0],(v(),B)[p+8>>>2>>>0],(v(),B)[p+4>>>2>>>0],(v(),B)[p>>>2>>>0],0),h=(v(),B)[p+32>>>2>>>0],g=d.getTimezoneOffset(),E=new Date(d.getFullYear(),6,1).getTimezoneOffset(),T=new Date(d.getFullYear(),0,1).getTimezoneOffset(),N=Math.min(T,E);return 0>h?(v(),B)[p+32>>>2>>>0]=+(E!=T&&N==g):0>>2>>>0]=d.getDay(),h=(Gk(d.getFullYear())?jk:qk)[d.getMonth()]+d.getDate()-1|0,(v(),B)[p+28>>>2>>>0]=h,(v(),B)[p>>>2>>>0]=d.getSeconds(),(v(),B)[p+4>>>2>>>0]=d.getMinutes(),(v(),B)[p+8>>>2>>>0]=d.getHours(),(v(),B)[p+12>>>2>>>0]=d.getDate(),(v(),B)[p+16>>>2>>>0]=d.getMonth(),(v(),B)[p+20>>>2>>>0]=d.getYear(),p=d.getTime(),BigInt(isNaN(p)?-1:p/1e3)}function Wk(p,d,h,g,E,T,N){return n?Ge(16,1,p,d,h,g,E,T,N):-52}function Vk(p,d,h,g,E,T){if(n)return Ge(17,1,p,d,h,g,E,T)}var To={},AI=()=>performance.timeOrigin+performance.now();function Hk(p,d){if(n)return Ge(18,1,p,d);if(To[p]&&(clearTimeout(To[p].id),delete To[p]),!d)return 0;var h=setTimeout(()=>{delete To[p],St(()=>OE(p,performance.timeOrigin+performance.now()))},d);return To[p]={id:h,Ve:d},0}function TI(p,d,h,g){p>>>=0,d>>>=0,h>>>=0,g>>>=0;var E=new Date().getFullYear(),T=new Date(E,0,1).getTimezoneOffset();E=new Date(E,6,1).getTimezoneOffset();var N=Math.max(T,E);(v(),I)[p>>>2>>>0]=60*N,(v(),B)[d>>>2>>>0]=+(T!=E),p=(d=P=>{var R=Math.abs(P);return`UTC${0<=P?"-":"+"}${String(Math.floor(R/60)).padStart(2,"0")}${String(R%60).padStart(2,"0")}`})(T),d=d(E),EDate.now(),MI=1;function OI(p,d,h){if(h>>>=0,!(0<=p&&3>=p))return 28;if(p===0)p=Date.now();else{if(!MI)return 52;p=performance.timeOrigin+performance.now()}return p=Math.round(1e6*p),(v(),Z)[h>>>3>>>0]=BigInt(p),0}var Vf=[],Xk=(p,d)=>{Vf.length=0;for(var h;h=(v(),K)[p++>>>0];){var g=h!=105;d+=(g&=h!=112)&&d%8?4:0,Vf.push(h==112?(v(),I)[d>>>2>>>0]:h==106?(v(),Z)[d>>>3>>>0]:h==105?(v(),B)[d>>>2>>>0]:(v(),J)[d>>>3>>>0]),d+=g?8:4}return Vf};function II(p,d,h){return p>>>=0,d=Xk(d>>>0,h>>>0),id[p](...d)}function CI(p,d,h){return p>>>=0,d=Xk(d>>>0,h>>>0),id[p](...d)}var PI=()=>{};function NI(p,d){return S(hn(p>>>0,d>>>0))}var LI=()=>{throw Pe+=1,"unwind"};function zI(){return 4294901760}var $I=()=>1,RI=()=>navigator.hardwareConcurrency,vs={},Kk=p=>{var d=vr(p)+1,h=ks(d);return h&&br(p,h,d),h},vc=p=>{var d;return(d=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(p))?+d[1]:(d=/:(\d+):\d+(?:\)|$)/.exec(p))?2147483648|+d[1]:0},Yk=p=>{for(var d of p)(p=vc(d))&&(vs[p]=d)};function BI(){var p=Error().stack.toString().split(` `);return p[0]=="Error"&&p.shift(),Yk(p),vs.ee=vc(p[3]),vs.xe=p,vs.ee}function kc(p){if(!(p=vs[p>>>0]))return 0;var d;if(d=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(p))p=d[1];else if(d=/^\s+at (.*) \(.*\)$/.exec(p))p=d[1];else{if(!(d=/^(.+?)@/.exec(p)))return 0;p=d[1]}return Ft(kc.ne??0),kc.ne=Kk(p),kc.ne}function DI(p){p>>>=0;var d=(v(),K).length;if(p<=d||4294901760=h;h*=2){var g=d*(1+.2/h);g=Math.min(g,p+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(p,g)/65536))-zr.buffer.byteLength+65535)/65536|0;try{zr.grow(g),G();var E=1;break e}catch{}E=void 0}if(E)return!0}return!1}function UI(p,d,h){if(p>>>=0,d>>>=0,vs.ee==p)var g=vs.xe;else(g=Error().stack.toString().split(` `))[0]=="Error"&&g.shift(),Yk(g);for(var E=3;g[E]&&vc(g[E])!=p;)++E;for(p=0;p>>2>>>0]=vc(g[p+E]);return p}var pr=p=>{var d=vr(p)+1,h=Sc(d);return br(p,h,d),h},wn=p=>(v(),I)[p>>>2>>>0]+4294967296*(v(),B)[p+4>>>2>>>0],wt=[],Qk=(p,d)=>{wt[p>>>0]=d},kr=[],Ec=[],xn=(p,d)=>{Ec[p]=new Promise(h=>d.finally(()=>h(p)))},ae=p=>{if(p)return wt[p>>>0]},Hf=(p,d)=>{for(p=(v(),I)[p>>>2>>>0];p;p=(v(),I)[p>>>2>>>0])d[(v(),B)[p+4>>>2>>>0]](p)},Ac=(p,d,h)=>{(v(),I)[p>>>2>>>0]=d,(v(),I)[p+4>>>2>>>0]=h},Jk=p=>{var d=(v(),I)[p>>>2>>>0];return p=(v(),I)[p+4>>>2>>>0],hn(d,p)},Yt=p=>{var d=(v(),I)[p>>>2>>>0];return p=(v(),I)[p+4>>>2>>>0],d?hn(d,p):p===0?"":void 0},FI=p=>{var d=Yt(p+4),h=(h=(v(),I)[p+12>>>2>>>0])?ae(h):"auto";if(p+=16){var g=ae((v(),I)[p+4>>>2>>>0]),E=(v(),I)[p+16>>>2>>>0],T=(v(),I)[p+20>>>2>>>0];if(E){for(var N={},P=0;P>>3>>>0]}E=N}else E=void 0;p={module:g,constants:E,entryPoint:Yt(p+8)}}else p=void 0;return{label:d,layout:h,compute:p}},Zk=(p,d)=>{function h(T,N,P,R=0){T=p[T]??R,(v(),I)[N+P>>>2>>>0]=T}function g(T,N,P,R=0){N+=P,T=p[T]??R,(v(),I)[N>>>2>>>0]=T,R=(v(),I)[N>>>2>>>0],(v(),I)[N+4>>>2>>>0]=(T-R)/4294967296}var E=(v(),I)[d>>>2>>>0];h("maxTextureDimension1D",d,4),h("maxTextureDimension2D",d,8),h("maxTextureDimension3D",d,12),h("maxTextureArrayLayers",d,16),h("maxBindGroups",d,20),h("maxBindGroupsPlusVertexBuffers",d,24),h("maxBindingsPerBindGroup",d,28),h("maxDynamicUniformBuffersPerPipelineLayout",d,32),h("maxDynamicStorageBuffersPerPipelineLayout",d,36),h("maxSampledTexturesPerShaderStage",d,40),h("maxSamplersPerShaderStage",d,44),h("maxStorageBuffersPerShaderStage",d,48),h("maxStorageTexturesPerShaderStage",d,52),h("maxUniformBuffersPerShaderStage",d,56),h("minUniformBufferOffsetAlignment",d,80),h("minStorageBufferOffsetAlignment",d,84),g("maxUniformBufferBindingSize",d,64),g("maxStorageBufferBindingSize",d,72),h("maxVertexBuffers",d,88),g("maxBufferSize",d,96),h("maxVertexAttributes",d,104),h("maxVertexBufferArrayStride",d,108),h("maxInterStageShaderVariables",d,112),h("maxColorAttachments",d,116),h("maxColorAttachmentBytesPerSample",d,120),h("maxComputeWorkgroupStorageSize",d,124),h("maxComputeInvocationsPerWorkgroup",d,128),h("maxComputeWorkgroupSizeX",d,132),h("maxComputeWorkgroupSizeY",d,136),h("maxComputeWorkgroupSizeZ",d,140),h("maxComputeWorkgroupsPerDimension",d,144),h("maxImmediateSize",d,148),E!==0&&(v(),h("maxStorageBuffersInVertexStage",E,8,p.maxStorageBuffersPerShaderStage),h("maxStorageBuffersInFragmentStage",E,16,p.maxStorageBuffersPerShaderStage),h("maxStorageTexturesInVertexStage",E,12,p.maxStorageTexturesPerShaderStage),h("maxStorageTexturesInFragmentStage",E,20,p.maxStorageTexturesPerShaderStage))},GI=(p,d)=>{(v(),I)[d+52>>>2>>>0]=p.subgroupMinSize,(v(),I)[d+56>>>2>>>0]=p.subgroupMaxSize;var h=Kk(p.vendor+p.architecture+p.device+p.description),g=vr(p.vendor);Ac(d+4,h,g),h+=g,g=vr(p.architecture),Ac(d+12,h,g),h+=g,g=vr(p.device),Ac(d+20,h,g),h+=g,g=vr(p.description),Ac(d+28,h,g),h+=g,(v(),B)[d+36>>>2>>>0]=2,h=p.isFallbackAdapter?3:4,(v(),B)[d+40>>>2>>>0]=h,(v(),I)[d+44>>>2>>>0]=0,(v(),I)[d+48>>>2>>>0]=0,Hf(d,{327739:E=>{let T=0,N=0;if(p.subgroupMatrixConfigs){T=p.subgroupMatrixConfigs.length,N=ks(20*T);for(let[P,R]of p.subgroupMatrixConfigs.entries()){let H=N+20*P,xe=tE.indexOf(R.componentType),ve=tE.indexOf(R.resultComponentType);(v(),B)[H>>>2>>>0]=xe,(v(),B)[H+4>>>2>>>0]=ve,(v(),I)[H+8>>>2>>>0]=R.M,(v(),I)[H+12>>>2>>>0]=R.N,(v(),I)[H+16>>>2>>>0]=R.K}}(v(),I)[E+12>>>2>>>0]=N,(v(),I)[E+8>>>2>>>0]=T}})},jI=[,,"uniform","storage","read-only-storage"],qI=[,"validation","out-of-memory","internal"],WI=[,"compatibility","core"],eE={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",23:"subgroup-size-control",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect",327732:"chromium-experimental-subgroup-matrix"},VI=[,"low-power","high-performance"],HI=[,"occlusion","timestamp"],XI=[,,"filtering","non-filtering","comparison"],KI=[,,"write-only","read-only","read-write"],tE=[,"f32","f16","u32","i32","u8","i8"],YI=[,"r8unorm","r8snorm","r8uint","r8sint","r16unorm","r16snorm","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32float","r32uint","r32sint","rg16unorm","rg16snorm","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rgb9e5ufloat","rg32float","rg32uint","rg32sint","rgba16unorm","rgba16snorm","rgba16uint","rgba16sint","rgba16float","rgba32float","rgba32uint","rgba32sint","stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8","bc1-rgba-unorm","bc1-rgba-unorm-srgb","bc2-rgba-unorm","bc2-rgba-unorm-srgb","bc3-rgba-unorm","bc3-rgba-unorm-srgb","bc4-r-unorm","bc4-r-snorm","bc5-rg-unorm","bc5-rg-snorm","bc6h-rgb-ufloat","bc6h-rgb-float","bc7-rgba-unorm","bc7-rgba-unorm-srgb","etc2-rgb8unorm","etc2-rgb8unorm-srgb","etc2-rgb8a1unorm","etc2-rgb8a1unorm-srgb","etc2-rgba8unorm","etc2-rgba8unorm-srgb","eac-r11unorm","eac-r11snorm","eac-rg11unorm","eac-rg11snorm","astc-4x4-unorm","astc-4x4-unorm-srgb","astc-5x4-unorm","astc-5x4-unorm-srgb","astc-5x5-unorm","astc-5x5-unorm-srgb","astc-6x5-unorm","astc-6x5-unorm-srgb","astc-6x6-unorm","astc-6x6-unorm-srgb","astc-8x5-unorm","astc-8x5-unorm-srgb","astc-8x6-unorm","astc-8x6-unorm-srgb","astc-8x8-unorm","astc-8x8-unorm-srgb","astc-10x5-unorm","astc-10x5-unorm-srgb","astc-10x6-unorm","astc-10x6-unorm-srgb","astc-10x8-unorm","astc-10x8-unorm-srgb","astc-10x10-unorm","astc-10x10-unorm-srgb","astc-12x10-unorm","astc-12x10-unorm-srgb","astc-12x12-unorm","astc-12x12-unorm-srgb"],QI=[,,"float","unfilterable-float","depth","sint","uint"],rE=[,"1d","2d","2d-array","cube","cube-array","3d"],JI={undefined:1,unknown:1,destroyed:2};function ZI(p,d,h,g,E,T){d=gt(d),h=gt(h),g>>>=0,E>>>=0,T>>>=0;var N=ae(p>>>0);if(p={},T){var P=(v(),I)[T+12>>>2>>>0];if(P){var R=(v(),I)[T+16>>>2>>>0];p.requiredFeatures=Array.from((v(),I).subarray(R>>>2>>>0,R+4*P>>>2>>>0),ee=>eE[ee])}if(P=(v(),I)[T+20>>>2>>>0]){let ee=function(Mt,Et,Es,As=!1){Et+=Es,(Et=(v(),I)[Et>>>2>>>0])==4294967295||As&&Et==0||(ve[Mt]=Et)},Be=function(Mt,Et,Es){Et+=Es,Es=(v(),I)[Et>>>2>>>0];var As=(v(),I)[Et+4>>>2>>>0];Es==4294967295&&As==4294967295||(ve[Mt]=wn(Et))};var H=ee,xe=Be;R=(v(),I)[P>>>2>>>0];var ve={};ee("maxTextureDimension1D",P,4),ee("maxTextureDimension2D",P,8),ee("maxTextureDimension3D",P,12),ee("maxTextureArrayLayers",P,16),ee("maxBindGroups",P,20),ee("maxBindGroupsPlusVertexBuffers",P,24),ee("maxBindingsPerBindGroup",P,28),ee("maxDynamicUniformBuffersPerPipelineLayout",P,32),ee("maxDynamicStorageBuffersPerPipelineLayout",P,36),ee("maxSampledTexturesPerShaderStage",P,40),ee("maxSamplersPerShaderStage",P,44),ee("maxStorageBuffersPerShaderStage",P,48),ee("maxStorageTexturesPerShaderStage",P,52),ee("maxUniformBuffersPerShaderStage",P,56),ee("minUniformBufferOffsetAlignment",P,80),ee("minStorageBufferOffsetAlignment",P,84),Be("maxUniformBufferBindingSize",P,64),Be("maxStorageBufferBindingSize",P,72),ee("maxVertexBuffers",P,88),Be("maxBufferSize",P,96),ee("maxVertexAttributes",P,104),ee("maxVertexBufferArrayStride",P,108),ee("maxInterStageShaderVariables",P,112),ee("maxColorAttachments",P,116),ee("maxColorAttachmentBytesPerSample",P,120),ee("maxComputeWorkgroupStorageSize",P,124),ee("maxComputeInvocationsPerWorkgroup",P,128),ee("maxComputeWorkgroupSizeX",P,132),ee("maxComputeWorkgroupSizeY",P,136),ee("maxComputeWorkgroupSizeZ",P,140),ee("maxComputeWorkgroupsPerDimension",P,144),ee("maxImmediateSize",P,148,!0),R!==0&&(v(),"maxStorageBuffersInVertexStage"in GPUSupportedLimits.prototype&&(ee("maxStorageBuffersInVertexStage",R,8),ee("maxStorageTexturesInVertexStage",R,12),ee("maxStorageBuffersInFragmentStage",R,16),ee("maxStorageTexturesInFragmentStage",R,20))),p.requiredLimits=ve}(P=(v(),I)[T+24>>>2>>>0])&&(P={label:Yt(P+4)},p.defaultQueue=P),p.label=Yt(T+4)}Pe+=1,xn(d,N.requestDevice(p).then(ee=>{--Pe,St(()=>{wt[E>>>0]=ee.queue,wt[g>>>0]=ee,Pe+=1,xn(h,ee.lost.then(Be=>{St(()=>{ee.onuncapturederror=()=>{};var Mt=ue(),Et=pr(Be.message);Jf(h,JI[Be.reason],Et),ce(Mt)}),--Pe})),ee.onuncapturederror=Be=>{var Mt=5;Be.error instanceof GPUValidationError?Mt=2:Be.error instanceof GPUOutOfMemoryError?Mt=3:Be.error instanceof GPUInternalError&&(Mt=4);var Et=ue();Be=pr(Be.error.message),AE(g,Mt,Be),ce(Et)},"adapterInfo"in ee||(ee.adapterInfo=N.info),td(d,1,g,0)})},ee=>{--Pe,St(()=>{var Be=ue(),Mt=pr(ee.message);td(d,3,g,Mt),h&&Jf(h,4,Mt),ce(Be)})}))}function eC(p){var d=ae(p>>>=0),h=kr[p];if(h){for(var g=0;g>>=0;var g=ae(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=nd(16,E.byteLength);return(v(),K).set(new Uint8Array(E),T>>>0),kr[p].push(()=>Ft(T)),T}function rC(p,d,h){h>>>=0;var g=ae(p>>>=0);h==4294967295&&(h=void 0);try{var E=g.getMappedRange(d>>>0,h)}catch{return 0}var T=nd(16,E.byteLength);return(v(),K).fill(0,T,E.byteLength),kr[p].push(()=>{new Uint8Array(E).set((v(),K).subarray(T>>>0,T+E.byteLength>>>0)),Ft(T)}),T}function sC(p,d,h,g,E){p>>>=0,d=gt(d),h=gt(h),E>>>=0;var T=ae(p);kr[p]=[],E==4294967295&&(E=void 0),Pe+=1,xn(d,T.mapAsync(h,g>>>0,E).then(()=>{--Pe,St(()=>{Zf(d,1,0)})},N=>{--Pe,St(()=>{ue();var P=pr(N.message);Zf(d,N.name==="AbortError"?4:N.name==="OperationError"?3:0,P),delete kr[p]})}))}function nC(p){var d=ae(p>>>=0),h=kr[p];if(h){for(var g=0;g>>0]}function aC(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=!!(v(),I)[d+32>>>2>>>0];d={label:Yt(d+4),usage:(v(),I)[d+16>>>2>>>0],size:wn(d+24),mappedAtCreation:g},p=ae(p);try{var E=p.createBuffer(d)}catch{return!1}return wt[h>>>0]=E,g&&(kr[h]=[]),!0}function iC(p,d,h,g){p>>>=0,d=gt(d),g>>>=0,h=FI(h>>>0),p=ae(p),Pe+=1,xn(d,p.createComputePipelineAsync(h).then(E=>{--Pe,St(()=>{wt[g>>>0]=E,Qf(d,1,g,0)})},E=>{--Pe,St(()=>{var T=ue(),N=pr(E.message);Qf(d,E.reason==="validation"?3:E.reason==="internal"?4:0,g,N),ce(T)})}))}function lC(p,d,h){p>>>=0,d>>>=0,h>>>=0;var g=(v(),I)[d>>>2>>>0],E=(v(),B)[g+4>>>2>>>0];d={label:Yt(d+4),code:""},E===2&&(d.code=Jk(g+8)),p=ae(p).createShaderModule(d),wt[h>>>0]=p}var cC=p=>{(p=ae(p)).onuncapturederror=null,p.destroy()};function uC(p,d){d=gt(d),p=ae(p>>>0),Pe+=1,xn(d,p.popErrorScope().then(h=>{--Pe,St(()=>{var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var E=ue(),T=h?pr(h.message):0;ed(d,1,g,T),ce(E)})},h=>{--Pe,St(()=>{var g=ue(),E=pr(h.message);ed(d,1,5,E),ce(g)})}))}function pC(p,d,h,g){if(d=gt(d),g>>>=0,h>>>=0){var E={featureLevel:WI[(v(),B)[h+4>>>2>>>0]],powerPreference:VI[(v(),B)[h+8>>>2>>>0]],forceFallbackAdapter:!!(v(),I)[h+12>>>2>>>0]};(p=(v(),I)[h>>>2>>>0])!==0&&(v(),E.Ye=!!(v(),I)[p+8>>>2>>>0])}"gpu"in navigator?(Pe+=1,xn(d,navigator.gpu.requestAdapter(E).then(T=>{--Pe,St(()=>{if(T)wt[g>>>0]=T,So(d,1,g,0);else{var N=ue(),P=pr("WebGPU not available on this browser (requestAdapter returned null)");So(d,3,g,P),ce(N)}})},T=>{--Pe,St(()=>{var N=ue(),P=pr(T.message);So(d,4,g,P),ce(N)})}))):(E=ue(),p=pr("WebGPU not available on this browser (navigator.gpu is not available)"),So(d,3,g,p),ce(E))}function fC(p,d,h){return p>>>=0,d>>>=0,h>>>=0,Uk(async()=>{var g=[];if(h){var E=(v(),B)[h>>>2>>>0];g.length=d+1,g[d]=new Promise(P=>setTimeout(P,E,0))}else g.length=d;for(var T=0;T{if(!Xf){var p,d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(p in Kf)Kf[p]===void 0?delete d[p]:d[p]=Kf[p];var h=[];for(p in d)h.push(`${p}=${d[p]}`);Xf=h}return Xf};function nE(p,d){if(n)return Ge(19,1,p,d);p>>>=0,d>>>=0;var h,g=0,E=0;for(h of sE()){var T=d+g;(v(),I)[p+E>>>2>>>0]=T,g+=br(h,T,1/0)+1,E+=4}return 0}function oE(p,d){if(n)return Ge(20,1,p,d);p>>>=0,d>>>=0;var h=sE();for(var g of((v(),I)[p>>>2>>>0]=h.length,p=0,h))p+=vr(g)+1;return(v(),I)[d>>>2>>>0]=p,0}function aE(p){return n?Ge(21,1,p):52}function iE(p,d,h,g,E){return n?Ge(22,1,p,d,h,g,E):52}function lE(p,d,h,g){return n?Ge(23,1,p,d,h,g):52}function cE(p,d,h,g){return n?Ge(24,1,p,d,h,g):70}var dC=[null,[],[]];function uE(p,d,h,g){if(n)return Ge(25,1,p,d,h,g);d>>>=0,h>>>=0,g>>>=0;for(var E=0,T=0;T>>2>>>0],P=(v(),I)[d+4>>>2>>>0];d+=8;for(var R=0;R>>0],ve=dC[H];xe===0||xe===10?((H===1?M:S)(yk(ve)),ve.length=0):ve.push(xe)}E+=P}return(v(),I)[g>>>2>>>0]=E,0}function mC(p){return p>>>0}function _C(p,d){return Zk(ae(p>>>0).limits,d>>>0),1}function hC(p,d){return ae(p>>>0).features.has(eE[d])}function gC(p){return BigInt(ae(p>>>0).size)}function wC(p){return BigInt(ae(p>>>0).usage)}function xC(p,d){if(p>>>=0,d>>>=0){var h=Yt(d+4);h={label:h,timestampWrites:d=(d=(v(),I)[d+12>>>2>>>0])!==0?{querySet:ae((v(),I)[d+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),I)[d+8>>>2>>>0],endOfPassWriteIndex:(v(),I)[d+12>>>2>>>0]}:void 0}}return d=ae(p),p=xE(0),h=d.beginComputePass(h),wt[p>>>0]=h,p}function yC(p,d,h,g){h=gt(h),(g=gt(g))==-1&&(g=void 0),(p=ae(p>>>0)).clearBuffer(ae(d>>>0),h,g)}function bC(p,d,h,g,E,T){h=gt(h),E=gt(E),T=gt(T),ae(p>>>0).copyBufferToBuffer(ae(d>>>0),h,ae(g>>>0),E,T)}function vC(p){var d=ae(p>>>0);return p=gE(0),d=d.finish(),wt[p>>>0]=d,p}function kC(p,d,h,g,E,T){T=gt(T),ae(p>>>0).resolveQuerySet(ae(d>>>0),h,g,ae(E>>>0),T)}function EC(p,d,h,g){ae(p>>>0).dispatchWorkgroups(d,h,g)}function AC(p,d,h){h=gt(h),ae(p>>>0).dispatchWorkgroupsIndirect(ae(d>>>0),h)}function TC(p){ae(p>>>0).end()}function SC(p,d,h,g,E){g>>>=0,E>>>=0,p=ae(p>>>0),h=ae(h>>>0),g==0?p.setBindGroup(d,h):p.setBindGroup(d,h,(v(),I),E>>>2,g)}function MC(p,d){ae(p>>>0).setPipeline(ae(d>>>0))}function OC(p,d,h){ae(p>>>0).Xe(ae(d>>>0),h)}function IC(p,d){function h(E){var T=(v(),I)[E+8>>>2>>>0],N=(v(),I)[E+32>>>2>>>0],P=(v(),I)[E+36>>>2>>>0],R=0;return Hf(E,{14:H=>{R=(v(),I)[H+8>>>2>>>0]}}),T?((N=wn(E+24))==-1&&(N=void 0),T={buffer:ae(T),offset:wn(E+16),size:N}):T=ae(N||P||R),{binding:(v(),I)[E+4>>>2>>>0],resource:T}}p>>>=0,d={label:Yt((d>>>=0)+4),layout:ae((v(),I)[d+12>>>2>>>0]),entries:(function(E,T){for(var N=[],P=0;P>>2>>>0],(v(),I)[d+20>>>2>>>0])},p=ae(p);var g=_E(0);return Qk(g,p.createBindGroup(d)),g}function CC(p,d){function h(R){var H=(v(),I)[R+4>>>2>>>0];if(H)return{type:jI[H],hasDynamicOffset:!!(v(),I)[R+8>>>2>>>0],minBindingSize:wn(R+16)}}function g(R){if(R=(v(),I)[R+4>>>2>>>0])return{type:XI[R]}}function E(R){var H=(v(),I)[R+4>>>2>>>0];if(H)return{sampleType:QI[H],viewDimension:rE[(v(),B)[R+8>>>2>>>0]],multisampled:!!(v(),I)[R+12>>>2>>>0]}}function T(R){var H=(v(),I)[R+4>>>2>>>0];if(H)return{access:KI[H],format:YI[(v(),B)[R+8>>>2>>>0]],viewDimension:rE[(v(),B)[R+12>>>2>>>0]]}}function N(R){var H={binding:(v(),I)[R+4>>>2>>>0],visibility:(v(),I)[R+8>>>2>>>0],buffer:h(R+24),sampler:g(R+48),texture:E(R+56),storageTexture:T(R+72)};return Hf(R,{13:()=>{H.externalTexture={}}}),H}p>>>=0,d={label:Yt((d>>>=0)+4),entries:(function(R,H){for(var xe=[],ve=0;ve>>2>>>0],(v(),I)[d+16>>>2>>>0])},p=ae(p);var P=hE(0);return Qk(P,p.createBindGroupLayout(d)),P}function PC(p,d){var h;return p>>>=0,(d>>>=0)&&(h={label:Yt(d+4)}),d=ae(p),p=wE(0),h=d.createCommandEncoder(h),wt[p>>>0]=h,p}function NC(p,d){p>>>=0,d>>>=0;for(var h=(v(),I)[d+12>>>2>>>0],g=(v(),I)[d+16>>>2>>>0],E=[],T=0;T>>2>>>0]));return d={label:Yt(d+4),bindGroupLayouts:E,immediateSize:(v(),I)[d+20>>>2>>>0]},h=ae(p),p=yE(0),d=h.createPipelineLayout(d),wt[p>>>0]=d,p}function LC(p,d){p>>>=0,d>>>=0,d={type:HI[(v(),B)[d+12>>>2>>>0]],count:(v(),I)[d+16>>>2>>>0]};var h=ae(p);return p=bE(0),d=h.createQuerySet(d),wt[p>>>0]=d,p}function zC(p,d){return GI(ae(p>>>0).adapterInfo,d>>>0),1}var $C={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"subgroup-size-control":23,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729,"chromium-experimental-subgroup-matrix":327732};function RC(p,d){d>>>=0;var h=ae(p>>>0);p=ks(4*h.features.size);var g=0,E=0;for(let T of h.features)0<=(h=$C[T])&&((v(),B)[p+g>>>2>>>0]=h,g+=4,E++);(v(),I)[d+4>>>2>>>0]=p,(v(),I)[d>>>2>>>0]=E}function BC(p,d){return Zk(ae(p>>>0).limits,d>>>0),1}function DC(p,d){ae(p>>>0).pushErrorScope(qI[d])}function UC(p,d,h){d>>>=0,h>>>=0,p=ae(p>>>0),d=Array.from((v(),B).subarray(h>>>2>>>0,h+4*d>>>2>>>0),g=>ae(g)),p.submit(d)}function FC(p,d,h,g,E){h=gt(h),g>>>=0,E>>>=0,p=ae(p>>>0),d=ae(d>>>0),g=(v(),K).subarray(g>>>0,g+E>>>0),p.writeBuffer(d,h,g,0,E)}n||(function(){for(var p=e.numThreads-1;p--;)dk();qe.push(async()=>{var d=(async function(){if(!n)return Promise.all(Lr.map(fk))})();Ce++,await d,--Ce==0&&at&&(d=at,at=null,d())})})(),n||(zr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),G()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ue(),e.stackRestore=p=>ce(p),e.stackAlloc=p=>Sc(p),e.setValue=function(p,d,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(v(),F)[p>>>0]=d;break;case"i16":(v(),Y)[p>>>1>>>0]=d;break;case"i32":(v(),B)[p>>>2>>>0]=d;break;case"i64":(v(),Z)[p>>>3>>>0]=BigInt(d);break;case"float":(v(),oe)[p>>>2>>>0]=d;break;case"double":(v(),J)[p>>>3>>>0]=d;break;case"*":(v(),I)[p>>>2>>>0]=d;break;default:ie(`invalid type for setValue: ${h}`)}},e.getValue=function(p,d="i8"){switch(d.endsWith("*")&&(d="*"),d){case"i1":case"i8":return(v(),F)[p>>>0];case"i16":return(v(),Y)[p>>>1>>>0];case"i32":return(v(),B)[p>>>2>>>0];case"i64":return(v(),Z)[p>>>3>>>0];case"float":return(v(),oe)[p>>>2>>>0];case"double":return(v(),J)[p>>>3>>>0];case"*":return(v(),I)[p>>>2>>>0];default:ie(`invalid type for getValue: ${d}`)}},e.UTF8ToString=hn,e.stringToUTF8=br,e.lengthBytesUTF8=vr;var pE,fE,dE,Yf,Tc,Ft,ks,mE,_E,hE,gE,wE,xE,yE,bE,vE,kE,EE,Qf,Jf,Zf,ed,So,td,AE,rd,TE,SE,ME,sd,OE,IE,nd,be,Mo,CE,ce,Sc,ue,PE,od,NE,LE,zE,ad,$E,RE,BE,DE,UE,FE,GE,jE,qE,WE,VE,HE,XE,KE,YE,QE,JE,ZE,eA,tA,rA,sA,nA,oA,aA,iA,lA,cA,uA,pA,fA,dA,mA,_A,hA,gA,wA,xA,yA,bA,vA,Er,GC=[dn,Eo,hk,bk,vk,kk,Ek,Ak,Tk,Sk,Mk,Ok,Ik,Ck,Pk,Nk,Wk,Vk,Hk,nE,oE,aE,iE,lE,cE,uE],id={1280444:(p,d,h,g,E)=>{if(e===void 0||!e.ed)return 1;if((p=hn(Number(p>>>0))).startsWith("./")&&(p=p.substring(2)),!(p=e.ed.get(p)))return 2;if(d=Number(d>>>0),h=Number(h>>>0),g=Number(g>>>0),d+h>p.byteLength)return 3;try{let T=p.subarray(d,d+h);switch(E){case 0:(v(),K).set(T,g>>>0);break;case 1:e.pe?e.pe(g,T):e.Re(g,T);break;default:return 4}return 0}catch{return 4}},1281268:(p,d,h)=>{e.re(p,(v(),K).subarray(d>>>0,d+h>>>0))},1281332:()=>e.Pe(),1281374:p=>{e.qe(p)},1281411:()=>typeof wasmOffsetConverter<"u"};function jC(){return typeof wasmOffsetConverter<"u"}function qC(p,d,h,g){var E=ue();try{return jE(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function WC(p,d,h){var g=ue();try{return UE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function VC(p){var d=ue();try{$E(p)}catch(h){if(ce(d),h!==h+0)throw h;be(1,0)}}function HC(p,d){var h=ue();try{return ad(p,d)}catch(g){if(ce(h),g!==g+0)throw g;be(1,0)}}function XC(p,d,h){var g=ue();try{zE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function KC(p,d){var h=ue();try{qE(p,d)}catch(g){if(ce(h),g!==g+0)throw g;be(1,0)}}function YC(p,d,h,g,E,T,N){var P=ue();try{return DE(p,d,h,g,E,T,N)}catch(R){if(ce(P),R!==R+0)throw R;be(1,0)}}function QC(p,d,h,g,E,T){var N=ue();try{RE(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function JC(p,d,h,g){var E=ue();try{GE(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function ZC(p,d,h,g,E,T,N){var P=ue();try{VE(p,d,h,g,E,T,N)}catch(R){if(ce(P),R!==R+0)throw R;be(1,0)}}function eP(p,d,h,g,E,T,N){var P=ue();try{HE(p,d,h,g,E,T,N)}catch(R){if(ce(P),R!==R+0)throw R;be(1,0)}}function tP(p,d,h,g,E,T,N,P){var R=ue();try{sA(p,d,h,g,E,T,N,P)}catch(H){if(ce(R),H!==H+0)throw H;be(1,0)}}function rP(p,d,h,g,E,T,N,P,R,H,xe,ve){var ee=ue();try{XE(p,d,h,g,E,T,N,P,R,H,xe,ve)}catch(Be){if(ce(ee),Be!==Be+0)throw Be;be(1,0)}}function sP(p,d,h,g,E){var T=ue();try{return WE(p,d,h,g,E)}catch(N){if(ce(T),N!==N+0)throw N;be(1,0)}}function nP(p,d,h,g,E,T){var N=ue();try{nA(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function oP(p,d,h,g,E){var T=ue();try{BE(p,d,h,g,E)}catch(N){if(ce(T),N!==N+0)throw N;be(1,0)}}function aP(p,d,h,g,E,T,N,P){var R=ue();try{FE(p,d,h,g,E,T,N,P)}catch(H){if(ce(R),H!==H+0)throw H;be(1,0)}}function iP(p){var d=ue();try{return oA(p)}catch(h){if(ce(d),h!==h+0)throw h;be(1,0)}}function lP(p,d,h,g,E,T,N,P,R){var H=ue();try{YE(p,d,h,g,E,T,N,P,R)}catch(xe){if(ce(H),xe!==xe+0)throw xe;be(1,0)}}function cP(p,d,h){var g=ue();try{return aA(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function uP(p,d){var h=ue();try{return wA(p,d)}catch(g){if(ce(h),g!==g+0)throw g;return be(1,0),0n}}function pP(p,d,h,g){var E=ue();try{return iA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function fP(p){var d=ue();try{return KE(p)}catch(h){if(ce(d),h!==h+0)throw h;return be(1,0),0n}}function dP(p,d,h,g){var E=ue();try{return lA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function mP(p,d,h,g,E){var T=ue();try{return cA(p,d,h,g,E)}catch(N){if(ce(T),N!==N+0)throw N;be(1,0)}}function _P(p,d,h,g,E,T){var N=ue();try{return uA(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function hP(p,d,h,g,E,T){var N=ue();try{return tA(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function gP(p,d,h,g,E,T){var N=ue();try{return pA(p,d,h,g,E,T)}catch(P){if(ce(N),P!==P+0)throw P;be(1,0)}}function wP(p,d,h,g,E,T,N,P){var R=ue();try{return rA(p,d,h,g,E,T,N,P)}catch(H){if(ce(R),H!==H+0)throw H;be(1,0)}}function xP(p,d,h,g,E){var T=ue();try{return fA(p,d,h,g,E)}catch(N){if(ce(T),N!==N+0)throw N;return be(1,0),0n}}function yP(p,d,h,g){var E=ue();try{return dA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function bP(p,d,h,g){var E=ue();try{return mA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function vP(p,d,h,g,E,T,N,P,R,H,xe,ve){var ee=ue();try{return _A(p,d,h,g,E,T,N,P,R,H,xe,ve)}catch(Be){if(ce(ee),Be!==Be+0)throw Be;be(1,0)}}function kP(p,d,h,g,E,T,N,P,R,H,xe){var ve=ue();try{hA(p,d,h,g,E,T,N,P,R,H,xe)}catch(ee){if(ce(ve),ee!==ee+0)throw ee;be(1,0)}}function EP(p,d,h,g,E,T,N,P,R,H,xe,ve,ee,Be,Mt,Et){var Es=ue();try{gA(p,d,h,g,E,T,N,P,R,H,xe,ve,ee,Be,Mt,Et)}catch(As){if(ce(Es),As!==As+0)throw As;be(1,0)}}function AP(p,d,h){var g=ue();try{return JE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;return be(1,0),0n}}function TP(p,d,h){var g=ue();try{return QE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function SP(p,d,h){var g=ue();try{return ZE(p,d,h)}catch(E){if(ce(g),E!==E+0)throw E;be(1,0)}}function MP(p,d,h,g){var E=ue();try{eA(p,d,h,g)}catch(T){if(ce(E),T!==T+0)throw T;be(1,0)}}function Mc(){if(0{let d=new WeakMap,h,g,E=1;e.webgpuRegisterDevice=P=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(P){var R=d.get(P);if(!R){let H=((xe,ve=0)=>{var ee=EE(ve);return ve=kE(ve,ee),wt[ee>>>0]=xe.queue,wt[ve>>>0]=xe,ve})(P,R=dE());R=[E++,R,H],d.set(P,R)}return h=P,g=R[0],R}h=void 0,g=0};let T=new Map;e.webgpuOnCreateSession=P=>{if(g!==void 0){var R=g;if(g=void 0,P){let H=Yf(R);T.set(P,H),R===0&&p(h??ae(H))}h=void 0}},e.webgpuOnReleaseSession=P=>{T.delete(P)};let N=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(P,R,H)=>{if(H)return P[N]=[H,NaN],H;if(H=P[N])return H[1]++,H[0];if((R=T.get(R))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return R=((xe,ve=0)=>(xe.mapState==="unmapped"||ie(),ve=vE(ve),wt[ve>>>0]=xe,ve))(P,R),P[N]=[R,1],R},e.webgpuUnregisterBuffer=P=>{let R=P[N];if(!R)throw Error("Buffer is not registered");R[1]--,R[1]===0&&(mE(R[0]),delete P[N])},e.webgpuGetBuffer=P=>ae(P),e.webgpuCreateDownloader=(P,R,H)=>{if((H=T.get(H))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let xe=ae(H),ve=16*Math.ceil(Number(R)/16);return async()=>{let ee=xe.createBuffer({size:ve,usage:9});try{let Be=xe.createCommandEncoder();return Be.copyBufferToBuffer(P,0,ee,0,ve),xe.queue.submit([Be.finish()]),await ee.mapAsync(GPUMapMode.READ),ee.getMappedRange().slice(0,R)}finally{ee.destroy()}}},e.pe=(P,R)=>{var H=R.buffer;let xe=R.byteOffset,ve=R.byteLength;if(R=16*Math.ceil(Number(ve)/16),P=ae(P),!h){var ee=Yf(g);h=ae(ee)}let Be=(ee=h.createBuffer({mappedAtCreation:!0,size:R,usage:6})).getMappedRange();new Uint8Array(Be).set(new Uint8Array(H,xe,ve)),ee.unmap(),(H=h.createCommandEncoder()).copyBufferToBuffer(ee,0,P,0,R),h.queue.submit([H.finish()]),ee.destroy()}},e.webnnInit=p=>{let d=p[0];[e.Pe,e.qe,e.webnnEnsureTensor,e.re,e.webnnDownloadTensor,e.Oe,e.webnnEnableTraceEvent]=p.slice(1),e.webnnReleaseTensorId=e.qe,e.webnnUploadTensor=e.re,e.webnnRegisterMLContext=e.Oe,e.webnnOnRunStart=h=>d.onRunStart(h),e.webnnOnRunEnd=d.onRunEnd.bind(d),e.webnnOnReleaseSession=h=>{d.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>d.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,E,T)=>d.registerMLTensor(h,g,E,T),e.webnnCreateMLContext=h=>d.createMLContext(h),e.webnnRegisterGraphInput=d.registerGraphInput.bind(d),e.webnnIsGraphInput=d.isGraphInput.bind(d),e.webnnRegisterGraphOutput=d.registerGraphOutput.bind(d),e.webnnIsGraphOutput=d.isGraphOutput.bind(d),e.webnnCreateTemporaryTensor=d.createTemporaryTensor.bind(d),e.webnnIsGraphInputOutputTypeSupported=d.isGraphInputOutputTypeSupported.bind(d)},z?e:new Promise((p,d)=>{w=p,x=d})}var GT,X2,F$=Ae(()=>{"use strict";GT=H2,X2=globalThis.self?.name?.startsWith("em-pthread"),X2&&H2()}),Nd,Kd,K2,Lt,jT,Yc,Y2,Q2,Ld,J2,zd,qT,$d,WT,sm=Ae(()=>{"use strict";rm(),Nd=typeof location>"u"?void 0:location.origin,Kd=import.meta.url>"file:"&&import.meta.url<"file;",K2=()=>{if(Kd){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Nd).href}return import.meta.url},Lt=K2(),jT=()=>{if(Lt&&!Lt.startsWith("blob:"))return Lt.substring(0,Lt.lastIndexOf("/")+1)},Yc=(t,e)=>{try{let r=e??Lt;return(r?new URL(t,r):new URL(t)).origin===Nd}catch{return!1}},Y2=(t,e)=>{let r=e??Lt;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},Q2=(t,e)=>`${e??"./"}${t}`,Ld=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},J2=async t=>(await import(t)).default,zd=(U$(),tu(DT)).default,qT=async()=>{if(!Lt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Yc(Lt))return[void 0,zd()];let t=await Ld(Lt);return[t,zd(t)]},$d=(F$(),tu(FT)).default,WT=async(t,e,r,s)=>{let n=$d&&!(t||e);if(n)if(Lt)n=Yc(Lt)||s&&!r;else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,$d];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??Y2(o,e),i=r&&a&&!Yc(a,e),l=i?await Ld(a):a??Q2(o,e);return[i?l:void 0,await J2(l)]}}}),Rd,Qc,Do,Bd,Z2,eT,tT,nm,je,Us=Ae(()=>{"use strict";sm(),Qc=!1,Do=!1,Bd=!1,Z2=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},eT=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},tT=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nm=async t=>{if(Qc)return Promise.resolve();if(Do)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bd)throw new Error("previous call to 'initializeWebAssembly()' failed.");Do=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!tT())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!eT())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Z2();r>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),t.numThreads=r=1);let n=t.wasmPaths,o=typeof n=="string"?n:void 0,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,u=t.wasmBinary,[f,m]=await WT(i,o,r>1,!!u||!!c),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,b)=>{let A={numThreads:r};if(u)A.wasmBinary=u,A.locateFile=k=>k;else if(c||o)A.locateFile=k=>c??o+k;else if(i&&i.indexOf("blob:")!==0)A.locateFile=k=>new URL(k,i).href;else if(f){let k=jT();k&&(A.locateFile=M=>k+M)}m(A).then(k=>{Do=!1,Qc=!0,Rd=k,x(),f&&URL.revokeObjectURL(f)},k=>{Do=!1,Bd=!0,b(k)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},je=()=>{if(Qc&&Rd)return Rd;throw new Error("WebAssembly is not initialized yet.")}}),zt,su,ze,om=Ae(()=>{"use strict";Us(),zt=(t,e)=>{let r=je(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},su=(t,e,r,s)=>{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach(([n,o])=>{let a=e?e+n:n;if(typeof o=="object")su(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},ze=t=>{let e=je(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetLastError(n,n+s);let o=Number(e.getValue(n,s===4?"i32":"i64")),a=e.getValue(n+s,"*"),i=a?e.UTF8ToString(a):"";throw new Error(`${t} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{e.stackRestore(r)}}}),VT,G$=Ae(()=>{"use strict";Us(),om(),VT=t=>{let e=je(),r=0,s=[],n=t||{};try{if(t?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${t.logSeverityLevel}`);if(t?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);t?.terminate===void 0&&(n.terminate=!1);let o=0;return t?.tag!==void 0&&(o=zt(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&ze("Can't create run options."),t?.extra!==void 0&&su(t.extra,"",new WeakSet,(a,i)=>{let l=zt(a,s),c=zt(i,s);e._OrtAddRunConfigEntry(r,l,c)!==0&&ze(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),rT,sT,nT,Mn,_r,oT,HT,j$=Ae(()=>{"use strict";Us(),om(),rT=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},sT=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},nT=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(t.enableMemPattern=!1)},Mn=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);je()._OrtAddSessionConfigEntry(t,n,o)!==0&&ze(`Can't set a session config entry: ${e} - ${r}.`)},_r=(t,e,r,s)=>{let n=zt(e,s),o=zt(r,s);t.push([n,o])},oT=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",Mn(t,"session.disable_quant_qdq","1",r),Mn(t,"session.disable_qdq_constant_folding","1",r),typeof n!="string"){let f=n?.deviceType;f&&Mn(t,"deviceType",f,r)}break;case"webgpu":{o="WebGPU";let f;if(typeof n!="string"){let _=n;if(_.device)if(typeof GPUDevice<"u"&&_.device instanceof GPUDevice)f=_.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:w}=e;if(typeof w=="boolean"&&w&&_r(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&_r(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];_r(a,"forceCpuNodeNames",x.join(` `),r)}_.validationMode&&_r(a,"validationMode",_.validationMode,r),typeof _.enableMatmulFp32Accumulation=="boolean"&&_r(a,"enableMatmulFp32Accumulation",_.enableMatmulFp32Accumulation?"1":"0",r);for(let x of["storageBufferCacheMode","uniformBufferCacheMode","queryResolveBufferCacheMode","defaultBufferCacheMode"]){let b=_[x];if(b){if(b!=="disabled"&&b!=="lazyRelease"&&b!=="simple"&&b!=="bucket")throw new Error(`${x} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${b}`);_r(a,x,b,r)}}}let m=je().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;_r(a,"deviceId",_.toString(),r),_r(a,"webgpuInstance",w.toString(),r),_r(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=zt(o,r),l=a.length,c=0,u=0;if(l>0){c=je()._malloc(l*je().PTR_SIZE),r.push(c),u=je()._malloc(l*je().PTR_SIZE),r.push(u);for(let f=0;f{let e=je(),r=0,s=[],n=t||{};nT(n);try{let o=rT(n.graphOptimizationLevel??"all"),a=sT(n.executionMode??"sequential"),i=typeof n.logId=="string"?zt(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log severity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let u=typeof n.optimizedModelFilePath=="string"?zt(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,u),r===0&&ze("Can't create session options."),n.executionProviders&&await oT(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Mn(r,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[f,m]of Object.entries(n.freeDimensionOverrides)){if(typeof f!="string")throw new Error(`free dimension override name must be a string: ${f}`);if(typeof m!="number"||!Number.isInteger(m)||m<0)throw new Error(`free dimension override value must be a non-negative integer: ${m}`);let _=zt(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&ze(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&su(n.extra,"",new WeakSet,(f,m)=>{Mn(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&ze("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),zs,eu,In,qo,nu,am,im,Yd,Cn=Ae(()=>{"use strict";zs=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${t}`)}},eu=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${t}`)}},In=(t,e)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][t],s=typeof e=="number"?e:e.reduce((n,o)=>n*o,1);return r>0?Math.ceil(s*r):void 0},qo=t=>{switch(t){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},nu=t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}},am=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",im=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Yd=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${t}`)}}}),lm,XT=Ae(()=>{"use strict";rm(),lm=async t=>{if(typeof t=="string"){let e=await fetch(t);if(!e.ok)throw new Error(`failed to load external data file: ${t}`);let r=e.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let n=e.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),KT,q$=Ae(()=>{"use strict";Cn(),KT=(t,e)=>new(qo(e))(t)}),aT,iT,lT,cT,YT,uT,Ot,QT=Ae(()=>{"use strict";Cn(),aT=["V","I","W","E","F"],iT=(t,e)=>{console.log(`[${aT[t]},${new Date().toISOString()}]${e}`)},YT=(t,e)=>{lT=t,cT=e},uT=(t,e)=>{let r=nu(t),s=nu(lT);r>=s&&iT(r,typeof e=="function"?e():e)},Ot=(...t)=>{cT&&uT(...t)}}),Dd,pT,Ud,fT,Fd,dT,Gd,jd,qd,mT,JT,W$=Ae(()=>{"use strict";Cn(),QT(),Dd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),pT=(t,e)=>{if(e==="int32")return t;let r=Dd.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);let s=r/8;if(t.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let n=t.byteLength/s,o=new(qo(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},Ud=(t,e)=>{if(e==="int32")return t;if(t.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=t.byteLength/4,s=new Int32Array(t.buffer,t.byteOffset,r);switch(e){case"int64":{let n=BigInt64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"uint64":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let n=BigUint64Array.from(s,BigInt);return new Uint8Array(n.buffer)}case"int8":{if(s.some(o=>o<-128||o>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let n=Int8Array.from(s,Number);return new Uint8Array(n.buffer)}case"uint8":{if(s.some(n=>n<0||n>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(s,Number)}case"uint32":{if(s.some(o=>o<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let n=Uint32Array.from(s,Number);return new Uint8Array(n.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${e}`)}},fT=1,Fd=()=>fT++,dT=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Gd=(t,e)=>{let r=Dd.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);return e.length>0?Math.ceil(e.reduce((s,n)=>s*n)*r/8):0},jd=class{constructor(t){this.isDataConverted=!1;let{sessionId:e,context:r,tensor:s,dataType:n,shape:o,fallbackDataType:a}=t;this.sessionId=e,this.mlContext=r,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Gd(this.dataType,this.tensorShape)}destroy(){Ot("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t){if(this.fallbackDataType){let e=await this.mlContext.readTensor(this.mlTensor),r=Ud(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return new Uint8Array(r).buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},qd=class{constructor(t,e){this.tensorManager=t,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,e,r,s){let n=this.tensorManager.getMLContext(t),o=this.tensorManager.getMLOpSupportLimits(t),a;if(!o?.input.dataTypes.includes(e)){if(a=dT.get(e),!a||!o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);Ot("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${e} to ${a}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(n,e,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Gd(e,r))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,e,r,i,!0,!0,a),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let e=t;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")e=pT(t,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(t.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else Ot("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(t){if(this.activeUpload){let e=this.wrapper?.isDataConverted?Ud(this.activeUpload,this.wrapper?.type):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(e):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(t):this.wrapper.read()}},mT=class{constructor(t){this.backend=t,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(t){let e=this.backend.getMLContext(t);if(!e)throw new Error("MLContext not found for session.");return e}getMLOpSupportLimits(t){return this.backend.getMLOpSupportLimits(t)}reserveTensorId(){let t=Fd();return this.tensorTrackersById.set(t,new qd(this)),t}releaseTensorId(t){let e=this.tensorTrackersById.get(t);e&&(this.tensorTrackersById.delete(t),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(t,e,r,s,n){Ot("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${r}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(t,r,s,n)}upload(t,e){let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");r.upload(e)}async download(t,e){Ot("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${e?.byteLength}}`);let r=this.tensorTrackersById.get(t);if(!r)throw new Error("Tensor not found.");return r.download(e)}releaseTensorsForSession(t){for(let e of this.freeTensors)e.sessionId===t&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==t)}registerTensor(t,e,r,s){let n=this.getMLContext(t),o=Fd(),a=new jd({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new qd(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[c,u]of this.freeTensors.entries())if(u.canReuseTensor(i,e,r)){Ot("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(c,1)[0];return f.sessionId=t,f}Ot("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}}`);let l=await i.createTensor({dataType:a??e,shape:r,dimensions:r,usage:s,writable:n,readable:o});return new jd({sessionId:t,context:i,tensor:l,dataType:e,shape:r,fallbackDataType:a})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},JT=(...t)=>new mT(...t)}),ZT={};Wo(ZT,{WebNNBackend:()=>eS});var Uo,_T,eS,V$=Ae(()=>{"use strict";Cn(),Us(),q$(),W$(),QT(),Uo=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),_T=(t,e)=>{if(t===e)return!0;if(t===void 0||e===void 0)return!1;let r=Object.keys(t).sort(),s=Object.keys(e).sort();return r.length===s.length&&r.every((n,o)=>n===s[o]&&t[n]===e[n])},eS=class{constructor(t){this.tensorManager=JT(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,YT(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){Ot("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){Ot("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)Ot("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===t);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:s}),s}}else if(t===void 0){let r=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let e=this.mlContextCache.findIndex(r=>_T(r.options,t));if(e!==-1)return this.mlContextCache[e].mlContext;{let r=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:r}),r}}registerMLContext(t,e){this.mlContextBySessionId.set(t,e);let r=this.sessionIdsByMLContext.get(e);r||(r=new Set,this.sessionIdsByMLContext.set(e,r)),r.add(t),this.mlOpSupportLimitsBySessionId.has(t)||this.mlOpSupportLimitsBySessionId.set(t,e.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(t,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t),this.sessionGraphOutputs.delete(t);let e=this.mlContextBySessionId.get(t);if(!e)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t),this.mlOpSupportLimitsBySessionId.delete(t);let r=this.sessionIdsByMLContext.get(e);if(r.delete(t),r.size===0){this.sessionIdsByMLContext.delete(e);let s=this.mlContextCache.findIndex(n=>n.mlContext===e);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}getMLOpSupportLimits(t){return this.mlOpSupportLimitsBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){Ot("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Uo.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,e,o,s,n)}async createTemporaryTensor(t,e,r){Ot("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Uo.get(e);if(!s)throw new Error(`Unsupported ONNX data type: ${e}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,n,s,r,!1);let o=this.temporarySessionTensorIds.get(t);return o?o.push(n):this.temporarySessionTensorIds.set(t,[n]),n}uploadTensor(t,e){if(!je().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ot("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${e.byteLength}}`),this.tensorManager.upload(t,e)}async downloadTensor(t,e){return this.tensorManager.download(t,e)}createMLTensorDownloader(t,e){return async()=>{let r=await this.tensorManager.download(t);return KT(r,e)}}registerMLTensor(t,e,r,s){let n=Uo.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return Ot("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerGraphInput(t){this.temporaryGraphInputs.push(t)}registerGraphOutput(t){this.temporaryGraphOutputs.push(t)}isGraphInput(t,e){let r=this.sessionGraphInputs.get(t);return r?r.includes(e):!1}isGraphOutput(t,e){let r=this.sessionGraphOutputs.get(t);return r?r.includes(e):!1}isGraphInputOutputTypeSupported(t,e,r=!0){let s=Uo.get(zs(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),hT,cm,um,Hr,gT,Wd,ou,pm,fm,Vd,dm,mm,_m,tS=Ae(()=>{"use strict";Ds(),G$(),j$(),Cn(),Us(),om(),XT(),hT=(t,e)=>{je()._OrtInit(t,e)!==0&&ze("Can't initialize onnxruntime.")},cm=async t=>{hT(t.wasm.numThreads,nu(t.logLevel))},um=async(t,e)=>{je().asyncInit?.();let r=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=t.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let n=t.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:n}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(e==="webgpu"&&je().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(V$(),tu(ZT)).WebNNBackend(t);je().webnnInit([s,()=>s.reserveTensorId(),n=>s.releaseTensorId(n),async(n,o,a,i,l)=>s.ensureTensor(n,o,a,i,l),(n,o)=>{s.uploadTensor(n,o)},async(n,o)=>s.downloadTensor(n,o),(n,o)=>s.registerMLContext(n,o),!!t.trace])}},Hr=new Map,gT=t=>{let e=je(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&ze("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},Wd=(t,e)=>{let r=je(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&ze("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let c=r.HEAPU32[n/4+1],u=[];for(let f=0;f{let e=je(),r=e._malloc(t.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,r),[r,t.byteLength]},pm=async(t,e)=>{let r,s,n=je();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=ou(t);let o=0,a=0,i=0,l=[],c=[],u=[];try{if([a,l]=await HT(e),e?.externalData&&n.mountExternalData){let S=[];for(let O of e.externalData){let C=typeof O=="string"?O:O.path,v=typeof O=="string"?O:O.data;S.push(lm(v).then(U=>{n.mountExternalData(C,U)}))}await Promise.all(S)}for(let S of e?.executionProviders??[])if((typeof S=="string"?S:S.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof S!="string"){let O=S,C=O?.context,v=O?.gpuDevice,U=O?.deviceType,j=O?.powerPreference;C?n.currentContext=C:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:U,powerPreference:j})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&ze("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=gT(o),_=!!e?.enableGraphCapture,w=[],x=[],b=[],A=[],k=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor"||S==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&ze("Can't create IO binding."),M={handle:i,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map(S=>S==="ml-tensor-cpu-output"?"ml-tensor":S).map(S=>Yd(S))}),Hr.set(o,[o,c,u,M,_,!1]),[o,w,x,b,A]}catch(f){throw c.forEach(m=>n._OrtFree(m)),u.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&ze("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&ze("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&ze("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},fm=t=>{let e=je(),r=Hr.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&ze("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&ze("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&ze("Can't release session."),Hr.delete(t)},Vd=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=je(),l=i.PTR_SIZE,c=t[0],u=t[1],f=t[3],m=f,_,w;if(c==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let A=t[2].gpuBuffer;w=In(zs(c),u);{let k=i.webgpuRegisterBuffer;if(!k)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=k(A,s)}}else if(f==="ml-tensor"){let A=t[2].mlTensor;w=In(zs(c),u);let k=i.webnnRegisterMLTensor;if(!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=k(s,A,zs(c),u)}else{let A=t[2];if(Array.isArray(A)){w=l*A.length,_=i._malloc(w),r.push(_);for(let k=0;ki.setValue(b+M*l,k,l===4?"i32":"i64"));let A=i._OrtCreateTensor(zs(c),_,w,b,u.length,Yd(m));A===0&&ze(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(A)}finally{i.stackRestore(x)}},dm=async(t,e,r,s,n,o)=>{let a=je(),i=a.PTR_SIZE,l=Hr.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let c=l[0],u=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,b=s.length,A=0,k=[],M=[],S=[],O=[],C=[],v=a.stackSave(),U=a.stackAlloc(x*i),j=a.stackAlloc(x*i),F=a.stackAlloc(b*i),K=a.stackAlloc(b*i);try{[A,k]=VT(o),Kr("wasm prepareInputOutputTensor");for(let I=0;Iqe*Ce,1);L=eu(ge);let et=m?.outputPreferredLocations[s[I]];if(L==="string"){if(et==="gpu-buffer"||et==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let qe=[];for(let Ce=0;Ce0){let qe=a.webgpuGetBuffer;if(!qe)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ce=qe(z),at=In(ge,Re);if(at===void 0||!am(L))throw new Error(`Unsupported data type: ${L}`);me=!0;{a.webgpuRegisterBuffer(Ce,t,z);let lr=a.webgpuCreateDownloader(Ce,at,t);Q.push([L,Fe,{gpuBuffer:Ce,download:async()=>{let Pe=await lr();return new(qo(L))(Pe)},dispose:()=>{a._OrtReleaseTensor(oe)!==0&&ze("Can't release tensor.")}},"gpu-buffer"])}}else if(et==="ml-tensor"&&Re>0){let qe=a.webnnEnsureTensor,Ce=a.webnnIsGraphInputOutputTypeSupported;if(!qe||!Ce)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(In(ge,Re)===void 0||!im(L))throw new Error(`Unsupported data type: ${L}`);if(!Ce(t,L,!1))throw new Error(`preferredLocation "ml-tensor" for ${L} output is not supported by current WebNN Context.`);let at=await qe(t,z,ge,Fe,!1);me=!0,Q.push([L,Fe,{mlTensor:at,download:a.webnnCreateMLTensorDownloader(z,L),dispose:()=>{a.webnnReleaseTensorId(z),a._OrtReleaseTensor(oe)}},"ml-tensor"])}else if(et==="ml-tensor-cpu-output"&&Re>0){let qe=a.webnnCreateMLTensorDownloader(z,L)(),Ce=Q.length;me=!0,B.push((async()=>{let at=[Ce,await qe];return a.webnnReleaseTensorId(z),a._OrtReleaseTensor(oe),at})()),Q.push([L,Fe,[],"cpu"])}else{let qe=qo(L),Ce=new qe(Re);new Uint8Array(Ce.buffer,Ce.byteOffset,Ce.byteLength).set(a.HEAPU8.subarray(z,z+Ce.byteLength)),Q.push([L,Fe,Ce,"cpu"])}}finally{a.stackRestore(J),L==="string"&&z&&a._free(z),me||a._OrtReleaseTensor(oe)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&ze("Can't clear bound outputs."),Hr.set(t,[c,u,f,m,_,!1]));for(let[I,oe]of await Promise.all(B))Q[I][2]=oe;return Yr("wasm ProcessOutputTensor"),Q}finally{a.webnnOnRunEnd?.(c),a.stackRestore(v),r.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),n.forEach(Y=>{Y&&Y[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(Y[2].gpuBuffer)}),M.forEach(Y=>a._OrtReleaseTensor(Y)),S.forEach(Y=>a._OrtReleaseTensor(Y)),O.forEach(Y=>a._free(Y)),A!==0&&a._OrtReleaseRunOptions(A),k.forEach(Y=>a._free(Y))}},mm=t=>{let e=je(),r=Hr.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&ze("Can't get an profile file name."),e._OrtFree(n)},_m=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Xr,Vt,On,Fo,Go,Jc,Hd,Zc,Ps,Ns,wT,rS,sS,nS,oS,aS,iS,lS,cS=Ae(()=>{"use strict";Ds(),tS(),Us(),sm(),Xr=()=>!!Je.wasm.proxy&&typeof document<"u",On=!1,Fo=!1,Go=!1,Zc=new Map,Ps=(t,e)=>{let r=Zc.get(t);r?r.push(e):Zc.set(t,[e])},Ns=()=>{if(On||!Fo||Go||!Vt)throw new Error("worker not ready")},wT=t=>{switch(t.data.type){case"init-wasm":On=!1,t.data.err?(Go=!0,Hd[1](t.data.err)):(Fo=!0,Hd[0]()),Jc&&(URL.revokeObjectURL(Jc),Jc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Zc.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},rS=async()=>{if(!Fo){if(On)throw new Error("multiple calls to 'initWasm()' detected.");if(Go)throw new Error("previous call to 'initWasm()' failed.");if(On=!0,Xr())return new Promise((t,e)=>{Vt?.terminate(),qT().then(([r,s])=>{try{Vt=s,Vt.onerror=o=>e(o),Vt.onmessage=wT,Hd=[t,e];let n={type:"init-wasm",in:Je};!n.in.wasm.wasmPaths&&(r||Kd)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Vt.postMessage(n),Jc=r}catch(n){e(n)}},e)});try{await nm(Je.wasm),await cm(Je),Fo=!0}catch(t){throw Go=!0,t}finally{On=!1}}},sS=async t=>{if(Xr())return Ns(),new Promise((e,r)=>{Ps("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:Je}};Vt.postMessage(s)});await um(Je,t)},nS=async t=>Xr()?(Ns(),new Promise((e,r)=>{Ps("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Vt.postMessage(s,[t.buffer])})):ou(t),oS=async(t,e)=>{if(Xr()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ns(),new Promise((r,s)=>{Ps("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Vt.postMessage(n,o)})}else return pm(t,e)},aS=async t=>{if(Xr())return Ns(),new Promise((e,r)=>{Ps("release",[e,r]);let s={type:"release",in:t};Vt.postMessage(s)});fm(t)},iS=async(t,e,r,s,n,o)=>{if(Xr()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ns(),new Promise((a,i)=>{Ps("run",[a,i]);let l=r,c={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Vt.postMessage(c,_m(l))})}else return dm(t,e,r,s,n,o)},lS=async t=>{if(Xr())return Ns(),new Promise((e,r)=>{Ps("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Vt.postMessage(s)});mm(t)}}),Xd,xT,uS,H$=Ae(()=>{"use strict";Ds(),cS(),Cn(),rm(),XT(),Xd=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},xT=t=>{switch(t[3]){case"cpu":return new sr(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!am(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return sr.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!im(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return sr.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},uS=class{async fetchModelAndCopyToWasmMemory(t){return nS(await lm(t))}async loadModel(t,e){Rs();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await oS(r,e),Bs()}async dispose(){return aS(this.sessionId)}async run(t,e,r){Rs();let s=[],n=[];Object.entries(t).forEach(f=>{let m=f[0],_=f[1],w=this.inputNames.indexOf(m);if(w===-1)throw new Error(`invalid input '${m}'`);s.push(_),n.push(w)});let o=[],a=[];Object.entries(e).forEach(f=>{let m=f[0],_=f[1],w=this.outputNames.indexOf(m);if(w===-1)throw new Error(`invalid output '${m}'`);o.push(_),a.push(w)});let i=s.map((f,m)=>Xd(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?Xd(f,()=>`output "${this.outputNames[a[m]]}"`):null),c=await iS(this.sessionId,n,i,a,l,r),u={};for(let f=0;fJd,initializeFlags:()=>Qd,wasmBackend:()=>fS});var Qd,Jd,fS,X$=Ae(()=>{"use strict";Ds(),cS(),H$(),Qd=()=>{(typeof Je.wasm.initTimeout!="number"||Je.wasm.initTimeout<0)&&(Je.wasm.initTimeout=0);let t=Je.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),Je.wasm.simd=!1),typeof Je.wasm.proxy!="boolean"&&(Je.wasm.proxy=!1),typeof Je.wasm.trace!="boolean"&&(Je.wasm.trace=!1),typeof Je.wasm.numThreads!="number"||!Number.isInteger(Je.wasm.numThreads)||Je.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Je.wasm.numThreads=1;else{let e=typeof navigator>"u"?A$("node:os").cpus().length:navigator.hardwareConcurrency;Je.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Jd=class{async init(t){Qd(),await rS(),await sS(t)}async createInferenceSessionHandler(t,e){let r=new uS;return await r.loadModel(t,e),r}},fS=new Jd});Ds();Ds();Ds();var K$="1.31.0-dev.20260914-8d85527a0",Y$=BT;{let t=(X$(),tu(pS)).wasmBackend;$s("webgpu",t,5),$s("webnn",t,5),$s("cpu",t,10),$s("wasm",t,10)}Object.defineProperty(Je.versions,"web",{value:K$,enumerable:!0});async function dS(t){let e=t.split("/").pop(),r;try{if(r=await rr(),r){let n=await r.match(t);if(n)return n}}catch(n){te.warn(`Failed to load ${e} from cache:`,n)}let s=await he.fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){te.warn(`Failed to cache ${e}:`,n)}return s}async function mS(t){let e=await dS(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return te.warn("Failed to read WASM binary:",r),null}}async function _S(t){if(le.IS_SERVICE_WORKER_ENV||le.IS_CHROME_AVAILABLE)return t;let e=await dS(t);if(!e||typeof e=="string")return null;try{let r=await e.text();r=r.replaceAll("globalThis.process?.versions?.node","false");let s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return te.warn("Failed to read WASM factory:",r),null}}var hS="1.30.0";var gS="warning",gm={wasm:{},webgl:{},webgpu:{},versions:{common:hS},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);gS=t}},get logLevel(){return gS}};Object.defineProperty(gm,"logLevel",{enumerable:!0});var wS=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=t.dims[3],r.height=t.dims[2];let s=r.getContext("2d");if(s!=null){let n,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[3]):(n=t.dims[3],o=t.dims[2]);let a=e?.format!==void 0?e.format:"RGB",i=e?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let u=o*n,f=0,m=u,_=u*2,w=-1;a==="RGBA"?(f=0,m=u,_=u*2,w=u*3):a==="RGB"?(f=0,m=u,_=u*2):a==="RBG"&&(f=0,_=u,m=u*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,c,u;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?u=[0,0,0,0]:typeof l.bias=="number"?u=[l.bias,l.bias,l.bias,l.bias]:(u=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(u[3]=l.bias[3]));let f=o*n;if(e!==void 0&&(e.format!==void 0&&a===4&&e.format!=="RGBA"||a===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let m=4,_=0,w=1,x=2,b=3,A=0,k=f,M=f*2,S=-1;i==="RGBA"?(A=0,k=f,M=f*2,S=f*3):i==="RGB"?(A=0,k=f,M=f*2):i==="RBG"&&(A=0,M=f,k=f*2),s=r.createImageData(n,o);for(let O=0;O{if(t===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=e,n=e.norm??{mean:255,bias:0},o,a;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=e.format!==void 0?e.format:"RGBA",l=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",c=r*s,u=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),f=4,m=0,_=1,w=2,x=3,b=0,A=c,k=c*2,M=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?M=c*3:l==="RBG"?(b=0,k=c,A=c*2):l==="BGR"&&(k=0,A=c,b=c*2);for(let O=0;O{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=u=>typeof HTMLCanvasElement<"u"&&u instanceof HTMLCanvasElement||u instanceof OffscreenCanvas?u.getContext("2d"):null;if(r){let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(m=e.resizedHeight,_=e.resizedWidth),e!==void 0){if(i=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=m,i.width=_}else i.tensorFormat="RGBA",i.height=m,i.width=_;f.drawImage(t,0,0),a=f.getImageData(0,0,_,m).data}else throw new Error("Can not access image data")}else if(s){let u,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(u=e.resizedHeight,f=e.resizedWidth):(u=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=u,i.width=f,e!==void 0){let m=l();m.width=f,m.height=u;let _=c(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,u).data;else throw new Error("Can not access image data")}else a=t.data}else if(n){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let u=l();u.width=t.width,u.height=t.height;let f=c(u);if(f!=null){let m=t.height,_=t.width;return f.drawImage(t,0,0,_,m),a=f.getImageData(0,0,_,m).data,i.height=m,i.width=_,wm(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((u,f)=>{let m=l(),_=c(m);if(!t||!_)return f();let w=new Image;w.crossOrigin="Anonymous",w.src=t,w.onload=()=>{m.width=w.width,m.height=w.height,_.drawImage(w,0,0,m.width,m.height);let x=_.getImageData(0,0,m.width,m.height);i.height=m.height,i.width=m.width,u(wm(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return wm(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},bS=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new vt({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},vS=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new vt({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},kS=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new vt({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},ES=(t,e,r)=>new vt({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]});var Fs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Vo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),AS=!1,TS=()=>{if(!AS){AS=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(Fs.set("int64",BigInt64Array),Vo.set(BigInt64Array,"int64")),e&&(Fs.set("uint64",BigUint64Array),Vo.set(BigUint64Array,"uint64")),s?(Fs.set("float16",r),Vo.set(r,"float16")):Fs.set("float16",Uint16Array)}};var SS=t=>{let e=1;for(let r=0;r{switch(t.location){case"cpu":return new vt(t.type,t.data,e);case"cpu-pinned":return new vt({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new vt({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new vt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new vt({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};var vt=class{constructor(e,r,s){TS();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Fs.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,l;if(typeof e=="string")if(n=e,l=s,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let c=Fs.get(e);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&c===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${c.name} as data.`);e==="uint64"||e==="int64"?i=c.from(r,BigInt):i=c.from(r)}else if(r instanceof c)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof e[0];if(c==="string")n="string",i=e;else if(c==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let c=Vo.get(e.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=c,i=e}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}let a=SS(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(e,r){return yS(e,r)}static fromTexture(e,r){return bS(e,r)}static fromGpuBuffer(e,r){return vS(e,r)}static fromMLTensor(e,r){return kS(e,r)}static fromPinnedBuffer(e,r,s){return ES(e,r,s)}toDataURL(e){return wS(this,e)}toImageData(e){return xS(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return MS(this,e)}};var au=vt;var Q$=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 PS(t){return t<=It.DEBUG?0:t<=It.INFO?2:t<=It.WARNING||t<=It.ERROR?3:4}var J$={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Rt=[],xm,Nn,OS=Symbol.for("onnxruntime");if(OS in globalThis)Nn=globalThis[OS];else if(le.IS_NODE_ENV){switch(Nn=W2,process.platform){case"win32":Rt.push("dml");break;case"linux":process.arch==="x64"&&Rt.push("cuda");break;case"darwin":Rt.push("coreml");break}Rt.push("webgpu"),Rt.push("cpu"),xm=["cpu"]}else Nn=hm,le.IS_WEBNN_AVAILABLE&&Rt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),le.IS_WEBGPU_AVAILABLE&&Rt.push("webgpu"),Rt.push("wasm"),xm=["wasm"];function Z$(){return[...Rt]}var eR=Nn.InferenceSession;function NS(t=null){if(!t)return xm;switch(t){case"auto":return Rt;case"gpu":return Rt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Rt.includes(t))return[Q$[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Rt.join(", ")}.`)}var IS=Promise.resolve(),Pn=null;async function tR(){if(Pn)return Pn;if(!(he.useWasmCache&&typeof ft?.wasm?.wasmPaths=="object"&&ft?.wasm?.wasmPaths?.wasm&&ft?.wasm?.wasmPaths?.mjs)){if(le.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return Pn=Promise.resolve(),Pn}return Pn=(async()=>{let e=ft.wasm.wasmPaths,r=!1;await Promise.all([e.wasm&&!vd(e.wasm)?(async()=>{try{let s=await mS(No(e.wasm));s&&(ft.wasm.wasmBinary=s,r=!0)}catch(s){te.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),e.mjs&&!vd(e.mjs)?(async()=>{try{let s=await _S(No(e.mjs));s&&(ft.wasm.wasmPaths.mjs=s)}catch(s){te.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(ft.wasm.wasmPaths.mjs=e.mjs)})(),Pn}async function iu(t,e,r){await tR();let s=PS(he.logLevel??It.WARNING),n=()=>eR.create(t,{logSeverityLevel:s,...e}),o=await(le.IS_WEB_ENV?IS=IS.then(n):n());return o.config=r,o}var CS=Promise.resolve();async function lu(t,e){let r=()=>t.run(e);return le.IS_WEB_ENV?CS=CS.then(r):r()}function cu(t){return t instanceof Nn.Tensor}var ft=Nn?.env;function Ho(){return ft?.wasm?.proxy}if(ft){let t=function(e){let r=PS(e);ft.logLevel=J$[r]};if(ft.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&ft.versions?.web&&!ft.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${ft.versions.web}/dist/`,r=".asyncify";le.IS_SAFARI_BELOW_26&&!le.IS_WEBGPU_AVAILABLE&&(r=""),ft.wasm.wasmPaths={mjs:`${e}ort-wasm-simd-threaded${r}.mjs`,wasm:`${e}ort-wasm-simd-threaded${r}.wasm`}}ft.wasm.proxy=!1}ft.webgpu&&(ft.webgpu.powerPreference="high-performance"),t(he.logLevel??It.WARNING),he.backends.onnx={...ft,setLogLevel:t,getSupportedDevices:Z$}}var Qr=async(t,e,r)=>{let s=await iu(new Uint8Array(t),e);return(async n=>{let o=Ho(),a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,(o?c.clone():c).ort_tensor])),i=await lu(s,a);return Array.isArray(r)?r.map(l=>new $(i[l])):new $(i[r])})},hr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Qr([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=Qr([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=Qr([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=Qr([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=Qr([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=Qr([8,9,58,93,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,19,10,1,120,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,1,90,11,10,1,97,18,6,10,4,8,7,18,0,98,19,10,1,121,18,14,10,12,8,1,18,8,10,0,10,0,10,2,8,2,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Qr([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=Qr([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}};var LS=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"}),ym=le.IS_NODE_ENV?"cpu":"wasm";function uu(t,e,{warn:r}={}){return t?typeof t=="string"?t:t.hasOwnProperty(e)?t[e]:(r&&r(`device not specified for "${e}". Using the default device (${ym}).`),ym):ym}var RS=(function(){let t;return async function(){if(t===void 0)if(!le.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),it=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"}),zS=it.fp32,$S=Object.freeze({[LS.wasm]:it.q8}),Jr=Object.freeze({[it.fp32]:"",[it.fp16]:"_fp16",[it.int8]:"_int8",[it.uint8]:"_uint8",[it.q8]:"_quantized",[it.q4]:"_q4",[it.q2]:"_q2",[it.q1]:"_q1",[it.q4f16]:"_q4f16",[it.q2f16]:"_q2f16",[it.q1f16]:"_q1f16",[it.bnb4]:"_bnb4"});function pu(t,e,r,{configDtype:s=null,warn:n}={}){let o,a=!1;t&&typeof t!="string"?t.hasOwnProperty(e)?o=t[e]:(o=null,a=!0):o=t;let i;if(o===it.auto){if(s){let l=typeof s=="string"?s:s?.[e];if(l&&l!==it.auto&&it.hasOwnProperty(l))return l}i=$S[r]??zS}else o&&it.hasOwnProperty(o)?i=o:i=$S[r]??zS;return a&&n&&n(`dtype not specified for "${e}". Using the default dtype (${i}) for this device (${r}).`),i}var Zr=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});var $=class t{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return cu(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new au(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}_subarray(e,r,s){let n=e*r,o=(e+1)*r,a="subarray"in this.data?this.data.subarray(n,o):this.data.slice(n,o);return new t(this.type,a,s)}item(){let e=this.data;if(e.length!==1)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return rR(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let r=0;r0||a>0&&n<0;r[o]=i?a+n:a}return this}clone(){return new t(this.type,this.data.slice(),this.dims.slice())}slice(...e){let r=[],s=[];for(let u=0;u_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[u])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([u,f])=>f-u),o=n.reduce((u,f)=>u*f),a=this.data,i=new a.constructor(o),l=this.stride(),c=!0;for(let u=1;u=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[u]=a[f]}return new t(this.type,i,r)}permute(...e){return sR(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,r=!1){return this.norm(1,e,r)}norm(e="fro",r=null,s=!1){if(e==="fro")e=2;else if(typeof e=="string")throw Error(`Unsupported norm: ${e}`);let n=this.data,o=n instanceof BigInt64Array||n instanceof BigUint64Array;if(o&&e!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let a,i;if(o?(a=(f,m)=>f+m,i=0n):(a=(f,m)=>f+m**e,i=0),r===null){let f=n.reduce(a,i);return e!==1&&(f=f**(1/e)),new t(this.type,[f],[])}let[l,c,u]=Xo(a,this,r,s);if(e!==1)for(let f=0;f=0;--l){let f=this.dims[l];if(l!==r){let m=c%f;i+=m*u,u*=this.dims[l]}c=Math.floor(c/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return bm(this.dims)}squeeze(e=null){return new t(this.type,this.data,BS(this.dims,e))}squeeze_(e=null){return this.dims=BS(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,DS(this.dims,e))}unsqueeze_(e){return this.dims=DS(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;ni!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;re?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;nMath.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Le(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Xo((a,i)=>Math.max(a,i),this,e,r,-1/0);return new t(s,n,o)}argmin(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Ro(this.data)[1];return new t("int64",[BigInt(s)],[])}argmax(e=null,r=!1){if(e!==null)throw new Error("`dim !== null` not yet implemented.");let s=Le(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.lengthu===1)){if(e.length===this.dims.length)return this.clone();let u=e.length-this.dims.length,f=Array(u).fill(1).concat(this.dims);return new t(this.type,this.data.slice(),f)}let r=e.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),n=s.map((u,f)=>u*e[f]),o=n.reduce((u,f)=>u*f,1),a=this.data,i=new a.constructor(o),l=bm(s),c=bm(n);for(let u=0;uBigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,q2(this.data),this.dims);return new t(e,Zr[e].from(this.data,r),this.dims)}};function rR(t,e){let r=t.length,s=e.length===0?1:e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.lengthnew $("int64",t,[t.length]);async function du(t,e,r,s,n){return await(await hr.slice)({x:t,s:fu(e),e:fu(r),a:fu(s),t:fu(n??new Array(s.length).fill(1))})}function FS(t,e){let r=t.data,s=e.data,n=[t.dims[0],t.dims[2]],o=new r.constructor(n[0]*n[1]),[a,i,l]=t.dims,c=0;for(let u=0;ur!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function DS(t,e){return e=nr(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function nr(t,e,r=null,s=!0){if(t<-e||t>=e){if(s)throw new Error(`IndexError: index ${t} is out of bounds for dimension${r===null?"":" "+r} with size ${e}`);return t<-e?0:e}return t<0&&(t=(t%e+e)%e),t}function Ee(t,e=0){e=nr(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i=0;--m){let x=c[m],b=_%x;m===e&&(b+=a),f+=b*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[u]}a+=c[e]}}return new $(o,n,r)}function kt(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function Xo(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=nr(r,a.length);let i=a.slice();i[r]=1;let l=new o.constructor(o.length/a[r]);n!==null&&l.fill(n);for(let c=0;c=0;--f){let w=a[f];if(f!==r){let x=m%w;u+=x*_,_*=i[f]}m=Math.floor(m/w)}l[u]=t(l[u],o[c],c,u)}return s||i.splice(r,1),[e.type,l,i]}function km(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((A,k)=>A+k,0)/n.length,w=Math.sqrt(n.reduce((A,k)=>A+(k-_)**2,0)/(n.length-r)),x=new $(t.type,[_],[]);return[new $(t.type,[w],[]),x]}e=nr(e,o.length);let a=mu(t,e,s),i=a.data,[l,c,u]=Xo((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;mc+u,0);return new $(t.type,[l/n.length],[])}e=nr(e,s.length);let[o,a,i]=Xo((l,c)=>l+c,t,e,r);if(s[e]!==1)for(let l=0;l=0;--r)e[r]=s,s*=t[r];return e}function Em(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new $(r,new s(n).fill(e),t)}function Ze(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return Em(t,e,r,s)}function Ko(t,e){return Ze(t.dims,e)}function st(t){return Em(t,1n,"int64",BigInt64Array)}function Ln(t){return st(t.dims)}function Am(t){return Em(t,0n,"int64",BigInt64Array)}function Yo(t){return Am(t.dims)}function e6(t){let e=t.reduce((r,s)=>r*s,1);return new $("float32",Float32Array.from({length:e},()=>Os.random()),t)}function GS(t){let e=t.reduce((r,s)=>r*s,1);return new $("float32",Float32Array.from({length:e},()=>Os.gauss()),t)}function jS(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i0?1:0,c=Math.floor(i/8),u=i%8;a[c]|=l<<7-u,r&&u===0&&(a[c]-=128)}return new $(s,a,[t.dims[0],t.dims[1]/8])}async function zn(t){if(!t)throw new Error("modelId is required for get_tokenizer_files");return(await Pt(t,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function Tm(t,e){let r=await zn(t);return await Promise.all(r.map(s=>lt(t,s,!0,e)))}function Qo(t){let e=t.dims;switch(e.length){case 1:return t.tolist();case 2:if(e[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return t.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${e.length}.`)}}var nR=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function oR(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?yt(t[n],i):yt(i,t[n])}}function aR(t,e){for(let r of Object.keys(t))t[r].length=e}function Gs(t,...e){for(let r of e){if(!Object.hasOwn(t,r))continue;let s=t[r];if(s)if(typeof s=="object"){if(s.__type==="AddedToken")return s.content;throw Error(`Unknown token: ${s}`)}else return s}return null}function iR(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var V=class extends We{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new l2(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Gs(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Gs(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Gs(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Gs(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Gs(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Gs(r,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){let n=Object.create(null);for(let{name:o,template:a}of this.chat_template){if(typeof o!="string"||typeof a!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');n[o]=a}this.chat_template=n}this._compiled_template_cache=new Map;let s=iR(this._tokenizer);this.all_special_ids=s.map(n=>n.id),this.all_special_tokens=s.map(n=>n.content)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let i=await Tm(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,r={}){let{text_pair:s=null,add_special_tokens:n=!0,padding:o=!1,return_token_type_ids:a=null}=r,{truncation:i=null,max_length:l=null}=r,c=r.return_tensor??!0,u=Array.isArray(e),f;if(u){if(e.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(e.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");f=e.map((_,w)=>this._encode_plus(_,{text_pair:s[w],add_special_tokens:n,return_token_type_ids:a}))}else f=e.map(_=>this._encode_plus(_,{add_special_tokens:n,return_token_type_ids:a}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");f=[this._encode_plus(e,{text_pair:s,add_special_tokens:n,return_token_type_ids:a})]}if(l===null?l=this.model_max_length:i===null&&(o===!0?(te.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):o===!1&&(te.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),o===!0&&(l=Math.min(Le(f.map(_=>_.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),o||i)for(let _=0;_l?i&&aR(f[_],l):o&&oR(f[_],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));let m={};if(c){if(!(o&&i)&&f.some(w=>{for(let x of Object.keys(w))if(w[x].length!==f[0][x]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let _=[f.length,f[0].input_ids.length];for(let w of Object.keys(f[0]))m[w]=new $("int64",BigInt64Array.from(f.flatMap(x=>x[w]).map(BigInt)),_)}else{for(let _ of Object.keys(f[0]))m[_]=f.map(w=>w[_]);if(!u)for(let _ of Object.keys(m))m[_]=m[_][0]}return m}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof $&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof $&&(e=Qo(e)),!Array.isArray(e)||e.length===0||!IA(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,r={}){let{tools:s=null,documents:n=null,chat_template:o=null,add_generation_prompt:a=!1,tokenize:i=!0,padding:l=!1,truncation:c=!1,max_length:u=null,return_tensor:f=!0,return_dict:m=!0,tokenizer_kwargs:_={},...w}=r;if(o=this.get_chat_template({chat_template:o,tools:s}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let x=this._compiled_template_cache.get(o);x===void 0&&(x=new T2(o),this._compiled_template_cache.set(o,x));let b=Object.create(null);for(let k of nR){let M=Gs(this.config,k);M&&(b[k]=M)}let A=x.render({messages:e,add_generation_prompt:a,tools:s,documents:n,...b,...w});if(i){let k=this._call(A,{add_special_tokens:!1,padding:l,truncation:c,max_length:u,return_tensor:f,..._});return m?k:k.input_ids}return A}};function $n(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);let a=t._tokenizer.post_processor?.config;if(a&&"single"in a){for(let i of a.single)if("SpecialToken"in i&&t.languageRegex.test(i.SpecialToken.id)){i.SpecialToken.id=t.lang_to_token(n);break}}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var w_={};yn(w_,{AlbertTokenizer:()=>Sm,AutoTokenizer:()=>ne,BartTokenizer:()=>Mm,BertTokenizer:()=>Om,BlenderbotSmallTokenizer:()=>Im,BlenderbotTokenizer:()=>Cm,BloomTokenizer:()=>Pm,CLIPTokenizer:()=>Lm,CamembertTokenizer:()=>Nm,CodeGenTokenizer:()=>$m,CodeLlamaTokenizer:()=>zm,CohereAsrTokenizer:()=>Bm,CohereTokenizer:()=>Rm,ConvBertTokenizer:()=>Dm,DebertaTokenizer:()=>Fm,DebertaV2Tokenizer:()=>Um,DistilBertTokenizer:()=>Gm,ElectraTokenizer:()=>jm,EsmTokenizer:()=>qm,FalconTokenizer:()=>Wm,GPT2Tokenizer:()=>Xm,GPTNeoXTokenizer:()=>Hm,GemmaTokenizer:()=>Vm,HerbertTokenizer:()=>Km,LlamaTokenizer:()=>Ym,M2M100Tokenizer:()=>Qm,MBart50Tokenizer:()=>Zm,MBartTokenizer:()=>Jo,MPNetTokenizer:()=>r_,MarianTokenizer:()=>Jm,MgpstrTokenizer:()=>e_,MobileBertTokenizer:()=>t_,NllbTokenizer:()=>s_,NougatTokenizer:()=>n_,PreTrainedTokenizer:()=>V,Qwen2Tokenizer:()=>o_,RoFormerTokenizer:()=>i_,RobertaTokenizer:()=>a_,SiglipTokenizer:()=>l_,SpeechT5Tokenizer:()=>c_,SqueezeBertTokenizer:()=>u_,T5Tokenizer:()=>p_,TokenizersBackend:()=>V,VitsTokenizer:()=>d_,Wav2Vec2CTCTokenizer:()=>m_,WhisperTokenizer:()=>__,XLMRobertaTokenizer:()=>h_,XLMTokenizer:()=>g_});var Sm=class extends V{return_token_type_ids=!0};var Mm=class extends V{};var Om=class extends V{return_token_type_ids=!0};var Im=class extends V{};var Cm=class extends V{};var Pm=class extends V{};var Nm=class extends V{};var Lm=class extends V{};var zm=class extends V{};var $m=class extends V{};var Rm=class extends V{};var Bm=class extends V{};var Dm=class extends V{return_token_type_ids=!0};var Um=class extends V{return_token_type_ids=!0};var Fm=class extends V{return_token_type_ids=!0};var Gm=class extends V{};var jm=class extends V{return_token_type_ids=!0};var qm=class extends V{};var Wm=class extends V{};var Vm=class extends V{};var Hm=class extends V{};var Xm=class extends V{};var Km=class extends V{return_token_type_ids=!0};var Ym=class extends V{padding_side="left"};var Qm=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return $n(this,e,r,s)}};var Jm=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),te.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||te.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),yt([n],super._encode_text(o))}}};var Jo=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return $n(this,e,r,s)}};var Zm=class extends Jo{};var e_=class extends V{};var t_=class extends V{return_token_type_ids=!0};var r_=class extends V{};var s_=class extends V{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return $n(this,e,r,s)}};var n_=class extends V{};var o_=class extends V{};var a_=class extends V{};var i_=class extends V{return_token_type_ids=!0};var l_=class extends V{};var c_=class extends V{};var u_=class extends V{return_token_type_ids=!0};var p_=class extends V{};var f_=class extends jt{decode_chain(e){let r="";for(let s=1;s[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function WS(t){t=t.toLowerCase();let e=lR.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Zo.has(t))e=t;else{let n=t.length===2?Zo.keys():Zo.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var cR="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",VS=new RegExp(`^[${cR}]+$`,"gu"),uR=.1,__=class extends V{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let c=[],u=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],b=[],A=!1,k=null,M=new Set(this.all_special_ids);for(let C of e){let v=C.tokens,U=i?C.token_timestamps:null,j=null,F=m;if("stride"in C){let[Q,B,I]=C.stride;if(f-=B,k=Q-I,B&&(F=B/n+m),I)for(let oe=v.length-1;oe>=0;--oe){let J=Number(v[oe]);if(J>=m){if(j!==null&&(J-m)*n=m&&B<=w){let I=(B-m)*n+f,oe=Cs(I,2);if(j!==null&&B>=j)A=!0;else if(A||x.length>0&&B0&&u.timestamp[1]!==null))for(let L of u.words)L.timestamp[1]>u.timestamp[1]&&u.timestamp[1]>=L.timestamp[0]&&(L.timestamp[1]=u.timestamp[1]);c.push(u),x=[],K=[],b=[],Y=[],u=l()}}else if(K.push(B),i){let I=Cs(U[Q]+f,2),oe;if(Q+10?(x.push(K),i&&b.push(Y)):x.every(Q=>Q.length===0)&&(u=l(),x=[],K=[],b=[],Y=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[C,v]=this.findLongestCommonSequence(x,b),U=this.decode(C);u.text=U,i&&(u.words=this.collateWordTimestamps(C,v,a)),c.push(u)}let S=Object.create(null),O=c.map(C=>C.text).join("");if(r||s){for(let C=0;C0,i=a?[]:null,l=a?r[0]:null;for(let c=1;cB===F[I]&&l[O+I][0]-uR<=r[c][U+I][0]).length:K=v.filter((B,I)=>B===F[I]).length;let Y=S/1e4,Q=K/S+Y;K>1&&Q>f&&(f=Q,m=[O,C,U,j])}let[w,x,b,A]=m,k=Math.floor((x+w)/2),M=Math.floor((A+b)/2);if(a&&f===0&&n>0){let S=l[n-1][0],O=r[c].findIndex(C=>C[0]>=S);M=O===-1?u.length:O}o.push(...s.slice(0,k)),s=u.slice(M),n=s.length,a&&(i.push(...l.slice(0,k)),l=r[c].slice(M))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],c=0;for(let u=0;u=this._tokenizer.token_to_id("<|endoftext|>"),_=c.startsWith(" "),w=c.trim(),x=VS.test(w);if(m||_||x||o.length===0)o.push(c),a.push(u),i.push(f);else{let b=o.length-1;o[b]+=c,a[b].push(...u),i[b].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),c=a.length-2,u=a.length-1;for(;c>=0;)a[c].startsWith(" ")&&n.includes(a[c].trim())?(a[u]=a[c]+a[u],i[u]=yt(i[c],i[u]),l[u]=yt(l[c],l[u]),a[c]="",i[c]=[],l[c]=[]):u=c,--c;for(c=0,u=1;uf),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var h_=class extends V{};var g_=class extends V{return_token_type_ids=!0;constructor(e,r){super(e,r),te.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var ne=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Tm(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),c=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",u=w_[c];return u||(te.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=V),new u(i,l)}};var es="https://github.com/huggingface/transformers.js/issues/new/choose",_u="preprocessor_config.json",Mr="preprocessor_config.json",hu="processor_config.json",gu="chat_template.jinja";var se=class extends We{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?lt(e,hu,!0,r):{},Promise.all(this.classes.filter(a=>a in this).map(async a=>{let i=await this[a].from_pretrained(e,r);return[a.replace(/_class$/,""),i]})).then(Object.fromEntries),this.uses_chat_template_file?$o(e,gu,!0,r):null]);return new this(s,n,o)}};var ju={};yn(ju,{ChatterboxProcessor:()=>L_,CohereAsrProcessor:()=>z_,EmbeddingGemma2Processor:()=>R_,EmbeddingGemma2VideoProcessor:()=>ca,Florence2Processor:()=>Ih,Gemma3Processor:()=>Ch,Gemma3nProcessor:()=>Ph,Gemma4Processor:()=>la,Glm46VProcessor:()=>Nh,GraniteSpeechProcessor:()=>Lh,GroundingDinoProcessor:()=>zh,Idefics3Processor:()=>Du,JinaCLIPProcessor:()=>Rh,Lfm2VlProcessor:()=>Bh,Lfm3VlProcessor:()=>Dh,LlavaProcessor:()=>Uh,MgpstrProcessor:()=>Fh,MoonshineProcessor:()=>Gh,OwlViTProcessor:()=>jh,PaliGemmaProcessor:()=>qh,Phi3VProcessor:()=>Wh,PixtralProcessor:()=>Vh,Processor:()=>se,PyAnnoteProcessor:()=>Hh,Qwen2VLProcessor:()=>Vs,Qwen2_5_VLProcessor:()=>pa,Qwen3VLProcessor:()=>Xh,Sam2Processor:()=>Uu,Sam2VideoProcessor:()=>Kh,SamProcessor:()=>fa,SmolVLMProcessor:()=>Du,SpeechT5Processor:()=>Yh,UltravoxProcessor:()=>Qh,VLChatProcessor:()=>$h,VoxtralProcessor:()=>Jh,VoxtralRealtimeProcessor:()=>eg,Wav2Vec2Processor:()=>tg,Wav2Vec2ProcessorWithLM:()=>rg,WhisperProcessor:()=>sg});var Oe=class extends We{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await lt(e,_u,!0,r);return new this(s)}};function Ie(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var ia={};yn(ia,{ASTFeatureExtractor:()=>b_,ChatterboxFeatureExtractor:()=>v_,ClapFeatureExtractor:()=>k_,CohereAsrFeatureExtractor:()=>E_,DacFeatureExtractor:()=>sa,EncodecFeatureExtractor:()=>ta,FeatureExtractor:()=>Oe,Gemma3nAudioFeatureExtractor:()=>na,Gemma4AudioFeatureExtractor:()=>oa,GraniteSpeechFeatureExtractor:()=>A_,MoonshineFeatureExtractor:()=>T_,ParakeetFeatureExtractor:()=>ra,PyAnnoteFeatureExtractor:()=>aa,SeamlessM4TFeatureExtractor:()=>S_,SnacFeatureExtractor:()=>M_,SpeechT5FeatureExtractor:()=>O_,VoxtralRealtimeFeatureExtractor:()=>P_,Wav2Vec2FeatureExtractor:()=>I_,WeSpeakerFeatureExtractor:()=>C_,WhisperFeatureExtractor:()=>N_});var pR=()=>{};var HS={fromWeb:pR};var fR=()=>{};var XS=fR;async function wu(t,e){if(le.IS_BROWSER_ENV){if(le.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(le.IS_FS_AVAILABLE){let r=e.stream(),s=HS.fromWeb(r),n=xt.createWriteStream(t);await XS(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function QS(t,e){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let r=await(await jr(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&te.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let c=0;c2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function x_(t,e="htk"){let r=mR[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}var _R={htk:t=>700*(10**(t/2595)-1),kaldi:t=>700*(Math.exp(t/1127)-1),slaney:(t,e=1e3,r=15,s=Math.log(6.4)/27)=>t>=r?e*Math.exp(s*(t-r)):200*t/3};function hR(t,e="htk"){let r=_R[e];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof t=="number"?r(t):t.map(s=>r(s))}function gR(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;anew Array(t.length));for(let a=0;at+s*o)}function dt(t,e,r,s,n,o=null,a="htk",i=!1){if(o!==null&&o!=="slaney")throw new Error('norm must be one of null or "slaney"');if(t<2)throw new Error(`Require num_frequency_bins: ${t} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);let l=x_(r,a),c=x_(s,a),u=YS(l,c,e+2),f=hR(u,a),m;if(i){let w=n/((t-1)*2);m=x_(Float64Array.from({length:t},(x,b)=>b*w),a),f=u}else m=YS(0,Math.floor(n/2),t);let _=gR(m,f);if(o!==null&&o==="slaney")for(let w=0;wn)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(j!==r)throw new Error(`Length of the window (${j}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a){let z=Math.floor(r/2);switch(i){case"reflect":{t=wR(t,z,z);break}case"constant":{let G=new t.constructor(t.length+2*z);G.set(t,z),t=G;break}case"semicausal":{let G=new t.constructor(t.length+z);G.set(t,z),t=G;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}}let F=Math.floor(1+Math.floor((t.length-r)/s));M!==null&&FF?O&&(Q=S):Q=Y=S);let B=new Xc(n),I=new Float64Array(n),oe=new Float64Array(B.outputBufferSize),J=new Float32Array(K*Q);for(let z=0;z=1;--ie)I[ie]-=c*I[ie-1];I[0]*=1-c}for(let ie=0;ieMath.pow(c,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null||t===s)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);let i=new Float64Array(s),l=n?Math.floor((s-t)/2):0;return i.set(a,l),i}function bR(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return xu(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),xu(n,8,"WAVE"),xu(n,12,"fmt "),n.setUint32(16,16,!0),n.setUint16(20,3,!0),n.setUint16(22,1,!0),n.setUint32(24,e,!0),n.setUint32(28,e*4,!0),n.setUint16(32,4,!0),n.setUint16(34,32,!0),xu(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer instanceof ArrayBuffer?new Uint8Array(o.buffer,o.byteOffset,o.byteLength):o.slice())],{type:"audio/wav"})}function xu(t,e,r){for(let s=0;sn+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),bR(e,this.sampling_rate)}async save(e){return wu(e,this.toBlob())}};var b_=class extends Oe{constructor(e){super(e);let r=this.config.sampling_rate,s=dt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return ct(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){Ie(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o0)if(s==="rand_trunc"){a=!0;let l=Math.floor(Os.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let c=e.length;c=1;--n)e[n]-=r*e[n-1];return await ct(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){Ie(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f1?s-1:1;for(let f=0;f=u){l.push(e.slice(c,u));break}let f=Math.max(c,c+a-i),m=Math.min(c+a,u),_;m<=f?_=c+a:_=this._find_split_point_energy(e,f,m,n),_=Math.max(c+1,Math.min(_,u)),l.push(e.slice(c,_)),c=_}return l}_find_split_point_energy(e,r,s,n){let o=s-r;if(o<=n)return Math.floor((r+s)/2);let a=1/0,i=r,l=o-n;for(let c=0;c<=l;c+=n){let u=0;for(let f=0;fr&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,c=new Float64Array(e.length+l);c.set(e),this.config.padding_value!==0&&c.fill(this.config.padding_value,e.length),e=c}let a=await this._extract_fbank_features(e,this.config.max_length),i=Ze([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var oa=class extends na{async _extract_fbank_features(e,r){let{frame_length:s,hop_length:n,fft_length:o}=this.config,a=Math.floor(s/2),i=Math.floor((e.length+a-(s+1))/n)+1;return ct(e,this.window,s,n,{fft_length:o,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:i})}async _call(e,r={}){Ie(e,"Gemma4AudioFeatureExtractor");let s=e.length,n=await super._call(e,r),{input_features:o}=n,[,a,i]=o.dims,{frame_length:l,hop_length:c}=this.config,u=Math.floor(l/2),f=l+1,m=new Uint8Array(s+u+(r.pad_to_multiple_of??128));m.fill(1,u,u+s);let _=new Uint8Array(a);for(let x=0;x({id:l,start:c*s,end:u*s,confidence:f/(u-c)})))}return n}};var S_=class extends Oe{constructor(e){super(e);let r=this.config.sampling_rate,s=dt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),ct(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){Ie(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,b=a.data;for(let A=0;A0){let k=new Float32Array(x*(w+A));k.set(b),k.fill(this.config.padding_value,b.length);let M=w+A;a=new $(a.type,k,[M,x]),o&&(i=new $("int64",new BigInt64Array(M),[1,M]),i.data.fill(1n,0,w))}}let[l,c]=a.dims,u=this.config.stride;if(l%u!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${u}).`);let m=a.view(1,Math.floor(l/u),c*u),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let b=i.data;for(let A=1,k=0;Ao+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){Ie(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new $("float32",r,s),attention_mask:new $("int64",new BigInt64Array(r.length).fill(1n),s)}}};var C_=class extends Oe{constructor(e){super(e);let r=this.config.sampling_rate,s=dt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=_t(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(r=>r*32768),ct(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){Ie(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;ln?(e.length>this.config.n_samples&&te.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var Ve=class{static async from_pretrained(e,r={}){let s=await lt(e,_u,!0,r),n=s.feature_extractor_type,o=ia[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${es}.`);return new o(s)}};var L_=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ve;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};var kR=new Set(["ja","zh"]),z_=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ve;static uses_processor_config=!0;get_decoder_prompt_ids(e="en"){let r=["\u2581","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${e}|>`,`<|${e}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(r)}static join_chunks(e,r="en"){let s=e.filter(a=>a&&a.trim());if(s.length===0)return"";let n=kR.has(r)?"":" ";return[s[0].trimEnd(),...s.slice(1).map(a=>a.trim())].join(n)}async _call(e){return await this.feature_extractor(e)}};var yu={};var js,eM,ts;if(le.IS_WEB_ENV)js=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(t,e)},ts=self.createImageBitmap,eM=self.ImageData;else if(yu)ts=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new rt(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var ER={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},AR=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),rt=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!le.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");let s=e.getContext("2d").getImageData(0,0,e.width,e.height).data;return new t(s,e.width,e.height,4)}static async fromURL(e){let r=await jr(e);if(r.status!==200)throw new Error(`Unable to read image from "${e}" (${r.status} ${r.statusText})`);let s=await r.blob();return this.fromBlob(s)}static async fromBlob(e){if(le.IS_WEB_ENV){let r=await ts(e),s=js(r.width,r.height).getContext("2d");return s.drawImage(r,0,0),new this(s.getImageData(0,0,r.width,r.height).data,r.width,r.height,4)}else{let r=yu(await e.arrayBuffer());return await ts(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.permute(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?l=s:u=-s,n>=0?c=n:f=-n,i.drawImage(a,l,c,e,r,u,f,e,r),new t(i.getImageData(0,0,e,r).data,e,r,4).convert(o)}else{let o=this.toSharp();if(s>=0&&n>=0)o=o.extract({left:Math.floor(s),top:Math.floor(n),width:e,height:r});else if(s<=0&&n<=0){let a=Math.floor(-n),i=Math.floor(-s);o=o.extend({top:a,left:i,right:e-this.width-i,bottom:r-this.height-a})}else{let a=[0,0],i=0;n<0?(a[0]=Math.floor(-n),a[1]=r-this.height-a[0]):i=Math.floor(n);let l=[0,0],c=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):c=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:c,top:i,width:e,height:r})}return await ts(o)}}async toBlob(e="image/png",r=1){if(!le.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:e,quality:r})}toTensor(e="CHW"){let r=new $("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!=="HWC")if(e==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${e}`);return r}toCanvas(){if(!le.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=js(e.width,e.height),s=new eM(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;lnew t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(le.IS_WEB_ENV){if(le.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=AR.get(r)??"image/png",n=await this.toBlob(s);return wu(e,n)}else if(le.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(le.IS_WEB_ENV)throw new Error("toSharp() is only supported in server-side environments.");return yu(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},TR=rt.read.bind(rt);function SR(t,e,r,s,n){let o=s*r**2,a=Math.sqrt(o/(t*e)),i=n*r,l=Math.floor(a*t/i)*i,c=Math.floor(a*e/i)*i;if(l===0&&c===0)throw new Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${i}.`);let u=Math.floor(s/n**2)*i;return l===0?(l=i,c=Math.min(Math.floor(e/t)*i,u)):c===0&&(c=i,l=Math.min(Math.floor(t/e)*i,u)),[l,c]}function MR(t,e,r,s,n,o,a){let i=Math.floor(e/n),l=Math.floor(r/n),c=i*l,u=n*n*s,f=new Float32Array(o*u),m=0;for(let x=0;xc.replaceAll(this.image_token,()=>` ${this.boi_token}${this.image_token.repeat(i[l++])}${this.eoi_token} `))}let a;if(s){let i=Array.isArray(s)?s:[s];a=await this.feature_extractor(i[0],n);let l=this.feature_extractor.config.sampling_rate??16e3,c=0;e=e.map(u=>u.replaceAll(this.audio_token,()=>` ${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(i[c++].length,l))}${this.eoa_token} `))}return{...this.tokenizer(e,n),...o,...a}}};var ca=class extends We{constructor(e){super(),this.config=e,this.frame_processor=new qs(e),this.max_frames=e.max_frames??32,this.overflow_strategy=e.overflow_strategy??"uniform"}sample_frames(e){let r=e.length,{max_frames:s}=this;if(r<=s)return e;if(this.overflow_strategy==="truncate")return e.slice(0,s);let n=s>1?(r-1)/(s-1):0;return Array.from({length:s},(o,a)=>e[a>0&&a===s-1?r-1:Math.floor(a*n)])}async _call(e){Array.isArray(e)||(e=[e]);let r=e.map(i=>this.sample_frames(i.frames.map(l=>l.image))),{pixel_values:s,image_position_ids:n,num_soft_tokens_per_image:o}=await this.frame_processor(r.flat()),a=0;return{pixel_values_videos:s,video_position_ids:n,num_frames_per_video:r.map(i=>i.length),num_soft_tokens_per_video:r.map(i=>o[(a+=i.length)-1])}}};function $_(t,e){return Array.isArray(t)?t.every(r=>Array.isArray(r))?t:e?[t]:t.map(r=>[r]):[[t]]}function OR(t,e,r){let s=0;if(t=t.map(n=>n.replaceAll(e,()=>r[s++]??"")),s!==r.length)throw new Error(`Found ${s} ${e} tokens in the text, but ${r.length} inputs were passed.`);return t}var R_=class extends la{constructor(e,r,s){super(e,r,s),this.video_token=this.tokenizer.config.video_token,this.video_processor=e.video_processor&&new ca(e.video_processor)}async _call(e,r=null,s=null,n=null,o={}){let a=[[this.image_token,r&&$_(r,!0)],[this.video_token,n&&$_(n,!1)],[this.audio_token,s&&$_(s,!1)]];if(e==null){let O=a.filter(([,v])=>v),C=O[0]?.[1].length;if(O.some(([,v])=>v.length!==C))throw new Error("Received a different number of samples per modality.");e=Array.from({length:C},(v,U)=>O.flatMap(([j,F])=>Array(F[U].length).fill(j)).join(" "))}else typeof e=="string"&&(e=[e]);let[i,l,c]=a.map(([,O])=>O?.flat()),u=i&&await this.image_processor(i),f=l&&await this.video_processor(l),m=c&&await this._process_audio(c),{image_token:_,video_token:w,audio_token:x,boi_token:b,eoi_token:A,boa_token:k,eoa_token:M}=this,S={[_]:u?.num_soft_tokens_per_image.map(O=>b+_.repeat(O)+A),[w]:f?.num_soft_tokens_per_video.map((O,C)=>(b+w.repeat(O)+A).repeat(f.num_frames_per_video[C])),[x]:m?.num_soft_tokens_per_audio.map(O=>k+x.repeat(O)+M)};for(let[O,C]of Object.entries(S))e=OR(e,O,C??[]);return{...this.tokenizer(e,{padding:!0,...o}),...u,...f,...m}}async _process_audio(e){let r=[];for(let i of e)r.push(await this.feature_extractor(i));let s=Math.max(...r.map(i=>i.input_features.dims[1])),n=r[0].input_features.dims[2],o=new Float32Array(e.length*s*n),a=new Uint8Array(e.length*s);return r.forEach((i,l)=>{o.set(i.input_features.data,l*s*n),a.set(i.input_features_mask.data,l*s)}),{input_features:new $("float32",o,[e.length,s,n]),input_features_mask:new $("bool",a,[e.length,s]),num_soft_tokens_per_audio:r.map(({input_features_mask:{data:i}})=>{let l=0;for(let c=0;cs&&(o=Math.floor(n)*e),oe&&A.push(M)}else{let M=Le(b.data)[1];if(M===l-1||(k=Ue(b.data),k[M]O*f[(C+1)%2])),m.boxes.push(S),m.classes.push(M),m.scores.push(k[M])}}c.push(m)}return c}function bu(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;of[A]&&(f[A]=b[A],m[A]=x)}let _=new Array(i.dims[0]);for(let x=0;xx!==void 0);n.push({segmentation:u,labels:w})}return n}function IR(t,e,r,s){let n=[],o=[],a=[];for(let i=0;ir&&(n.push(c),o.push(m),a.push(u))}return[n,o,a]}function CR(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let u=0;u=s&&++i;let c=a>0&&i>0;return c&&(c=a/i>n),[c,o]}function PR(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,c=new $("int32",new Int32Array(i*l),[i,l]),u=[];if(a!==null)for(let x=0;xm[k]&&(f[k]=x,m[k]=A[k])}let _=0,w=c.data;for(let x=0;x200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let a=Math.round(t/r)*r,i=Math.round(e/r)*r;if(o*a*i>n){let l=Math.sqrt(o*t*e/n);a=Math.max(r,Math.floor(t/l/r)*r),i=Math.max(r,Math.floor(e/l/r)*r)}else if(o*a*io?c=Math.floor(o*l/n):o>n&&(l=Math.floor(n*c/o)),await e.resize(c,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=Ro(s.data)[0],a=Le(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,c=s.height,u=0,f=0,m=s.data;for(let _=0;_this.preprocess(o)));return{pixel_values:kt(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await lt(e,Mr,!0,r);return new this(s)}};var Gn={};yn(Gn,{BeitFeatureExtractor:()=>D_,BitImageProcessor:()=>U_,CHMv2ImageProcessor:()=>G_,CLIPFeatureExtractor:()=>j_,CLIPImageProcessor:()=>Eu,ChineseCLIPFeatureExtractor:()=>F_,ConvNextFeatureExtractor:()=>q_,ConvNextImageProcessor:()=>Au,DINOv3ViTImageProcessor:()=>H_,DPTFeatureExtractor:()=>K_,DPTImageProcessor:()=>Mu,DeiTFeatureExtractor:()=>W_,DeiTImageProcessor:()=>Tu,DetrFeatureExtractor:()=>V_,DetrImageProcessor:()=>Su,DonutFeatureExtractor:()=>X_,DonutImageProcessor:()=>Bn,EfficientNetImageProcessor:()=>Y_,GLPNFeatureExtractor:()=>Z_,Gemma3ImageProcessor:()=>Q_,Gemma4ImageProcessor:()=>qs,Glm46VImageProcessor:()=>J_,GroundingDinoImageProcessor:()=>eh,Idefics3ImageProcessor:()=>Ou,ImageFeatureExtractor:()=>X,ImageProcessor:()=>X,JinaCLIPImageProcessor:()=>rh,Lfm2VlImageProcessor:()=>sh,Lfm3VlImageProcessor:()=>nh,LlavaOnevisionImageProcessor:()=>oh,Mask2FormerImageProcessor:()=>ih,MaskFormerFeatureExtractor:()=>ah,MaskFormerImageProcessor:()=>Dn,MobileNetV1FeatureExtractor:()=>lh,MobileNetV1ImageProcessor:()=>Iu,MobileNetV2FeatureExtractor:()=>ch,MobileNetV2ImageProcessor:()=>Cu,MobileNetV3FeatureExtractor:()=>uh,MobileNetV3ImageProcessor:()=>Pu,MobileNetV4FeatureExtractor:()=>ph,MobileNetV4ImageProcessor:()=>Nu,MobileViTFeatureExtractor:()=>fh,MobileViTImageProcessor:()=>Lu,NougatImageProcessor:()=>dh,OwlViTFeatureExtractor:()=>mh,OwlViTImageProcessor:()=>Un,Owlv2ImageProcessor:()=>_h,Phi3VImageProcessor:()=>wh,PixtralImageProcessor:()=>xh,PvtImageProcessor:()=>yh,Qwen2VLImageProcessor:()=>Ws,RTDetrImageProcessor:()=>bh,Sam2ImageProcessor:()=>ua,Sam3ImageProcessor:()=>ua,SamImageProcessor:()=>ua,SapiensFeatureExtractor:()=>vh,SapiensImageProcessor:()=>zu,SegformerFeatureExtractor:()=>kh,SegformerImageProcessor:()=>$u,SiglipImageProcessor:()=>Eh,SmolVLMImageProcessor:()=>Ou,Swin2SRImageProcessor:()=>Ah,VLMImageProcessor:()=>th,ViTFeatureExtractor:()=>Th,ViTImageProcessor:()=>Ru,VitMatteImageProcessor:()=>Sh,VitPoseImageProcessor:()=>Mh,YolosFeatureExtractor:()=>Oh,YolosImageProcessor:()=>Bu});var D_=class extends X{};var U_=class extends X{};var F_=class extends X{};var G_=class extends X{};var Eu=class extends X{},j_=class extends Eu{};var Au=class extends X{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let r=this.size?.shortest_edge;if(r===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(r<384){let s=Math.floor(r/this.crop_pct),[n,o]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(n,o,{resample:this.resample}),e=await e.center_crop(r,r)}else e=await e.resize(r,r,{resample:this.resample});return e}},q_=class extends Au{};var Tu=class extends X{},W_=class extends Tu{};var Su=class extends X{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ze(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return rs(...e)}post_process_panoptic_segmentation(...e){return vu(...e)}post_process_instance_segmentation(...e){return ku(...e)}},V_=class extends Su{};var H_=class extends X{};var Bn=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r,l=this.image_mean;Array.isArray(this.image_mean)||(l=new Array(i).fill(l));let c=this.image_std;Array.isArray(c)||(c=new Array(i).fill(l));let u=l.map((f,m)=>-f/c[m]);return super.pad_image(e,r,s,{center:!0,constant_values:u,...n})}},X_=class extends Bn{};var Mu=class extends X{},K_=class extends Mu{};var Y_=class extends X{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(r=>r*r))}};var Q_=class extends X{};var Ws=class extends X{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size;return Rn(e.height,e.width,s,this.min_pixels,this.max_pixels)}async _call(e,...r){let{pixel_values:s,original_sizes:n,reshaped_input_sizes:o}=await super._call(e,...r),a=s,{temporal_patch_size:i,merge_size:l,patch_size:c}=this.config;a.dims[0]===1&&(a=Ee(Array.from({length:i},()=>a),0));let u=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/c),_=Math.floor(a.dims[3]/c),w=a.view(u,i,f,Math.floor(m/l),l,c,Math.floor(_/l),l,c).permute(0,3,6,4,7,2,1,5,8).view(u*m*_,f*i*c*c),x=new $("int64",[u,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var J_=class extends Ws{get_resize_output_image_size(e,r){let s=this.patch_size*this.merge_size,n=this.config.temporal_patch_size??2;return Rn(e.height,e.width,s,this.min_pixels,this.max_pixels,n)}};var Z_=class extends X{};var eh=class extends X{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=st([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var Ou=class extends X{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,r){let[s,n]=e.dims.slice(-2),o=n/s;return n>=s?(n=Math.ceil(n/r)*r,s=Math.floor(n/o),s=Math.ceil(s/r)*r):(s=Math.ceil(s/r)*r,n=Math.floor(s*o),n=Math.ceil(n/r)*r),{height:s,width:n}}async _call(e,{do_image_splitting:r=null,return_row_col_info:s=!1}={}){let n;if(!Array.isArray(e))n=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?n=e:n=[e]}let o=[],a=[],i=[],l=[],c=[];for(let A of n){let k=await Promise.all(A.map(O=>this.preprocess(O)));l.push(...k.map(O=>O.original_size)),c.push(...k.map(O=>O.reshaped_input_size)),k.forEach(O=>O.pixel_values.unsqueeze_(0));let{longest_edge:M}=this.max_image_size,S;if(r??this.do_image_splitting){let O=new Array(k.length),C=new Array(k.length);S=await Promise.all(k.map(async(v,U)=>{let j=this.get_resize_for_vision_encoder(v.pixel_values,M),F=await Tt(v.pixel_values,{size:[j.height,j.width]}),{frames:K,num_splits_h:Y,num_splits_w:Q}=await this.split_image(F,this.max_image_size);return O[U]=Y,C[U]=Q,Ee(K,0)})),a.push(O),i.push(C)}else{let O=[M,M];S=await Promise.all(k.map(C=>Tt(C.pixel_values,{size:O}))),a.push(new Array(k.length).fill(0)),i.push(new Array(k.length).fill(0))}o.push(Ee(S,0))}let u=o.length,[f,m,_,w]=o[0].dims,x,b;if(u===1)x=o[0].unsqueeze_(0),b=Ze([u,f,_,w],!0);else{let A=Math.max(...o.map(S=>S.dims.at(0)));b=Ze([u,A,_,w],!0);let k=b.data,M=A*_*w;for(let S=0;Ss||i>n){l=Math.ceil(a/s),c=Math.ceil(i/n);let u=Math.ceil(a/l),f=Math.ceil(i/c);for(let w=0;wr*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var rh=class extends X{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function sM(t,e){return Math.round(t/e)*e}function NR(t,e,r,s,n){let o=1/0,a=[1,1],i=r*s;for(let l of e){let c=Math.abs(t-l[0]/l[1]);c.5*n*n*l[0]*l[1]&&(a=l)}return a}function LR(t,e){let r=[],s=new Set;for(let n=t;n<=e;++n)for(let o=1;o<=n;++o)for(let a=1;a<=n;++a){let i=o*a;if(i>=t&&i<=e){let l=o<<16|a;s.has(l)||(s.add(l),r.push([o,a]))}}return r.sort((n,o)=>n[0]*n[1]-o[0]*o[1])}function zR(t,e){let[r,s,n,o]=t.dims,a=Math.floor(n/e),i=Math.floor(o/e),l=e*e*s,c=t.data,u=new Float32Array(r*a*i*l),f=n*o;for(let m=0;mthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,r){let s=LR(this.min_tiles,this.max_tiles),[n,o]=NR(r/e,s,r,e,this.tile_size);return{grid_width:n,grid_height:o,target_width:this.tile_size*n,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:r=null}={}){let s;Array.isArray(e)?Array.isArray(e[0])?s=e:s=[e]:s=[[e]];let n=[],o=[],a=[],i=[],l=[],c=[];for(let f of s){let m=await Promise.all(f.map(_=>this.preprocess(_,{do_pad:!1})));for(let{pixel_values:_}of m){let[,w,x]=_.dims,b=_.unsqueeze_(0),A=this.encoder_patch_size*this.downsample_factor,k=A**2,[M,S]=Rn(Math.max(A,w),Math.max(A,x),A,this.min_image_tokens*k,this.max_image_tokens*k).map(F=>Math.max(A,F)),O,C=1,v=1,U=this._is_image_too_large(w,x),j=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(U&&j){let{grid_width:F,grid_height:K,target_width:Y,target_height:Q}=this._get_grid_layout(w,x);C=K,v=F;let B=await Tt(b,{size:[Q,Y]});O=[];for(let I=0;Isuper._call(n,...r)));return{pixel_values:Ee(s.map(n=>n.pixel_values),0),image_grid_thw:Ee(s.map(n=>n.image_grid_thw),0),original_sizes:s.flatMap(n=>n.original_sizes),reshaped_input_sizes:s.flatMap(n=>n.reshaped_input_sizes)}}};var oh=class extends X{};var Dn=class extends X{post_process_panoptic_segmentation(...e){return vu(...e)}post_process_instance_segmentation(...e){return ku(...e)}},ah=class extends Dn{};var ih=class extends Dn{};var Iu=class extends X{},lh=class extends Iu{};var Cu=class extends X{},ch=class extends Cu{};var Pu=class extends X{},uh=class extends Pu{};var Nu=class extends X{},ph=class extends Nu{};var Lu=class extends X{},fh=class extends Lu{};var dh=class extends Bn{};var Un=class extends X{post_process_object_detection(...e){return rs(...e)}},mh=class extends Un{};var _h=class extends Un{};var Bt=336,RR=[2,3],{ceil:hh,floor:Fn,sqrt:gh}=Math,wh=class extends X{constructor(e){super({...e,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=e.num_crops}calc_num_image_tokens_from_image_size(e,r){let{num_img_tokens:s}=this.config;return Fn((Fn(r/Bt)*Fn(e/Bt)+1)*s+1+(Fn(r/Bt)+1)*gh(s))}get_resize_output_image_size(e,r){let s=this._num_crops,[n,o]=e.size,a=n/o,i=1;for(;i*Math.ceil(i/a)<=s;)i+=1;i-=1;let l=Math.floor(i*336),c=Math.floor(l/a);return[l,c]}pad_image(e,r,s,n={}){let[o,a]=r,i=Bt*hh(o/Bt),l=Bt*hh(a/Bt),c=[1,1,1].map((u,f)=>(u-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:c,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||gh(r)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);let s=e.length,n=await Promise.all(e.map(m=>this.preprocess(m))),o=n.map(m=>m.original_size),a=n.map(m=>m.reshaped_input_size),i=[];for(let{pixel_values:m}of n){m.unsqueeze_(0);let[_,w]=m.dims.slice(-2),x=await Tt(m,{size:[Bt,Bt],mode:"bicubic"});if(r>0){let b=[],A=gh(r),k=Fn(w/A),M=Fn(_/A);for(let O=0;Om.map(_=>Bt*hh(_/Bt))),u=new $("int64",c.flat(),[s,2]),f=c.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:u,num_img_tokens:f}}};var xh=class extends X{get_resize_output_image_size(e,r){let{longest_edge:s}=r;if(s===void 0)throw new Error("size must contain 'longest_edge'");let[n,o]=e.size,a=Math.max(n,o)/s,i=n,l=o;a>1&&(i=Math.floor(n/a),l=Math.floor(o/a));let{patch_size:c,spatial_merge_size:u}=this.config;if(!u)throw new Error("config must contain 'spatial_merge_size'");let f=c*u,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var yh=class extends X{};var bh=class extends X{post_process_object_detection(...e){return rs(...e)}};var ua=class extends X{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=dd(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;an!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new $("int64",e.flat(1/0).map(BigInt),s)}async _call(e,{input_points:r=null,input_labels:s=null,input_boxes:n=null}={}){let o=await super._call(e);if(r&&(o.input_points=this.reshape_input_points(r,o.original_sizes,o.reshaped_input_sizes)),s){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(s,o.input_points)}return n&&(o.input_boxes=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,r,s,{mask_threshold:n=0,binarize:o=!0,pad_size:a=null}={}){let i=[];a=a??this.pad_size??this.size;let l=[a.height,a.width];for(let c=0;cn&&(w[x]=1);m=new $("bool",w,m.dims)}i.push(m)}return i}generate_crop_boxes(e,r,{crop_n_layers:s=0,overlap_ratio:n=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:a=1}={}){}};var zu=class extends X{post_process_semantic_segmentation(...e){return bu(...e)}},vh=class extends zu{};var $u=class extends X{post_process_semantic_segmentation(...e){return bu(...e)}},kh=class extends $u{};var Eh=class extends X{};var Ah=class extends X{pad_image(e,r,s,n={}){let[o,a,i]=r;return super.pad_image(e,r,{width:a+(s-a%s)%s,height:o+(s-o%s)%s},{mode:"symmetric",center:!1,constant_values:-1,...n})}};var Ru=class extends X{},Th=class extends Ru{};var Sh=class extends X{async _call(e,r){Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);let s=await Promise.all(e.map(a=>this.preprocess(a))),n=await Promise.all(r.map(a=>this.preprocess(a,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:kt(s.map((a,i)=>Ee([a.pixel_values,n[i].pixel_values],0)),0),original_sizes:s.map(a=>a.original_size),reshaped_input_sizes:s.map(a=>a.reshaped_input_size)}}};var Mh=class extends X{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,c=[];for(let u=0;u/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],c=[];for(let[u,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),c.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:c};break;default:throw new Error(`Task "${r}" (of type "${n}") not yet implemented.`)}return{[r]:o}}async _call(e,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=await this.image_processor(e,s),o=r?this.tokenizer(this.construct_prompts(r),s):{};return{...n,...o}}};var Ch=class extends se{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.image_seq_length=this.config.image_seq_length;let{boi_token:n,image_token:o,eoi_token:a}=this.tokenizer.config;this.boi_token=n,this.image_token=o,this.eoi_token=a;let i=o.repeat(this.image_seq_length);this.full_image_sequence=` ${n}${i}${a} `}async _call(e,r=null,s={}){typeof e=="string"&&(e=[e]);let n;return r&&(n=await this.image_processor(r,s),e=e.map(a=>a.replaceAll(this.boi_token,this.full_image_sequence))),{...this.tokenizer(e,s),...n}}};var Ph=class extends se{static image_processor_class=Te;static feature_extractor_class=Ve;static tokenizer_class=ne;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:c,image_token:u,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=` ${o}${m}${i} `,this.image_token_id=l,this.boi_token=c,this.image_token=u;let _=u.repeat(this.image_seq_length);this.full_image_sequence=` ${c}${_}${f} `}async _call(e,r=null,s=null,n={}){typeof e=="string"&&(e=[e]);let o;s&&(o=await this.feature_extractor(s,n),e=e.map(l=>l.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return r&&(a=await this.image_processor(r,n),e=e.map(l=>l.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,n),...a,...o}}};var Vs=class extends se{static image_processor_class=Te;static tokenizer_class=ne;static image_token="<|image_pad|>";async _call(e,r=null,...s){Array.isArray(e)||(e=[e]);let n,o;if(r&&(n=await this.image_processor(r),o=n.image_grid_thw),o){let i=this.image_processor.config.merge_size**2,l=0,c=this.constructor.image_token,u=o.tolist();e=e.map(f=>{for(;f.includes(c);){let m=Number(u[l++].reduce((_,w)=>_*w,1n));f=f.replace(c,"<|placeholder|>".repeat(Math.floor(m/i)))}return f.replaceAll("<|placeholder|>",c)})}return{...this.tokenizer(e),...n}}};var Nh=class extends Vs{static image_token="<|image|>"};var Lh=class extends se{static tokenizer_class=ne;static feature_extractor_class=Ve;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:r}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:s,projector_downsample_rate:n}=this.feature_extractor.config,o=Math.floor(s/n),a=Math.floor(e/r)+1,i=Math.floor(a/2);return Math.ceil(i/s)*o}async _call(e,r=null,s={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let n={};if(r){let{input_features:a}=await this.feature_extractor(r);n.input_features=a;let i=this._get_num_audio_features(r.length),l=new Uint8Array(i).fill(1);n.input_features_mask=new $("bool",l,[1,i]);let c=this.config.audio_token??"<|audio|>";if(!e.includes(c))throw new Error(`The input text does not contain the audio token ${c}.`);e=e.replaceAll(c,c.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...s}),...n}}};function BR(t,e){let s=t.dims.at(-1)-1,n=t.tolist();n.fill(!1,0,1),n.fill(!1,s);let o=e.tolist();return n.map((a,i)=>a?i:null).filter(a=>a!==null).map(a=>o[a])}var zh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;async _call(e,r,s={}){let n=e?await this.image_processor(e,s):{};return{...r?this.tokenizer(r,s):{},...n}}post_process_grounded_object_detection(e,r,{box_threshold:s=.25,text_threshold:n=.25,target_sizes:o=null}={}){let{logits:a,pred_boxes:i}=e,l=a.dims[0];if(o!==null&&o.length!==l)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let c=a.dims.at(1),u=a.sigmoid(),f=u.max(-1).tolist(),m=i.tolist().map(w=>w.map(x=>B_(x))),_=[];for(let w=0;wS.map((O,C)=>O*x[(C+1)%2])));let b=f[w],A=[],k=[],M=[];for(let S=0;S`+n.repeat(t);a+=` `}return a+=` ${s}${o}`+n.repeat(t)+`${s}`,a}function UR(t,e,r,s){return`${e}${s}`+r.repeat(t)+`${e}`}function FR(t,e,r,s,n,o){return t===0&&e===0?UR(r,s,n,o):DR(r,t,e,s,n,o)}var Du=class extends se{static image_processor_class=Te;static tokenizer_class=ne;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(e,r=null,s={}){s.return_row_col_info??=!0;let n;r&&(n=await this.image_processor(r,s)),Array.isArray(e)||(e=[e]);let o=n.rows??[new Array(e.length).fill(0)],a=n.cols??[new Array(e.length).fill(0)],i=this.config.image_seq_len,l=[],c=[];for(let f=0;fFR(k,w[M],i,this.fake_image_token,this.image_token,this.global_img_token)),b=m.split(this.image_token);if(b.length===0)throw new Error("The image token should be present in the text.");let A=b[0];for(let k=0;kb.images).flatMap(b=>b.images).map(b=>rt.read(b)));let n=this.tokenizer,o=n.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:s}),a=b=>n.encode(b,{add_special_tokens:!1}),i=o.split(this.image_tag),l=i.length-1;if(r.length!==l)throw new Error(`Number of images provided (${r.length}) does not match number of "${this.image_tag}" image tags (${l})`);let[c,u,f]=n.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),m=a(i[0]),_=new Array(m.length).fill(!1);for(let b=1;b0){let b=await this.image_processor(r);return b.pixel_values.unsqueeze_(0),{...x,...b}}return x}};var Rh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;async _call(e=null,r=null,s={}){if(!e&&!r)throw new Error("Either text or images must be provided");let n=e?this.tokenizer(e,s):{},o=r?await this.image_processor(r,s):{};return{...n,...o}}};var Bh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;async _call(e,r=null,s={}){let{image_rows:n,image_cols:o,image_sizes:a,...i}=await this.image_processor(e,{...s,return_row_col_info:!0});if(r){let l=this.config.image_token??"",{tile_size:c=512,downsample_factor:u=2,encoder_patch_size:f=16,use_thumbnail:m=!0}=this.image_processor.config,_=M=>Math.ceil(Math.floor(M/f)/u),w=_(c)**2,x=this.config.image_start_token??"<|image_start|>",b=this.config.image_end_token??"<|image_end|>",A=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(r)||(r=[r]);let k=0;r=r.map(M=>{let S=M.split(l);return S[0]+S.slice(1).map(O=>{let C=k++,[v,U]=a[C],j=n[C],F=o[C],K=_(v)*_(U),Y=x;if(j>1||F>1){let Q=l.repeat(w);for(let B=0;B`+Q;m&&(Y+=A+l.repeat(K))}else Y+=l.repeat(K);return Y+b+O}).join("")})}return{...i,...r?this.tokenizer(r,s):{}}}};var Dh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;async _call(e,r=null,s={}){let n=e?await this.image_processor(e,s):{};if(r!==null){Array.isArray(r)||(r=[r]);let o=this.tokenizer.config.image_token??"<|image|>",a=n.image_grid_thw?.tolist()??[],i=r.reduce((u,f)=>u+f.split(o).length-1,0);if(i!==a.length)throw new Error(`Found ${i} ${o} tokens in the text but received ${a.length} images.`);let l=this.image_processor.config.merge_size,c=0;r=r.map(u=>u.replaceAll(o,()=>{let f=Number(a[c++].reduce((m,_)=>m*_,1n));return o.repeat(f/l**2)}))}return{...n,...r!==null?this.tokenizer(r,s):{}}}};var Uh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,patch_size:c,num_additional_image_tokens:u}=this.config,f=Math.floor(a/c)*Math.floor(i/c)+u;r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let m=0;m0?x.reduce((A,k)=>A*k,1):0;c.push(w),l.push(b)}return[o(c),l]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(r=>r.replaceAll(" ",""))}batch_decode([e,r,s]){let[n,o]=this._decode_helper(e,"char"),[a,i]=this._decode_helper(r,"bpe"),[l,c]=this._decode_helper(s,"wp"),u=[],f=[];for(let m=0;mc.includes(jn))?a=r.map(c=>{let u=c.replaceAll(jn,jn.repeat(o)),f=u.lastIndexOf(jn),m=f===-1?0:f+jn.length;return u.slice(0,m)+n+u.slice(m)+` `}):(te.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=r.map(c=>GR(c,n,o,jn,e.length)));let i=this.tokenizer(a,s);return{...await this.image_processor(e,s),...i}}};var oM="<|image|>",jR=/<\|image_\d+\|>/g,Wh=class extends se{static image_processor_class=Te;static tokenizer_class=ne;async _call(e,r=null,{padding:s=!0,truncation:n=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let a,i;if(r){i=await this.image_processor(r,{num_crops:o});let{num_img_tokens:l}=i,c=e.map((f,m)=>f.split(jR).join(oM.repeat(l[m])));a=this.tokenizer(c,{padding:s,truncation:n});let u=this.tokenizer._tokenizer.token_to_id(oM);a.input_ids.map_(f=>f==u?-f:f)}else a=this.tokenizer(e);return{...a,...i}}};var Vh=class extends se{static tokenizer_class=ne;static image_processor_class=Te;static uses_processor_config=!0;async _call(e,r=null,s={}){let n=await this.image_processor(e,s);if(r){let[a,i]=n.pixel_values.dims.slice(-2),{image_token:l,image_break_token:c,image_end_token:u,patch_size:f,spatial_merge_size:m}=this.config,_=f*m,w=Math.floor(a/_),x=Math.floor(i/_);r=structuredClone(r),Array.isArray(r)||(r=[r]);for(let b=0;bVR(w,l)),u=c.map(w=>w.length),f=c.flat(),m=(await Promise.all(f.map(w=>this.feature_extractor(w,s)))).map(w=>w.input_features);n.audio_values=m.length>1?Ee(m,0):m[0];let _=a[0];for(let w=0;w0){if(c>jc)throw new Error(`The number of external data chunks (${c}) exceeds the maximum allowed value (${jc}).`);let u=og(a,c);for(let f of u){let m=`${s.subfolder??""}/${f}`;l.push(zo(t,m,!0,s,i).then(_=>_ instanceof Uint8Array?{path:f,data:_}:f))}}else o.externalData!==void 0&&(l=o.externalData.map(async u=>{if(typeof u.data=="string"){let f=await zo(t,u.data,!0,s);return{...u,data:f}}return u}));return Promise.all(l)}async function QR(t,e,r,s=!1,n=void 0){let o=r.config?.["transformers.js_config"]??{},a=uu(r.device??o.device,e,{warn:k=>te.info(k)}),i=NS(a),l=o.device_config??{};l.hasOwnProperty(a)&&(o={...o,...l[a]});let c=pu(r.dtype??o.dtype,e,a,{configDtype:o.dtype,warn:k=>te.info(k)});if(Jr.hasOwnProperty(c)){if(a==="webgpu"&&!le.IS_NODE_ENV&&c===it.fp16&&!await RS())throw new Error(`The device (${a}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${c}. Should be one of: ${Object.keys(it).join(", ")}`);let u=Jr[c],f={...r.session_options};f.executionProviders??=i;let m=o.free_dimension_overrides;m?f.freeDimensionOverrides??=m:a.startsWith("webnn")&&!f.freeDimensionOverrides&&te.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${a}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let _=iM(t,e,r,u),w=r.use_external_data_format??o.use_external_data_format,x=await lM(t,e,u,r,w,f);if(x.length>0&&(!le.IS_NODE_ENV||x.some(k=>typeof k!="string"))&&(f.externalData=x),s&&a==="webgpu"){let k=Hs(r.config,{prefix:"present",session_name:n});if(k.size>0&&!Ho()){let M={};for(let S of k)M[S]="gpu-buffer";f.preferredOutputLocation=M}}return{buffer_or_path:await _,session_options:f,session_config:{dtype:c,device:a}}}async function cM(t,e,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(e).map(async n=>{let o=s?.[n]??!1,{buffer_or_path:a,session_options:i,session_config:l}=await QR(t,e[n],r,o,n),c=await iu(a,i,l);return[n,c]})))}function uM(t){for(let e in t)cu(t[e])?t[e]=new $(t[e]):typeof t[e]=="object"&&uM(t[e]);return t}async function pe(t,e){let r=JR(t,e);try{let s=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i=a.ort_tensor;return le.IS_NODE_ENV&&typeof Float16Array<"u"&&i.cpuData instanceof Float16Array&&(i.cpuData=new Uint16Array(i.cpuData.buffer)),[o,i]})),n=await lu(t,s);return uM(n)}catch(s){let n=Object.fromEntries(Object.entries(r).map(([o,a])=>{let i={type:a.type,dims:a.dims,location:a.location};return i.location!=="gpu-buffer"&&(i.data=a.data),[o,i]}));throw te.error(`An error occurred during model execution: "${s}".`),te.error("Inputs given to model:",n),s}}function JR(t,e){let r=Object.create(null),s=[];for(let a of t.inputNames){let i=e[a];if(!(i instanceof $)){s.push(a);continue}r[a]=Ho()?i.clone():i}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);let n=Object.keys(e).length,o=t.inputNames.length;if(n>o){let a=Object.keys(e).filter(i=>!t.inputNames.includes(i));te.warn(`WARNING: Too many inputs were provided (${n} > ${o}). The following inputs will be ignored: "${a.join(", ")}".`)}return r}var Se=class{},Wu=class extends Se{constructor({last_hidden_state:e,hidden_states:r=null,attentions:s=null}){super(),this.last_hidden_state=e,this.hidden_states=r,this.attentions=s}},q=class extends Se{constructor({logits:e,...r}){super(),this.logits=e;let s=Object.values(r);s.length>0&&(this.attentions=s)}},we=class extends Se{constructor({logits:e}){super(),this.logits=e}},ye=class extends Se{constructor({logits:e}){super(),this.logits=e}},Me=class extends Se{constructor({start_logits:e,end_logits:r}){super(),this.start_logits=e,this.end_logits=r}},ht=class extends Se{constructor({logits:e}){super(),this.logits=e}},Vu=class extends Se{constructor({logits:e,past_key_values:r}){super(),this.logits=e,this.past_key_values=r}},Hu=class extends Se{constructor({logits:e,past_key_values:r,encoder_outputs:s,decoder_attentions:n=null,cross_attentions:o=null}){super(),this.logits=e,this.past_key_values=r,this.encoder_outputs=s,this.decoder_attentions=n,this.cross_attentions=o}},Vn=class extends Se{constructor({alphas:e}){super(),this.alphas=e}};var Dt=class extends We{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},da=class extends We{_call(e,r){throw Error("`_call` should be implemented in a subclass")}},Xs=class extends We{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,r){let s=r;for(let n of this.processors)s=n(e,s);return s}[Symbol.iterator](){return this.processors.values()}},Xu=class extends Dt{constructor(e){super(),this.bos_token_id=e}_call(e,r){for(let s=0;s=1&&o[o.length-1]>=this.timestamp_begin,i=o.length<2||o[o.length-2]>=this.timestamp_begin;if(a&&(i?n.subarray(this.timestamp_begin).fill(-1/0):n.subarray(0,this.eos_token_id).fill(-1/0)),e[s].length===this.begin_index&&this.max_initial_timestamp_index!==null){let f=this.timestamp_begin+this.max_initial_timestamp_index;n.subarray(f+1).fill(-1/0)}let l=Sd(n),c=Math.log(l.subarray(this.timestamp_begin).map(Math.exp).reduce((f,m)=>f+m)),u=Le(l.subarray(0,this.timestamp_begin))[0];c>u&&n.subarray(0,this.timestamp_begin).fill(-1/0)}return r}},Ju=class extends Dt{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let r=e.length,s=[];for(let o=0;o1 to use the classifier-free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,r){if(r.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${r.dims[0]} for the logits and ${e.length} for the input ids.`);let s=e.length,n=r.slice([0,s],null),o=r.slice([s,r.dims[0]],null);for(let a=0;a1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${e}`);if(!Number.isInteger(s)||s<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${s}`);this.top_p=e,this.filter_value=r,this.min_tokens_to_keep=s}},fM=class extends da{constructor(e,{filter_value:r=-1/0,min_tokens_to_keep:s=1}={}){if(super(),!Number.isInteger(e)||e<0)throw new Error(`\`top_k\` must be a positive integer, but is ${e}`);this.top_k=Math.max(e,s),this.filter_value=r}};var Ks=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,He(e,Object.getOwnPropertyNames(this)))}};var ss=class extends We{_call(e,r){throw Error("StoppingCriteria needs to be subclassed")}},Xn=class t extends We{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(e){e instanceof t?e=e.criteria:e instanceof ss&&(e=[e]),this.criteria.push(...e)}_call(e,r){let s=new Array(e.length).fill(!1);for(let n of this.criteria){let o=n(e,r);for(let a=0;ar.length>=this.max_length)}},ap=class extends ss{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,r){return e.map(s=>{let n=s.at(-1);return this.eos_token_id.some(o=>n==o)})}},dM=class extends ss{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(e,r){return new Array(e.length).fill(this.interrupted)}};var Ys=class extends We{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,r){let s=e.dims.at(-1),n=e.data;if(r===-1)n=n.slice(-s);else{let o=r*s;n=n.slice(o,o+s)}return n}randomSelect(e){return M2(e)}static getSampler(e){if(e.do_sample)return new ig(e);if(e.num_beams>1)return new lg(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 ag(e)}},ag=class extends Ys{async sample(e){let r=Le(e.data)[1];return[[BigInt(r),0]]}},ig=class extends Ys{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await or(e,r),o=Ue(s.data);return Array.from({length:this.generation_config.num_beams},()=>{let a=this.randomSelect(o);return[n.data[a],Math.log(o[a])]})}},lg=class extends Ys{async sample(e){let r=e.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));let[s,n]=await or(e,r),o=Ue(s.data);return Array.from({length:this.generation_config.num_beams},(a,i)=>[n.data[i],Math.log(o[i])])}};var cg=class{constructor(e){if(e)for(let r in e){if(r in this)throw new TypeError(`Key "${r}" conflicts with an existing property on DynamicCache`);let s=e[r];if(!(s instanceof $))throw new TypeError(`Expected a Tensor for key "${r}", got ${typeof s}`);this[r]=s}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let r in e)if(r.startsWith("past_key_values."))return e[r].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}update(e){for(let r in e){let s=this[r],n=e[r];s&&s!==n&&s.location==="gpu-buffer"&&s.dispose(),this[r]=n}}async dispose(){let e=[];for(let r of Object.values(this))r.location==="gpu-buffer"&&e.push(r.dispose());await Promise.all(e)}},Kn=cg;var W={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,MultimodalEncoder:17},gr={[W.DecoderOnly]:{sessions:(t,e)=>({model:e.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[W.DecoderOnlyWithoutHead]:{sessions:(t,e)=>({model:e.model_file_name??"model"})},[W.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.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"}},[W.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[W.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[W.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...gr[W.ImageTextToText].text_only_sessions};return r||(s.vision_encoder="vision_encoder"),t.is_encoder_decoder&&(s.model="encoder_model"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...gr[W.AudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...gr[W.ImageAudioTextToText].text_only_sessions};return r||(s.audio_encoder="audio_encoder",s.vision_encoder="vision_encoder"),s},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[W.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"}},[W.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"}},[W.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[W.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[W.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[W.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(t,e,r)=>{let s={...gr[W.VoxtralRealtime].text_only_sessions};return r||(s.audio_encoder="audio_encoder"),s},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},[W.MultimodalEncoder]:{sessions:(t,e)=>({model:e.model_file_name??"model",...t.vision_config&&{vision_encoder:"vision_encoder"},...t.audio_config&&{audio_encoder:"audio_encoder"}})},default:{sessions:(t,e)=>({model:e.model_file_name??"model"})}};function mM(t){return gr[t]?.text_only_sessions??null}function ip(t,e,r={}){let s=gr[t]??gr.default;return{sessions:s.sessions(e,r,r.textOnly??!1),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}function Yn(t,{warn:e=!0}={}){let r=t.architectures||[];for(let s of r){let n=ar.get(s);if(n!==void 0)return n}if(t.model_type){let s=ar.get(t.model_type);if(s!==void 0)return s;for(let n of Object.values(Qs))if(n.has(t.model_type)){let o=ar.get(n.get(t.model_type));if(o!==void 0)return o}}if(e){let s=r.length>0?r.join(", "):"(none)";te.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${s}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${es}`)}return W.EncoderOnly}function ma(t,{config:e=null,cache_dir:r=null,local_files_only:s=!1,revision:n="main"}={}){if(e!==null)return Ht.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n});let o=Sn(t,{cache_dir:r,local_files_only:s,revision:n});return Vc(o,()=>Ht.from_pretrained(t,{config:e,cache_dir:r,local_files_only:s,revision:n}))}async function Qn(t,{config:e=null,dtype:r=null,device:s=null,model_file_name:n=null}={}){e=await ma(t,{config:e});let o=["config.json"],a=e["transformers.js_config"]??{},i=a.use_external_data_format,l="onnx",c=s??a.device,u=r??a.dtype,f=Yn(e),m=(x,b=null)=>{b=b??x;let A=uu(c,x),k=pu(u,x,A),M=Jr[k]??"",S=`${b}${M}.onnx`,O=l?`${l}/${S}`:S;o.push(O);let C=ng(i,S,x);for(let v of og(S,C)){let U=l?`${l}/${v}`:v;o.push(U)}},{sessions:_,optional_configs:w}=ip(f,e,{model_file_name:n});for(let[x,b]of Object.entries(_))m(x,b);if(w)for(let x of Object.values(w))o.push(x);return o}var Qs=null;function gM(t){Qs=t}function ug(t){if(t instanceof $)return t;if(t.length===0)throw Error("items must be non-empty");if(Array.isArray(t[0])){if(t.some(e=>e.length!==t[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new $("int64",BigInt64Array.from(t.flat().map(e=>BigInt(e))),[t.length,t[0].length])}else return new $("int64",BigInt64Array.from(t.map(e=>BigInt(e))),[1,t.length])}function pg(t){return new $("bool",[t],[1])}var _M={[W.DecoderOnly]:{can_generate:!0,forward:Nt,prepare_inputs:ns},[W.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Nt,prepare_inputs:ns},[W.Seq2Seq]:{can_generate:!0,forward:lp,prepare_inputs:_a},[W.Vision2Seq]:{can_generate:!0,forward:lp,prepare_inputs:_a},[W.Musicgen]:{can_generate:!0,forward:lp},[W.EncoderDecoder]:{can_generate:!1,forward:lp},[W.ImageTextToText]:{can_generate:!0,forward:r3,prepare_inputs:cp},[W.AudioTextToText]:{can_generate:!0,forward:t3,prepare_inputs:cp},[W.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:cp},[W.Phi3V]:{can_generate:!0,prepare_inputs:cp},[W.MultiModality]:{can_generate:!0},[W.AutoEncoder]:{can_generate:!1,forward:ZR},[W.Chatterbox]:{can_generate:!0,forward:Xt},[W.VoxtralRealtime]:{can_generate:!0,prepare_inputs:ns},default:{can_generate:!1,forward:Xt}};function hM(t,e){let r=ar.get(t),s=!1,n=e?.architectures?.[0];if(n&&n!==t&&t?.endsWith("ForCausalLM")&&n.endsWith("ForConditionalGeneration")){let i=ar.get(n);i!==void 0&&(r=i,s=!0)}let o=_M[r]??_M.default,a=gr[r]??gr.default;return{typeConfig:{...o,...a},textOnly:s,modelType:r}}var ar=new Map,pp=new Map,Js=new Map,y=class extends We{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,r,s){super(),this.config=e,this.sessions=r,this.configs=s;let n=Js.get(this.constructor),{typeConfig:o}=hM(n,e);this.can_generate=o.can_generate,this._forward=o.forward,this._prepare_inputs_for_generation=o.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let e=[];for(let r of Object.values(this.sessions))e.push(r.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:f,session_options:m},w=Js.get(this);s=_.config=await Ht.from_pretrained(e,_);let{typeConfig:x,textOnly:b,modelType:A}=hM(w,s);if(A===void 0){let O=w??s?.model_type;O!=="custom"&&te.warn(`Model type for '${O}' not found, assuming encoder-only architecture. Please report this at ${es}.`)}if(r&&!(r instanceof Ar)){let O={};try{let C=await Qn(e,{config:s,dtype:u,device:c,model_file_name:i});(await Promise.all(C.map(U=>Pt(e,U,_)))).forEach((U,j)=>{if(U.exists){let F=C[j]==="config.json";O[C[j]]={loaded:F?U.size??0:0,total:U.size??0}}})}catch(C){te.warn(`Unable to fetch model file metadata for total progress tracking: ${C}`)}Object.keys(O).length>0&&(_.progress_callback=new Ar(r,O))}let k=x.sessions(s,_,b),M=[cM(e,k,_,x.cache_sessions)];x.optional_configs&&M.push(n3(e,x.optional_configs,_));let S=await Promise.all(M);return new this(s,...S)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,r,s=null){let n=new Xs;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&n.push(new Zu(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&n.push(new Ju(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&n.push(new rp(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&n.push(new ep(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&n.push(new tp(r,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&n.push(new Xu(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&n.push(new Ku(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&n.push(new Yu(e.suppress_tokens)),e.begin_suppress_tokens!==null){let o=r>1||e.forced_bos_token_id===null?r:r+1;n.push(new Hn(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&n.push(new sp(e.guidance_scale)),e.temperature===0&&e.do_sample&&(te.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&n.push(new np(e.temperature)),s!==null&&n.extend(s),n}_prepare_generation_config(e,r,s=Ks){let n={...this.config};for(let a of["decoder","generator","text_config"])a in n&&Object.assign(n,n[a]);let o=new s(n);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),r&&Object.assign(o,He(r,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,r=null){let s=new Xn;return e.max_length!==null&&s.push(new op(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&s.push(new ap(e.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){let e=[Qs.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Qs.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Qs.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Qs.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Js.get(this.constructor),s=new Set,n=this.config.model_type;for(let a of e){let i=a?.get(n);i&&s.add(i)}let o=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(o+=` Please use the following class instead: ${[...s].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:r,model_inputs:s,is_encoder_decoder:n}){return s.past_key_values=up(r,s.past_key_values),s.input_ids=new $("int64",e.flat(),[e.length,1]),n?"decoder_attention_mask"in s&&(s.decoder_attention_mask=Ee([s.decoder_attention_mask,st([s.decoder_attention_mask.dims[0],1])],1)):s.attention_mask=Ee([s.attention_mask,st([s.attention_mask.dims[0],1])],1),s.position_ids=null,s}_prepare_model_inputs({inputs:e,bos_token_id:r,model_kwargs:s}){let n=He(s,this.forward_params),o=this.main_input_name;if(o in n){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else n[o]=e;return{inputs_tensor:n[o],model_inputs:n,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:r,model_input_name:s,generation_config:n}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:a,pixel_values:i,attention_mask:l,...c}=r,u=await this._prepare_inputs_embeds(r);r={...c,...He(u,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Xt(this,r);if(n.guidance_scale!==null&&n.guidance_scale>1)o=Ee([o,Ko(o,0)],0),"attention_mask"in r&&(r.attention_mask=Ee([r.attention_mask,Yo(r.attention_mask)],0));else if(r.decoder_input_ids){let a=ug(r.decoder_input_ids).dims[0];if(a!==o.dims[0]){if(o.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${o.dims[0]}) than the decoder inputs (${a}).`);o=Ee(Array.from({length:a},()=>o),0)}}return r.encoder_outputs=o,r}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:r,model_kwargs:s,decoder_start_token_id:n,bos_token_id:o,generation_config:a}){let{decoder_input_ids:i,...l}=s;if(!(i instanceof $)){if(i)Array.isArray(i[0])||(i=Array.from({length:e},()=>i));else if(n??=o,this.config.model_type==="musicgen")i=Array.from({length:e*this.config.decoder.num_codebooks},()=>[n]);else if(Array.isArray(n)){if(n.length!==e)throw new Error(`\`decoder_start_token_id\` expected to have length ${e} but got ${n.length}`);i=n}else i=Array.from({length:e},()=>[n]);i=ug(i)}return l.decoder_attention_mask=Ln(i),{input_ids:i,model_inputs:l}}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,streamer:o=null,...a}){this._validate_model_class(),r=this._prepare_generation_config(r,a);let{inputs_tensor:i,model_inputs:l,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),u=this.config.is_encoder_decoder;u&&("encoder_outputs"in l||(l=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:i,model_inputs:l,model_input_name:c,generation_config:r})));let f;u?{input_ids:f,model_inputs:l}=this._prepare_decoder_input_ids_for_generation({batch_size:l[c].dims.at(0),model_input_name:c,model_kwargs:l,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=l[c];let m=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=m+r.max_new_tokens);let _=this._get_logits_processor(r,m,s),w=this._get_stopping_criteria(r,n),x=l[c].dims.at(0),b=Ys.getSampler(r),A=new Array(x).fill(0),k=f.tolist();o&&o.put(k);let M,S={},O={};for(;;){if(l=this.prepare_inputs_for_generation(k,l,r),M=await this.forward(l),r.return_dict_in_generate)if(r.output_attentions){let B=e3(M);for(let I in B)I in S||(S[I]=[]),S[I].push(B[I])}else this._return_dict_in_generate_keys&&Object.assign(O,He(M,this._return_dict_in_generate_keys));let F=M.logits.slice(null,-1,null).to("float32"),K=_(k,F),Y=[];for(let B=0;BB))break;l=this._update_model_kwargs_for_generation({generated_input_ids:Y,outputs:M,model_inputs:l,is_encoder_decoder:u})}o&&o.end();let C=new $("int64",k.flat(),[k.length,k[0].length]),v=up(M,l.past_key_values),U=new Set(Object.values(v));for(let F of Object.values(M))F.location==="gpu-buffer"&&!U.has(F)&&F.dispose();return"past_key_values"in a||r.return_dict_in_generate||await v.dispose(),r.return_dict_in_generate?{sequences:C,past_key_values:v,...S,...O}:C}async _encode_input(e,r,s){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);let n=this.sessions[e];return(await pe(n,He(r,n.inputNames)))[s]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function lp(t,e){let{encoder_outputs:r,input_ids:s,decoder_input_ids:n,decoder_attention_mask:o,...a}=e;if(!r){let i=He(e,t.sessions.model.inputNames);r=(await Xt(t,i)).last_hidden_state}return a.input_ids=n,a.encoder_hidden_states=r,t.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=e.attention_mask),o&&!a.attention_mask&&(a.attention_mask=o),await Nt(t,a,!0)}async function Xt(t,e){let r=t.sessions.model,s=He(e,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!e.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await t.encode_text({input_ids:e.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Yo(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let n=s.pixel_values.dims;s.pixel_mask=st([n[0],n[2],n[3]])}return await pe(r,s)}async function ZR(t,e){let r=await t.encode(e);return await t.decode(r)}function up(t,e){let r=Object.create(null);for(let s in t)if(s.startsWith("present")){let n=s.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present_compressor","past_compressor").replace("present_indexer","past_indexer").replace("present","past_key_values");s.includes("encoder")&&e?r[n]=e[n]:r[n]=t[s]}return e?(e.update(r),e):new Kn(r)}function e3(t){let e={};for(let r of["cross_attentions","encoder_attentions","decoder_attentions"])for(let s in t)s.startsWith(r)&&(r in e||(e[r]=[]),e[r].push(t[s]));return e}function fg(t,e){return t.map(r=>typeof r=="number"?r:e[r]??0)}function ha(t,e,r){if(r&&Object.keys(r).length>0)return Object.assign(e,r),r;let s=t.sessions.decoder_model_merged??t.sessions.model,n=(e[t.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=Hs(t.config),a=t.config?.normalized_config?.num_heads,i={batch_size:n};typeof a=="number"&&(i["batch_size x num_heads"]=n*a);let l=Object.create(null);for(let c of s.inputMetadata){if(!o.has(c.name))continue;let u=fg(c.shape,i),f=u.reduce((w,x)=>w*x,1),m=Zr[c.type],_=new $(c.type,new m(f),u);e[c.name]=_,l[c.name]=_}return r?(r.update(l),r):new Kn(l)}function Zs(t,e,r){if(e.num_logits_to_keep)return;(t.sessions.decoder_model_merged??t.sessions.model)?.inputNames.includes("num_logits_to_keep")&&(e.num_logits_to_keep=new $("int64",[r],[]))}async function Nt(t,e,r=!1){let s=t.sessions[r?"decoder_model_merged":"model"],{past_key_values:n,...o}=e;if(s.inputNames.includes("use_cache_branch")&&(o.use_cache_branch=pg(n!=null&&Object.keys(n).length>0)),s.inputNames.includes("position_ids")&&o.attention_mask&&!o.position_ids){let i=["paligemma","gemma3_text","gemma3"].includes(t.config.model_type)?1:0;o.position_ids=s3(o,n,i)}Zs(t,o,0n),ha(t,o,n);let a=He(o,s.inputNames);return await pe(s,a)}async function wM(t,{encode_function:e,merge_function:r,modality_input_names:s,modality_output_name:n,input_ids:o=null,attention_mask:a=null,position_ids:i=null,inputs_embeds:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:f=null,num_logits_to_keep:m=null,..._}){if(!l){l=await t.encode_text({input_ids:o,..._});let x=He(_,s);if(Object.keys(x).length>0){if(o.dims[1]!==1){let b=await e({...x,..._});({inputs_embeds:l,attention_mask:a}=r({[n]:b,inputs_embeds:l,input_ids:o,attention_mask:a}))}else if(c&&o.dims[1]===1){let b=o.dims[1],A=c.get_seq_length();a=Ee([st([o.dims[0],A]),a.slice(null,[a.dims[1]-b,a.dims[1]])],1)}}}if(!i&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(t.config.model_type)){let{image_grid_thw:x,video_grid_thw:b}=_;[i]=t.get_rope_index(o,x,b,a)}return await Nt(t,{inputs_embeds:l,past_key_values:c,attention_mask:a,position_ids:i,generation_config:u,logits_processor:f,num_logits_to_keep:m},!0)}async function t3(t,e){return await wM(t,{...e,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:t.encode_audio.bind(t),merge_function:t._merge_input_ids_with_audio_features.bind(t)})}async function r3(t,e){return await wM(t,{...e,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:t.encode_image.bind(t),merge_function:t._merge_input_ids_with_image_features.bind(t)})}function dg(t,e=0){let[r,s]=t.dims,n=t.data,o=new BigInt64Array(n.length);for(let a=0;ao.dims[1]||n[n.at(-1)])),Zs(t,r,1n),{...r,decoder_input_ids:ug(e)}}function cp(t,...e){return t.config.is_encoder_decoder?_a(t,...e):ns(t,...e)}function xM({modality_token_id:t,inputs_embeds:e,modality_features:r,input_ids:s,attention_mask:n}){let o=s.tolist().map(c=>c.reduce((u,f,m)=>(f==t&&u.push(m),u),[])),a=o.reduce((c,u)=>c+u.length,0),i=r.dims[0];if(a!==i)throw new Error(`Number of tokens and features do not match: tokens: ${a}, features ${i}`);let l=0;for(let c=0;c{let n=await lt(t,e[s],!1,r);return[s,n]})))}var Ul={};yn(Ul,{ASTForAudioClassification:()=>Ag,ASTModel:()=>Eg,ASTPreTrainedModel:()=>ya,AfmoeForCausalLM:()=>bg,AfmoeModel:()=>yg,AfmoePreTrainedModel:()=>wa,AlbertForMaskedLM:()=>gg,AlbertForQuestionAnswering:()=>hg,AlbertForSequenceClassification:()=>_g,AlbertModel:()=>mg,AlbertPreTrainedModel:()=>en,ApertusForCausalLM:()=>xg,ApertusModel:()=>wg,ApertusPreTrainedModel:()=>ga,ArceeForCausalLM:()=>kg,ArceeModel:()=>vg,ArceePreTrainedModel:()=>xa,BartForConditionalGeneration:()=>Sg,BartForSequenceClassification:()=>Mg,BartModel:()=>Tg,BartPretrainedModel:()=>Zn,BaseModelOutput:()=>Wu,BeitForImageClassification:()=>Ig,BeitModel:()=>Og,BeitPreTrainedModel:()=>ba,BertForMaskedLM:()=>Pg,BertForQuestionAnswering:()=>zg,BertForSequenceClassification:()=>Ng,BertForTokenClassification:()=>Lg,BertModel:()=>Cg,BertPreTrainedModel:()=>os,BlenderbotForConditionalGeneration:()=>Rg,BlenderbotModel:()=>$g,BlenderbotPreTrainedModel:()=>va,BlenderbotSmallForConditionalGeneration:()=>Dg,BlenderbotSmallModel:()=>Bg,BlenderbotSmallPreTrainedModel:()=>ka,BloomForCausalLM:()=>Fg,BloomModel:()=>Ug,BloomPreTrainedModel:()=>Ea,CHMv2ForDepthEstimation:()=>Xg,CHMv2PreTrainedModel:()=>_p,CLIPModel:()=>Yg,CLIPPreTrainedModel:()=>wr,CLIPSegForImageSegmentation:()=>tw,CLIPSegModel:()=>ew,CLIPSegPreTrainedModel:()=>Oa,CLIPTextModel:()=>Qg,CLIPTextModelWithProjection:()=>Ma,CLIPVisionModel:()=>Jg,CLIPVisionModelWithProjection:()=>Zg,CamembertForMaskedLM:()=>jg,CamembertForQuestionAnswering:()=>Vg,CamembertForSequenceClassification:()=>qg,CamembertForTokenClassification:()=>Wg,CamembertModel:()=>Gg,CamembertPreTrainedModel:()=>as,CausalLMOutput:()=>ht,CausalLMOutputWithPast:()=>Vu,ChatterboxModel:()=>Aa,ChatterboxPreTrainedModel:()=>dp,ChineseCLIPModel:()=>Hg,ChineseCLIPPreTrainedModel:()=>mp,ClapAudioModelWithProjection:()=>Sa,ClapModel:()=>Kg,ClapPreTrainedModel:()=>eo,ClapTextModelWithProjection:()=>Ta,CodeGenForCausalLM:()=>sw,CodeGenModel:()=>rw,CodeGenPreTrainedModel:()=>Ia,Cohere2ForCausalLM:()=>iw,Cohere2Model:()=>aw,Cohere2PreTrainedModel:()=>Pa,CohereAsrForConditionalGeneration:()=>cw,CohereAsrModel:()=>lw,CohereAsrPreTrainedModel:()=>Na,CohereForCausalLM:()=>ow,CohereModel:()=>nw,CoherePreTrainedModel:()=>Ca,ConvBertForMaskedLM:()=>pw,ConvBertForQuestionAnswering:()=>mw,ConvBertForSequenceClassification:()=>fw,ConvBertForTokenClassification:()=>dw,ConvBertModel:()=>uw,ConvBertPreTrainedModel:()=>is,ConvNextForImageClassification:()=>hw,ConvNextModel:()=>_w,ConvNextPreTrainedModel:()=>La,ConvNextV2ForImageClassification:()=>ww,ConvNextV2Model:()=>gw,ConvNextV2PreTrainedModel:()=>za,DFineForObjectDetection:()=>vw,DFineModel:()=>bw,DFinePreTrainedModel:()=>Ra,DINOv3ConvNextModel:()=>Yw,DINOv3ConvNextPreTrainedModel:()=>vp,DINOv3ViTModel:()=>Qw,DINOv3ViTPreTrainedModel:()=>kp,DPTForDepthEstimation:()=>ox,DPTModel:()=>nx,DPTPreTrainedModel:()=>Wa,DacDecoderModel:()=>Da,DacDecoderOutput:()=>gp,DacEncoderModel:()=>Ba,DacEncoderOutput:()=>hp,DacModel:()=>kw,DacPreTrainedModel:()=>to,DebertaForMaskedLM:()=>Aw,DebertaForQuestionAnswering:()=>Mw,DebertaForSequenceClassification:()=>Tw,DebertaForTokenClassification:()=>Sw,DebertaModel:()=>Ew,DebertaPreTrainedModel:()=>ls,DebertaV2ForMaskedLM:()=>Lw,DebertaV2ForQuestionAnswering:()=>Rw,DebertaV2ForSequenceClassification:()=>zw,DebertaV2ForTokenClassification:()=>$w,DebertaV2Model:()=>Nw,DebertaV2PreTrainedModel:()=>cs,DecisionTransformerModel:()=>Bw,DecisionTransformerPreTrainedModel:()=>wp,DeepseekV3ForCausalLM:()=>Iw,DeepseekV3Model:()=>Ow,DeepseekV3PreTrainedModel:()=>Ua,DeepseekV4ForCausalLM:()=>Pw,DeepseekV4Model:()=>Cw,DeepseekV4PreTrainedModel:()=>Fa,DeiTForImageClassification:()=>Uw,DeiTModel:()=>Dw,DeiTPreTrainedModel:()=>Ga,DepthAnythingForDepthEstimation:()=>Fw,DepthAnythingPreTrainedModel:()=>xp,DepthProForDepthEstimation:()=>Gw,DepthProPreTrainedModel:()=>yp,DetrForObjectDetection:()=>qw,DetrForSegmentation:()=>Ww,DetrModel:()=>jw,DetrObjectDetectionOutput:()=>so,DetrPreTrainedModel:()=>ro,DetrSegmentationOutput:()=>bp,Dinov2ForImageClassification:()=>Hw,Dinov2Model:()=>Vw,Dinov2PreTrainedModel:()=>ja,Dinov2WithRegistersForImageClassification:()=>Kw,Dinov2WithRegistersModel:()=>Xw,Dinov2WithRegistersPreTrainedModel:()=>qa,DistilBertForMaskedLM:()=>rx,DistilBertForQuestionAnswering:()=>tx,DistilBertForSequenceClassification:()=>Zw,DistilBertForTokenClassification:()=>ex,DistilBertModel:()=>Jw,DistilBertPreTrainedModel:()=>us,DonutSwinModel:()=>sx,DonutSwinPreTrainedModel:()=>Ep,EdgeTamModel:()=>T1,EfficientNetForImageClassification:()=>ix,EfficientNetModel:()=>ax,EfficientNetPreTrainedModel:()=>Va,ElectraForMaskedLM:()=>cx,ElectraForQuestionAnswering:()=>fx,ElectraForSequenceClassification:()=>ux,ElectraForTokenClassification:()=>px,ElectraModel:()=>lx,ElectraPreTrainedModel:()=>ps,EmbeddingGemma2Model:()=>Ha,EmbeddingGemma2PreTrainedModel:()=>Ap,Ernie4_5ForCausalLM:()=>mx,Ernie4_5Model:()=>dx,Ernie4_5PretrainedModel:()=>Xa,EsmForMaskedLM:()=>hx,EsmForSequenceClassification:()=>gx,EsmForTokenClassification:()=>wx,EsmModel:()=>_x,EsmPreTrainedModel:()=>tn,EuroBertForMaskedLM:()=>yx,EuroBertForSequenceClassification:()=>bx,EuroBertForTokenClassification:()=>vx,EuroBertModel:()=>xx,EuroBertPreTrainedModel:()=>rn,ExaoneForCausalLM:()=>Ex,ExaoneModel:()=>kx,ExaonePreTrainedModel:()=>Ka,FalconForCausalLM:()=>Tx,FalconH1ForCausalLM:()=>Mx,FalconH1Model:()=>Sx,FalconH1PreTrainedModel:()=>Qa,FalconModel:()=>Ax,FalconPreTrainedModel:()=>Ya,FastViTForImageClassification:()=>Ix,FastViTModel:()=>Ox,FastViTPreTrainedModel:()=>Ja,Florence2ForConditionalGeneration:()=>Cx,Florence2PreTrainedModel:()=>Tp,GLPNForDepthEstimation:()=>Xx,GLPNModel:()=>Hx,GLPNPreTrainedModel:()=>oi,GPT2LMHeadModel:()=>ny,GPT2Model:()=>sy,GPT2PreTrainedModel:()=>ui,GPTBigCodeForCausalLM:()=>Yx,GPTBigCodeModel:()=>Kx,GPTBigCodePreTrainedModel:()=>ai,GPTJForCausalLM:()=>ay,GPTJModel:()=>oy,GPTJPreTrainedModel:()=>pi,GPTNeoForCausalLM:()=>Jx,GPTNeoModel:()=>Qx,GPTNeoPreTrainedModel:()=>ii,GPTNeoXForCausalLM:()=>ey,GPTNeoXModel:()=>Zx,GPTNeoXPreTrainedModel:()=>li,Gemma2ForCausalLM:()=>zx,Gemma2Model:()=>Lx,Gemma2PreTrainedModel:()=>ei,Gemma3ForCausalLM:()=>Dx,Gemma3ForConditionalGeneration:()=>Op,Gemma3Model:()=>Bx,Gemma3PreTrainedModel:()=>Mp,Gemma3nForCausalLM:()=>Ux,Gemma3nForConditionalGeneration:()=>fs,Gemma3nPreTrainedModel:()=>Ip,Gemma4ForCausalLM:()=>Fx,Gemma4ForConditionalGeneration:()=>no,GemmaForCausalLM:()=>Nx,GemmaModel:()=>Px,GemmaPreTrainedModel:()=>Za,GlmForCausalLM:()=>jx,GlmModel:()=>Gx,GlmMoeDsaForCausalLM:()=>Wx,GlmMoeDsaModel:()=>qx,GlmMoeDsaPreTrainedModel:()=>ri,GlmOcrForConditionalGeneration:()=>Vx,GlmPreTrainedModel:()=>ti,GptOssForCausalLM:()=>ry,GptOssModel:()=>ty,GptOssPreTrainedModel:()=>ci,GraniteForCausalLM:()=>ly,GraniteModel:()=>iy,GraniteMoeHybridForCausalLM:()=>uy,GraniteMoeHybridModel:()=>cy,GraniteMoeHybridPreTrainedModel:()=>di,GranitePreTrainedModel:()=>fi,GraniteSpeechForConditionalGeneration:()=>py,GroundingDinoForObjectDetection:()=>fy,GroundingDinoPreTrainedModel:()=>Np,GroupViTModel:()=>dy,GroupViTPreTrainedModel:()=>Lp,HeliumForCausalLM:()=>_y,HeliumModel:()=>my,HeliumPreTrainedModel:()=>mi,HieraForImageClassification:()=>gy,HieraModel:()=>hy,HieraPreTrainedModel:()=>_i,HrmTextForCausalLM:()=>xy,HrmTextModel:()=>wy,HrmTextPreTrainedModel:()=>hi,HubertForCTC:()=>Ty,HubertForSequenceClassification:()=>Sy,HubertModel:()=>Ay,HubertPreTrainedModel:()=>Ey,HunYuanDenseV1ForCausalLM:()=>Oy,HunYuanDenseV1Model:()=>My,HunYuanDenseV1PreTrainedModel:()=>gi,IJepaForImageClassification:()=>Cy,IJepaModel:()=>Iy,IJepaPreTrainedModel:()=>xi,Idefics3ForConditionalGeneration:()=>wi,ImageMattingOutput:()=>Vn,JAISLMHeadModel:()=>Ny,JAISModel:()=>Py,JAISPreTrainedModel:()=>yi,JinaCLIPModel:()=>Ly,JinaCLIPPreTrainedModel:()=>ao,JinaCLIPTextModel:()=>bi,JinaCLIPVisionModel:()=>zy,Lfm2ForCausalLM:()=>Ry,Lfm2Model:()=>$y,Lfm2MoeForCausalLM:()=>Uy,Lfm2MoeModel:()=>Dy,Lfm2MoePreTrainedModel:()=>ki,Lfm2PreTrainedModel:()=>vi,Lfm2VlForConditionalGeneration:()=>Fy,Lfm3ForCausalLM:()=>jy,Lfm3Model:()=>Gy,Lfm3PreTrainedModel:()=>Ei,Lfm3VlForConditionalGeneration:()=>qy,LightOnOcrForConditionalGeneration:()=>By,LiteWhisperForConditionalGeneration:()=>Gv,Llama4ForCausalLM:()=>Hy,Llama4PreTrainedModel:()=>zp,LlamaForCausalLM:()=>Vy,LlamaModel:()=>Wy,LlamaPreTrainedModel:()=>Ai,LlavaForConditionalGeneration:()=>ut,LlavaOnevisionForConditionalGeneration:()=>ut,LlavaPreTrainedModel:()=>Sp,LlavaQwen2ForCausalLM:()=>Rx,LongT5ForConditionalGeneration:()=>Ky,LongT5Model:()=>Xy,LongT5PreTrainedModel:()=>Ti,M2M100ForConditionalGeneration:()=>Qy,M2M100Model:()=>Yy,M2M100PreTrainedModel:()=>Si,MBartForCausalLM:()=>o0,MBartForConditionalGeneration:()=>s0,MBartForSequenceClassification:()=>n0,MBartModel:()=>r0,MBartPreTrainedModel:()=>on,MPNetForMaskedLM:()=>Y0,MPNetForQuestionAnswering:()=>Z0,MPNetForSequenceClassification:()=>Q0,MPNetForTokenClassification:()=>J0,MPNetModel:()=>K0,MPNetPreTrainedModel:()=>ds,MT5ForConditionalGeneration:()=>sb,MT5Model:()=>rb,MT5PreTrainedModel:()=>Gi,MarianMTModel:()=>Zy,MarianModel:()=>Jy,MarianPreTrainedModel:()=>Mi,MaskFormerForInstanceSegmentation:()=>t0,MaskFormerModel:()=>e0,MaskFormerPreTrainedModel:()=>Oi,MaskedLMOutput:()=>ye,Metric3DForDepthEstimation:()=>a0,Metric3DPreTrainedModel:()=>$p,Metric3Dv2ForDepthEstimation:()=>i0,Metric3Dv2PreTrainedModel:()=>Rp,MgpstrForSceneTextRecognition:()=>l0,MgpstrModelOutput:()=>Bp,MgpstrPreTrainedModel:()=>Dp,MimiDecoderModel:()=>Ci,MimiDecoderOutput:()=>Fp,MimiEncoderModel:()=>Ii,MimiEncoderOutput:()=>Up,MimiModel:()=>c0,MimiPreTrainedModel:()=>io,Ministral3ForCausalLM:()=>d0,Ministral3Model:()=>f0,Ministral3PreTrainedModel:()=>Ni,MinistralForCausalLM:()=>p0,MinistralModel:()=>u0,MinistralPreTrainedModel:()=>Pi,Mistral3ForConditionalGeneration:()=>h0,Mistral4ForCausalLM:()=>w0,Mistral4Model:()=>g0,Mistral4PreTrainedModel:()=>zi,MistralForCausalLM:()=>_0,MistralModel:()=>m0,MistralPreTrainedModel:()=>Li,MobileBertForMaskedLM:()=>y0,MobileBertForQuestionAnswering:()=>v0,MobileBertForSequenceClassification:()=>b0,MobileBertModel:()=>x0,MobileBertPreTrainedModel:()=>an,MobileLLMForCausalLM:()=>E0,MobileLLMModel:()=>k0,MobileLLMPreTrainedModel:()=>$i,MobileNetV1ForImageClassification:()=>T0,MobileNetV1ForSemanticSegmentation:()=>S0,MobileNetV1Model:()=>A0,MobileNetV1PreTrainedModel:()=>lo,MobileNetV2ForImageClassification:()=>O0,MobileNetV2ForSemanticSegmentation:()=>I0,MobileNetV2Model:()=>M0,MobileNetV2PreTrainedModel:()=>co,MobileNetV3ForImageClassification:()=>P0,MobileNetV3ForSemanticSegmentation:()=>N0,MobileNetV3Model:()=>C0,MobileNetV3PreTrainedModel:()=>uo,MobileNetV4ForImageClassification:()=>z0,MobileNetV4ForSemanticSegmentation:()=>$0,MobileNetV4Model:()=>L0,MobileNetV4PreTrainedModel:()=>po,MobileViTForImageClassification:()=>B0,MobileViTModel:()=>R0,MobileViTPreTrainedModel:()=>Ri,MobileViTV2ForImageClassification:()=>U0,MobileViTV2Model:()=>D0,MobileViTV2PreTrainedModel:()=>Bi,ModelOutput:()=>Se,ModernBertDecoderForCausalLM:()=>V0,ModernBertDecoderModel:()=>W0,ModernBertDecoderPreTrainedModel:()=>Di,ModernBertForMaskedLM:()=>G0,ModernBertForSequenceClassification:()=>j0,ModernBertForTokenClassification:()=>q0,ModernBertModel:()=>F0,ModernBertPreTrainedModel:()=>ln,Moondream1ForConditionalGeneration:()=>$x,MoonshineForConditionalGeneration:()=>X0,MoonshineModel:()=>H0,MoonshinePreTrainedModel:()=>Ui,MptForCausalLM:()=>tb,MptModel:()=>eb,MptPreTrainedModel:()=>Fi,MultiModalityCausalLM:()=>nb,MultiModalityPreTrainedModel:()=>Gp,MusicgenForCausalLM:()=>ab,MusicgenForConditionalGeneration:()=>qi,MusicgenModel:()=>ob,MusicgenPreTrainedModel:()=>ji,NanoChatForCausalLM:()=>lb,NanoChatModel:()=>ib,NanoChatPreTrainedModel:()=>Wi,NemotronHForCausalLM:()=>ub,NemotronHModel:()=>cb,NemotronHPreTrainedModel:()=>Vi,NeoBertForMaskedLM:()=>fb,NeoBertForQuestionAnswering:()=>_b,NeoBertForSequenceClassification:()=>db,NeoBertForTokenClassification:()=>mb,NeoBertModel:()=>pb,NeoBertPreTrainedModel:()=>ms,NomicBertModel:()=>hb,NomicBertPreTrainedModel:()=>jp,OPTForCausalLM:()=>Ib,OPTModel:()=>Ob,OPTPreTrainedModel:()=>Zi,Olmo2ForCausalLM:()=>yb,Olmo2Model:()=>xb,Olmo2PreTrainedModel:()=>Xi,Olmo3ForCausalLM:()=>vb,Olmo3Model:()=>bb,Olmo3PreTrainedModel:()=>Ki,OlmoForCausalLM:()=>wb,OlmoHybridForCausalLM:()=>Eb,OlmoHybridModel:()=>kb,OlmoHybridPreTrainedModel:()=>Yi,OlmoModel:()=>gb,OlmoPreTrainedModel:()=>Hi,OpenAIPrivacyFilterForTokenClassification:()=>Tb,OpenAIPrivacyFilterModel:()=>Ab,OpenAIPrivacyFilterPreTrainedModel:()=>Qi,OpenELMForCausalLM:()=>Mb,OpenELMModel:()=>Sb,OpenELMPreTrainedModel:()=>Ji,OwlViTForObjectDetection:()=>Lb,OwlViTModel:()=>Nb,OwlViTPreTrainedModel:()=>tl,Owlv2ForObjectDetection:()=>Pb,Owlv2Model:()=>Cb,Owlv2PreTrainedModel:()=>el,PaliGemmaForConditionalGeneration:()=>zb,ParakeetForCTC:()=>$b,ParakeetPreTrainedModel:()=>qp,PatchTSMixerForPrediction:()=>Bb,PatchTSMixerModel:()=>Rb,PatchTSMixerPreTrainedModel:()=>rl,PatchTSTForPrediction:()=>Ub,PatchTSTModel:()=>Db,PatchTSTPreTrainedModel:()=>sl,Phi3ForCausalLM:()=>qb,Phi3Model:()=>jb,Phi3PreTrainedModel:()=>ol,Phi3VForCausalLM:()=>al,Phi3VPreTrainedModel:()=>Wp,PhiForCausalLM:()=>Gb,PhiModel:()=>Fb,PhiPreTrainedModel:()=>nl,PreTrainedModel:()=>y,PvtForImageClassification:()=>Vb,PvtModel:()=>Wb,PvtPreTrainedModel:()=>il,PyAnnoteForAudioFrameClassification:()=>Xb,PyAnnoteModel:()=>Hb,PyAnnotePreTrainedModel:()=>ll,QuestionAnsweringModelOutput:()=>Me,Qwen2ForCausalLM:()=>Yb,Qwen2Model:()=>Kb,Qwen2MoeForCausalLM:()=>Jb,Qwen2MoeModel:()=>Qb,Qwen2MoePreTrainedModel:()=>ul,Qwen2PreTrainedModel:()=>cl,Qwen2VLForCausalLM:()=>si,Qwen2VLForConditionalGeneration:()=>oo,Qwen2VLPreTrainedModel:()=>Cp,Qwen2_5_VLForCausalLM:()=>ni,Qwen2_5_VLForConditionalGeneration:()=>sn,Qwen3ForCausalLM:()=>e1,Qwen3Model:()=>Zb,Qwen3MoeForCausalLM:()=>r1,Qwen3MoeModel:()=>t1,Qwen3MoePreTrainedModel:()=>fl,Qwen3NextForCausalLM:()=>n1,Qwen3NextModel:()=>s1,Qwen3NextPreTrainedModel:()=>dl,Qwen3PreTrainedModel:()=>pl,Qwen3VLForCausalLM:()=>ml,Qwen3VLForConditionalGeneration:()=>cn,Qwen3VLMoeForCausalLM:()=>a1,Qwen3VLMoeForConditionalGeneration:()=>o1,Qwen3_5ForCausalLM:()=>_l,Qwen3_5ForConditionalGeneration:()=>fo,Qwen3_5MoeForCausalLM:()=>l1,Qwen3_5MoeForConditionalGeneration:()=>i1,RFDetrForObjectDetection:()=>f1,RFDetrModel:()=>p1,RFDetrObjectDetectionOutput:()=>Vp,RFDetrPreTrainedModel:()=>gl,RTDetrForObjectDetection:()=>yw,RTDetrModel:()=>xw,RTDetrObjectDetectionOutput:()=>xr,RTDetrPreTrainedModel:()=>$a,RTDetrV2ForObjectDetection:()=>E1,RTDetrV2Model:()=>k1,RTDetrV2ObjectDetectionOutput:()=>Hp,RTDetrV2PreTrainedModel:()=>wl,ResNetForImageClassification:()=>u1,ResNetModel:()=>c1,ResNetPreTrainedModel:()=>hl,RoFormerForMaskedLM:()=>x1,RoFormerForQuestionAnswering:()=>v1,RoFormerForSequenceClassification:()=>y1,RoFormerForTokenClassification:()=>b1,RoFormerModel:()=>w1,RoFormerPreTrainedModel:()=>hs,RobertaForMaskedLM:()=>m1,RobertaForQuestionAnswering:()=>g1,RobertaForSequenceClassification:()=>_1,RobertaForTokenClassification:()=>h1,RobertaModel:()=>d1,RobertaPreTrainedModel:()=>_s,Sam2ImageSegmentationOutput:()=>Yp,Sam2Model:()=>xl,Sam2PreTrainedModel:()=>Qp,Sam3TrackerModel:()=>S1,SamImageSegmentationOutput:()=>Xp,SamModel:()=>A1,SamPreTrainedModel:()=>Kp,SapiensForDepthEstimation:()=>O1,SapiensForNormalEstimation:()=>I1,SapiensForSemanticSegmentation:()=>M1,SapiensPreTrainedModel:()=>mo,SegformerForImageClassification:()=>P1,SegformerForSemanticSegmentation:()=>N1,SegformerModel:()=>C1,SegformerPreTrainedModel:()=>_o,Seq2SeqLMOutput:()=>Hu,SequenceClassifierOutput:()=>q,SiglipModel:()=>L1,SiglipPreTrainedModel:()=>yl,SiglipTextModel:()=>bl,SiglipVisionModel:()=>z1,SmolLM3ForCausalLM:()=>R1,SmolLM3Model:()=>$1,SmolLM3PreTrainedModel:()=>vl,SmolVLMForConditionalGeneration:()=>B1,SnacDecoderModel:()=>El,SnacEncoderModel:()=>kl,SnacModel:()=>D1,SnacPreTrainedModel:()=>ho,SolarOpenForCausalLM:()=>F1,SolarOpenModel:()=>U1,SolarOpenPreTrainedModel:()=>Al,SpeechT5ForSpeechToText:()=>j1,SpeechT5ForTextToSpeech:()=>q1,SpeechT5HifiGan:()=>W1,SpeechT5Model:()=>G1,SpeechT5PreTrainedModel:()=>go,SqueezeBertForMaskedLM:()=>H1,SqueezeBertForQuestionAnswering:()=>K1,SqueezeBertForSequenceClassification:()=>X1,SqueezeBertModel:()=>V1,SqueezeBertPreTrainedModel:()=>un,StableLmForCausalLM:()=>Q1,StableLmModel:()=>Y1,StableLmPreTrainedModel:()=>Tl,Starcoder2ForCausalLM:()=>Z1,Starcoder2Model:()=>J1,Starcoder2PreTrainedModel:()=>Sl,StyleTextToSpeech2Model:()=>ev,StyleTextToSpeech2PreTrainedModel:()=>Jp,SupertonicForConditionalGeneration:()=>Ml,SupertonicPreTrainedModel:()=>Zp,Swin2SRForImageSuperResolution:()=>ov,Swin2SRModel:()=>nv,Swin2SRPreTrainedModel:()=>Ol,SwinForImageClassification:()=>rv,SwinForSemanticSegmentation:()=>sv,SwinModel:()=>tv,SwinPreTrainedModel:()=>wo,T5ForConditionalGeneration:()=>iv,T5Model:()=>av,T5PreTrainedModel:()=>Il,TableTransformerForObjectDetection:()=>cv,TableTransformerModel:()=>lv,TableTransformerObjectDetectionOutput:()=>ef,TableTransformerPreTrainedModel:()=>Cl,TokenClassifierOutput:()=>we,TrOCRForCausalLM:()=>uv,TrOCRPreTrainedModel:()=>tf,UltravoxModel:()=>nn,UltravoxPreTrainedModel:()=>Pp,UniSpeechForCTC:()=>fv,UniSpeechForSequenceClassification:()=>dv,UniSpeechModel:()=>pv,UniSpeechPreTrainedModel:()=>xo,UniSpeechSatForAudioFrameClassification:()=>gv,UniSpeechSatForCTC:()=>_v,UniSpeechSatForSequenceClassification:()=>hv,UniSpeechSatModel:()=>mv,UniSpeechSatPreTrainedModel:()=>pn,VaultGemmaForCausalLM:()=>xv,VaultGemmaModel:()=>wv,VaultGemmaPreTrainedModel:()=>Pl,ViTForImageClassification:()=>vv,ViTMAEModel:()=>kv,ViTMAEPreTrainedModel:()=>rf,ViTMSNForImageClassification:()=>Av,ViTMSNModel:()=>Ev,ViTMSNPreTrainedModel:()=>Ll,ViTModel:()=>bv,ViTPreTrainedModel:()=>Nl,VisionEncoderDecoderModel:()=>yv,VitMatteForImageMatting:()=>Tv,VitMattePreTrainedModel:()=>sf,VitPoseForPoseEstimation:()=>Sv,VitPosePreTrainedModel:()=>nf,VitsModel:()=>Mv,VitsModelOutput:()=>of,VitsPreTrainedModel:()=>af,VoxtralForConditionalGeneration:()=>Ov,VoxtralRealtimeForConditionalGeneration:()=>zl,VoxtralRealtimePreTrainedModel:()=>lf,Wav2Vec2BertForCTC:()=>Nv,Wav2Vec2BertForSequenceClassification:()=>Lv,Wav2Vec2BertModel:()=>Pv,Wav2Vec2BertPreTrainedModel:()=>yo,Wav2Vec2ForAudioFrameClassification:()=>ky,Wav2Vec2ForCTC:()=>by,Wav2Vec2ForSequenceClassification:()=>vy,Wav2Vec2Model:()=>yy,Wav2Vec2PreTrainedModel:()=>ir,WavLMForAudioFrameClassification:()=>Dv,WavLMForCTC:()=>$v,WavLMForSequenceClassification:()=>Rv,WavLMForXVector:()=>Bv,WavLMModel:()=>zv,WavLMPreTrainedModel:()=>gs,WeSpeakerResNetModel:()=>Uv,WeSpeakerResNetPreTrainedModel:()=>uf,WhisperForConditionalGeneration:()=>ff,WhisperModel:()=>Fv,WhisperPreTrainedModel:()=>$l,XLMForQuestionAnswering:()=>Hv,XLMForSequenceClassification:()=>Wv,XLMForTokenClassification:()=>Vv,XLMModel:()=>jv,XLMPreTrainedModel:()=>ws,XLMRobertaForMaskedLM:()=>Kv,XLMRobertaForQuestionAnswering:()=>Jv,XLMRobertaForSequenceClassification:()=>Yv,XLMRobertaForTokenClassification:()=>Qv,XLMRobertaModel:()=>Xv,XLMRobertaPreTrainedModel:()=>xs,XLMWithLMHeadModel:()=>qv,XVectorOutput:()=>cf,YolosForObjectDetection:()=>ek,YolosModel:()=>Zv,YolosObjectDetectionOutput:()=>df,YolosPreTrainedModel:()=>Rl,YoutuForCausalLM:()=>rk,YoutuModel:()=>tk,YoutuPreTrainedModel:()=>Bl,ZayaForCausalLM:()=>nk,ZayaModel:()=>sk,ZayaPreTrainedModel:()=>Dl});var en=class extends y{},mg=class extends en{},_g=class extends en{async _call(e){return new q(await super._call(e))}},hg=class extends en{async _call(e){return new Me(await super._call(e))}},gg=class extends en{async _call(e){return new ye(await super._call(e))}};var ga=class extends y{},wg=class extends ga{},xg=class extends ga{};var wa=class extends y{},yg=class extends wa{},bg=class extends wa{};var xa=class extends y{},vg=class extends xa{},kg=class extends xa{};var ya=class extends y{},Eg=class extends ya{},Ag=class extends ya{};var Zn=class extends y{},Tg=class extends Zn{},Sg=class extends Zn{},Mg=class extends Zn{async _call(e){return new q(await super._call(e))}};var ba=class extends y{},Og=class extends ba{},Ig=class extends ba{async _call(e){return new q(await super._call(e))}};var os=class extends y{},Cg=class extends os{},Pg=class extends os{async _call(e){return new ye(await super._call(e))}},Ng=class extends os{async _call(e){return new q(await super._call(e))}},Lg=class extends os{async _call(e){return new we(await super._call(e))}},zg=class extends os{async _call(e){return new Me(await super._call(e))}};var va=class extends y{},$g=class extends va{},Rg=class extends va{};var ka=class extends y{},Bg=class extends ka{},Dg=class extends ka{};var Ea=class extends y{},Ug=class extends Ea{},Fg=class extends Ea{};var as=class extends y{},Gg=class extends as{},jg=class extends as{async _call(e){return new ye(await super._call(e))}},qg=class extends as{async _call(e){return new q(await super._call(e))}},Wg=class extends as{async _call(e){return new we(await super._call(e))}},Vg=class extends as{async _call(e){return new Me(await super._call(e))}};var o3=4299n,yM=6561n,dp=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},Aa=class extends dp{async encode_speech(e){return pe(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:r=null,audio_values:s=null,exaggeration:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,num_logits_to_keep:u=null,audio_features:f=null,audio_tokens:m=null,speaker_embeddings:_=null,speaker_features:w=null,...x}){let b;if(!a){let k=this.sessions.embed_tokens.inputNames,M={input_ids:e};if(k.includes("exaggeration")){if(!(n instanceof $)){let S=e.dims[0];if(n==null)n=Ze([S],.5);else if(typeof n=="number")n=Ze([S],n);else if(Array.isArray(n))n=new $("float32",n,[S]);else throw new Error("Unsupported type for `exaggeration` input")}M.exaggeration=n}if(k.includes("position_ids")&&(M.position_ids=o),{inputs_embeds:a}=await pe(this.sessions.embed_tokens,M),f&&m&&_&&w&&(b={audio_features:f,audio_tokens:m,speaker_embeddings:_,speaker_features:w}),b||s)b??=await this.encode_speech(s),a=Ee([b.audio_features,a],1),r=st([a.dims[0],a.dims[1]]);else{let S=a.dims[1];if(!i||S!==1)throw new Error("Incorrect state encountered during generation.");let O=i.get_seq_length();r=st([a.dims[0],O+S])}}return{...await Nt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,generation_config:l,logits_processor:c,num_logits_to_keep:u},!1),...b}}prepare_inputs_for_generation(e,r,s){if(!r.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(r.input_ids.dims[1]===1){let n=Array.from({length:e.length},(o,a)=>e[a].length-e[a].findLastIndex(i=>i==yM)-1);r.position_ids=new $("int64",n,[e.length,1])}else{let o=r.input_ids.tolist().map(a=>{let i=0;return a.map(l=>l>=yM?0:i++)});r.position_ids=new $("int64",o.flat(),r.input_ids.dims)}return r.input_ids.dims[1]===1&&(delete r.audio_values,delete r.audio_features,delete r.audio_tokens,delete r.speaker_embeddings,delete r.speaker_features),ns(this,e,r,s)}async generate(e){let r=e.past_key_values,{sequences:s,audio_tokens:n,speaker_embeddings:o,speaker_features:a,past_key_values:i}=await super.generate({...e,return_dict_in_generate:!0});try{let l=s.slice(null,[e.input_ids.dims[1],-1]),c=Ze([l.dims[0],3],o3),u=Ee([n,l,c],1),{waveform:f}=await pe(this.sessions.conditional_decoder,{speech_tokens:u,speaker_features:a,speaker_embeddings:o});return f}finally{i!==r&&await i?.dispose()}}};var mp=class extends y{},Hg=class extends mp{};var _p=class extends y{},Xg=class extends _p{};var eo=class extends y{},Kg=class extends eo{},Ta=class extends eo{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Sa=class extends eo{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"audio_model"})}};var wr=class extends y{},Yg=class extends wr{},Qg=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Ma=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},Jg=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}},Zg=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var Oa=class extends y{},ew=class extends Oa{},tw=class extends Oa{};var Ia=class extends y{},rw=class extends Ia{},sw=class extends Ia{};var Ca=class extends y{},nw=class extends Ca{},ow=class extends Ca{};var Pa=class extends y{},aw=class extends Pa{},iw=class extends Pa{};var Na=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},lw=class extends Na{},cw=class extends Na{};var is=class extends y{},uw=class extends is{},pw=class extends is{async _call(e){return new ye(await super._call(e))}},fw=class extends is{async _call(e){return new q(await super._call(e))}},dw=class extends is{async _call(e){return new we(await super._call(e))}},mw=class extends is{async _call(e){return new Me(await super._call(e))}};var La=class extends y{},_w=class extends La{},hw=class extends La{async _call(e){return new q(await super._call(e))}};var za=class extends y{},gw=class extends za{},ww=class extends za{async _call(e){return new q(await super._call(e))}};var $a=class extends y{},xw=class extends $a{},yw=class extends $a{async _call(e){return new xr(await super._call(e))}},xr=class extends Se{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Ra=class extends y{},bw=class extends Ra{},vw=class extends Ra{async _call(e){return new xr(await super._call(e))}};var hp=class extends Se{constructor({audio_codes:e}){super(),this.audio_codes=e}},gp=class extends Se{constructor({audio_values:e}){super(),this.audio_values=e}},to=class extends y{main_input_name="input_values";forward_params=["input_values"]},kw=class extends to{async encode(e){return new hp(await pe(this.sessions.encoder_model,e))}async decode(e){return new gp(await pe(this.sessions.decoder_model,e))}},Ba=class extends to{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Da=class extends to{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var ls=class extends y{},Ew=class extends ls{},Aw=class extends ls{async _call(e){return new ye(await super._call(e))}},Tw=class extends ls{async _call(e){return new q(await super._call(e))}},Sw=class extends ls{async _call(e){return new we(await super._call(e))}},Mw=class extends ls{async _call(e){return new Me(await super._call(e))}};var Ua=class extends y{},Ow=class extends Ua{},Iw=class extends Ua{};var Fa=class extends y{},Cw=class extends Fa{},Pw=class extends Fa{};var cs=class extends y{},Nw=class extends cs{},Lw=class extends cs{async _call(e){return new ye(await super._call(e))}},zw=class extends cs{async _call(e){return new q(await super._call(e))}},$w=class extends cs{async _call(e){return new we(await super._call(e))}},Rw=class extends cs{async _call(e){return new Me(await super._call(e))}};var wp=class extends y{},Bw=class extends wp{};var Ga=class extends y{},Dw=class extends Ga{},Uw=class extends Ga{async _call(e){return new q(await super._call(e))}};var xp=class extends y{},Fw=class extends xp{};var yp=class extends y{},Gw=class extends yp{};var ro=class extends y{},jw=class extends ro{},qw=class extends ro{async _call(e){return new so(await super._call(e))}},Ww=class extends ro{async _call(e){return new bp(await super._call(e))}},so=class extends Se{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}},bp=class extends Se{constructor({logits:e,pred_boxes:r,pred_masks:s}){super(),this.logits=e,this.pred_boxes=r,this.pred_masks=s}};var ja=class extends y{},Vw=class extends ja{},Hw=class extends ja{async _call(e){return new q(await super._call(e))}};var qa=class extends y{},Xw=class extends qa{},Kw=class extends qa{async _call(e){return new q(await super._call(e))}};var vp=class extends y{},Yw=class extends vp{};var kp=class extends y{},Qw=class extends kp{};var us=class extends y{},Jw=class extends us{},Zw=class extends us{async _call(e){return new q(await super._call(e))}},ex=class extends us{async _call(e){return new we(await super._call(e))}},tx=class extends us{async _call(e){return new Me(await super._call(e))}},rx=class extends us{async _call(e){return new ye(await super._call(e))}};var Ep=class extends y{},sx=class extends Ep{};var Wa=class extends y{},nx=class extends Wa{},ox=class extends Wa{};var Va=class extends y{},ax=class extends Va{},ix=class extends Va{async _call(e){return new q(await super._call(e))}};var ps=class extends y{},lx=class extends ps{},cx=class extends ps{async _call(e){return new ye(await super._call(e))}},ux=class extends ps{async _call(e){return new q(await super._call(e))}},px=class extends ps{async _call(e){return new we(await super._call(e))}},fx=class extends ps{async _call(e){return new Me(await super._call(e))}};var Ap=class extends y{},Ha=class extends Ap{async forward({input_ids:e,attention_mask:r,pixel_values:s=null,image_position_ids:n=null,pixel_values_videos:o=null,video_position_ids:a=null,input_features:i=null,input_features_mask:l=null}){let c={image_features:s&&await this.encode_image({pixel_values:s,pixel_position_ids:n}),video_features:o&&await this.encode_image({pixel_values:o,pixel_position_ids:a}),audio_features:i&&await this.encode_audio({input_features:i,input_features_mask:l})},{image_token_id:u,video_token_id:f,audio_token_id:m,text_config:_}=this.config,w={image:u,video:f,audio:m};for(let[x,b]of Object.entries(w)){let A=`${x}_features`;c[A]??=new $("float32",new Float32Array(0),[0,_.hidden_size]);let k=0;for(let M of e.data)Number(M)===b&&++k;if(k!==c[A].dims[0])throw new Error(`The number of ${x} tokens (${k}) and ${x} features (${c[A].dims[0]}) do not match.`)}return await pe(this.sessions.model,{input_ids:e,attention_mask:r,...c})}};var Xa=class extends y{},dx=class extends Xa{},mx=class extends Xa{};var tn=class extends y{},_x=class extends tn{},hx=class extends tn{async _call(e){return new ye(await super._call(e))}},gx=class extends tn{async _call(e){return new q(await super._call(e))}},wx=class extends tn{async _call(e){return new we(await super._call(e))}};var rn=class extends y{},xx=class extends rn{},yx=class extends rn{async _call(e){return new ye(await super._call(e))}},bx=class extends rn{async _call(e){return new q(await super._call(e))}},vx=class extends rn{async _call(e){return new we(await super._call(e))}};var Ka=class extends y{},kx=class extends Ka{},Ex=class extends Ka{};var Ya=class extends y{},Ax=class extends Ya{},Tx=class extends Ya{};var Qa=class extends y{},Sx=class extends Qa{},Mx=class extends Qa{};var Ja=class extends y{},Ox=class extends Ja{},Ix=class extends Ja{async _call(e){return new q(await super._call(e))}};var Tp=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},Cx=class extends Tp{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:r,input_ids:s,attention_mask:n}){return{inputs_embeds:Ee([r,e],1),attention_mask:Ee([st(r.dims.slice(0,2)),n],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:s,attention_mask:n}){if(!e&&!r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,a;return e&&(o=await this.encode_text({input_ids:e})),r&&(a=await this.encode_image({pixel_values:r})),o&&a?{inputs_embeds:s,attention_mask:n}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:a,input_ids:e,attention_mask:n}):s=o||a,{inputs_embeds:s,attention_mask:n}}async forward({input_ids:e,pixel_values:r,attention_mask:s,decoder_input_ids:n,decoder_attention_mask:o,encoder_outputs:a,past_key_values:i,inputs_embeds:l,decoder_inputs_embeds:c,num_logits_to_keep:u=null}){if(l||({inputs_embeds:l,attention_mask:s}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:r,inputs_embeds:l,attention_mask:s})),!a){let{last_hidden_state:m}=await Xt(this,{inputs_embeds:l,attention_mask:s});a=m}if(!c){if(!n)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:n})}return await Nt(this,{inputs_embeds:c,attention_mask:o,encoder_attention_mask:s,encoder_hidden_states:a,past_key_values:i,num_logits_to_keep:u},!0)}};var Za=class extends y{},Px=class extends Za{},Nx=class extends Za{};var ei=class extends y{},Lx=class extends ei{},zx=class extends ei{};var Sp=class extends y{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},ut=class extends Sp{_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Jn({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:s})}},$x=class extends ut{},Rx=class extends ut{};var Mp=class extends y{},Bx=class extends Mp{},Op=class extends ut{},Dx=class extends Op{};var Ip=class extends y{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},fs=class extends Ip{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,input_features:n=null,input_features_mask:o=null,position_ids:a=null,inputs_embeds:i=null,per_layer_inputs:l=null,past_key_values:c=null,generation_config:u=null,logits_processor:f=null,num_logits_to_keep:m=null,..._}){if((!i||!l)&&({inputs_embeds:i,per_layer_inputs:l}=await pe(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(s){let{image_features:x}=await this._encode_vision({pixel_values:s,..._});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_image_features({image_features:x,inputs_embeds:i,input_ids:e,attention_mask:r}))}if(n){let{audio_features:x}=await pe(this.sessions.audio_encoder,{input_features:n,input_features_mask:o});({inputs_embeds:i,attention_mask:r}=this._merge_input_ids_with_audio_features({audio_features:x,inputs_embeds:i,input_ids:e,attention_mask:r}))}}return await Nt(this,{inputs_embeds:i,per_layer_inputs:l,past_key_values:c,attention_mask:r,position_ids:a,generation_config:u,logits_processor:f,num_logits_to_keep:m},!0)}_encode_vision(e){return pe(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let r=e.image_features.dims.at(-1),s=e.image_features.view(-1,r);return Jn({image_token_id:this.config.image_token_id,...e,image_features:s})}_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return fp({audio_token_id:this.config.audio_token_id,...e,audio_features:s})}},Ux=class extends fs{};var no=class extends fs{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 pe(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},Fx=class extends no{};var ti=class extends y{},Gx=class extends ti{},jx=class extends ti{};var ri=class extends y{},qx=class extends ri{},Wx=class extends ri{};var Cp=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},oo=class extends Cp{image_grid_thw_name="grid_thw";_get_text_only_rope_index(e,r){if(r){let{data:s,dims:n}=dg(r),o=BigInt64Array.from({length:3*s.length},(i,l)=>s[l%s.length]),a=Array.from({length:n[0]},(i,l)=>Le(s.subarray(n[1]*l,n[1]*(l+1)))[0]+1n+BigInt(n[1]));return[new $("int64",o,[3,...n]),new $("int64",a,[a.length,1])]}else{let[s,n]=e.dims,o=BigInt64Array.from({length:3*s*n},(a,i)=>BigInt(Math.floor(i%n/s)));return[new $("int64",o,[3,...e.dims]),Am([s,1])]}}_reorder_and_write_positions(e,r,s,n){let o=e.reduce((c,u)=>c+u.length,0),a=new Array(o),i=0;for(let c=0;c<3;++c)for(let u of e){let f=u.length/3;for(let m=c*f;m<(c+1)*f;++m)a[i++]=u[m]}let l=0;for(let c=0;c(M==l&&k.push(S),k),[]).map(k=>c[k+1]),m=f.filter(k=>k==a).length,_=f.filter(k=>k==i).length,w=[],x=0,b=m,A=_;for(let k=0;kG>x&&z==a),S=c.findIndex((z,G)=>G>x&&z==i),O=b>0&&M!==-1?M:c.length+1,C=A>0&&S!==-1?S:c.length+1,v,U,j,F;O0?Le(w.at(-1))[0]+1:0;w.push(Array.from({length:3*B},(z,G)=>I+G%B));let oe=B+I,J=K*Y*Q,Z=Array.from({length:J},(z,G)=>oe+Math.floor(G/(Y*Q))),me=Array.from({length:J},(z,G)=>oe+Math.floor(G/Q)%Y),L=Array.from({length:J},(z,G)=>oe+G%Q);w.push([Z,me,L].flat()),x=v+J}if(x0?Le(w.at(-1))[0]+1:0,M=c.length-x;w.push(Array.from({length:3*M},(S,O)=>k+O%M))}return w}get_rope_index(e,r,s,n){let{vision_config:o}=this.config,a=o.spatial_merge_size??2;if(r||s){let i=e.tolist();n||(n=Ln(e));let l=n.tolist(),c=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),u=r?r.tolist():[],f=s?s.tolist():[],m={image_index:0,video_index:0},_=[];for(let w=0;wl[w][M]==1),b=this._get_multimodal_rope_positions({filtered_ids:x,image_grid_thw_list:u,video_grid_thw_list:f,spatial_merge_size:a,state:m}),A=this._reorder_and_write_positions(b,l[w],c,w);_.push(Le(A)[0]+1-i[w].length)}return[new $("int64",c.flat(1/0),[3,e.dims[0],e.dims[1]]),new $("int64",_,[_.length,1])]}else return this._get_text_only_rope_index(e,n)}async encode_image({pixel_values:e,image_grid_thw:r}){return(await pe(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:r})).image_features}_merge_input_ids_with_image_features(e){return Jn({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,r,s){if(Zs(this,r,1n),!r.attention_mask||r.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return r;if(!r.past_key_values)[r.position_ids,r.rope_deltas]=this.get_rope_index(r.input_ids,r.image_grid_thw,r.video_grid_thw,r.attention_mask);else{r.pixel_values=null;let o=r.past_key_values.get_seq_length();if(oa+l);r.position_ids=kt([i,i,i],0)}}return r}},si=class extends oo{};var sn=class extends oo{image_grid_thw_name="image_grid_thw"},ni=class extends si{image_grid_thw_name="image_grid_thw"};var Vx=class extends sn{get_vision_position_ids(e,r,s,n){let o=Math.floor(r[0]/s),a=Math.floor(r[1]/n),i=Math.floor(r[2]/n),l=a*i*o,c=Array.from({length:l},()=>e),u=Array.from({length:l},(m,_)=>e+Math.floor(_/(i*o))),f=Array.from({length:l},(m,_)=>e+_%i);return[...c,...u,...f]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:r,video_grid_thw_list:s,spatial_merge_size:n,state:o}){let{image_token_id:a}=this.config,i=[],l=0,c=e[0]==a?1:0;for(let m=1;m<=e.length;++m){let _=mu+A%x)),u+=x}else{let x=r[o.image_index++].map(Number),b=x[0];f.push(this.get_vision_position_ids(u,x,b,n)),u+=Math.max(x[1],x[2])/n}return f}};var oi=class extends y{},Hx=class extends oi{},Xx=class extends oi{};var ai=class extends y{},Kx=class extends ai{},Yx=class extends ai{};var ii=class extends y{},Qx=class extends ii{},Jx=class extends ii{};var li=class extends y{},Zx=class extends li{},ey=class extends li{};var ci=class extends y{},ty=class extends ci{},ry=class extends ci{};var ui=class extends y{},sy=class extends ui{},ny=class extends ui{};var pi=class extends y{},oy=class extends pi{},ay=class extends pi{};var fi=class extends y{},iy=class extends fi{},ly=class extends fi{};var di=class extends y{},cy=class extends di{},uy=class extends di{};var Pp=class extends y{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},nn=class extends Pp{_merge_input_ids_with_audio_features(e){let r=e.audio_features.dims.at(-1),s=e.audio_features.view(-1,r);return fp({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:s})}};var py=class extends nn{forward_params=["input_ids","attention_mask","input_features","past_key_values"]};var Np=class extends y{},fy=class extends Np{};var Lp=class extends y{},dy=class extends Lp{};var mi=class extends y{},my=class extends mi{},_y=class extends mi{};var _i=class extends y{},hy=class extends _i{},gy=class extends _i{async _call(e){return new q(await super._call(e))}};var hi=class extends y{},wy=class extends hi{},xy=class extends hi{forward_params=["input_ids","attention_mask","token_type_ids","past_key_values"];prepare_inputs_for_generation(e,r,s){let n=ns(this,e,r,s);return n.token_type_ids=(n.past_key_values?Yo:Ln)(n.input_ids),n}};var ir=class extends y{},yy=class extends ir{},by=class extends ir{async _call(e){return new ht(await super._call(e))}},vy=class extends ir{async _call(e){return new q(await super._call(e))}},ky=class extends ir{async _call(e){return new we(await super._call(e))}};var Ey=class extends y{},Ay=class extends ir{},Ty=class extends ir{async _call(e){return new ht(await super._call(e))}},Sy=class extends ir{async _call(e){return new q(await super._call(e))}};var gi=class extends y{},My=class extends gi{},Oy=class extends gi{};var wi=class extends ut{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]};var xi=class extends y{},Iy=class extends xi{},Cy=class extends xi{async _call(e){return new q(await super._call(e))}};var yi=class extends y{},Py=class extends yi{},Ny=class extends yi{};var ao=class extends y{},Ly=class extends ao{async forward(e){let r=!e.input_ids,s=!e.pixel_values;if(r&&s)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(r&&(e.input_ids=st([e.pixel_values.dims[0],1])),s){let{image_size:c}=this.config.vision_config;e.pixel_values=Ze([0,3,c,c],0)}let{text_embeddings:n,image_embeddings:o,l2norm_text_embeddings:a,l2norm_image_embeddings:i}=await super.forward(e),l={};return r||(l.text_embeddings=n,l.l2norm_text_embeddings=a),s||(l.image_embeddings=o,l.l2norm_image_embeddings=i),l}},bi=class extends ao{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},zy=class extends ao{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var vi=class extends y{},$y=class extends vi{},Ry=class extends vi{};var By=class extends ut{};var ki=class extends y{},Dy=class extends ki{},Uy=class extends ki{};var Fy=class extends ut{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]};var Ei=class extends y{},Gy=class extends Ei{},jy=class extends Ei{};var qy=class extends ut{forward_params=["input_ids","attention_mask","pixel_values","image_grid_thw","position_ids","past_key_values"]};var Ai=class extends y{},Wy=class extends Ai{},Vy=class extends Ai{};var zp=class extends y{},Hy=class extends zp{};var Ti=class extends y{},Xy=class extends Ti{},Ky=class extends Ti{};var Si=class extends y{},Yy=class extends Si{},Qy=class extends Si{};var Mi=class extends y{},Jy=class extends Mi{},Zy=class extends Mi{};var Oi=class extends y{},e0=class extends Oi{},t0=class extends Oi{};var on=class extends y{},r0=class extends on{},s0=class extends on{},n0=class extends on{async _call(e){return new q(await super._call(e))}},o0=class extends on{};var $p=class extends y{},a0=class extends $p{};var Rp=class extends y{},i0=class extends Rp{};var Bp=class extends Se{constructor({char_logits:e,bpe_logits:r,wp_logits:s}){super(),this.char_logits=e,this.bpe_logits=r,this.wp_logits=s}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},Dp=class extends y{},l0=class extends Dp{async _call(e){return new Bp(await super._call(e))}};var Up=class extends Se{constructor({audio_codes:e}){super(),this.audio_codes=e}},Fp=class extends Se{constructor({audio_values:e}){super(),this.audio_values=e}},io=class extends y{main_input_name="input_values";forward_params=["input_values"]},c0=class extends io{async encode(e){return new Up(await pe(this.sessions.encoder_model,e))}async decode(e){return new Fp(await pe(this.sessions.decoder_model,e))}},Ii=class extends io{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},Ci=class extends io{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Pi=class extends y{},u0=class extends Pi{},p0=class extends Pi{};var Ni=class extends y{},f0=class extends Ni{},d0=class extends Ni{};var Li=class extends y{},m0=class extends Li{},_0=class extends Li{};var h0=class extends ut{};var zi=class extends y{},g0=class extends zi{},w0=class extends zi{};var an=class extends y{},x0=class extends an{},y0=class extends an{async _call(e){return new ye(await super._call(e))}},b0=class extends an{async _call(e){return new q(await super._call(e))}},v0=class extends an{async _call(e){return new Me(await super._call(e))}};var $i=class extends y{},k0=class extends $i{},E0=class extends $i{};var lo=class extends y{},A0=class extends lo{},T0=class extends lo{async _call(e){return new q(await super._call(e))}},S0=class extends lo{};var co=class extends y{},M0=class extends co{},O0=class extends co{async _call(e){return new q(await super._call(e))}},I0=class extends co{};var uo=class extends y{},C0=class extends uo{},P0=class extends uo{async _call(e){return new q(await super._call(e))}},N0=class extends uo{};var po=class extends y{},L0=class extends po{},z0=class extends po{async _call(e){return new q(await super._call(e))}},$0=class extends po{};var Ri=class extends y{},R0=class extends Ri{},B0=class extends Ri{async _call(e){return new q(await super._call(e))}};var Bi=class extends y{},D0=class extends Bi{},U0=class extends Bi{async _call(e){return new q(await super._call(e))}};var ln=class extends y{},F0=class extends ln{},G0=class extends ln{async _call(e){return new ye(await super._call(e))}},j0=class extends ln{async _call(e){return new q(await super._call(e))}},q0=class extends ln{async _call(e){return new we(await super._call(e))}};var Di=class extends y{},W0=class extends Di{},V0=class extends Di{};var Ui=class extends y{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},H0=class extends Ui{},X0=class extends Ui{};var ds=class extends y{},K0=class extends ds{},Y0=class extends ds{async _call(e){return new ye(await super._call(e))}},Q0=class extends ds{async _call(e){return new q(await super._call(e))}},J0=class extends ds{async _call(e){return new we(await super._call(e))}},Z0=class extends ds{async _call(e){return new Me(await super._call(e))}};var Fi=class extends y{},eb=class extends Fi{},tb=class extends Fi{};var Gi=class extends y{},rb=class extends Gi{},sb=class extends Gi{};var Gp=class extends y{},nb=class extends Gp{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){let r=this._generation_mode??"text",s;if(r==="text"||!e.past_key_values){let l=this.sessions.prepare_inputs_embeds,c=He(e,l.inputNames);s=await pe(l,c)}else{let l=this.sessions.gen_img_embeds,c=He({image_ids:e.input_ids},l.inputNames);s=await pe(l,c)}let n={...e,...s},o=await Nt(this,n),a=this.sessions[r==="text"?"lm_head":"gen_head"];if(!a)throw new Error(`Unable to find "${a}" generation head`);let i=await pe(a,He(o,a.inputNames));return{...s,...o,...i}}prepare_inputs_for_generation(e,r,s){let n=!!r.past_key_values;return Zs(this,r,1n),s.guidance_scale!==null&&s.guidance_scale>1&&(n?r.input_ids=Ee([r.input_ids,r.input_ids],0):(r.input_ids=Ee([r.input_ids,Ko(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Ee([r.attention_mask,Ko(r.attention_mask,0n)],0))),(n||!r.pixel_values)&&(r.pixel_values=Ze([0,0,3,384,384],1)),n&&(r.images_seq_mask=new $("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new $("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";let r=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[r,null]),o=this.sessions.image_decode,{decoded_image:a}=await pe(o,{generated_tokens:n}),i=a.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),l=[];for(let c of i){let u=rt.fromTensor(c);l.push(u)}return l}};var ji=class extends y{},ob=class extends ji{},ab=class extends ji{},qi=class extends y{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){let[r,s]=e.dims,n=this.config.decoder.num_codebooks,o=s-n,a=0;for(let c=0;c0&&m<=o&&(e.data[a++]=e.data[c])}let i=Math.floor(r/n),l=a/(i*n);return new $(e.type,e.data.slice(0,a),[i,n,l])}prepare_inputs_for_generation(e,r,s){let n=BigInt(this.config.decoder.pad_token_id),o=structuredClone(e);for(let a=0;a=i&&(o[a][i]=n);return s.guidance_scale!==null&&s.guidance_scale>1&&(o=o.concat(o)),_a(this,o,r,s)}async generate(e){let r=await super.generate(e),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:n}=await pe(this.sessions.encodec_decode,{audio_codes:s});return n}};var Wi=class extends y{},ib=class extends Wi{},lb=class extends Wi{};var Vi=class extends y{},cb=class extends Vi{},ub=class extends Vi{};var ms=class extends y{},pb=class extends ms{},fb=class extends ms{async _call(e){return new ye(await super._call(e))}},db=class extends ms{async _call(e){return new q(await super._call(e))}},mb=class extends ms{async _call(e){return new we(await super._call(e))}},_b=class extends ms{async _call(e){return new Me(await super._call(e))}};var jp=class extends y{},hb=class extends jp{};var Hi=class extends y{},gb=class extends Hi{},wb=class extends Hi{};var Xi=class extends y{},xb=class extends Xi{},yb=class extends Xi{};var Ki=class extends y{},bb=class extends Ki{},vb=class extends Ki{};var Yi=class extends y{},kb=class extends Yi{},Eb=class extends Yi{};var Qi=class extends y{},Ab=class extends Qi{},Tb=class extends Qi{async _call(e){return new q(await super._call(e))}};var Ji=class extends y{},Sb=class extends Ji{},Mb=class extends Ji{};var Zi=class extends y{},Ob=class extends Zi{},Ib=class extends Zi{};var el=class extends y{},Cb=class extends el{},Pb=class extends el{};var tl=class extends y{},Nb=class extends tl{},Lb=class extends tl{};var zb=class extends ut{};var qp=class extends y{},$b=class extends qp{async _call(e){return new ht(await super._call(e))}};var rl=class extends y{},Rb=class extends rl{},Bb=class extends rl{};var sl=class extends y{},Db=class extends sl{},Ub=class extends sl{};var nl=class extends y{},Fb=class extends nl{},Gb=class extends nl{};var ol=class extends y{},jb=class extends ol{},qb=class extends ol{};var Wp=class extends y{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},al=class extends Wp{async forward({input_ids:e=null,attention_mask:r=null,pixel_values:s=null,image_sizes:n=null,position_ids:o=null,inputs_embeds:a=null,past_key_values:i=null,generation_config:l=null,logits_processor:c=null,num_logits_to_keep:u=null,...f}){if(!a){let _;if(s&&e.dims[1]!==1){if(!n)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:_}=await pe(this.sessions.vision_encoder,{pixel_values:s,image_sizes:n}))}else{let w=this.config.normalized_config.hidden_size;_=new $("float32",[],[0,w])}({inputs_embeds:a}=await pe(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:_}))}return await Nt(this,{inputs_embeds:a,past_key_values:i,attention_mask:r,position_ids:o,generation_config:l,logits_processor:c,num_logits_to_keep:u},!1)}};var il=class extends y{},Wb=class extends il{},Vb=class extends il{async _call(e){return new q(await super._call(e))}};var ll=class extends y{},Hb=class extends ll{},Xb=class extends ll{async _call(e){return new we(await super._call(e))}};var cl=class extends y{},Kb=class extends cl{},Yb=class extends cl{};var ul=class extends y{},Qb=class extends ul{},Jb=class extends ul{};var pl=class extends y{},Zb=class extends pl{},e1=class extends pl{};var fl=class extends y{},t1=class extends fl{},r1=class extends fl{};var dl=class extends y{},s1=class extends dl{},n1=class extends dl{};var cn=class extends sn{},ml=class extends ni{};var o1=class extends cn{},a1=class extends ml{};var fo=class extends cn{},_l=class extends fo{};var i1=class extends fo{},l1=class extends _l{};var hl=class extends y{},c1=class extends hl{},u1=class extends hl{async _call(e){return new q(await super._call(e))}};var gl=class extends y{},p1=class extends gl{},f1=class extends gl{async _call(e){return new Vp(await super._call(e))}},Vp=class extends xr{};var _s=class extends y{},d1=class extends _s{},m1=class extends _s{async _call(e){return new ye(await super._call(e))}},_1=class extends _s{async _call(e){return new q(await super._call(e))}},h1=class extends _s{async _call(e){return new we(await super._call(e))}},g1=class extends _s{async _call(e){return new Me(await super._call(e))}};var hs=class extends y{},w1=class extends hs{},x1=class extends hs{async _call(e){return new ye(await super._call(e))}},y1=class extends hs{async _call(e){return new q(await super._call(e))}},b1=class extends hs{async _call(e){return new we(await super._call(e))}},v1=class extends hs{async _call(e){return new Me(await super._call(e))}};var wl=class extends y{},k1=class extends wl{},E1=class extends wl{async _call(e){return new Hp(await super._call(e))}},Hp=class extends xr{};var Xp=class extends Se{constructor({iou_scores:e,pred_masks:r}){super(),this.iou_scores=e,this.pred_masks=r}},Kp=class extends y{},A1=class extends Kp{async get_image_embeddings({pixel_values:e}){return await Xt(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??=st(e.input_points.dims.slice(0,-1));let r={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(r.input_points=e.input_points),e.input_labels&&(r.input_labels=e.input_labels),e.input_boxes&&(r.input_boxes=e.input_boxes),await pe(this.sessions.prompt_encoder_mask_decoder,r)}async _call(e){return new Xp(await super._call(e))}};var Yp=class extends Se{constructor({iou_scores:e,pred_masks:r,object_score_logits:s}){super(),this.iou_scores=e,this.pred_masks=r,this.object_score_logits=s}},Qp=class extends y{},xl=class extends Qp{async get_image_embeddings({pixel_values:e}){return await Xt(this,{pixel_values:e})}async forward(e){let{num_feature_levels:r}=this.config.vision_config;if(Array.from({length:r},(a,i)=>`image_embeddings.${i}`).some(a=>!e[a])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let a=e.input_points.dims;e.input_labels??=st(a.slice(0,-1)),e.input_boxes??=Ze([a[0],0,4],0)}else if(e.input_boxes){let a=e.input_boxes.dims;e.input_labels=Ze([a[0],a[1],0],-1n),e.input_points=Ze([a[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder,o=He(e,n.inputNames);return await pe(n,o)}async _call(e){return new Yp(await super._call(e))}},T1=class extends xl{},S1=class extends xl{};var mo=class extends y{},M1=class extends mo{},O1=class extends mo{},I1=class extends mo{};var _o=class extends y{},C1=class extends _o{},P1=class extends _o{},N1=class extends _o{};var yl=class extends y{},L1=class extends yl{},bl=class extends yl{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"text_model"})}},z1=class extends wr{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"vision_model"})}};var vl=class extends y{},$1=class extends vl{},R1=class extends vl{};var B1=class extends wi{};var ho=class extends y{main_input_name="input_values";forward_params=["input_values"]},D1=class extends ho{async encode(e){return await pe(this.sessions.encoder_model,e)}async decode(e){return await pe(this.sessions.decoder_model,e)}},kl=class extends ho{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"encoder_model"})}},El=class extends ho{static async from_pretrained(e,r={}){return super.from_pretrained(e,{...r,model_file_name:r.model_file_name??"decoder_model"})}};var Al=class extends y{},U1=class extends Al{},F1=class extends Al{};var go=class extends y{},G1=class extends go{},j1=class extends go{},q1=class extends go{async generate_speech(e,r,{threshold:s=.5,minlenratio:n=0,maxlenratio:o=20,vocoder:a=null}={}){let i={input_ids:e},{encoder_outputs:l,encoder_attention_mask:c}=await Xt(this,i),u=l.dims[1]/this.config.reduction_factor,f=Math.floor(u*o),m=Math.floor(u*n),_=this.config.num_mel_bins,w=[],x=null,b=null,A=0;for(;;){++A;let S=pg(!!b),O;b?O=b.output_sequence_out:O=new $("float32",new Float32Array(_),[1,1,_]);let C={use_cache_branch:S,output_sequence:O,encoder_attention_mask:c,speaker_embeddings:r,encoder_hidden_states:l};ha(this,C,x),b=await pe(this.sessions.decoder_model_merged,C),x=up(b,x);let{prob:v,spectrum:U}=b;if(w.push(U),A>=m&&(Array.from(v.data).filter(j=>j>=s).length>0||A>=f))break}let k=Ee(w),{waveform:M}=await pe(a.sessions.model,{spectrogram:k});return{spectrogram:k,waveform:M}}},W1=class extends y{main_input_name="spectrogram"};var un=class extends y{},V1=class extends un{},H1=class extends un{async _call(e){return new ye(await super._call(e))}},X1=class extends un{async _call(e){return new q(await super._call(e))}},K1=class extends un{async _call(e){return new Me(await super._call(e))}};var Tl=class extends y{},Y1=class extends Tl{},Q1=class extends Tl{};var Sl=class extends y{},J1=class extends Sl{},Z1=class extends Sl{};var Jp=class extends y{},ev=class extends Jp{};var Zp=class extends y{},Ml=class extends Zp{async generate_speech({input_ids:e,attention_mask:r,style:s,num_inference_steps:n=5,speed:o=1.05}){let{sampling_rate:a,chunk_compress_factor:i,base_chunk_size:l,latent_dim:c}=this.config,{last_hidden_state:u,durations:f}=await pe(this.sessions.text_encoder,{input_ids:e,attention_mask:r,style:s}),m=f.div(o).mul_(a),_=l*i,w=m.data,x=Int32Array.from(w,F=>Math.ceil(F/_)),b=Math.max(...x),A=e.dims[0],k=new BigInt64Array(A*b);for(let F=0;FM*S,1),k=Zr[x.type];l[x.name]=new $(x.type,new k(A),b)}let m=Zr[f],_=new $(f,new m(i*bM),[1,i,bM]),w=e[Symbol.asyncIterator]?.()??e[Symbol.iterator]?.();if(!w)throw new Error("input_features must be iterable or async iterable");return{encoder_session:n,enc_kv_cache:l,enc_padding_cache:_,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:w,text_hidden_size:r.hidden_size}}async function l3(t,e){let r=e.dims[2],s=Math.floor((a3+r-3)/2)+1,n=new $("int64",BigInt64Array.from({length:s},(u,f)=>BigInt(t.enc_past_seq_len+f)),[1,s]),o=t.enc_past_seq_len+s,a=st([1,o]),{audio_embeds:i,present_padding_cache:l,...c}=await pe(t.encoder_session,{input_features:e,attention_mask:a,position_ids:n,past_padding_cache:t.enc_padding_cache,...t.enc_kv_cache});t.enc_padding_cache.location==="gpu-buffer"&&t.enc_padding_cache.dispose(),t.enc_padding_cache=l;for(let u in c)if(u.startsWith("present.")){let f=u.replace("present","past_key_values"),m=t.enc_kv_cache[f];m?.location==="gpu-buffer"&&m.dispose(),t.enc_kv_cache[f]=c[u]}return t.enc_past_seq_len=o,i}async function c3(t,e){for(;t.audio_embed_total_tokens0&&t.audio_embed_queue.length>0;){let a=t.audio_embed_queue[0],i=a.tokens-t.audio_queue_offset,l=Math.min(o,i),c=t.audio_queue_offset*t.text_hidden_size;for(let u=0;u=a.tokens&&(t.audio_embed_queue.shift(),t.audio_queue_offset=0)}t.audio_consumed+=r-o}var Cv=class extends ss{constructor(e){super(),this._s=e}_call(e){let r=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>r)}},lf=class extends y{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},zl=class extends lf{async forward({input_ids:e,past_key_values:r,...s}){let n=e.dims[1],o=Iv.get(this);o&&await c3(o,o.audio_consumed+n);let{inputs_embeds:a}=await pe(this.sessions.embed_tokens,{input_ids:e});o&&u3(o,a,n);let i={inputs_embeds:a,...s};ha(this,i,r);let l=this.sessions.decoder_model_merged,c=He(i,l.inputNames);return await pe(l,c)}async generate({input_features:e,stopping_criteria:r,...s}){if(!e)throw new Error("input_features (generator/iterable) must be provided");let n=i3(this,e);Iv.set(this,n);let o=new Xn;o.push(new Cv(n)),r&&o.extend(r);try{return await super.generate({...s,stopping_criteria:o})}finally{n.enc_kv_cache.dispose(),Iv.delete(this)}}};var yo=class extends y{},Pv=class extends yo{},Nv=class extends yo{async _call(e){return new ht(await super._call(e))}},Lv=class extends yo{async _call(e){return new q(await super._call(e))}};var cf=class extends Se{constructor({logits:e,embeddings:r}){super(),this.logits=e,this.embeddings=r}},gs=class extends y{},zv=class extends gs{},$v=class extends gs{async _call(e){return new ht(await super._call(e))}},Rv=class extends gs{async _call(e){return new q(await super._call(e))}},Bv=class extends gs{async _call(e){return new cf(await super._call(e))}},Dv=class extends gs{async _call(e){return new we(await super._call(e))}};var uf=class extends y{},Uv=class extends uf{};var pf=class extends Ks{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1};var $l=class extends y{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},Fv=class extends $l{},ff=class extends $l{_prepare_generation_config(e,r){return super._prepare_generation_config(e,r,pf)}_retrieve_init_tokens(e){let r=[e.decoder_start_token_id],s=e.language,n=e.task;if(e.is_multilingual){s||(te.warn("No language specified - defaulting to English (en)."),s="en");let a=`<|${WS(s)}|>`;r.push(e.lang_to_id[a]),r.push(e.task_to_id[n??"transcribe"])}else if(s||n)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&r.at(-1)!==e.no_timestamps_token_id?r.push(e.no_timestamps_token_id):e.return_timestamps&&r.at(-1)===e.no_timestamps_token_id&&(te.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),r.pop()),r.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:n=null,...o}){r=this._prepare_generation_config(r,o);let a=o.decoder_input_ids instanceof $?Qo(o.decoder_input_ids):o.decoder_input_ids??this._retrieve_init_tokens(r);if(r.return_timestamps&&(s??=new Xs,s.push(new Qu(r,a))),r.begin_suppress_tokens&&(s??=new Xs,s.push(new Hn(r.begin_suppress_tokens,a.length))),r.return_token_timestamps){if(!r.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");r.task==="translate"&&te.warn("Token-level timestamps may not be reliable for task 'translate'."),r.output_attentions=!0,r.return_dict_in_generate=!0}if(r.return_timestamps&&!o.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:a,kwargs:o});let i=await super.generate({inputs:e,generation_config:r,logits_processor:s,decoder_input_ids:a,...o});return r.return_token_timestamps&&(i.token_timestamps=this._extract_token_timestamps(i,r.alignment_heads,r.num_frames,.02,a.length)),i}async _generate_with_seek({inputs:e,generation_config:r,logits_processor:s,init_tokens:n,kwargs:o}){let a=r.no_timestamps_token_id+1,i=Array.isArray(r.eos_token_id)?r.eos_token_id[0]:r.eos_token_id,l=r.return_token_timestamps,c=e,u=c.dims[2],f=2,m=this.config.max_source_positions,_=f*m,w=0,x=[],b=[];for(;wZ+J)}if(U.length>0&&U.at(-1)===i&&U.pop(),U.length===0)break;let F=U.map(J=>J>=a),K=U.length>=2&&F[U.length-1]&&!F[U.length-2],Y=[];for(let J=0;J0)if(K)Q=k-w;else{let J=Y.at(-1);Q=(U[J-1]-a)*f,B=J}else Q=k-w;let I=Math.floor(w/f),oe=a+1500;for(let J=0;J=a&&(U[J]=Math.min(U[J]+I,oe));x.push(...U.slice(0,B)),j&&b.push(...j.slice(0,B)),w+=Q}x.push(i);let A=[...n,...x];if(l){let k=new $("int64",A.map(BigInt),[1,A.length]),M=[...new Array(n.length).fill(0),...b,0],S=new $("float32",new Float32Array(M),[1,M.length]);return{sequences:k,token_timestamps:S}}return new $("int64",A.map(BigInt),[1,A.length])}_extract_token_timestamps(e,r,s=null,n=.02,o=0){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");s==null&&te.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(te.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let i=e.cross_attentions,l=Array.from({length:this.config.decoder_layers},(A,k)=>Ee(i.map(M=>M[k]),2)),c=kt(r.map(([A,k])=>{if(A>=l.length)throw new Error(`Layer index ${A} is out of bounds for cross attentions (length ${l.length}).`);return s?l[A].slice(null,k,null,[0,s]):l[A].slice(null,k)})).permute(1,0,2,3),[u,f]=km(c,-2,0,!0),m=c.clone();for(let A=0;A0?m.slice(null,null,[o,m.dims[2]],null):m,w=[mu(_,1)],x=e.sequences.dims,b=new $("float32",new Float32Array(x[0]*x[1]),x);for(let A=0;AM[F+1]-M[F]),C=yt([1],O).map(j=>!!j),v=[];for(let j=0;j0&&U.push(v.at(-1)),b[A].data.set(U)}return b}},Gv=class extends ff{};var ws=class extends y{},jv=class extends ws{},qv=class extends ws{async _call(e){return new ye(await super._call(e))}},Wv=class extends ws{async _call(e){return new q(await super._call(e))}},Vv=class extends ws{async _call(e){return new we(await super._call(e))}},Hv=class extends ws{async _call(e){return new Me(await super._call(e))}};var xs=class extends y{},Xv=class extends xs{},Kv=class extends xs{async _call(e){return new ye(await super._call(e))}},Yv=class extends xs{async _call(e){return new q(await super._call(e))}},Qv=class extends xs{async _call(e){return new we(await super._call(e))}},Jv=class extends xs{async _call(e){return new Me(await super._call(e))}};var Rl=class extends y{},Zv=class extends Rl{},ek=class extends Rl{async _call(e){return new df(await super._call(e))}},df=class extends Se{constructor({logits:e,pred_boxes:r}){super(),this.logits=e,this.pred_boxes=r}};var Bl=class extends y{},tk=class extends Bl{},rk=class extends Bl{};var Dl=class extends y{},sk=class extends Dl{},nk=class extends Dl{};var p3=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"],["embedding_gemma2","EmbeddingGemma2Model"]]),f3=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"]]),d3=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),m3=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"],["lfm3","Lfm3Model"],["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"],["deepseek_v4","DeepseekV4Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"],["zaya","ZayaModel"],["hrm_text","HrmTextModel"]]),vM=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),kM=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),EM=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),AM=new Map([["bert","BertForSequenceClassification"],["eurobert","EuroBertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraForSequenceClassification"],["esm","EsmForSequenceClassification"],["convbert","ConvBertForSequenceClassification"],["camembert","CamembertForSequenceClassification"],["deberta","DebertaForSequenceClassification"],["deberta-v2","DebertaV2ForSequenceClassification"],["mpnet","MPNetForSequenceClassification"],["albert","AlbertForSequenceClassification"],["distilbert","DistilBertForSequenceClassification"],["roberta","RobertaForSequenceClassification"],["xlm","XLMForSequenceClassification"],["xlm-roberta","XLMRobertaForSequenceClassification"],["bart","BartForSequenceClassification"],["mbart","MBartForSequenceClassification"],["mobilebert","MobileBertForSequenceClassification"],["squeezebert","SqueezeBertForSequenceClassification"]]),TM=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"]]),SM=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),MM=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"],["lfm3","Lfm3ForCausalLM"],["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"],["deepseek_v4","DeepseekV4ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["zaya","ZayaForCausalLM"],["hrm_text","HrmTextForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),_3=new Map([["multi_modality","MultiModalityCausalLM"]]),OM=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"]]),IM=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"]]),CM=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),PM=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"],["lfm3_vl","Lfm3VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),NM=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),h3=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),LM=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"]]),zM=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),$M=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),bo=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),RM=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),BM=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),DM=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),UM=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),FM=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),GM=new Map([["wavlm","WavLMForXVector"]]),jM=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),qM=new Map([["vitmatte","VitMatteForImageMatting"]]),g3=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),WM=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),VM=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),HM=new Map([["sapiens","SapiensForNormalEstimation"]]),XM=new Map([["vitpose","VitPoseForPoseEstimation"]]),KM=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),ok=[[p3,W.EncoderOnly],[f3,W.EncoderDecoder],[m3,W.DecoderOnlyWithoutHead],[d3,W.AutoEncoder],[AM,W.EncoderOnly],[TM,W.EncoderOnly],[SM,W.Seq2Seq],[vM,W.Seq2Seq],[MM,W.DecoderOnly],[_3,W.MultiModality],[OM,W.EncoderOnly],[IM,W.EncoderOnly],[CM,W.Vision2Seq],[PM,W.ImageTextToText],[NM,W.AudioTextToText],[LM,W.EncoderOnly],[bo,W.EncoderOnly],[BM,W.EncoderOnly],[RM,W.EncoderOnly],[qM,W.EncoderOnly],[g3,W.EncoderOnly],[WM,W.EncoderOnly],[VM,W.EncoderOnly],[HM,W.EncoderOnly],[XM,W.EncoderOnly],[zM,W.EncoderOnly],[$M,W.EncoderOnly],[DM,W.MaskGeneration],[UM,W.EncoderOnly],[FM,W.EncoderOnly],[kM,W.Seq2Seq],[EM,W.EncoderOnly],[GM,W.EncoderOnly],[jM,W.EncoderOnly],[KM,W.EncoderOnly]];for(let[t,e]of ok)for(let r of t.values()){ar.set(r,e);let s=Ul[r];Js.set(s,r),pp.set(r,s)}var w3=[["MusicgenForConditionalGeneration",qi,W.Musicgen],["Phi3VForCausalLM",al,W.Phi3V],["CLIPTextModelWithProjection",Ma,W.EncoderOnly],["SiglipTextModel",bl,W.EncoderOnly],["JinaCLIPTextModel",bi,W.EncoderOnly],["ClapTextModelWithProjection",Ta,W.EncoderOnly],["ClapAudioModelWithProjection",Sa,W.EncoderOnly],["DacEncoderModel",Ba,W.EncoderOnly],["DacDecoderModel",Da,W.EncoderOnly],["MimiEncoderModel",Ii,W.EncoderOnly],["MimiDecoderModel",Ci,W.EncoderOnly],["SnacEncoderModel",kl,W.EncoderOnly],["SnacDecoderModel",El,W.EncoderOnly],["Gemma3nForConditionalGeneration",fs,W.ImageAudioTextToText],["Gemma4ForConditionalGeneration",no,W.ImageAudioTextToText],["SupertonicForConditionalGeneration",Ml,W.Supertonic],["ChatterboxModel",Aa,W.Chatterbox],["EmbeddingGemma2Model",Ha,W.MultimodalEncoder],["VoxtralRealtimeForConditionalGeneration",zl,W.VoxtralRealtime]];for(let[t,e,r]of w3)ar.set(t,r),Js.set(e,t),pp.set(t,e);var YM=new Map([["modnet",bo],["birefnet",bo],["isnet",bo],["ben",bo]]);for(let[t,e]of YM.entries())e.set(t,"PreTrainedModel"),ar.set(t,W.EncoderOnly),pp.set(t,y);var QM=new Set(YM.keys());ar.set("PreTrainedModel",W.EncoderOnly);Js.set(y,"PreTrainedModel");var $e={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:AM,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:TM,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:kM,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:EM,MODEL_FOR_MASKED_LM_MAPPING_NAMES:OM,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:IM,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:LM,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:bo,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:RM,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:BM,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:zM,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:$M,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:DM,MODEL_FOR_CTC_MAPPING_NAMES:UM,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:FM,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:GM,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:jM,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:h3,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:qM,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:WM,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:VM,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:HM,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:XM,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:KM,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:PM,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:NM,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:SM,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:vM,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:MM,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:CM};gM($e);var Ne=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let r of this.MODEL_CLASS_MAPPINGS)if(r.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",model_file_name:i=null,subfolder:l="onnx",device:c=null,dtype:u=null,use_external_data_format:f=null,session_options:m={}}={}){let _={progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a,model_file_name:i,subfolder:l,device:c,dtype:u,use_external_data_format:f,session_options:m};if(_.config=await Ht.from_pretrained(e,_),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:w}=_.config;for(let x of this.MODEL_CLASS_MAPPINGS){let b=x.get(w);if(!b){for(let A of x.values())if(A[0]===w){b=A;break}if(!b)continue}return await Ul[b].from_pretrained(e,_)}if(this.BASE_IF_FAIL)return QM.has(w)||te.warn(`Unknown model class "${w}", attempting to construct from base class.`),await y.from_pretrained(e,_);throw Error(`Unsupported model type: ${w}`)}},Or=class extends Ne{static MODEL_CLASS_MAPPINGS=ok.map(e=>e[0]);static BASE_IF_FAIL=!0},Fl=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},mf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},vo=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},_f=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},hf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},gf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},wf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},xf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},yf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},bf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},vf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},Gl=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},jl=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},ql=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},kf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},Ef=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},JM=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},Af=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_CTC_MAPPING_NAMES]},Tf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},ZM=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},eO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},Sf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},tO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},Mf=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},Of=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},rO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},sO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},If=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},nO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},oO=class extends Ne{static MODEL_CLASS_MAPPINGS=[$e.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function nt(t){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(e=>rt.read(e)))}async function Ir(t,e){return Array.isArray(t)||(t=[t]),await Promise.all(t.map(r=>typeof r=="string"||r instanceof URL?y_(r,e):r instanceof Float64Array?new Float32Array(r):r))}function Wl(t,e){e&&(t=t.map(a=>a|0));let[r,s,n,o]=t;return{xmin:r,ymin:s,xmax:n,ymax:o}}var _e=class extends We{constructor({task:e,model:r,tokenizer:s=null,processor:n=null}){super(),this.task=e,this.model=r,this.tokenizer=s,this.processor=n}async dispose(){await this.model.dispose()}};var Vl=class extends _e{async _call(e,{top_k:r=1}={}){let s=this.tokenizer(e,{padding:!0,truncation:!0}),n=await this.model(s),{problem_type:o,id2label:a}=this.model.config,i=o==="multi_label_classification"?c=>c.sigmoid():c=>new $("float32",Ue(c.data),c.dims),l=[];for(let c of n.logits){let u=i(c),f=await or(u,r),m=f[0].tolist(),w=f[1].tolist().map((x,b)=>({label:a?a[x]:`LABEL_${x}`,score:m[b]}));r===1?l.push(...w):l.push(w)}return Array.isArray(e)||r===1?l:l[0]}};var Hl=class extends _e{async _call(e,{ignore_labels:r=["O"],aggregation_strategy:s="none"}={}){if(s!=="none"&&s!=="simple")throw new Error(`Invalid aggregation_strategy: "${s}". Must be one of "none" or "simple".`);let n=Array.isArray(e),o=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(o)).logits,l=this.model.config.id2label,c=[];for(let u=0;u{let l=0,c=[];for(let u=a;uC==f),b=a[_].tolist(),A=i[_].tolist();for(let C=1;Cv==w[C])!==-1)&&(b[C]=-1/0,A[C]=-1/0);let k=Ue(b).map((C,v)=>[C,v]),M=Ue(A).map((C,v)=>[C,v]);k[0][0]=0,M[0][0]=0;let S=CA(k,M).filter(C=>C[0][1]<=C[1][1]).map(C=>[C[0][1],C[1][1],C[0][0]*C[1][0]]).sort((C,v)=>v[2]-C[2]),O=[];for(let C=0;Cb==s);if(f===-1)throw Error(`Mask token (${n}) not found in text.`);let m=a[c][f],_=await or(new $("float32",Ue(m.data),m.dims),r),w=_[0].tolist(),x=_[1].tolist();i.push(x.map((b,A)=>{let k=u.slice();return k[f]=b,{score:w[A],token:Number(b),token_str:this.tokenizer.decode([b]),sequence:this.tokenizer.decode(k,{skip_special_tokens:!0})}}))}return Array.isArray(e)?i:i[0]}};var Cr=class extends _e{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(e,r={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(l=>this.model.config.prefix+l));let s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(e=e.map(l=>s[this.task].prefix+l));let n=this.tokenizer,o={padding:!0,truncation:!0},a;this.task==="translation"&&"_build_translation_inputs"in n?a=n._build_translation_inputs(e,o,r):a=n(e,o);let i=await this.model.generate({...a,...this._default_generation_config,...r});return n.batch_decode(i,{skip_special_tokens:!0}).map(l=>({[this._key]:l}))}};var Yl=class extends Cr{_key="summary_text"};var Ql=class extends Cr{_key="translation_text"};function aO(t){return Array.isArray(t)&&t.every(e=>"role"in e&&"content"in e)}var Jl=class extends _e{_default_generation_config={max_new_tokens:256};async _call(e,r={}){let{add_special_tokens:s,return_full_text:n,tools:o,documents:a,chat_template:i,tokenizer_encode_kwargs:l,...c}=r,u=!1,f=!1,m=s??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,_=l,w;if(typeof e=="string")w=e=[e];else if(Array.isArray(e)&&e.every(O=>typeof O=="string"))u=!0,w=e;else{if(aO(e))e=[e];else if(Array.isArray(e)&&e.every(aO))u=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");f=!0;let O={tokenize:!1,add_generation_prompt:!0,...He({tools:o,documents:a,chat_template:i},["tools","documents","chat_template"]),..._};w=e.map(C=>this.tokenizer.apply_chat_template(C,O)),m=!1,_=void 0}let x=f?!1:n??!0;this.tokenizer.padding_side="left";let b=this.tokenizer(w,{add_special_tokens:m,padding:!0,truncation:!0,..._}),A=await this.model.generate({...b,...this._default_generation_config,...c}),k=this.tokenizer.batch_decode(A,{skip_special_tokens:!0}),M;!x&&b.input_ids.dims.at(-1)>0&&(M=this.tokenizer.batch_decode(b.input_ids,{skip_special_tokens:!0}).map(O=>O.length));let S=Array.from({length:e.length},O=>[]);for(let O=0;O[r.toLowerCase(),s])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(te.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(te.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,r,{hypothesis_template:s="This example is {}.",multi_label:n=!1}={}){let o=Array.isArray(e);o||(e=[e]),Array.isArray(r)||(r=[r]);let a=r.map(c=>s.replace("{}",c)),i=n||r.length===1,l=[];for(let c of e){let u=[];for(let _ of a){let w=this.tokenizer(c,{text_pair:_,padding:!0,truncation:!0}),x=await this.model(w);i?u.push([x.logits.data[this.contradiction_id],x.logits.data[this.entailment_id]]):u.push(x.logits.data[this.entailment_id])}let m=(i?u.map(_=>Ue(_)[1]):Ue(u)).map((_,w)=>[_,w]).sort((_,w)=>w[0]-_[0]);l.push({sequence:c,labels:m.map(_=>r[_[1]]),scores:m.map(_=>_[0])})}return o?l:l[0]}};var ec=class extends _e{async _call(e,{top_k:r=5}={}){let s=this.processor.feature_extractor.config.sampling_rate,n=await Ir(e,s),o=this.model.config.id2label,a=[];for(let i of n){let l=await this.processor(i),u=(await this.model(l)).logits[0],f=await or(new $("float32",Ue(u.data),u.dims),r),m=f[0].tolist(),w=f[1].tolist().map((x,b)=>({label:o?o[x]:`LABEL_${x}`,score:m[b]}));a.push(w)}return Array.isArray(e)?a:a[0]}};var tc=class extends _e{async _call(e,r,{hypothesis_template:s="This is a sound of {}."}={}){let n=!Array.isArray(e);n&&(e=[e]);let o=r.map(u=>s.replace("{}",u)),a=this.tokenizer(o,{padding:!0,truncation:!0}),i=this.processor.feature_extractor.config.sampling_rate,l=await Ir(e,i),c=[];for(let u of l){let f=await this.processor(u),m=await this.model({...a,...f}),_=Ue(m.logits_per_audio.data);c.push([..._].map((w,x)=>({score:w,label:r[x]})))}return n?c[0]:c}};var rc=class extends _e{_default_generation_config={};async _call(e,r={}){switch(r={...this._default_generation_config,...r},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,r);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,r);case"moonshine":return this._call_moonshine(e,r);case"cohere_asr":return this._call_cohere_asr(e,r);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,r){r.language&&te.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),r.task&&te.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Ir(n,o),i=[];for(let l of a){let c=await this.processor(l),f=(await this.model(c)).logits[0],m=[];for(let w of f)m.push(Le(w.data)[1]);let _=this.tokenizer.decode(m,{skip_special_tokens:!0}).trim();i.push({text:_})}return s?i[0]:i}async _call_whisper(e,r){let s=r.return_timestamps??!1,n=r.chunk_length_s??0,o=r.force_full_sequences??!1,a=r.stride_length_s??null,i={...r};s==="word"&&(i.return_token_timestamps=!0,i.return_timestamps=!0);let l=!Array.isArray(e),c=l?[e]:e,u=this.processor.feature_extractor.config,f=u.chunk_length/this.model.config.max_source_positions,m=u.hop_length,_=u.sampling_rate,w=await Ir(c,_),x=[];for(let b of w){let A=[];if(n>0){if(a===null)a=n/6;else if(n<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let S=_*n,O=_*a,C=S-2*O,v=0;for(;;){let U=v+S,j=b.subarray(v,U),F=await this.processor(j),K=v===0,Y=U>=b.length;if(A.push({stride:[j.length,K?0:O,Y?0:O],input_features:F.input_features,is_last:Y}),Y)break;v+=C}}else A=[{stride:[b.length,0,0],input_features:(await this.processor(b)).input_features,is_last:!0}];for(let S of A){i.num_frames=Math.floor(S.stride[0]/m);let O=await this.model.generate({inputs:S.input_features,...i});if(s==="word"){let C=O.sequences.tolist()[0],v=O.token_timestamps.tolist()[0],U=this.tokenizer.timestamp_begin,j=Math.max(C.findIndex(F=>Number(F)>=U),0);S.tokens=C.slice(j),S.token_timestamps=v.slice(j).map(F=>Cs(F,2))}else S.tokens=O[0].tolist();S.stride=S.stride.map(C=>C/_)}let[k,M]=this.tokenizer._decode_asr(A,{time_precision:f,return_timestamps:s,force_full_sequences:o});x.push({text:k,...M})}return l?x[0]:x}async _call_moonshine(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,a=await Ir(n,o),i=[];for(let l of a){let c=await this.processor(l),u=Math.floor(l.length/o)*6,f=await this.model.generate({max_new_tokens:u,...r,...c}),m=this.tokenizer.batch_decode(f,{skip_special_tokens:!0})[0];i.push({text:m})}return s?i[0]:i}async _call_cohere_asr(e,r){let s=!Array.isArray(e),n=s?[e]:e,o=this.processor.feature_extractor,a=o.config.sampling_rate,i=await Ir(n,a),l=r.language??"en",c=this.processor.get_decoder_prompt_ids(l),u=[];for(let f of i){let m=o.split_audio(f),_=[];for(let x of m){let b=await this.processor(x),A=await this.model.generate({...b,decoder_input_ids:c,...r}),k=this.tokenizer.decode(A[0].tolist(),{skip_special_tokens:!0}).trim();_.push(k)}let w=this.processor.constructor.join_chunks(_,l);u.push({text:w})}return s?u[0]:u}};var sc=class extends _e{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,r){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await he.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new $("float32",e,[e.length]);else if(!(e instanceof $))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(e.dims[0]===1)e=e.repeat(r,1);else if(e.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,r,s,n=null){let o=r.data,[a,i]=r.dims,l=n?n.data:null,c=[];for(let u=0;u({generated_text:u.trim()}));a.push(c)}return s?a:a[0]}};var oc=class extends _e{async _call(e,{top_k:r=5}={}){let s=await nt(e),{pixel_values:n}=await this.processor(s),o=await this.model({pixel_values:n}),{id2label:a}=this.model.config,i=[];for(let l of o.logits){let c=await or(new $("float32",Ue(l.data),l.dims),r),u=c[0].tolist(),m=c[1].tolist().map((_,w)=>({label:a?a[_]:`LABEL_${_}`,score:u[w]}));i.push(m)}return Array.isArray(e)?i:i[0]}};var iO={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},fn=class extends _e{async _call(e,{threshold:r=.5,mask_threshold:s=.5,overlap_mask_area_threshold:n=.8,label_ids_to_fuse:o=null,target_sizes:a=null,subtask:i=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let c=await nt(e),u=c.map(k=>[k.height,k.width]),f=await this.processor(c),{inputNames:m,outputNames:_}=this.model.sessions.model;if(!m.includes("pixel_values")){if(m.length!==1)throw Error(`Expected a single input name, but got ${m.length} inputs: ${m}.`);let k=m[0];if(k in f)throw Error(`Input name ${k} already exists in the inputs.`);f[k]=f.pixel_values}let w=await this.model(f),x=null;if(i!==null)x=iO[i];else if(this.processor.image_processor){for(let[k,M]of Object.entries(iO))if(M in this.processor.image_processor){x=this.processor.image_processor[M].bind(this.processor.image_processor),i=k;break}}let b=this.model.config.id2label,A=[];if(i)if(i==="panoptic"||i==="instance"){let k=x(w,r,s,n,o,a??u)[0],M=k.segmentation;for(let S of k.segments_info){let O=new Uint8ClampedArray(M.data.length);for(let v=0;vU<-1e-5||U>1+1e-5)&&C.sigmoid_();let v=await rt.fromTensor(C.mul_(255).to("uint8")).resize(O[1],O[0]);A.push({label:null,score:null,mask:v})}}return A}};var ac=class extends fn{async _call(e,r={}){let s=await nt(e),n=await super._call(e,r),o=s.map((a,i)=>{let l=a.clone();return l.putAlpha(n[i].mask),l});return Array.isArray(e)?o:o[0]}};var ic=class extends _e{async _call(e,r,{hypothesis_template:s="This is a photo of {}"}={}){let n=Array.isArray(e),o=await nt(e),a=r.map(m=>s.replace("{}",m)),i=this.tokenizer(a,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:l}=await this.processor(o),c=await this.model({...i,pixel_values:l}),u=this.model.config.model_type==="siglip"?m=>m.sigmoid().data:m=>Ue(m.data),f=[];for(let m of c.logits_per_image){let w=[...u(m)].map((x,b)=>({score:x,label:r[b]}));w.sort((x,b)=>b.score-x.score),f.push(w)}return n?f:f[0]}};var lc=class extends _e{async _call(e,{threshold:r=.9,percentage:s=!1}={}){let n=Array.isArray(e);if(n&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let o=await nt(e),a=s?null:o.map(_=>[_.height,_.width]),{pixel_values:i,pixel_mask:l}=await this.processor(o),c=await this.model({pixel_values:i,pixel_mask:l}),u=this.processor.image_processor.post_process_object_detection(c,r,a),{id2label:f}=this.model.config,m=u.map(_=>_.boxes.map((w,x)=>({score:_.scores[x],label:f[_.classes[x]],box:Wl(w,!s)})));return n?m:m[0]}};var cc=class extends _e{async _call(e,r,{threshold:s=.1,top_k:n=null,percentage:o=!1}={}){let a=Array.isArray(e),i=await nt(e),l=this.tokenizer(r,{padding:!0,truncation:!0}),c=await this.processor(i),u=[];for(let f=0;f({score:A.scores[M],label:A.labels[M],box:Wl(k,!o)}))}else{let A=this.processor.image_processor.post_process_object_detection(x,s,_,!0)[0];b=A.boxes.map((k,M)=>({score:A.scores[M],label:r[A.classes[M]],box:Wl(k,!o)}))}b.sort((A,k)=>k.score-A.score),n!==null&&(b=b.slice(0,n)),u.push(b)}return a?u:u[0]}};var uc=class extends _e{_default_generation_config={max_new_tokens:256};async _call(e,r,s={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}let n=(await nt(e))[0],{pixel_values:o}=await this.processor(n),a=`${r}`,i=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,l=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:i,...this._default_generation_config,...s}),u=this.tokenizer.batch_decode(l)[0].match(/(.*?)<\/s_answer>/),f=null;return u&&u.length>=2&&(f=u[1].trim()),[{answer:f}]}};var pc=class extends _e{async _call(e){let r=await nt(e),s=await this.processor(r),n=await this.model(s),o=[];for(let a of n.reconstruction){let i=a.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(rt.fromTensor(i))}return Array.isArray(e)?o:o[0]}};var fc=class extends _e{async _call(e){let r=await nt(e),s=await this.processor(r),{predicted_depth:n}=await this.model(s),o=[];for(let a=0;a`onnx/${m}`);return i.filter(m=>!m.startsWith("onnx/")||f.some(_=>m.startsWith(_)))}}return i}async function rde(t,e=null,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main",device:i=null,dtype:l=null,subfolder:c="onnx",use_external_data_format:u=null,model_file_name:f=null,session_options:m={}}={}){t=Cf[t]??t;let _=ko[t.split("_",1)[0]];if(!_)throw Error(`Unsupported pipeline: ${t}. Must be one of [${Object.keys(ko)}]`);e||(e=_.default.model,te.info(`No model specified. Using default model: "${e}".`),!l&&_.default.dtype&&(l=_.default.dtype));let w=await Nr(t,e,{device:i,dtype:l}),x={};if(r)try{(await Promise.all(w.map(async K=>Pt(e,K)))).forEach((K,Y)=>{K.exists&&(x[w[Y]]={loaded:0,total:K.size??0})})}catch(F){te.warn(`Unable to fetch model file metadata for total progress tracking: ${F}`)}let b={progress_callback:r?new Ar(r,x):void 0,config:s,cache_dir:n,local_files_only:o,revision:a,device:i,dtype:l,subfolder:c,use_external_data_format:u,model_file_name:f,session_options:m},A=w.includes("tokenizer.json"),k=w.includes("preprocessor_config.json"),M=_.model,S;if(Array.isArray(M)){let F=s??await Ht.from_pretrained(e,b),{model_type:K}=F,Y=M.find(Q=>Q.supports(K));if(!Y)throw Error(`Unsupported model type "${K}" for task "${t}". None of the candidate model classes support this type.`);S=Y.from_pretrained(e,{...b,config:F})}else S=M.from_pretrained(e,b);let[O,C,v]=await Promise.all([A?ne.from_pretrained(e,b):null,k?qu.from_pretrained(e,b):null,S]),U={task:t,model:v};O&&(U.tokenizer=O),C&&(U.processor=C),fr(r,{status:"ready",task:t,model:e});let j=_.pipeline;return new j(U)}var b3=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,ak=class{put(e){throw Error("Not implemented")}end(){throw Error("Not implemented")}},lO=le.IS_PROCESS_AVAILABLE?t=>process.stdout.write(t):t=>console.log(t),ik=class extends ak{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,skip_special_tokens:o=!0,decode_kwargs:a={},...i}={}){super(),this.tokenizer=e,this.skip_prompt=r,this.callback_function=s??lO,this.token_callback_function=n,this.decode_kwargs={skip_special_tokens:o,...a,...i},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error("TextStreamer only supports batch size of 1");let r=this.next_tokens_are_prompt;if(r&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let s=e[0];if(this.token_callback_function?.(s),s.length===1&&this.special_ids.has(s[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let l=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(l,!1),this.token_cache=[],this.print_len=0}let a=this.tokenizer.decode(s,this.decode_kwargs);this.on_finalized_text(a,!1);return}this.token_cache=yt(this.token_cache,s);let n=this.tokenizer.decode(this.token_cache,this.decode_kwargs),o;r||n.endsWith(` `)?(o=n.slice(this.print_len),this.token_cache=[],this.print_len=0):n.length>0&&b3(n.charCodeAt(n.length-1))?(o=n.slice(this.print_len),this.print_len+=o.length):(o=n.slice(this.print_len,n.lastIndexOf(" ")+1),this.print_len+=o.length),this.on_finalized_text(o,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e="",this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,r){e.length>0&&this.callback_function?.(e),r&&this.callback_function===lO&&le.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}},cO=class extends ik{constructor(e,{skip_prompt:r=!1,callback_function:s=null,token_callback_function:n=null,on_chunk_start:o=null,on_chunk_end:a=null,on_finalize:i=null,time_precision:l=.02,skip_special_tokens:c=!0,decode_kwargs:u={}}={}){super(e,{skip_prompt:r,skip_special_tokens:c,callback_function:s,token_callback_function:n,decode_kwargs:u}),this.timestamp_begin=e.timestamp_begin,this.on_chunk_start=o,this.on_chunk_end=a,this.on_finalize=i,this.time_precision=l,this.waiting_for_timestamp=!1}put(e){if(e.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");let r=e[0];if(r.length===1){let s=Number(r[0])-this.timestamp_begin;if(s>=0){let n=s*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(n):this.on_chunk_start?.(n),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(r);return}}return super.put(e)}end(){super.end(),this.on_finalize?.()}};var _c=class{constructor(e,r){this.image=e,this.timestamp=r}},Nf=class{constructor(e,r){e.length>0&&e[0]instanceof rt&&(e=e.map((s,n)=>new _c(s,(n+1)/(e.length+1)*r))),this.frames=e,this.duration=r}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}};async function v3(t,{num_frames:e=null,fps:r=null}={}){if(!le.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(e==null&&r==null)throw new Error("Either num_frames or fps must be provided.");let s=[],n=document.createElement("video");if(n.crossOrigin="anonymous",n.muted=!0,typeof t=="string")n.src=t;else if(t instanceof Blob)n.src=URL.createObjectURL(t);else if(t instanceof HTMLVideoElement)n.src=t.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(f=>n.onloadedmetadata=f),n.seekable.start(0)===n.seekable.end(0)){let m=await(await he.fetch(n.src)).blob();n.src=URL.createObjectURL(m),await new Promise(_=>n.onloadedmetadata=_)}let o=n.duration,a,i;e!=null?(a=e,i=e===1?0:o/(e-1)):(i=1/r,a=Math.floor(o/i));let l=[];for(let f=0;f{n.onseeked=x}),u.drawImage(n,0,0,c.width,c.height);let m=u.getImageData(0,0,c.width,c.height),_=new rt(m.data,c.width,c.height,4),w=new _c(_,f);s.push(w)}return n.remove(),new Nf(s,o)}async function Lf(t,e,r={}){let s=await rr(r?.cache_dir);if(!s)return{allCached:!1,files:e.map(a=>({file:a,cached:!1}))};let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=qr(t,o,r,s),l=await Wr(s,a,i);return{file:o,cached:!!l}}));return{allCached:n.every(o=>o.cached),files:n}}async function uO(t,e,r={}){let s=await rr(r?.cache_dir);if(!s)return!1;let{localPath:n,proposedCacheKey:o}=qr(t,e,r,s);return!!await Wr(s,n,o)}async function pO(t,e={}){if(!t)throw new Error("modelId is required");if(!await uO(t,"config.json",e))return!1;let r=await Pr(t,e);return(await Lf(t,r,e)).allCached}async function fO(t,e={}){if(!t)throw new Error("modelId is required");let r=await Pr(t,e);return await Lf(t,r,e)}async function dO(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");if(!await uO(e,"config.json",r))return!1;let s=await Nr(t,e,r);return(await Lf(e,s,r)).allCached}async function mO(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Nr(t,e,r);return await Lf(e,s,r)}async function _O(t,e,r={}){let s=await rr(r?.cache_dir);if(!s)return{filesDeleted:0,filesCached:0,files:e.map(o=>({file:o,deleted:!1,wasCached:!1}))};if(!s.delete)throw new Error("Cache does not support delete operation");let n=await Promise.all(e.map(async o=>{let{localPath:a,proposedCacheKey:i}=qr(t,o,r,s),c=!!await Wr(s,a,i),u=!1;if(c){let f=await s.delete(i),m=!f&&i!==a?await s.delete(a):!1;u=f||m}return{file:o,deleted:u,wasCached:c}}));return{filesDeleted:n.filter(o=>o.deleted).length,filesCached:n.filter(o=>o.wasCached).length,files:n}}async function hO(t,e={}){if(!t)throw new Error("modelId is required");let r=await Pr(t,e);return await _O(t,r,e)}async function gO(t,e,r={}){if(!t)throw new Error("task is required");if(!e)throw new Error("modelId is required");let s=await Nr(t,e,r);return await _O(e,s,r)}var k3=Object.keys(Jr);async function wO(t,{config:e=null,model_file_name:r=null,revision:s="main",cache_dir:n=null,local_files_only:o=!1}={}){e=await ma(t,{config:e,cache_dir:n,local_files_only:o,revision:s});let a="onnx",i=Yn(e),{sessions:l}=ip(i,e,{model_file_name:r}),c=Object.values(l),u={revision:s,cache_dir:n,local_files_only:o};return(await Promise.all(k3.map(async m=>{let _=Jr[m]??"",w=await Promise.all(c.map(async x=>{let b=`${a}/${x}${_}.onnx`;return(await Pt(t,b,u)).exists}));return{dtype:m,available:w.every(Boolean)}}))).filter(m=>m.available).map(m=>m.dtype)}var lk=class{static async get_files(e,r={}){return Pr(e,r)}static async get_pipeline_files(e,r,s={}){return Nr(e,r,s)}static async get_model_files(e,r={}){return Qn(e,r)}static async get_tokenizer_files(e){return zn(e)}static async get_processor_files(e){return Pf(e)}static async get_available_dtypes(e,r={}){return wO(e,r)}static async is_cached(e,r={}){return pO(e,r)}static async is_cached_files(e,r={}){return fO(e,r)}static async is_pipeline_cached(e,r,s={}){return dO(e,r,s)}static async is_pipeline_cached_files(e,r,s={}){return mO(e,r,s)}static async get_file_metadata(e,r,s={}){return Pt(e,r,s)}static async clear_cache(e,r={}){return hO(e,r)}static async clear_pipeline_cache(e,r,s={}){return gO(e,r,s)}};export{b_ as ASTFeatureExtractor,Ag as ASTForAudioClassification,Eg as ASTModel,ya as ASTPreTrainedModel,bg as AfmoeForCausalLM,yg as AfmoeModel,wa as AfmoePreTrainedModel,gg as AlbertForMaskedLM,hg as AlbertForQuestionAnswering,_g as AlbertForSequenceClassification,mg as AlbertModel,en as AlbertPreTrainedModel,Sm as AlbertTokenizer,xg as ApertusForCausalLM,wg as ApertusModel,ga as ApertusPreTrainedModel,kg as ArceeForCausalLM,vg as ArceeModel,xa as ArceePreTrainedModel,ec as AudioClassificationPipeline,Ht as AutoConfig,Ve as AutoFeatureExtractor,Te as AutoImageProcessor,Or as AutoModel,Tf as AutoModelForAudioClassification,eO as AutoModelForAudioFrameClassification,oO as AutoModelForAudioTextToText,Af as AutoModelForCTC,wf as AutoModelForCausalLM,Of as AutoModelForDepthEstimation,Sf as AutoModelForDocumentQuestionAnswering,vf as AutoModelForImageClassification,If as AutoModelForImageFeatureExtraction,tO as AutoModelForImageMatting,Gl as AutoModelForImageSegmentation,nO as AutoModelForImageTextToText,Mf as AutoModelForImageToImage,JM as AutoModelForMaskGeneration,xf as AutoModelForMaskedLM,rO as AutoModelForNormalEstimation,kf as AutoModelForObjectDetection,sO as AutoModelForPoseEstimation,yf as AutoModelForQuestionAnswering,jl as AutoModelForSemanticSegmentation,vo as AutoModelForSeq2SeqLM,Fl as AutoModelForSequenceClassification,_f as AutoModelForSpeechSeq2Seq,hf as AutoModelForTextToSpectrogram,gf as AutoModelForTextToWaveform,mf as AutoModelForTokenClassification,ql as AutoModelForUniversalSegmentation,bf as AutoModelForVision2Seq,ZM as AutoModelForXVector,Ef as AutoModelForZeroShotObjectDetection,qu as AutoProcessor,ne as AutoTokenizer,rc as AutomaticSpeechRecognitionPipeline,ac as BackgroundRemovalPipeline,Sg as BartForConditionalGeneration,Mg as BartForSequenceClassification,Tg as BartModel,Zn as BartPretrainedModel,Mm as BartTokenizer,Wu as BaseModelOutput,ak as BaseStreamer,D_ as BeitFeatureExtractor,Ig as BeitForImageClassification,Og as BeitModel,ba as BeitPreTrainedModel,Pg as BertForMaskedLM,zg as BertForQuestionAnswering,Ng as BertForSequenceClassification,Lg as BertForTokenClassification,Cg as BertModel,os as BertPreTrainedModel,Om as BertTokenizer,U_ as BitImageProcessor,Rg as BlenderbotForConditionalGeneration,$g as BlenderbotModel,va as BlenderbotPreTrainedModel,Dg as BlenderbotSmallForConditionalGeneration,Bg as BlenderbotSmallModel,ka as BlenderbotSmallPreTrainedModel,Im as BlenderbotSmallTokenizer,Cm as BlenderbotTokenizer,Fg as BloomForCausalLM,Ug as BloomModel,Ea as BloomPreTrainedModel,Pm as BloomTokenizer,Xg as CHMv2ForDepthEstimation,G_ as CHMv2ImageProcessor,_p as CHMv2PreTrainedModel,j_ as CLIPFeatureExtractor,Eu as CLIPImageProcessor,Yg as CLIPModel,wr as CLIPPreTrainedModel,tw as CLIPSegForImageSegmentation,ew as CLIPSegModel,Oa as CLIPSegPreTrainedModel,Qg as CLIPTextModel,Ma as CLIPTextModelWithProjection,Lm as CLIPTokenizer,Jg as CLIPVisionModel,Zg as CLIPVisionModelWithProjection,jg as CamembertForMaskedLM,Vg as CamembertForQuestionAnswering,qg as CamembertForSequenceClassification,Wg as CamembertForTokenClassification,Gg as CamembertModel,as as CamembertPreTrainedModel,Nm as CamembertTokenizer,ht as CausalLMOutput,Vu as CausalLMOutputWithPast,v_ as ChatterboxFeatureExtractor,Aa as ChatterboxModel,dp as ChatterboxPreTrainedModel,L_ as ChatterboxProcessor,F_ as ChineseCLIPFeatureExtractor,Hg as ChineseCLIPModel,mp as ChineseCLIPPreTrainedModel,Sa as ClapAudioModelWithProjection,k_ as ClapFeatureExtractor,Kg as ClapModel,eo as ClapPreTrainedModel,Ta as ClapTextModelWithProjection,sp as ClassifierFreeGuidanceLogitsProcessor,sw as CodeGenForCausalLM,rw as CodeGenModel,Ia as CodeGenPreTrainedModel,$m as CodeGenTokenizer,zm as CodeLlamaTokenizer,iw as Cohere2ForCausalLM,aw as Cohere2Model,Pa as Cohere2PreTrainedModel,E_ as CohereAsrFeatureExtractor,cw as CohereAsrForConditionalGeneration,lw as CohereAsrModel,Na as CohereAsrPreTrainedModel,z_ as CohereAsrProcessor,Bm as CohereAsrTokenizer,ow as CohereForCausalLM,nw as CohereModel,Ca as CoherePreTrainedModel,Rm as CohereTokenizer,pw as ConvBertForMaskedLM,mw as ConvBertForQuestionAnswering,fw as ConvBertForSequenceClassification,dw as ConvBertForTokenClassification,uw as ConvBertModel,is as ConvBertPreTrainedModel,Dm as ConvBertTokenizer,q_ as ConvNextFeatureExtractor,hw as ConvNextForImageClassification,Au as ConvNextImageProcessor,_w as ConvNextModel,La as ConvNextPreTrainedModel,ww as ConvNextV2ForImageClassification,gw as ConvNextV2Model,za as ConvNextV2PreTrainedModel,vw as DFineForObjectDetection,bw as DFineModel,Ra as DFinePreTrainedModel,Yw as DINOv3ConvNextModel,vp as DINOv3ConvNextPreTrainedModel,H_ as DINOv3ViTImageProcessor,Qw as DINOv3ViTModel,kp as DINOv3ViTPreTrainedModel,K_ as DPTFeatureExtractor,ox as DPTForDepthEstimation,Mu as DPTImageProcessor,nx as DPTModel,Wa as DPTPreTrainedModel,Da as DacDecoderModel,gp as DacDecoderOutput,Ba as DacEncoderModel,hp as DacEncoderOutput,sa as DacFeatureExtractor,kw as DacModel,to as DacPreTrainedModel,Aw as DebertaForMaskedLM,Mw as DebertaForQuestionAnswering,Tw as DebertaForSequenceClassification,Sw as DebertaForTokenClassification,Ew as DebertaModel,ls as DebertaPreTrainedModel,Fm as DebertaTokenizer,Lw as DebertaV2ForMaskedLM,Rw as DebertaV2ForQuestionAnswering,zw as DebertaV2ForSequenceClassification,$w as DebertaV2ForTokenClassification,Nw as DebertaV2Model,cs as DebertaV2PreTrainedModel,Um as DebertaV2Tokenizer,Bw as DecisionTransformerModel,wp as DecisionTransformerPreTrainedModel,Iw as DeepseekV3ForCausalLM,Ow as DeepseekV3Model,Ua as DeepseekV3PreTrainedModel,Pw as DeepseekV4ForCausalLM,Cw as DeepseekV4Model,Fa as DeepseekV4PreTrainedModel,W_ as DeiTFeatureExtractor,Uw as DeiTForImageClassification,Tu as DeiTImageProcessor,Dw as DeiTModel,Ga as DeiTPreTrainedModel,Fw as DepthAnythingForDepthEstimation,xp as DepthAnythingPreTrainedModel,fc as DepthEstimationPipeline,Gw as DepthProForDepthEstimation,yp as DepthProPreTrainedModel,V_ as DetrFeatureExtractor,qw as DetrForObjectDetection,Ww as DetrForSegmentation,Su as DetrImageProcessor,jw as DetrModel,so as DetrObjectDetectionOutput,ro as DetrPreTrainedModel,bp as DetrSegmentationOutput,Hw as Dinov2ForImageClassification,Vw as Dinov2Model,ja as Dinov2PreTrainedModel,Kw as Dinov2WithRegistersForImageClassification,Xw as Dinov2WithRegistersModel,qa as Dinov2WithRegistersPreTrainedModel,rx as DistilBertForMaskedLM,tx as DistilBertForQuestionAnswering,Zw as DistilBertForSequenceClassification,ex as DistilBertForTokenClassification,Jw as DistilBertModel,us as DistilBertPreTrainedModel,Gm as DistilBertTokenizer,uc as DocumentQuestionAnsweringPipeline,X_ as DonutFeatureExtractor,Bn as DonutImageProcessor,sx as DonutSwinModel,Ep as DonutSwinPreTrainedModel,Kn as DynamicCache,T1 as EdgeTamModel,ix as EfficientNetForImageClassification,Y_ as EfficientNetImageProcessor,ax as EfficientNetModel,Va as EfficientNetPreTrainedModel,cx as ElectraForMaskedLM,fx as ElectraForQuestionAnswering,ux as ElectraForSequenceClassification,px as ElectraForTokenClassification,lx as ElectraModel,ps as ElectraPreTrainedModel,jm as ElectraTokenizer,Ha as EmbeddingGemma2Model,Ap as EmbeddingGemma2PreTrainedModel,R_ as EmbeddingGemma2Processor,ca as EmbeddingGemma2VideoProcessor,ta as EncodecFeatureExtractor,ap as EosTokenCriteria,mx as Ernie4_5ForCausalLM,dx as Ernie4_5Model,Xa as Ernie4_5PretrainedModel,hx as EsmForMaskedLM,gx as EsmForSequenceClassification,wx as EsmForTokenClassification,_x as EsmModel,tn as EsmPreTrainedModel,qm as EsmTokenizer,yx as EuroBertForMaskedLM,bx as EuroBertForSequenceClassification,vx as EuroBertForTokenClassification,xx as EuroBertModel,rn as EuroBertPreTrainedModel,Ex as ExaoneForCausalLM,kx as ExaoneModel,Ka as ExaonePreTrainedModel,Tx as FalconForCausalLM,Mx as FalconH1ForCausalLM,Sx as FalconH1Model,Qa as FalconH1PreTrainedModel,Ax as FalconModel,Ya as FalconPreTrainedModel,Wm as FalconTokenizer,Ix as FastViTForImageClassification,Ox as FastViTModel,Ja as FastViTPreTrainedModel,dc as FeatureExtractionPipeline,Oe as FeatureExtractor,Kl as FillMaskPipeline,Cx as Florence2ForConditionalGeneration,Tp as Florence2PreTrainedModel,Ih as Florence2Processor,Xu as ForcedBOSTokenLogitsProcessor,Ku as ForcedEOSTokenLogitsProcessor,Z_ as GLPNFeatureExtractor,Xx as GLPNForDepthEstimation,Hx as GLPNModel,oi as GLPNPreTrainedModel,ny as GPT2LMHeadModel,sy as GPT2Model,ui as GPT2PreTrainedModel,Xm as GPT2Tokenizer,Yx as GPTBigCodeForCausalLM,Kx as GPTBigCodeModel,ai as GPTBigCodePreTrainedModel,ay as GPTJForCausalLM,oy as GPTJModel,pi as GPTJPreTrainedModel,Jx as GPTNeoForCausalLM,Qx as GPTNeoModel,ii as GPTNeoPreTrainedModel,ey as GPTNeoXForCausalLM,Zx as GPTNeoXModel,li as GPTNeoXPreTrainedModel,Hm as GPTNeoXTokenizer,zx as Gemma2ForCausalLM,Lx as Gemma2Model,ei as Gemma2PreTrainedModel,Dx as Gemma3ForCausalLM,Op as Gemma3ForConditionalGeneration,Q_ as Gemma3ImageProcessor,Bx as Gemma3Model,Mp as Gemma3PreTrainedModel,Ch as Gemma3Processor,na as Gemma3nAudioFeatureExtractor,Ux as Gemma3nForCausalLM,fs as Gemma3nForConditionalGeneration,Ip as Gemma3nPreTrainedModel,Ph as Gemma3nProcessor,oa as Gemma4AudioFeatureExtractor,Fx as Gemma4ForCausalLM,no as Gemma4ForConditionalGeneration,qs as Gemma4ImageProcessor,la as Gemma4Processor,Nx as GemmaForCausalLM,Px as GemmaModel,Za as GemmaPreTrainedModel,Vm as GemmaTokenizer,Ks as GenerationConfig,J_ as Glm46VImageProcessor,Nh as Glm46VProcessor,jx as GlmForCausalLM,Gx as GlmModel,Wx as GlmMoeDsaForCausalLM,qx as GlmMoeDsaModel,ri as GlmMoeDsaPreTrainedModel,Vx as GlmOcrForConditionalGeneration,ti as GlmPreTrainedModel,ry as GptOssForCausalLM,ty as GptOssModel,ci as GptOssPreTrainedModel,ly as GraniteForCausalLM,iy as GraniteModel,uy as GraniteMoeHybridForCausalLM,cy as GraniteMoeHybridModel,di as GraniteMoeHybridPreTrainedModel,fi as GranitePreTrainedModel,A_ as GraniteSpeechFeatureExtractor,py as GraniteSpeechForConditionalGeneration,Lh as GraniteSpeechProcessor,fy as GroundingDinoForObjectDetection,eh as GroundingDinoImageProcessor,Np as GroundingDinoPreTrainedModel,zh as GroundingDinoProcessor,dy as GroupViTModel,Lp as GroupViTPreTrainedModel,_y as HeliumForCausalLM,my as HeliumModel,mi as HeliumPreTrainedModel,Km as HerbertTokenizer,gy as HieraForImageClassification,hy as HieraModel,_i as HieraPreTrainedModel,xy as HrmTextForCausalLM,wy as HrmTextModel,hi as HrmTextPreTrainedModel,Ty as HubertForCTC,Sy as HubertForSequenceClassification,Ay as HubertModel,Ey as HubertPreTrainedModel,Oy as HunYuanDenseV1ForCausalLM,My as HunYuanDenseV1Model,gi as HunYuanDenseV1PreTrainedModel,Cy as IJepaForImageClassification,Iy as IJepaModel,xi as IJepaPreTrainedModel,wi as Idefics3ForConditionalGeneration,Ou as Idefics3ImageProcessor,Du as Idefics3Processor,oc as ImageClassificationPipeline,mc as ImageFeatureExtractionPipeline,X as ImageFeatureExtractor,Vn as ImageMattingOutput,X as ImageProcessor,fn as ImageSegmentationPipeline,pc as ImageToImagePipeline,nc as ImageToTextPipeline,dM as InterruptableStoppingCriteria,Ny as JAISLMHeadModel,Py as JAISModel,yi as JAISPreTrainedModel,rh as JinaCLIPImageProcessor,Ly as JinaCLIPModel,ao as JinaCLIPPreTrainedModel,Rh as JinaCLIPProcessor,bi as JinaCLIPTextModel,zy as JinaCLIPVisionModel,Ry as Lfm2ForCausalLM,$y as Lfm2Model,Uy as Lfm2MoeForCausalLM,Dy as Lfm2MoeModel,ki as Lfm2MoePreTrainedModel,vi as Lfm2PreTrainedModel,Fy as Lfm2VlForConditionalGeneration,sh as Lfm2VlImageProcessor,Bh as Lfm2VlProcessor,jy as Lfm3ForCausalLM,Gy as Lfm3Model,Ei as Lfm3PreTrainedModel,qy as Lfm3VlForConditionalGeneration,nh as Lfm3VlImageProcessor,Dh as Lfm3VlProcessor,By as LightOnOcrForConditionalGeneration,Gv as LiteWhisperForConditionalGeneration,Hy as Llama4ForCausalLM,zp as Llama4PreTrainedModel,Vy as LlamaForCausalLM,Wy as LlamaModel,Ai as LlamaPreTrainedModel,Ym as LlamaTokenizer,ut as LlavaForConditionalGeneration,ut as LlavaOnevisionForConditionalGeneration,oh as LlavaOnevisionImageProcessor,Sp as LlavaPreTrainedModel,Uh as LlavaProcessor,Rx as LlavaQwen2ForCausalLM,It as LogLevel,Dt as LogitsProcessor,Xs as LogitsProcessorList,da as LogitsWarper,Ky as LongT5ForConditionalGeneration,Xy as LongT5Model,Ti as LongT5PreTrainedModel,Qy as M2M100ForConditionalGeneration,Yy as M2M100Model,Si as M2M100PreTrainedModel,Qm as M2M100Tokenizer,Zm as MBart50Tokenizer,o0 as MBartForCausalLM,s0 as MBartForConditionalGeneration,n0 as MBartForSequenceClassification,r0 as MBartModel,on as MBartPreTrainedModel,Jo as MBartTokenizer,Y0 as MPNetForMaskedLM,Z0 as MPNetForQuestionAnswering,Q0 as MPNetForSequenceClassification,J0 as MPNetForTokenClassification,K0 as MPNetModel,ds as MPNetPreTrainedModel,r_ as MPNetTokenizer,sb as MT5ForConditionalGeneration,rb as MT5Model,Gi as MT5PreTrainedModel,Zy as MarianMTModel,Jy as MarianModel,Mi as MarianPreTrainedModel,Jm as MarianTokenizer,ih as Mask2FormerImageProcessor,ah as MaskFormerFeatureExtractor,t0 as MaskFormerForInstanceSegmentation,Dn as MaskFormerImageProcessor,e0 as MaskFormerModel,Oi as MaskFormerPreTrainedModel,ye as MaskedLMOutput,op as MaxLengthCriteria,a0 as Metric3DForDepthEstimation,$p as Metric3DPreTrainedModel,i0 as Metric3Dv2ForDepthEstimation,Rp as Metric3Dv2PreTrainedModel,l0 as MgpstrForSceneTextRecognition,Bp as MgpstrModelOutput,Dp as MgpstrPreTrainedModel,Fh as MgpstrProcessor,e_ as MgpstrTokenizer,Ci as MimiDecoderModel,Fp as MimiDecoderOutput,Ii as MimiEncoderModel,Up as MimiEncoderOutput,c0 as MimiModel,io as MimiPreTrainedModel,ep as MinLengthLogitsProcessor,tp as MinNewTokensLengthLogitsProcessor,d0 as Ministral3ForCausalLM,f0 as Ministral3Model,Ni as Ministral3PreTrainedModel,p0 as MinistralForCausalLM,u0 as MinistralModel,Pi as MinistralPreTrainedModel,h0 as Mistral3ForConditionalGeneration,w0 as Mistral4ForCausalLM,g0 as Mistral4Model,zi as Mistral4PreTrainedModel,_0 as MistralForCausalLM,m0 as MistralModel,Li as MistralPreTrainedModel,y0 as MobileBertForMaskedLM,v0 as MobileBertForQuestionAnswering,b0 as MobileBertForSequenceClassification,x0 as MobileBertModel,an as MobileBertPreTrainedModel,t_ as MobileBertTokenizer,E0 as MobileLLMForCausalLM,k0 as MobileLLMModel,$i as MobileLLMPreTrainedModel,lh as MobileNetV1FeatureExtractor,T0 as MobileNetV1ForImageClassification,S0 as MobileNetV1ForSemanticSegmentation,Iu as MobileNetV1ImageProcessor,A0 as MobileNetV1Model,lo as MobileNetV1PreTrainedModel,ch as MobileNetV2FeatureExtractor,O0 as MobileNetV2ForImageClassification,I0 as MobileNetV2ForSemanticSegmentation,Cu as MobileNetV2ImageProcessor,M0 as MobileNetV2Model,co as MobileNetV2PreTrainedModel,uh as MobileNetV3FeatureExtractor,P0 as MobileNetV3ForImageClassification,N0 as MobileNetV3ForSemanticSegmentation,Pu as MobileNetV3ImageProcessor,C0 as MobileNetV3Model,uo as MobileNetV3PreTrainedModel,ph as MobileNetV4FeatureExtractor,z0 as MobileNetV4ForImageClassification,$0 as MobileNetV4ForSemanticSegmentation,Nu as MobileNetV4ImageProcessor,L0 as MobileNetV4Model,po as MobileNetV4PreTrainedModel,fh as MobileViTFeatureExtractor,B0 as MobileViTForImageClassification,Lu as MobileViTImageProcessor,R0 as MobileViTModel,Ri as MobileViTPreTrainedModel,U0 as MobileViTV2ForImageClassification,D0 as MobileViTV2Model,Bi as MobileViTV2PreTrainedModel,Is as ModelFileNotFoundError,Se as ModelOutput,lk as ModelRegistry,V0 as ModernBertDecoderForCausalLM,W0 as ModernBertDecoderModel,Di as ModernBertDecoderPreTrainedModel,G0 as ModernBertForMaskedLM,j0 as ModernBertForSequenceClassification,q0 as ModernBertForTokenClassification,F0 as ModernBertModel,ln as ModernBertPreTrainedModel,$x as Moondream1ForConditionalGeneration,T_ as MoonshineFeatureExtractor,X0 as MoonshineForConditionalGeneration,H0 as MoonshineModel,Ui as MoonshinePreTrainedModel,Gh as MoonshineProcessor,tb as MptForCausalLM,eb as MptModel,Fi as MptPreTrainedModel,nb as MultiModalityCausalLM,Gp as MultiModalityPreTrainedModel,ab as MusicgenForCausalLM,qi as MusicgenForConditionalGeneration,ob as MusicgenModel,ji as MusicgenPreTrainedModel,lb as NanoChatForCausalLM,ib as NanoChatModel,Wi as NanoChatPreTrainedModel,ub as NemotronHForCausalLM,cb as NemotronHModel,Vi as NemotronHPreTrainedModel,fb as NeoBertForMaskedLM,_b as NeoBertForQuestionAnswering,db as NeoBertForSequenceClassification,mb as NeoBertForTokenClassification,pb as NeoBertModel,ms as NeoBertPreTrainedModel,s_ as NllbTokenizer,rp as NoBadWordsLogitsProcessor,Ju as NoRepeatNGramLogitsProcessor,hb as NomicBertModel,jp as NomicBertPreTrainedModel,dh as NougatImageProcessor,n_ as NougatTokenizer,Ib as OPTForCausalLM,Ob as OPTModel,Zi as OPTPreTrainedModel,lc as ObjectDetectionPipeline,yb as Olmo2ForCausalLM,xb as Olmo2Model,Xi as Olmo2PreTrainedModel,vb as Olmo3ForCausalLM,bb as Olmo3Model,Ki as Olmo3PreTrainedModel,wb as OlmoForCausalLM,Eb as OlmoHybridForCausalLM,kb as OlmoHybridModel,Yi as OlmoHybridPreTrainedModel,gb as OlmoModel,Hi as OlmoPreTrainedModel,Tb as OpenAIPrivacyFilterForTokenClassification,Ab as OpenAIPrivacyFilterModel,Qi as OpenAIPrivacyFilterPreTrainedModel,Mb as OpenELMForCausalLM,Sb as OpenELMModel,Ji as OpenELMPreTrainedModel,mh as OwlViTFeatureExtractor,Lb as OwlViTForObjectDetection,Un as OwlViTImageProcessor,Nb as OwlViTModel,tl as OwlViTPreTrainedModel,jh as OwlViTProcessor,Pb as Owlv2ForObjectDetection,_h as Owlv2ImageProcessor,Cb as Owlv2Model,el as Owlv2PreTrainedModel,zb as PaliGemmaForConditionalGeneration,qh as PaliGemmaProcessor,ra as ParakeetFeatureExtractor,$b as ParakeetForCTC,qp as ParakeetPreTrainedModel,Bb as PatchTSMixerForPrediction,Rb as PatchTSMixerModel,rl as PatchTSMixerPreTrainedModel,Ub as PatchTSTForPrediction,Db as PatchTSTModel,sl as PatchTSTPreTrainedModel,qb as Phi3ForCausalLM,jb as Phi3Model,ol as Phi3PreTrainedModel,al as Phi3VForCausalLM,wh as Phi3VImageProcessor,Wp as Phi3VPreTrainedModel,Wh as Phi3VProcessor,Gb as PhiForCausalLM,Fb as PhiModel,nl as PhiPreTrainedModel,xh as PixtralImageProcessor,Vh as PixtralProcessor,y as PreTrainedModel,V as PreTrainedTokenizer,Wn as PretrainedConfig,se as Processor,Vb as PvtForImageClassification,yh as PvtImageProcessor,Wb as PvtModel,il as PvtPreTrainedModel,aa as PyAnnoteFeatureExtractor,Xb as PyAnnoteForAudioFrameClassification,Hb as PyAnnoteModel,ll as PyAnnotePreTrainedModel,Hh as PyAnnoteProcessor,Me as QuestionAnsweringModelOutput,Xl as QuestionAnsweringPipeline,Yb as Qwen2ForCausalLM,Kb as Qwen2Model,Jb as Qwen2MoeForCausalLM,Qb as Qwen2MoeModel,ul as Qwen2MoePreTrainedModel,cl as Qwen2PreTrainedModel,o_ as Qwen2Tokenizer,si as Qwen2VLForCausalLM,oo as Qwen2VLForConditionalGeneration,Ws as Qwen2VLImageProcessor,Cp as Qwen2VLPreTrainedModel,Vs as Qwen2VLProcessor,ni as Qwen2_5_VLForCausalLM,sn as Qwen2_5_VLForConditionalGeneration,pa as Qwen2_5_VLProcessor,e1 as Qwen3ForCausalLM,Zb as Qwen3Model,r1 as Qwen3MoeForCausalLM,t1 as Qwen3MoeModel,fl as Qwen3MoePreTrainedModel,n1 as Qwen3NextForCausalLM,s1 as Qwen3NextModel,dl as Qwen3NextPreTrainedModel,pl as Qwen3PreTrainedModel,ml as Qwen3VLForCausalLM,cn as Qwen3VLForConditionalGeneration,a1 as Qwen3VLMoeForCausalLM,o1 as Qwen3VLMoeForConditionalGeneration,Xh as Qwen3VLProcessor,_l as Qwen3_5ForCausalLM,fo as Qwen3_5ForConditionalGeneration,l1 as Qwen3_5MoeForCausalLM,i1 as Qwen3_5MoeForConditionalGeneration,f1 as RFDetrForObjectDetection,p1 as RFDetrModel,Vp as RFDetrObjectDetectionOutput,gl as RFDetrPreTrainedModel,yw as RTDetrForObjectDetection,bh as RTDetrImageProcessor,xw as RTDetrModel,xr as RTDetrObjectDetectionOutput,$a as RTDetrPreTrainedModel,E1 as RTDetrV2ForObjectDetection,k1 as RTDetrV2Model,Hp as RTDetrV2ObjectDetectionOutput,wl as RTDetrV2PreTrainedModel,ea as RawAudio,rt as RawImage,Nf as RawVideo,_c as RawVideoFrame,Zu as RepetitionPenaltyLogitsProcessor,u1 as ResNetForImageClassification,c1 as ResNetModel,hl as ResNetPreTrainedModel,x1 as RoFormerForMaskedLM,v1 as RoFormerForQuestionAnswering,y1 as RoFormerForSequenceClassification,b1 as RoFormerForTokenClassification,w1 as RoFormerModel,hs as RoFormerPreTrainedModel,i_ as RoFormerTokenizer,m1 as RobertaForMaskedLM,g1 as RobertaForQuestionAnswering,_1 as RobertaForSequenceClassification,h1 as RobertaForTokenClassification,d1 as RobertaModel,_s as RobertaPreTrainedModel,a_ as RobertaTokenizer,ua as Sam2ImageProcessor,Yp as Sam2ImageSegmentationOutput,xl as Sam2Model,Qp as Sam2PreTrainedModel,Uu as Sam2Processor,Kh as Sam2VideoProcessor,ua as Sam3ImageProcessor,S1 as Sam3TrackerModel,ua as SamImageProcessor,Xp as SamImageSegmentationOutput,A1 as SamModel,Kp as SamPreTrainedModel,fa as SamProcessor,vh as SapiensFeatureExtractor,O1 as SapiensForDepthEstimation,I1 as SapiensForNormalEstimation,M1 as SapiensForSemanticSegmentation,zu as SapiensImageProcessor,mo as SapiensPreTrainedModel,S_ as SeamlessM4TFeatureExtractor,kh as SegformerFeatureExtractor,P1 as SegformerForImageClassification,N1 as SegformerForSemanticSegmentation,$u as SegformerImageProcessor,C1 as SegformerModel,_o as SegformerPreTrainedModel,Hu as Seq2SeqLMOutput,q as SequenceClassifierOutput,Eh as SiglipImageProcessor,L1 as SiglipModel,yl as SiglipPreTrainedModel,bl as SiglipTextModel,l_ as SiglipTokenizer,z1 as SiglipVisionModel,R1 as SmolLM3ForCausalLM,$1 as SmolLM3Model,vl as SmolLM3PreTrainedModel,B1 as SmolVLMForConditionalGeneration,Ou as SmolVLMImageProcessor,Du as SmolVLMProcessor,El as SnacDecoderModel,kl as SnacEncoderModel,M_ as SnacFeatureExtractor,D1 as SnacModel,ho as SnacPreTrainedModel,F1 as SolarOpenForCausalLM,U1 as SolarOpenModel,Al as SolarOpenPreTrainedModel,O_ as SpeechT5FeatureExtractor,j1 as SpeechT5ForSpeechToText,q1 as SpeechT5ForTextToSpeech,W1 as SpeechT5HifiGan,G1 as SpeechT5Model,go as SpeechT5PreTrainedModel,Yh as SpeechT5Processor,c_ as SpeechT5Tokenizer,H1 as SqueezeBertForMaskedLM,K1 as SqueezeBertForQuestionAnswering,X1 as SqueezeBertForSequenceClassification,V1 as SqueezeBertModel,un as SqueezeBertPreTrainedModel,u_ as SqueezeBertTokenizer,Q1 as StableLmForCausalLM,Y1 as StableLmModel,Tl as StableLmPreTrainedModel,Z1 as Starcoder2ForCausalLM,J1 as Starcoder2Model,Sl as Starcoder2PreTrainedModel,ss as StoppingCriteria,Xn as StoppingCriteriaList,ev as StyleTextToSpeech2Model,Jp as StyleTextToSpeech2PreTrainedModel,Yl as SummarizationPipeline,Ml as SupertonicForConditionalGeneration,Zp as SupertonicPreTrainedModel,Hn as SuppressTokensAtBeginLogitsProcessor,Yu as SuppressTokensLogitsProcessor,ov as Swin2SRForImageSuperResolution,Ah as Swin2SRImageProcessor,nv as Swin2SRModel,Ol as Swin2SRPreTrainedModel,rv as SwinForImageClassification,sv as SwinForSemanticSegmentation,tv as SwinModel,wo as SwinPreTrainedModel,iv as T5ForConditionalGeneration,av as T5Model,Il as T5PreTrainedModel,p_ as T5Tokenizer,cv as TableTransformerForObjectDetection,lv as TableTransformerModel,ef as TableTransformerObjectDetectionOutput,Cl as TableTransformerPreTrainedModel,np as TemperatureLogitsWarper,$ as Tensor,Cr as Text2TextGenerationPipeline,Vl as TextClassificationPipeline,Jl as TextGenerationPipeline,ik as TextStreamer,sc as TextToAudioPipeline,Hl as TokenClassificationPipeline,we as TokenClassifierOutput,V as TokenizersBackend,fM as TopKLogitsWarper,pM as TopPLogitsWarper,uv as TrOCRForCausalLM,tf as TrOCRPreTrainedModel,Ql as TranslationPipeline,nn as UltravoxModel,Pp as UltravoxPreTrainedModel,Qh as UltravoxProcessor,fv as UniSpeechForCTC,dv as UniSpeechForSequenceClassification,pv as UniSpeechModel,xo as UniSpeechPreTrainedModel,gv as UniSpeechSatForAudioFrameClassification,_v as UniSpeechSatForCTC,hv as UniSpeechSatForSequenceClassification,mv as UniSpeechSatModel,pn as UniSpeechSatPreTrainedModel,$h as VLChatProcessor,th as VLMImageProcessor,xv as VaultGemmaForCausalLM,wv as VaultGemmaModel,Pl as VaultGemmaPreTrainedModel,Th as ViTFeatureExtractor,vv as ViTForImageClassification,Ru as ViTImageProcessor,kv as ViTMAEModel,rf as ViTMAEPreTrainedModel,Av as ViTMSNForImageClassification,Ev as ViTMSNModel,Ll as ViTMSNPreTrainedModel,bv as ViTModel,Nl as ViTPreTrainedModel,yv as VisionEncoderDecoderModel,Tv as VitMatteForImageMatting,Sh as VitMatteImageProcessor,sf as VitMattePreTrainedModel,Sv as VitPoseForPoseEstimation,Mh as VitPoseImageProcessor,nf as VitPosePreTrainedModel,Mv as VitsModel,of as VitsModelOutput,af as VitsPreTrainedModel,d_ as VitsTokenizer,Ov as VoxtralForConditionalGeneration,Jh as VoxtralProcessor,P_ as VoxtralRealtimeFeatureExtractor,zl as VoxtralRealtimeForConditionalGeneration,lf as VoxtralRealtimePreTrainedModel,eg as VoxtralRealtimeProcessor,Nv as Wav2Vec2BertForCTC,Lv as Wav2Vec2BertForSequenceClassification,Pv as Wav2Vec2BertModel,yo as Wav2Vec2BertPreTrainedModel,m_ as Wav2Vec2CTCTokenizer,I_ as Wav2Vec2FeatureExtractor,ky as Wav2Vec2ForAudioFrameClassification,by as Wav2Vec2ForCTC,vy as Wav2Vec2ForSequenceClassification,yy as Wav2Vec2Model,ir as Wav2Vec2PreTrainedModel,tg as Wav2Vec2Processor,rg as Wav2Vec2ProcessorWithLM,Dv as WavLMForAudioFrameClassification,$v as WavLMForCTC,Rv as WavLMForSequenceClassification,Bv as WavLMForXVector,zv as WavLMModel,gs as WavLMPreTrainedModel,C_ as WeSpeakerFeatureExtractor,Uv as WeSpeakerResNetModel,uf as WeSpeakerResNetPreTrainedModel,N_ as WhisperFeatureExtractor,ff as WhisperForConditionalGeneration,Fv as WhisperModel,$l as WhisperPreTrainedModel,sg as WhisperProcessor,cO as WhisperTextStreamer,Qu as WhisperTimeStampLogitsProcessor,__ as WhisperTokenizer,Hv as XLMForQuestionAnswering,Wv as XLMForSequenceClassification,Vv as XLMForTokenClassification,jv as XLMModel,ws as XLMPreTrainedModel,Kv as XLMRobertaForMaskedLM,Jv as XLMRobertaForQuestionAnswering,Yv as XLMRobertaForSequenceClassification,Qv as XLMRobertaForTokenClassification,Xv as XLMRobertaModel,xs as XLMRobertaPreTrainedModel,h_ as XLMRobertaTokenizer,g_ as XLMTokenizer,qv as XLMWithLMHeadModel,cf as XVectorOutput,Oh as YolosFeatureExtractor,ek as YolosForObjectDetection,Bu as YolosImageProcessor,Zv as YolosModel,df as YolosObjectDetectionOutput,Rl as YolosPreTrainedModel,rk as YoutuForCausalLM,tk as YoutuModel,Bl as YoutuPreTrainedModel,nk as ZayaForCausalLM,sk as ZayaModel,Dl as ZayaPreTrainedModel,tc as ZeroShotAudioClassificationPipeline,Zl as ZeroShotClassificationPipeline,ic as ZeroShotImageClassificationPipeline,cc as ZeroShotObjectDetectionPipeline,Ee as cat,b$ as cos_sim,D2 as dot,he as env,Ze as full,Ko as full_like,vm as interpolate,Tt as interpolate_4d,ZU as layer_norm,QS as load_audio,TR as load_image,v3 as load_video,Sd as log_softmax,US as matmul,mu as mean,FS as mean_pooling,st as ones,Ln as ones_like,sR as permute,rde as pipeline,jS as quantize_embeddings,e6 as rand,GS as randn,Os as random,y_ as read_audio,JU as rfft,du as slice,Ue as softmax,kt as stack,km as std_mean,or as topk,Am as zeros,Yo as zeros_like};