@huggingface/transformers 4.0.0-next.1 → 4.0.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/ort-wasm-simd-threaded.jsep.mjs +25 -25
- package/dist/transformers.js +10 -10
- package/dist/transformers.min.js +4 -4
- package/dist/transformers.node.cjs +10 -10
- package/dist/transformers.node.min.cjs +4 -4
- package/dist/transformers.node.min.mjs +4 -4
- package/dist/transformers.node.mjs +10 -10
- package/dist/transformers.web.js +1 -1
- package/dist/transformers.web.min.js +1 -1
- package/package.json +2 -2
- package/src/env.js +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var HT=Object.defineProperty;var Jr=(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 Ps=(t,e)=>{for(var r in e)HT(t,r,{get:e[r],enumerable:!0})};import XT from"fs";import zs from"path";import KT from"url";var YT="4.0.0-next.
|
|
1
|
+
var HT=Object.defineProperty;var Jr=(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 Ps=(t,e)=>{for(var r in e)HT(t,r,{get:e[r],enumerable:!0})};import XT from"fs";import zs from"path";import KT from"url";var YT="4.0.0-next.2",J1=typeof process<"u",Z1=J1&&process?.release?.name==="node",Pn=!sv(XT),ev=!sv(zs),QT=typeof globalThis.Deno<"u",sz=typeof globalThis.Bun<"u",tv=typeof window<"u"&&typeof window.document<"u",rv=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),pp=typeof self<"u"&&"caches"in self,JT=Z1||typeof navigator<"u"&&"gpu"in navigator,ZT=typeof navigator<"u"&&"ml"in navigator,eS=()=>{if(typeof navigator>"u")return!1;let t=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!t.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!t.includes("Chrome")&&!t.includes("Android");return r&&s},tS=eS(),be=Object.freeze({IS_BROWSER_ENV:tv,IS_WEBWORKER_ENV:rv,IS_WEB_CACHE_AVAILABLE:pp,IS_WEBGPU_AVAILABLE:JT,IS_WEBNN_AVAILABLE:ZT,IS_SAFARI:tS,IS_PROCESS_AVAILABLE:J1,IS_NODE_ENV:Z1,IS_FS_AVAILABLE:Pn,IS_PATH_AVAILABLE:ev}),dp=Pn&&ev,zi="./";if(dp){let t=Object(import.meta).url;t?zi=zs.dirname(zs.dirname(KT.fileURLToPath(t))):typeof __dirname<"u"&&(zi=zs.dirname(__dirname))}var rS=dp?zs.join(zi,"/.cache/"):null,Q1="/models/",sS=dp?zs.join(zi,Q1):Q1,De={version:YT,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(tv||rv),localModelPath:sS,useFS:Pn,useBrowserCache:pp&&!QT,useFSCache:Pn,cacheDir:rS,useCustomCache:!1,customCache:null,useWasmCache:pp||Pn,cacheKey:"transformers-cache"};function sv(t){return Object.keys(t).length===0}var nS=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let r of t){let s=e;for(let n=0;n<r.length;++n){let o=r[n];s=s[o]??=Object.create(null)}s.end=r}return e}split(t){let e=[],r=t.length,s=0,n=0;for(;n<r;){let o=this.trie,a=null,i=n;for(;i<r&&(o=o[t[i]]);)o.end&&(a=o.end),++i;a?(n>s&&e.push(t.slice(s,n)),e.push(a),n+=a.length,s=n):++n}return s<r&&e.push(t.slice(s)),e}},nv=nS,oS=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??!this.special}},aS=oS,pv=(()=>{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]]))})(),iS=t=>Object.fromEntries(Object.entries(t).map(([e,r])=>[r,e])),lS=iS(pv),ov=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",cS=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],[` ?[^(\\s|[${ov}])]+`,` ?[^\\s${ov}]+`]]),Li="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",mp=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"),Ni=(t,e=!0)=>{if(t.Regex!==void 0){let r=t.Regex.replace(/\\([#&~])/g,"$1");for(let[s,n]of cS)r=r.replaceAll(s,n);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let n=!1,o=r.replace(/(\\[pP])\{([^}=]+)\}/g,(a,i,l)=>{try{return new RegExp(`\\p{${l}}`,"u"),`${i}{${l}}`}catch{return n=!0,`${i}{Script=${l}}`}});if(!n)throw s;try{return new RegExp(o,"gu")}catch{throw s}}}else if(t.String!==void 0){let r=uS(t.String);return new RegExp(e?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",t),null},uS=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pS=(t,e,r)=>{let s=[],n=0;for(;n<t.length;){if(s.push(t[n]),(e.get(t[n])??r)!==r){++n;continue}for(;++n<t.length&&(e.get(t[n])??r)===r;)e.get(s.at(-1))!==r&&(s[s.length-1]+=t[n])}return s},dS=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,fS=t=>Number.isInteger(t)||typeof t=="bigint",mS=t=>{let e=0;for(let r of t)++e;return e},hS=t=>dv(t.toLowerCase()),Wt=(...t)=>Array.prototype.concat.apply([],t),hp=t=>new Map(Object.entries(t)),_S=(t,e)=>{let r=[],s=0;for(let n of t.matchAll(e)){let o=n[0];s<n.index&&r.push(t.slice(s,n.index)),o.length>0&&r.push(o),s=n.index+o.length}return s<t.length&&r.push(t.slice(s)),r},dv=t=>t.replace(/\p{M}/gu,""),av=(t,e,r=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let s of r)if(!(s in t))return`${e} must contain a "${s}" property`;return null},gS=t=>t.match(/\S+/g)||[],wS=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},zn=wS,xS=class extends zn{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},mr=xS,yS=class extends mr{tokenize_chinese_chars(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r],n=s.charCodeAt(0);dS(n)?(e.push(" "),e.push(s),e.push(" ")):e.push(s)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(t){switch(t){case" ":case`
|
|
2
2
|
`:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(t)}}clean_text(t){let e=[];for(let r of t){let s=r.charCodeAt(0);s===0||s===65533||this.is_control(r)||(/^\s$/.test(r)?e.push(" "):e.push(r))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},bS=yS,vS=class extends mr{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(r=>r.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},kS=vS,ES=class extends mr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>fv(e))}normalize(t){return this.normalizers.reduce((e,r)=>r?r.normalize(e):e,t)}},AS=ES,MS=class extends mr{normalize(t){let e=Ni(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},TS=MS,SS=class extends mr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},$i=SS,OS=class extends $i{constructor(){super(...arguments),this.form="NFC"}},IS=OS,CS=class extends $i{constructor(){super(...arguments),this.form="NFD"}},PS=CS,zS=class extends $i{constructor(){super(...arguments),this.form="NFKC"}},LS=zS,NS=class extends $i{constructor(){super(...arguments),this.form="NFKD"}},$S=NS,RS=class extends mr{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}},US=RS,BS=class extends mr{normalize(t){return dv(t)}},DS=BS,FS=class extends mr{normalize(t){return t.toLowerCase()}},jS=FS,GS=class extends mr{normalize(t){return t=this.config.prepend+t,t}},qS=GS;function WS(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new bS(t);case"Precompiled":return new kS(t);case"Sequence":return new AS(t);case"Replace":return new TS(t);case"NFC":return new IS(t);case"NFD":return new PS(t);case"NFKC":return new LS(t);case"NFKD":return new $S(t);case"Strip":return new US(t);case"StripAccents":return new DS(t);case"Lowercase":return new jS(t);case"Prepend":return new qS(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var fv=WS,VS=class extends zn{pre_tokenize(t,e){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},Vt=VS,HS=class extends Vt{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=pv,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(""))}},XS=HS,KS=class extends Vt{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},YS=KS,QS=class extends Vt{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]}},JS=QS,ZS=class extends Vt{constructor(t){super(),this.config=t,this.pattern=Ni(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):_S(t,this.pattern)}},eO=ZS,tO=class extends Vt{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Li}]+|[${Li}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},rO=tO,sO=class extends Vt{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)||[]}},nO=sO,oO=class extends Vt{constructor(){super(),this.pattern=new RegExp(`[^\\s${Li}]+|[${Li}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},aO=oO,iO=class extends Vt{constructor(t){super(),this.config=t,this.pattern=Ni(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},lO=iO,cO=class extends Vt{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>mv(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,e):r,[t])}},uO=cO,pO=class extends Vt{pre_tokenize_text(t){return gS(t)}},dO=pO,fO=class extends Vt{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let r=0;r<t.length;r+=this._length)e.push(t.slice(r,r+this._length));return e}},mO=fO;function hO(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new aO;case"Sequence":return new uO(t);case"Whitespace":return new YS;case"WhitespaceSplit":return new dO;case"Metaspace":return new JS(t);case"ByteLevel":return new XS(t);case"Split":return new eO(t);case"Punctuation":return new rO(t);case"Digits":return new nO(t);case"Replace":return new lO(t);case"FixedLength":return new mO(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var mv=hO,_O=class extends zn{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=pS(e,this.tokens_to_ids,this.unk_token_id)),e}},Ri=_O,gO=class extends Ri{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=hp(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,r]of this.tokens_to_ids)this.vocab[r]=e}encode(t){let e=[];for(let r of t){let s=[...r];if(s.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let n=!1,o=0,a=[];for(;o<s.length;){let i=s.length,l=null;for(;o<i;){let u=s.slice(o,i).join("");if(o>0&&(u=this.config.continuing_subword_prefix+u),this.tokens_to_ids.has(u)){l=u;break}--i}if(l===null){n=!0;break}a.push(l),o=i}n?e.push(this.unk_token):e.push(...a)}return e}},iv=gO,lv=class hv{constructor(e,r){this.is_leaf=e,this.children=r}static default(){return new hv(!1,new Map)}},wO=class{constructor(){this.root=lv.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=lv.default(),e.children.set(r,s)),e=s}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let r="";for(let s of t){if(r+=s,e=e.children.get(s),e===void 0)return;e.is_leaf&&(yield r)}}},xO=wO,fp=class _v{constructor(e,r,s,n,o){this.token_id=e,this.node_id=r,this.pos=s,this.length=n,this.score=o,this.prev=null,this.backtrace_score=0}clone(){let e=new _v(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},yO=class{constructor(t,e,r){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=r,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let s=new fp(this.bos_token_id??0,0,0,0,0),n=new fp(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 fp(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 u of this.end_nodes[e]){let d=u.backtrace_score+a.score;(l===null||d>i)&&(l=u.clone(),i=d)}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)}},bO=yO;function vO(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}var kO=class extends Ri{constructor(t,e){super(t);let r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let s=0;s<r;++s)[this.vocab[s],this.scores[s]]=t.vocab[s];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((s,n)=>[s,n])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=vO(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new xO,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,r=1,s=0;for(;s<e.length;){let n=!1,o=[],a=e.slice(s).join(""),i=this.trie.common_prefix_search(a);for(let l of i){o.push(l);let u=this.tokens_to_ids.get(l),d=this.scores[u],f=mS(l);t.insert(s,f,d,u),!n&&f===r&&(n=!0)}n||t.insert(s,r,this.unk_score,this.unk_token_id),s+=r}}tokenize(t){let e=new bO(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let r of t){let s=this.tokenize(r);e.push(...s)}return e}},cv=kO,EO=class{constructor(t=(r,s)=>r>s,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let r=this._smallest();this._comparator(e,this._heap[r])&&(this._heap[r]=e,this._sift_up_from(r))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let r=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},AO=EO,MO=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},TO=MO,SO=class extends Ri{constructor(t){super(t),this.tokens_to_ids=hp(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 TO(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 AO((i,l)=>i.score<l.score),o={token:r[0],bias:0,prev:null,next:null},a=o;for(let i=1;i<r.length;++i){let l={bias:i/r.length,token:r[i],prev:a,next:null};a.next=l,this.add_node(n,a),a=l}for(;!n.is_empty();){let i=n.pop();if(i.deleted||!i.next||i.next.deleted)continue;if(i.deleted=!0,i.next.deleted=!0,i.prev){let u={...i.prev};i.prev.deleted=!0,i.prev=u,u.prev?u.prev.next=u:o=u}let l={token:i.token+i.next.token,bias:i.bias,prev:i.prev,next:i.next.next};l.prev?(l.prev.next=l,this.add_node(n,l.prev)):o=l,l.next&&(l.next.prev=l,this.add_node(n,l))}for(let i=o;i!==null;i=i.next)s.push(i.token)}else s=r;if(this.continuing_subword_suffix)for(let n=0;n<s.length-1;++n)s[n]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,s),s}add_node(t,e){let r=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));r!==void 0&&(e.score=r+e.bias,t.push(e))}encode(t){let e=[];for(let r of t){if(this.ignore_merges&&this.tokens_to_ids.has(r)){e.push(r);continue}let s=this.bpe(r);for(let n of s)if(this.tokens_to_ids.has(n))e.push(n);else if(this.byte_fallback){let o=Array.from(this.text_encoder.encode(n)).map(a=>`<0x${a.toString(16).toUpperCase().padStart(2,"0")}>`);o.every(a=>this.tokens_to_ids.has(a))?e.push(...o):e.push(this.unk_token)}else e.push(this.unk_token)}return e}},uv=SO,OO=class extends Ri{constructor(t,e){super(t);let r=t.vocab;this.tokens_to_ids=hp(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}},IO=OO;function CO(t,e){switch(t.type){case"WordPiece":return new iv(t);case"Unigram":return new cv(t,e.eos_token);case"BPE":return new uv(t);default:if(t.vocab)return Array.isArray(t.vocab)?new cv(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new uv(t):new iv(t):new IO(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 PO=CO,zO=class extends zn{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Ln=zO,LO=class extends Ln{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=Wt(n,t),o=Wt(o,new Array(t.length).fill(a.Sequence.type_id))):a.Sequence.id==="B"&&(n=Wt(n,e),o=Wt(o,new Array(e.length).fill(a.Sequence.type_id))));return{tokens:n,token_type_ids:o}}},NO=LO,$O=class extends Ln{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},RO=$O,UO=class extends Ln{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,r=!0){r&&(t=Wt([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=Wt(t,n,e,o),s=Wt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},BO=UO,DO=class extends Ln{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,r=!0){r&&(t=Wt([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=Wt(t,n,e,o),s=Wt(s,new Array(e.length+n.length+o.length).fill(1))}return{tokens:t,token_type_ids:s}}},FO=DO,jO=class extends Ln{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>gv(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}},GO=jO;function qO(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new NO(t);case"ByteLevel":return new RO(t);case"BertProcessing":return new BO(t);case"RobertaProcessing":return new FO(t);case"Sequence":return new GO(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var gv=qO,WO=class extends zn{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},$t=WO,VO=class extends $t{constructor(t){super(t),this.byte_decoder=lS,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}},HO=VO,XO=class extends $t{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=mp(e)),e})}},KO=XO,YO=class extends $t{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let r=0;r<t.length;++r){let s=t[r].replaceAll(this.replacement," ");r==0&&s.startsWith(" ")&&(s=s.substring(1)),e.push(s)}return e}},QO=YO,JO=class extends $t{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,r)=>e.replaceAll(this.suffix,r===t.length-1?"":" "))}},ZO=JO,eI=class extends $t{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let n=1;n<t.length;++n)t[n]!==e.at(-1)&&e.push(t[n]);let s=e.filter(n=>n!==this.pad_token).join("");return this.cleanup&&(s=mp(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(t){return[this.convert_tokens_to_string(t)]}},tI=eI,rI=class extends $t{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>wv(e))}decode_chain(t){return this.decoders.reduce((e,r)=>r.decode_chain(e),t)}},sI=rI,nI=class extends $t{decode_chain(t){let e=Ni(this.config.pattern),r=this.config.content??"";return e===null?t:t.map(s=>s.replaceAll(e,r))}},oI=nI,aI=class extends $t{decode_chain(t){return[t.join("")]}},iI=aI,lI=class extends $t{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let r=0;for(let n=0;n<this.start&&e[n]===this.content;++n){r=n+1;continue}let s=e.length;for(let n=0;n<this.stop;++n){let o=e.length-n-1;if(e[o]===this.content){s=o;continue}else break}return e.slice(r,s)})}},cI=lI,uI=class extends $t{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],r=[];for(let s of t){let n=null;if(s.length===6&&s.startsWith("<0x")&&s.endsWith(">")){let o=parseInt(s.slice(3,5),16);isNaN(o)||(n=o)}if(n!==null)r.push(n);else{if(r.length>0){let o=this.text_decoder.decode(Uint8Array.from(r));e.push(o),r=[]}e.push(s)}}if(r.length>0){let s=this.text_decoder.decode(Uint8Array.from(r));e.push(s),r=[]}return e}},pI=uI;function dI(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new HO(t);case"WordPiece":return new KO(t);case"Metaspace":return new QO(t);case"BPEDecoder":return new ZO(t);case"CTC":return new tI(t);case"Sequence":return new sI(t);case"Replace":return new oI(t);case"Fuse":return new iI(t);case"Strip":return new cI(t);case"ByteFallback":return new pI(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var wv=dI,fI=class{constructor(t,e){let r=av(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);let s=av(e,"Config");if(s)throw new Error(s);this.tokenizer=t,this.config=e,this.normalizer=fv(this.tokenizer.normalizer),this.pre_tokenizer=mv(this.tokenizer.pre_tokenizer),this.model=PO(this.tokenizer.model,this.config),this.post_processor=gv(this.tokenizer.post_processor),this.decoder=wv(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 aS(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 nv(n),this.splitter_normalized=new nv(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||!fS(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=mp(s)),s}tokenize(t,{text_pair:e=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:r}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((r,s)=>{let n=this.added_tokens_map.get(r);n&&(n.lstrip&&s>0&&(e[s-1]=e[s-1].trimEnd()),n.rstrip&&s<e.length-1&&(e[s+1]=e[s+1].trimStart()))}),e.flatMap((r,s)=>{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=hS(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];let n=this.splitter_normalized.split(r);return n.forEach((o,a)=>{let i=this.added_tokens_map.get(o);i&&(i.lstrip&&a>0&&(n[a-1]=n[a-1].trimEnd()),i.rstrip&&a<n.length-1&&(n[a+1]=n[a+1].trimStart()))}),n.flatMap(o=>{if(o.length===0)return[];if(this.added_tokens_map.has(o))return[o];let a=this.pre_tokenizer!==null?this.pre_tokenizer(o,{section_index:s}):[o];return this.model(a)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:r=!0}){let s=this.encode_text(t),n=this.encode_text(e||null);return this.post_processor?this.post_processor(s,n,r):{tokens:Wt(s??[],n??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let r=0;r<this.model.vocab.length;++r){let s=this.model.vocab[r];(t||!this.added_tokens_map.has(s))&&e.set(s,r)}return e}},xv=fI;var $=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),Rt=class{constructor(t,e){this.value=t,this.type=e}};function yv(t){return/\w/.test(t)}function Nn(t){return/[0-9]/.test(t)}function bv(t){return/\s/.test(t)}var mI=[["{%",$.OpenStatement],["%}",$.CloseStatement],["{{",$.OpenExpression],["}}",$.CloseExpression],["(",$.OpenParen],[")",$.CloseParen],["{",$.OpenCurlyBracket],["}",$.CloseCurlyBracket],["[",$.OpenSquareBracket],["]",$.CloseSquareBracket],[",",$.Comma],[".",$.Dot],[":",$.Colon],["|",$.Pipe],["<=",$.ComparisonBinaryOperator],[">=",$.ComparisonBinaryOperator],["==",$.ComparisonBinaryOperator],["!=",$.ComparisonBinaryOperator],["<",$.ComparisonBinaryOperator],[">",$.ComparisonBinaryOperator],["+",$.AdditiveBinaryOperator],["-",$.AdditiveBinaryOperator],["~",$.AdditiveBinaryOperator],["*",$.MultiplicativeBinaryOperator],["/",$.MultiplicativeBinaryOperator],["%",$.MultiplicativeBinaryOperator],["=",$.Equals]],hI=new Map([["n",`
|
|
3
3
|
`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function _I(t,e={}){return t.endsWith(`
|
|
4
4
|
`)&&(t=t.slice(0,-1)),e.lstrip_blocks&&(t=t.replace(/^[ \t]*({[#%-])/gm,"$1")),e.trim_blocks&&(t=t.replace(/([#%-]})\n/g,"$1")),t.replace(/{%\s*(end)?generation\s*%}/gs,"")}function gI(t,e={}){let r=[],s=_I(t,e),n=0,o=0,a=u=>{let d="";for(;u(s[n]);){if(s[n]==="\\"){if(++n,n>=s.length)throw new SyntaxError("Unexpected end of input");let f=s[n++],m=hI.get(f);if(m===void 0)throw new SyntaxError(`Unexpected escaped character: ${f}`);d+=m;continue}if(d+=s[n++],n>=s.length)throw new SyntaxError("Unexpected end of input")}return d},i=()=>{let u=r.at(-1);u&&u.type===$.Text&&(u.value=u.value.trimEnd(),u.value===""&&r.pop())},l=()=>{for(;n<s.length&&bv(s[n]);)++n};e:for(;n<s.length;){let u=r.at(-1)?.type;if(u===void 0||u===$.CloseStatement||u===$.CloseExpression||u===$.Comment){let f="";for(;n<s.length&&!(s[n]==="{"&&(s[n+1]==="%"||s[n+1]==="{"||s[n+1]==="#"));)f+=s[n++];if(f.length>0){r.push(new Rt(f,$.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 Rt(m,$.Comment)),n+=2,_&&l();continue}if(s.slice(n,n+3)==="{%-"){i(),r.push(new Rt("{%",$.OpenStatement)),n+=3;continue}if(s.slice(n,n+3)==="{{-"){i(),r.push(new Rt("{{",$.OpenExpression)),o=0,n+=3;continue}if(a(bv),s.slice(n,n+3)==="-%}"){r.push(new Rt("%}",$.CloseStatement)),n+=3,l();continue}if(s.slice(n,n+3)==="-}}"){r.push(new Rt("}}",$.CloseExpression)),n+=3,l();continue}let d=s[n];if(d==="-"||d==="+"){let f=r.at(-1)?.type;if(f===$.Text||f===void 0)throw new SyntaxError(`Unexpected character: ${d}`);switch(f){case $.Identifier:case $.NumericLiteral:case $.StringLiteral:case $.CloseParen:case $.CloseSquareBracket:break;default:{++n;let m=a(Nn);r.push(new Rt(`${d}${m}`,m.length>0?$.NumericLiteral:$.UnaryOperator));continue}}}for(let[f,m]of mI){if(f==="}}"&&o>0)continue;if(s.slice(n,n+f.length)===f){r.push(new Rt(f,m)),m===$.OpenExpression?o=0:m===$.OpenCurlyBracket?++o:m===$.CloseCurlyBracket&&--o,n+=f.length;continue e}}if(d==="'"||d==='"'){++n;let f=a(m=>m!==d);r.push(new Rt(f,$.StringLiteral)),++n;continue}if(Nn(d)){let f=a(Nn);if(s[n]==="."&&Nn(s[n+1])){++n;let m=a(Nn);f=`${f}.${m}`}r.push(new Rt(f,$.NumericLiteral));continue}if(yv(d)){let f=a(yv);r.push(new Rt(f,$.Identifier));continue}throw new SyntaxError(`Unexpected character: ${d}`)}return r}var Xt=class{type="Statement"},wI=class extends Xt{constructor(t){super(),this.body=t}type="Program"},xI=class extends Xt{constructor(t,e,r){super(),this.test=t,this.body=e,this.alternate=r}type="If"},yI=class extends Xt{constructor(t,e,r,s){super(),this.loopvar=t,this.iterable=e,this.body=r,this.defaultBlock=s}type="For"},bI=class extends Xt{type="Break"},vI=class extends Xt{type="Continue"},kI=class extends Xt{constructor(t,e,r){super(),this.assignee=t,this.value=e,this.body=r}type="Set"},EI=class extends Xt{constructor(t,e,r){super(),this.name=t,this.args=e,this.body=r}type="Macro"},AI=class extends Xt{constructor(t){super(),this.value=t}type="Comment"},St=class extends Xt{type="Expression"},MI=class extends St{constructor(t,e,r){super(),this.object=t,this.property=e,this.computed=r}type="MemberExpression"},vv=class extends St{constructor(t,e){super(),this.callee=t,this.args=e}type="CallExpression"},Ls=class extends St{constructor(t){super(),this.value=t}type="Identifier"},Ns=class extends St{constructor(t){super(),this.value=t}type="Literal"},TI=class extends Ns{type="IntegerLiteral"},SI=class extends Ns{type="FloatLiteral"},kv=class extends Ns{type="StringLiteral"},OI=class extends Ns{type="ArrayLiteral"},Ev=class extends Ns{type="TupleLiteral"},II=class extends Ns{type="ObjectLiteral"},$n=class extends St{constructor(t,e,r){super(),this.operator=t,this.left=e,this.right=r}type="BinaryExpression"},CI=class extends St{constructor(t,e){super(),this.operand=t,this.filter=e}type="FilterExpression"},PI=class extends Xt{constructor(t,e){super(),this.filter=t,this.body=e}type="FilterStatement"},zI=class extends St{constructor(t,e){super(),this.lhs=t,this.test=e}type="SelectExpression"},LI=class extends St{constructor(t,e,r){super(),this.operand=t,this.negate=e,this.test=r}type="TestExpression"},NI=class extends St{constructor(t,e){super(),this.operator=t,this.argument=e}type="UnaryExpression"},$I=class extends St{constructor(t=void 0,e=void 0,r=void 0){super(),this.start=t,this.stop=e,this.step=r}type="SliceExpression"},RI=class extends St{constructor(t,e){super(),this.key=t,this.value=e}type="KeywordArgumentExpression"},UI=class extends St{constructor(t){super(),this.argument=t}type="SpreadExpression"},BI=class extends Xt{constructor(t,e,r){super(),this.call=t,this.callerArgs=e,this.body=r}type="CallStatement"},DI=class extends St{constructor(t,e,r){super(),this.condition=t,this.trueExpr=e,this.falseExpr=r}type="Ternary"};function FI(t){let e=new wI([]),r=0;function s(S,L){let R=t[r++];if(!R||R.type!==S)throw new Error(`Parser Error: ${L}. ${R.type} !== ${S}.`);return R}function n(S){if(!l(S))throw new SyntaxError(`Expected ${S}`);++r}function o(){switch(t[r].type){case $.Comment:return new AI(t[r++].value);case $.Text:return u();case $.OpenStatement:return d();case $.OpenExpression:return f();default:throw new SyntaxError(`Unexpected token type: ${t[r].type}`)}}function a(...S){return r+S.length<=t.length&&S.every((L,R)=>L===t[r+R].type)}function i(...S){return t[r]?.type===$.OpenStatement&&t[r+1]?.type===$.Identifier&&S.includes(t[r+1]?.value)}function l(...S){return r+S.length<=t.length&&S.every((L,R)=>t[r+R].type==="Identifier"&&L===t[r+R].value)}function u(){return new kv(s($.Text,"Expected text token").value)}function d(){if(s($.OpenStatement,"Expected opening statement token"),t[r].type!==$.Identifier)throw new SyntaxError(`Unknown statement, got ${t[r].type}`);let S=t[r].value,L;switch(S){case"set":++r,L=m();break;case"if":++r,L=_(),s($.OpenStatement,"Expected {% token"),n("endif"),s($.CloseStatement,"Expected %} token");break;case"macro":++r,L=w(),s($.OpenStatement,"Expected {% token"),n("endmacro"),s($.CloseStatement,"Expected %} token");break;case"for":++r,L=k(),s($.OpenStatement,"Expected {% token"),n("endfor"),s($.CloseStatement,"Expected %} token");break;case"call":{++r;let R=null;a($.OpenParen)&&(R=V());let te=ie();if(te.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");let ue=V();s($.CloseStatement,"Expected closing statement token");let Be=[];for(;!i("endcall");)Be.push(o());s($.OpenStatement,"Expected '{%'"),n("endcall"),s($.CloseStatement,"Expected closing statement token");let Ce=new vv(te,ue);L=new BI(Ce,R,Be);break}case"break":++r,s($.CloseStatement,"Expected closing statement token"),L=new bI;break;case"continue":++r,s($.CloseStatement,"Expected closing statement token"),L=new vI;break;case"filter":{++r;let R=ie();R instanceof Ls&&a($.OpenParen)&&(R=X(R)),s($.CloseStatement,"Expected closing statement token");let te=[];for(;!i("endfilter");)te.push(o());s($.OpenStatement,"Expected '{%'"),n("endfilter"),s($.CloseStatement,"Expected '%}'"),L=new PI(R,te);break}default:throw new SyntaxError(`Unknown statement type: ${S}`)}return L}function f(){s($.OpenExpression,"Expected opening expression token");let S=E();return s($.CloseExpression,"Expected closing expression token"),S}function m(){let S=x(),L=null,R=[];if(a($.Equals))++r,L=x();else{for(s($.CloseStatement,"Expected %} token");!i("endset");)R.push(o());s($.OpenStatement,"Expected {% token"),n("endset")}return s($.CloseStatement,"Expected closing statement token"),new kI(S,L,R)}function _(){let S=E();s($.CloseStatement,"Expected closing statement token");let L=[],R=[];for(;!i("elif","else","endif");)L.push(o());if(i("elif")){++r,++r;let te=_();R.push(te)}else if(i("else"))for(++r,++r,s($.CloseStatement,"Expected closing statement token");!i("endif");)R.push(o());return new xI(S,L,R)}function w(){let S=ie();if(S.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");let L=V();s($.CloseStatement,"Expected closing statement token");let R=[];for(;!i("endmacro");)R.push(o());return new EI(S,L,R)}function x(S=!1){let L=S?ie:E,R=[L()],te=a($.Comma);for(;te&&(++r,R.push(L()),!!a($.Comma)););return te?new Ev(R):R[0]}function k(){let S=x(!0);if(!(S instanceof Ls||S instanceof Ev))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${S.type} instead`);if(!l("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;let L=E();s($.CloseStatement,"Expected closing statement token");let R=[];for(;!i("endfor","else");)R.push(o());let te=[];if(i("else"))for(++r,++r,s($.CloseStatement,"Expected closing statement token");!i("endfor");)te.push(o());return new yI(S,L,R,te)}function E(){return M()}function M(){let S=I();if(l("if")){++r;let L=I();if(l("else")){++r;let R=M();return new DI(L,S,R)}else return new zI(S,L)}return S}function I(){let S=T();for(;l("or");){let L=t[r];++r;let R=T();S=new $n(L,S,R)}return S}function T(){let S=z();for(;l("and");){let L=t[r];++r;let R=z();S=new $n(L,S,R)}return S}function z(){let S;for(;l("not");){let L=t[r];++r;let R=z();S=new NI(L,R)}return S??C()}function C(){let S=v();for(;;){let L;if(l("not","in"))L=new Rt("not in",$.Identifier),r+=2;else if(l("in"))L=t[r++];else if(a($.ComparisonBinaryOperator))L=t[r++];else break;let R=v();S=new $n(L,S,R)}return S}function v(){let S=B();for(;a($.AdditiveBinaryOperator);){let L=t[r];++r;let R=B();S=new $n(L,S,R)}return S}function G(){let S=Y(ie());return a($.OpenParen)?X(S):S}function X(S){let L=new vv(S,V());return L=Y(L),a($.OpenParen)&&(L=X(L)),L}function V(){s($.OpenParen,"Expected opening parenthesis for arguments list");let S=Q();return s($.CloseParen,"Expected closing parenthesis for arguments list"),S}function Q(){let S=[];for(;!a($.CloseParen);){let L;if(t[r].type===$.MultiplicativeBinaryOperator&&t[r].value==="*"){++r;let R=E();L=new UI(R)}else if(L=E(),a($.Equals)){if(++r,!(L instanceof Ls))throw new SyntaxError("Expected identifier for keyword argument");let R=E();L=new RI(L,R)}S.push(L),a($.Comma)&&++r}return S}function K(){let S=[],L=!1;for(;!a($.CloseSquareBracket);)a($.Colon)?(S.push(void 0),++r,L=!0):(S.push(E()),a($.Colon)&&(++r,L=!0));if(S.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(L){if(S.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new $I(...S)}return S[0]}function Y(S){for(;a($.Dot)||a($.OpenSquareBracket);){let L=t[r];++r;let R,te=L.type===$.OpenSquareBracket;if(te)R=K(),s($.CloseSquareBracket,"Expected closing square bracket");else if(R=ie(),R.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");S=new MI(S,R,te)}return S}function B(){let S=P();for(;a($.MultiplicativeBinaryOperator);){let L=t[r++],R=P();S=new $n(L,S,R)}return S}function P(){let S=se();for(;l("is");){++r;let L=l("not");L&&++r;let R=ie();if(!(R instanceof Ls))throw new SyntaxError("Expected identifier for the test");S=new LI(S,L,R)}return S}function se(){let S=G();for(;a($.Pipe);){++r;let L=ie();if(!(L instanceof Ls))throw new SyntaxError("Expected identifier for the filter");a($.OpenParen)&&(L=X(L)),S=new CI(S,L)}return S}function ie(){let S=t[r++];switch(S.type){case $.NumericLiteral:{let L=S.value;return L.includes(".")?new SI(Number(L)):new TI(Number(L))}case $.StringLiteral:{let L=S.value;for(;a($.StringLiteral);)L+=t[r++].value;return new kv(L)}case $.Identifier:return new Ls(S.value);case $.OpenParen:{let L=x();return s($.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),L}case $.OpenSquareBracket:{let L=[];for(;!a($.CloseSquareBracket);)L.push(E()),a($.Comma)&&++r;return++r,new OI(L)}case $.OpenCurlyBracket:{let L=new Map;for(;!a($.CloseCurlyBracket);){let R=E();s($.Colon,"Expected colon between key and value in object literal");let te=E();L.set(R,te),a($.Comma)&&++r}return++r,new II(L)}default:throw new SyntaxError(`Unexpected token: ${S.type}`)}}for(;r<t.length;)e.body.push(o());return e}function jI(t,e,r=1){if(e===void 0&&(e=t,t=0),r===0)throw new Error("range() step must not be zero");let s=[];if(r>0)for(let n=t;n<e;n+=r)s.push(n);else for(let n=t;n>e;n+=r)s.push(n);return s}function Av(t,e,r,s=1){let n=Math.sign(s);n>=0?(e=(e??=0)<0?Math.max(t.length+e,0):Math.min(e,t.length),r=(r??=t.length)<0?Math.max(t.length+r,0):Math.min(r,t.length)):(e=(e??=t.length-1)<0?Math.max(t.length+e,-1):Math.min(e,t.length-1),r=(r??=-1)<-1?Math.max(t.length+r,-1):Math.min(r,t.length-1));let o=[];for(let a=e;n*a<n*r;a+=s)o.push(t[a]);return o}function GI(t){return t.replace(/\b\w/g,e=>e.toUpperCase())}function qI(t){return WI(new Date,t)}function WI(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 VI(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function HI(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(VI(e),"gu");return t.replaceAll(o,a=>n>0?(--n,r):a)}var Mv=class extends Error{},Tv=class extends Error{},sr=class{type="RuntimeValue";value;builtins=new Map;constructor(t=void 0){this.value=t}__bool__(){return new le(!!this.value)}toString(){return String(this.value)}},de=class extends sr{type="IntegerValue"},Ke=class extends sr{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Z=class extends sr{type="StringValue";builtins=new Map([["upper",new je(()=>new Z(this.value.toUpperCase()))],["lower",new je(()=>new Z(this.value.toLowerCase()))],["strip",new je(()=>new Z(this.value.trim()))],["title",new je(()=>new Z(GI(this.value)))],["capitalize",new je(()=>new Z(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new de(this.value.length)],["rstrip",new je(()=>new Z(this.value.trimEnd()))],["lstrip",new je(()=>new Z(this.value.trimStart()))],["startswith",new je(t=>{if(t.length===0)throw new Error("startswith() requires at least one argument");let e=t[0];if(e instanceof Z)return new le(this.value.startsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof Z))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new le(!0)}return new le(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new je(t=>{if(t.length===0)throw new Error("endswith() requires at least one argument");let e=t[0];if(e instanceof Z)return new le(this.value.endsWith(e.value));if(e instanceof ve){for(let r of e.value){if(!(r instanceof Z))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new le(!0)}return new le(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new je(t=>{let e=t[0]??new qe;if(!(e instanceof Z||e instanceof qe))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 qe){let n=this.value.trimStart();for(let{0:o,index:a}of n.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&a!==void 0){s.push(o+n.slice(a+o.length));break}s.push(o)}}else{if(e.value==="")throw new Error("empty separator");s=this.value.split(e.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(e.value))}return new ve(s.map(n=>new Z(n)))})],["replace",new je(t=>{if(t.length<2)throw new Error("replace() requires at least two arguments");let e=t[0],r=t[1];if(!(e instanceof Z&&r instanceof Z))throw new Error("replace() arguments must be strings");let s;if(t.length>2?t[2].type==="KeywordArgumentsValue"?s=t[2].value.get("count")??new qe:s=t[2]:s=new qe,!(s instanceof de||s instanceof qe))throw new Error("replace() count argument must be a number or null");return new Z(HI(this.value,e.value,r.value,s.value))})]])},le=class extends sr{type="BooleanValue"},XI=/[\x7f-\uffff]/g;function Sv(t){return t.replace(XI,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function es(t,e={},r=0,s=!0){let{indent:n=null,ensureAscii:o=!1,separators:a=null,sortKeys:i=!1}=e,l,u;switch(a?[l,u]=a:n?(l=",",u=": "):(l=", ",u=": "),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 d=JSON.stringify(t.value);return o&&(d=Sv(d)),d}case"ArrayValue":case"ObjectValue":{let d=n?" ".repeat(n):"",f=`
|
|
@@ -7,12 +7,12 @@ var HT=Object.defineProperty;var Jr=(t=>typeof require<"u"?require:typeof Proxy<
|
|
|
7
7
|
`));case"join":case"string":return t;case"int":{let n=parseInt(t.value,10);return new de(isNaN(n)?0:n)}case"float":{let n=parseFloat(t.value);return new Ke(isNaN(n)?0:n)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(t instanceof de||t instanceof Ke)switch(s.value){case"abs":return t instanceof de?new de(Math.abs(t.value)):new Ke(Math.abs(t.value));case"int":return new de(Math.floor(t.value));case"float":return new Ke(t.value);default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(t instanceof ht)switch(s.value){case"items":return new ve(Array.from(t.value.entries()).map(([n,o])=>new ve([new Z(n),o])));case"length":return new de(t.value.size);default:{let n=t.builtins.get(s.value);if(n)return n instanceof je?n.value([],r):n;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(t instanceof le)switch(s.value){case"bool":return new le(t.value);case"int":return new de(t.value?1:0);case"float":return new Ke(t.value?1:0);case"string":return new Z(t.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${t.type}`)}else if(e.type==="CallExpression"){let s=e;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);let n=s.callee.value;if(n==="tojson"){let[,o]=this.evaluateArguments(s.args,r),a=o.get("indent")??new qe;if(!(a instanceof de||a instanceof qe))throw new Error("If set, indent must be a number");let i=o.get("ensure_ascii")??new le(!1);if(!(i instanceof le))throw new Error("If set, ensure_ascii must be a boolean");let l=o.get("sort_keys")??new le(!1);if(!(l instanceof le))throw new Error("If set, sort_keys must be a boolean");let u=o.get("separators")??new qe,d=null;if(u instanceof ve||u instanceof Ov){if(u.value.length!==2)throw new Error("separators must be a tuple of two strings");let[f,m]=u.value;if(!(f instanceof Z)||!(m instanceof Z))throw new Error("separators must be a tuple of two strings");d=[f.value,m.value]}else if(!(u instanceof qe))throw new Error("If set, separators must be a tuple of two strings");return new Z(es(t,{indent:a.value,ensureAscii:i.value,sortKeys:l.value,separators:d}))}else if(n==="join"){let o;if(t instanceof Z)o=Array.from(t.value);else if(t instanceof ve)o=t.value.map(u=>u.value);else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`);let[a,i]=this.evaluateArguments(s.args,r),l=a.at(0)??i.get("separator")??new Z("");if(!(l instanceof Z))throw new Error("separator must be a string");return new Z(o.join(l.value))}else if(n==="int"||n==="float"){let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("default")??(n==="int"?new de(0):new Ke(0));if(t instanceof Z){let l=n==="int"?parseInt(t.value,10):parseFloat(t.value);return isNaN(l)?i:n==="int"?new de(l):new Ke(l)}else{if(t instanceof de||t instanceof Ke)return t;if(t instanceof le)return n==="int"?new de(t.value?1:0):new Ke(t.value?1:0);throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}}else if(n==="default"){let[o,a]=this.evaluateArguments(s.args,r),i=o[0]??new Z(""),l=o[1]??a.get("boolean")??new le(!1);if(!(l instanceof le))throw new Error("`default` filter flag must be a boolean");return t instanceof Fe||l.value&&!t.__bool__().value?i:t}if(t instanceof ve){switch(n){case"sort":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("reverse")??new le(!1);if(!(i instanceof le))throw new Error("reverse must be a boolean");let l=o.at(1)??a.get("case_sensitive")??new le(!1);if(!(l instanceof le))throw new Error("case_sensitive must be a boolean");let u=o.at(2)??a.get("attribute")??new qe;if(!(u instanceof Z||u instanceof de||u instanceof qe))throw new Error("attribute must be a string, integer, or null");let d=f=>{if(u instanceof qe)return f;let m=u instanceof de?String(u.value):u.value;return Iv(f,m)};return new ve(t.value.slice().sort((f,m)=>{let _=d(f),w=d(m),x=_p(_,w,l.value);return i.value?-x:x}))}case"selectattr":case"rejectattr":{let o=n==="selectattr";if(t.value.some(f=>!(f instanceof ht)))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)),u;if(i){let f=r.tests.get(i.value);if(!f)throw new Error(`Unknown test: ${i.value}`);u=f}else u=(...f)=>f[0].__bool__().value;let d=t.value.filter(f=>{let m=f.value.get(a.value),_=m?u(m,l):!1;return o?_:!_});return new ve(d)}case"map":{let[,o]=this.evaluateArguments(s.args,r);if(o.has("attribute")){let a=o.get("attribute");if(!(a instanceof Z))throw new Error("attribute must be a string");let i=o.get("default"),l=t.value.map(u=>{if(!(u instanceof ht))throw new Error("items in map must be an object");let d=Iv(u,a.value);return d instanceof Fe?i??new Fe:d});return new ve(l)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${n}`)}else if(t instanceof Z){switch(n){case"indent":{let[o,a]=this.evaluateArguments(s.args,r),i=o.at(0)??a.get("width")??new de(4);if(!(i instanceof de))throw new Error("width must be a number");let l=o.at(1)??a.get("first")??new le(!1),u=o.at(2)??a.get("blank")??new le(!1),d=t.value.split(`
|
|
8
8
|
`),f=" ".repeat(i.value),m=d.map((_,w)=>!l.value&&w===0||!u.value&&_.length===0?_:f+_);return new Z(m.join(`
|
|
9
9
|
`))}case"replace":{let o=t.builtins.get("replace");if(!(o instanceof je))throw new Error("replace filter not available");let[a,i]=this.evaluateArguments(s.args,r);return o.value([...a,new Rn(i)],r)}}throw new Error(`Unknown StringValue filter: ${n}`)}else if(t instanceof ht){let o=t.builtins.get(n);if(o&&o instanceof je){let[a,i]=this.evaluateArguments(s.args,r);return i.size>0&&a.push(new Rn(i)),o.value(a,r)}throw new Error(`Unknown ObjectValue filter: ${n}`)}else throw new Error(`Cannot apply filter "${n}" to type: ${t.type}`)}throw new Error(`Unknown filter: ${e.type}`)}evaluateFilterExpression(t,e){let r=this.evaluate(t.operand,e);return this.applyFilter(r,t.filter,e)}evaluateTestExpression(t,e){let r=this.evaluate(t.operand,e),s=e.tests.get(t.test.value);if(!s)throw new Error(`Unknown test: ${t.test.value}`);let n=s(r);return new le(t.negate?!n:n)}evaluateSelectExpression(t,e){return this.evaluate(t.test,e).__bool__().value?this.evaluate(t.lhs,e):new Fe}evaluateUnaryExpression(t,e){let r=this.evaluate(t.argument,e);if(t.operator.value==="not")return new le(!r.value);throw new SyntaxError(`Unknown operator: ${t.operator.value}`)}evaluateTernaryExpression(t,e){return this.evaluate(t.condition,e).__bool__().value?this.evaluate(t.trueExpr,e):this.evaluate(t.falseExpr,e)}evalProgram(t,e){return this.evaluateBlock(t.body,e)}evaluateBlock(t,e){let r="";for(let s of t){let n=this.evaluate(s,e);n.type!=="NullValue"&&n.type!=="UndefinedValue"&&(r+=n.toString())}return new Z(r)}evaluateIdentifier(t,e){return e.lookupVariable(t.value)}evaluateCallExpression(t,e){let[r,s]=this.evaluateArguments(t.args,e);s.size>0&&r.push(new Rn(s));let n=this.evaluate(t.callee,e);if(n.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${n.type}`);return n.value(r,e)}evaluateSliceExpression(t,e,r){if(!(t instanceof ve||t instanceof Z))throw new Error("Slice object must be an array or string");let s=this.evaluate(e.start,r),n=this.evaluate(e.stop,r),o=this.evaluate(e.step,r);if(!(s instanceof de||s instanceof Fe))throw new Error("Slice start must be numeric or undefined");if(!(n instanceof de||n instanceof Fe))throw new Error("Slice stop must be numeric or undefined");if(!(o instanceof de||o instanceof Fe))throw new Error("Slice step must be numeric or undefined");return t instanceof ve?new ve(Av(t.value,s.value,n.value,o.value)):new Z(Av(Array.from(t.value),s.value,n.value,o.value).join(""))}evaluateMemberExpression(t,e){let r=this.evaluate(t.object,e),s;if(t.computed){if(t.property.type==="SliceExpression")return this.evaluateSliceExpression(r,t.property,e);s=this.evaluate(t.property,e)}else s=new Z(t.property.value);let n;if(r instanceof ht){if(!(s instanceof Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof ve||r instanceof Z)if(s instanceof de)n=r.value.at(s.value),r instanceof Z&&(n=new Z(r.value.at(s.value)));else if(s instanceof Z)n=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof Z))throw new Error(`Cannot access property with non-string: got ${s.type}`);n=r.builtins.get(s.value)}return n instanceof sr?n:new Fe}evaluateSet(t,e){let r=t.value?this.evaluate(t.value,e):this.evaluateBlock(t.body,e);if(t.assignee.type==="Identifier"){let s=t.assignee.value;e.setVariable(s,r)}else if(t.assignee.type==="TupleLiteral"){let s=t.assignee;if(!(r instanceof ve))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);let n=r.value;if(n.length!==s.value.length)throw new Error(`Too ${s.value.length>n.length?"few":"many"} items to unpack in set`);for(let o=0;o<s.value.length;++o){let a=s.value[o];if(a.type!=="Identifier")throw new Error(`Cannot unpack to non-identifier in set: ${a.type}`);e.setVariable(a.value,n[o])}}else if(t.assignee.type==="MemberExpression"){let s=t.assignee,n=this.evaluate(s.object,e);if(!(n instanceof ht))throw new Error("Cannot assign to member of non-object");if(s.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");n.value.set(s.property.value,r)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(t.assignee)}`);return new qe}evaluateIf(t,e){let r=this.evaluate(t.test,e);return this.evaluateBlock(r.__bool__().value?t.body:t.alternate,e)}evaluateFor(t,e){let r=new Zr(e),s,n;if(t.iterable.type==="SelectExpression"){let u=t.iterable;n=this.evaluate(u.lhs,r),s=u.test}else n=this.evaluate(t.iterable,r);if(!(n instanceof ve||n instanceof ht))throw new Error(`Expected iterable or object type in for loop: got ${n.type}`);n instanceof ht&&(n=n.keys());let o=[],a=[];for(let u=0;u<n.value.length;++u){let d=new Zr(r),f=n.value[u],m;if(t.loopvar.type==="Identifier")m=_=>_.setVariable(t.loopvar.value,f);else if(t.loopvar.type==="TupleLiteral"){let _=t.loopvar;if(f.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${f.type}`);let w=f;if(_.value.length!==w.value.length)throw new Error(`Too ${_.value.length>w.value.length?"few":"many"} items to unpack`);m=x=>{for(let k=0;k<_.value.length;++k){if(_.value[k].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_.value[k].type}`);x.setVariable(_.value[k].value,w.value[k])}}}else throw new Error(`Invalid loop variable(s): ${t.loopvar.type}`);s&&(m(d),!this.evaluate(s,d).__bool__().value)||(o.push(f),a.push(m))}let i="",l=!0;for(let u=0;u<o.length;++u){let d=new Map([["index",new de(u+1)],["index0",new de(u)],["revindex",new de(o.length-u)],["revindex0",new de(o.length-u-1)],["first",new le(u===0)],["last",new le(u===o.length-1)],["length",new de(o.length)],["previtem",u>0?o[u-1]:new Fe],["nextitem",u<o.length-1?o[u+1]:new Fe]]);r.setVariable("loop",new ht(d)),a[u](r);try{let f=this.evaluateBlock(t.body,r);i+=f.value}catch(f){if(f instanceof Tv)continue;if(f instanceof Mv)break;throw f}l=!1}if(l){let u=this.evaluateBlock(t.defaultBlock,r);i+=u.value}return new Z(i)}evaluateMacro(t,e){return e.setVariable(t.name.value,new je((r,s)=>{let n=new Zr(s);r=r.slice();let o;r.at(-1)?.type==="KeywordArgumentsValue"&&(o=r.pop());for(let a=0;a<t.args.length;++a){let i=t.args[a],l=r[a];if(i.type==="Identifier"){let u=i;if(!l)throw new Error(`Missing positional argument: ${u.value}`);n.setVariable(u.value,l)}else if(i.type==="KeywordArgumentExpression"){let u=i,d=l??o?.value.get(u.key.value)??this.evaluate(u.value,n);n.setVariable(u.key.value,d)}else throw new Error(`Unknown argument type: ${i.type}`)}return this.evaluateBlock(t.body,n)})),new qe}evaluateCallStatement(t,e){let r=new je((i,l)=>{let u=new Zr(l);if(t.callerArgs)for(let d=0;d<t.callerArgs.length;++d){let f=t.callerArgs[d];if(f.type!=="Identifier")throw new Error(`Caller parameter must be an identifier, got ${f.type}`);u.setVariable(f.value,i[d]??new Fe)}return this.evaluateBlock(t.body,u)}),[s,n]=this.evaluateArguments(t.call.args,e);s.push(new Rn(n));let o=this.evaluate(t.call.callee,e);if(o.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${o.type}`);let a=new Zr(e);return a.setVariable("caller",r),o.value(s,a)}evaluateFilterStatement(t,e){let r=this.evaluateBlock(t.body,e);return this.applyFilter(r,t.filter,e)}evaluate(t,e){if(!t)return new Fe;switch(t.type){case"Program":return this.evalProgram(t,e);case"Set":return this.evaluateSet(t,e);case"If":return this.evaluateIf(t,e);case"For":return this.evaluateFor(t,e);case"Macro":return this.evaluateMacro(t,e);case"CallStatement":return this.evaluateCallStatement(t,e);case"Break":throw new Mv;case"Continue":throw new Tv;case"IntegerLiteral":return new de(t.value);case"FloatLiteral":return new Ke(t.value);case"StringLiteral":return new Z(t.value);case"ArrayLiteral":return new ve(t.value.map(r=>this.evaluate(r,e)));case"TupleLiteral":return new Ov(t.value.map(r=>this.evaluate(r,e)));case"ObjectLiteral":{let r=new Map;for(let[s,n]of t.value){let o=this.evaluate(s,e);if(!(o instanceof Z))throw new Error(`Object keys must be strings: got ${o.type}`);r.set(o.value,this.evaluate(n,e))}return new ht(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 qe;default:throw new SyntaxError(`Unknown node type: ${t.type}`)}}};function Ui(t){switch(typeof t){case"number":return Number.isInteger(t)?new de(t):new Ke(t);case"string":return new Z(t);case"boolean":return new le(t);case"undefined":return new Fe;case"object":return t===null?new qe:Array.isArray(t)?new ve(t.map(Ui)):new ht(new Map(Object.entries(t).map(([e,r])=>[e,Ui(r)])));case"function":return new je((e,r)=>{let s=t(...e.map(n=>n.value))??null;return Ui(s)});default:throw new Error(`Cannot convert to runtime value: ${t}`)}}var nt=`
|
|
10
|
-
`,QI="{%- ",JI=" -%}";function ZI(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function eC(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Ht(t.body,0,r).replace(/\n$/,"")}function pt(...t){return QI+t.join(" ")+JI}function Ht(t,e,r){return t.map(s=>tC(s,e,r)).join(nt)}function tC(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Ht(t.body,e,r);case"If":return rC(t,e,r);case"For":return sC(t,e,r);case"Set":return nC(t,e,r);case"Macro":return oC(t,e,r);case"Break":return s+pt("break");case"Continue":return s+pt("continue");case"CallStatement":return aC(t,e,r);case"FilterStatement":return iC(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function rC(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+pt("if",ke(n[0].test))+nt+Ht(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=nt+s+pt("elif",ke(n[i].test))+nt+Ht(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=nt+s+pt("else")+nt+Ht(o.alternate,e+1,r)),a+=nt+s+pt("endif"),a}function sC(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+pt("for",ke(t.loopvar),"in",n)+nt+Ht(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=nt+s+pt("else")+nt+Ht(t.defaultBlock,e+1,r)),o+=nt+s+pt("endfor"),o}function nC(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+pt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+nt+Ht(t.body,e+1,r)+nt+s+pt("endset")}function oC(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+pt("macro",`${t.name.value}(${n})`)+nt+Ht(t.body,e+1,r)+nt+s+pt("endmacro")}function aC(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+pt(`call${n}`,o)+nt;return a+=Ht(t.body,e+1,r)+nt,a+=s+pt("endcall"),a}function iC(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+pt("filter",n)+nt;return o+=Ht(t.body,e+1,r)+nt,o+=s+pt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=ZI(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s<e?`(${a})`:a}case"UnaryExpression":{let r=t;return r.operator.value+(r.operator.value==="not"?" ":"")+ke(r.argument,1/0)}case"CallExpression":{let r=t,s=r.args.map(ke).join(", ");return`${ke(r.callee)}(${s})`}case"MemberExpression":{let r=t,s=ke(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ke(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{let r=t,s=ke(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ke(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{let r=t;return`${ke(r.lhs)} if ${ke(r.test)}`}case"TestExpression":{let r=t;return`${ke(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=t.value.map(ke),s=t.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([s,n])=>`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var Cv=class{parsed;constructor(t){let e=gI(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=FI(e)}render(t){let e=new Zr;if(KI(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new YI(e).run(this.parsed).value}format(t){return eC(this.parsed,t?.indent||" ")}};var Je=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function hr(t,e){t&&t(e)}function Pv(t){return Number.isInteger(t)||typeof t=="bigint"}function gp(t){return t==null||t===-1}function wp(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function dt(...t){return Array.prototype.concat.apply([],t)}function zv(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function $s(t,e){return Math.abs((t+e)%(2*e)-e)}function ot(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function Lv(t,e){let r=0;for(let s of t)s===e&&++r;return r}import _r from"fs";import xp from"path";var lC={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"},ts=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=_r.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=_r.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=_r.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",lC[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 _r.promises.readFile(this.filePath)).buffer}async blob(){let e=await _r.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await _r.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Rs=class{constructor(e){this.path=e}async match(e){let r=xp.join(this.path,e),s=new ts(r);if(s.exists)return s}async put(e,r,s=void 0){let n=xp.join(this.path,e);try{let o=r.headers.get("Content-Length"),a=parseInt(o??"0"),i=0;await _r.promises.mkdir(xp.dirname(n),{recursive:!0});let l=_r.createWriteStream(n),u=r.body.getReader();for(;;){let{done:d,value:f}=await u.read();if(d)break;await new Promise((_,w)=>{l.write(f,x=>{if(x){w(x);return}_()})}),i+=f.length;let m=a?i/a*100:0;s?.({progress:m,loaded:i,total:a})}l.close()}catch(o){try{await _r.promises.unlink(n)}catch{}throw o}}};var Nv={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"},Bi=100,$v=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Un(...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 Us(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 Rv(t){return!(!$v.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function Uv(t,e,r){if(!r)return null;let s=Nv[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function Bv(t,e){let r=t.headers.get("Content-Length");r===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let s=parseInt(r??"0"),n=new Uint8Array(s),o=0,a=t.body.getReader();async function i(){let{done:l,value:u}=await a.read();if(l)return;let d=o+u.length;if(d>s){s=d;let m=new Uint8Array(s);m.set(n),n=m}n.set(u,o),o=d;let f=o/s*100;return e({progress:f,loaded:o,total:s}),i()}return await i(),n}async function Di(t=null){let e=null;if(De.useCustomCache){if(!De.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!De.customCache.match||!De.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=De.customCache}if(!e&&De.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(De.cacheKey)}catch(r){console.warn("An error occurred while opening the browser cache:",r)}}if(!e&&De.useFSCache){if(!be.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Rs(t??De.cacheDir)}return e}async function Dv(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}async function Bs(t){if(De.useFS&&!Us(t,["http:","https:","blob:"]))return new ts(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t);if(typeof process<"u"&&process?.release?.name==="node"){let e=!!process.env?.TESTING_REMOTELY,r=De.version,s=new Headers;if(s.set("User-Agent",`transformers.js/${r}; is_ci/${e};`),Us(t,["http:","https:"],["huggingface.co","hf.co"])){let o=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;o&&s.set("Authorization",`Bearer ${o}`)}return fetch(t,{headers:s})}else return fetch(t)}function cC(t,e,r={},s=null){let n=r.revision??"main",o=Un(t,e),a=Rv(t),i=a?Un(De.localModelPath,o):o,l=Un(De.remoteHost,De.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),u=s instanceof Rs?n==="main"?o:Un(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:a}}async function uC(t,e,r){if(t)return await Dv(t,e,r)}async function pC(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o)typeof n!="string"&&await r.put(s,new Response(o,{headers:n.headers})).catch(i=>{console.warn(`Unable to add response to browser cache: ${i}.`)});else{let i=a.progress_callback?l=>hr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function dC(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:d}=cC(t,e,s,o),f,m=!1,_;_=await uC(o,i,u);let w=_!==void 0;if(!w){if(De.allowLocalModels)if(Us(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!De.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{_=await Bs(i),f=i}catch(M){console.warn(`Unable to load from local path "${i}": "${M}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!De.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Bs(l),_.status!==200)return Uv(_.status,l,r);f=u}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}hr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(be.IS_NODE_ENV&&n)){let E;typeof _!="string"&&(s.progress_callback?w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(E=new Uint8Array(await _.arrayBuffer()),hr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:E.length,total:E.length})):E=await Bv(_,M=>{hr(s.progress_callback,{status:"progress",name:t,file:e,...M})}):E=new Uint8Array(await _.arrayBuffer())),x=E}if(m&&f&&typeof _!="string"&&await pC(t,e,o,f,_,x,s),hr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!be.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof ts)return _.filePath;let k=await o?.match(f);if(k instanceof ts)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}async function Bn(t,e,r=!0,s={},n=!1){if(!De.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!De.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}hr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await Di(s?.cache_dir);return await dC(t,e,r,s,n,o)}async function yp(t,e,r=!0,s={}){let n=await Bn(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function at(t,e,r=!0,s={}){let n=await yp(t,e,r,s);return n===null?{}:JSON.parse(n)}function jv(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,u=n/r,d=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_<n;++_)for(let w=0;w<o;++w){let x=_*o+w,k=(w+.5)/l-.5,E=(_+.5)/u-.5,M=Math.floor(k),I=Math.floor(E),T=Math.min(M+1,s-1),z=Math.min(I+1,r-1);M=Math.max(M,0),I=Math.max(I,0);let C=k-M,v=E-I,G=(1-C)*(1-v),X=C*(1-v),V=(1-C)*v,Q=C*v,K=I*s,Y=z*s,B=K+M,P=K+T,se=Y+M,ie=Y+T;for(let S=0;S<e;++S){let L=S*f;d[S*m+x]=G*t[L+B]+X*t[L+P]+V*t[L+se]+Q*t[L+ie]}}return d}function Gv(t,e,r){let s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i<t.length;++i){let l=0;for(let u=e.length-1,d=i;u>=0;--u)l+=d%e[u]*o[u],d=Math.floor(d/e[u]);a[l]=t[i]}return[a,s]}function Pe(t){let e=Te(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 vp(t){let e=Te(t)[0],r=0;for(let o=0;o<t.length;++o)r+=Math.exp(t[o]-e);let s=Math.log(r);return t.map(o=>o-e-s)}function qv(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function fC(t,e){let r=qv(t,e),s=Fv(t),n=Fv(e);return r/(s*n)}function Fv(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function Dn(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}function Te(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]>e&&(e=t[s],r=s);return[e,r]}function Wv(t){return t>0&&(t&t-1)===0}var Fi=class{constructor(e){if(this.size=e|0,this.size<=1||!Wv(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;s<this.table.length;s+=2){let n=Math.PI*s/this.size;this.table[s]=Math.cos(n),this.table[s+1]=-Math.sin(n)}let r=0;for(let s=1;this.size>s;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<<this._width);for(let s=0;s<this._bitrev.length;++s){this._bitrev[s]=0;for(let n=0;n<this._width;n+=2){let o=this._width-n-2;this._bitrev[s]|=(s>>>n&3)<<o}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,r){let s=r||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)s[n>>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n<s.length;n+=2)s[n]=e[n>>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s<e.length;++s)e[s]/=this.size}_transform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,u,d=this._bitrev;if(i===4)for(l=0,u=0;l<n;l+=i,++u){let m=d[u];this._singleTransform2(r,e,l,m,a)}else for(l=0,u=0;l<n;l+=i,++u){let m=d[u];this._singleTransform4(r,e,l,m,a,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l<n;l+=i){let _=l+m-1;for(let w=l,x=0;w<_;w+=2,x+=a){let k=w,E=k+m,M=E+m,I=M+m,T=e[k],z=e[k+1],C=e[E],v=e[E+1],G=e[M],X=e[M+1],V=e[I],Q=e[I+1],K=f[x],Y=s*f[x+1],B=C*K-v*Y,P=C*Y+v*K,se=f[2*x],ie=s*f[2*x+1],S=G*se-X*ie,L=G*ie+X*se,R=f[3*x],te=s*f[3*x+1],ue=V*R-Q*te,Be=V*te+Q*R,Ce=T+S,vt=z+L,Qe=T-S,Ze=z-L,rt=B+ue,Me=P+Be,xe=s*(B-ue),Ge=s*(P-Be);e[k]=Ce+rt,e[k+1]=vt+Me,e[E]=Qe+Ge,e[E+1]=Ze-xe,e[M]=Ce-rt,e[M+1]=vt-Me,e[I]=Qe-Ge,e[I+1]=Ze+xe}}}}_singleTransform2(e,r,s,n,o){let a=e[n],i=e[n+1],l=e[n+o],u=e[n+o+1];r[s]=a+l,r[s+1]=i+u,r[s+2]=a-l,r[s+3]=i-u}_singleTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,u=e[n],d=e[n+1],f=e[n+o],m=e[n+o+1],_=e[n+i],w=e[n+i+1],x=e[n+l],k=e[n+l+1],E=u+_,M=d+w,I=u-_,T=d-w,z=f+x,C=m+k,v=a*(f-x),G=a*(m-k);r[s]=E+z,r[s+1]=M+C,r[s+2]=I+G,r[s+3]=T-v,r[s+4]=E-z,r[s+5]=M-C,r[s+6]=I-G,r[s+7]=T+v}_realTransform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,u,d=this._bitrev;if(i===4)for(l=0,u=0;l<n;l+=i,++u){let _=d[u];this._singleRealTransform2(r,e,l,_>>>1,a>>>1)}else for(l=0,u=0;l<n;l+=i,++u){let _=d[u];this._singleRealTransform4(r,e,l,_>>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l<n;l+=i)for(let k=0,E=0;k<=x;k+=2,E+=a){let M=l+k,I=M+w,T=I+w,z=T+w,C=e[M],v=e[M+1],G=e[I],X=e[I+1],V=e[T],Q=e[T+1],K=e[z],Y=e[z+1],B=C,P=v,se=f[E],ie=s*f[E+1],S=G*se-X*ie,L=G*ie+X*se,R=f[2*E],te=s*f[2*E+1],ue=V*R-Q*te,Be=V*te+Q*R,Ce=f[3*E],vt=s*f[3*E+1],Qe=K*Ce-Y*vt,Ze=K*vt+Y*Ce,rt=B+ue,Me=P+Be,xe=B-ue,Ge=P-Be,kt=S+Qe,ge=L+Ze,Le=s*(S-Qe),xr=s*(L-Ze);if(e[M]=rt+kt,e[M+1]=Me+ge,e[I]=xe+xr,e[I+1]=Ge-Le,k===0){e[T]=rt-kt,e[T+1]=Me-ge;continue}if(k===x)continue;let Hr=l+w-k,Et=l+_-k;e[Hr]=xe-s*xr,e[Hr+1]=-Ge-s*Le,e[Et]=rt-s*kt,e[Et+1]=-Me+s*ge}}let m=n>>>1;for(let _=2;_<m;_+=2)e[n-_]=e[_],e[n-_+1]=-e[_+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,u=e[n],d=e[n+o],f=e[n+i],m=e[n+l],_=u+f,w=u-f,x=d+m,k=a*(d-m);r[s]=_+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=_-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},bp=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),u=Math.sin(i);for(let d=0;d<s>>1;++d){let f=(d+1-e)**2/2,m=Math.sqrt(l**2+u**2)**f,_=f*Math.atan2(u,l),w=2*d;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 Fi(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,u=this._slicedChirpBuffer,d=this._a;if(s)for(let f=0;f<u.length;f+=2){let m=f+1,_=f>>1,w=r[_];n[f]=w*u[f],n[m]=w*u[m]}else for(let f=0;f<u.length;f+=2){let m=f+1;n[f]=r[f]*u[f]-r[m]*u[m],n[m]=r[f]*u[m]+r[m]*u[f]}this._f.transform(a,n);for(let f=0;f<l.length;f+=2){let m=f+1;o[f]=a[f]*l[f]-a[m]*l[m],o[m]=a[f]*l[m]+a[m]*l[f]}this._f.inverseTransform(i,o);for(let f=0;f<i.length;f+=2){let m=i[f+d],_=i[f+d+1],w=u[f],x=u[f+1];e[f]=m*w-_*x,e[f+1]=m*x+_*w}}transform(e,r){this._transform(e,r,!1)}realTransform(e,r){this._transform(e,r,!0)}},ji=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Wv(e),this.isPowerOfTwo?(this.fft=new Fi(e),this.outputBufferSize=2*e):(this.fft=new bp(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function Vv(t,e){if(e%2===0||e<=0)throw new Error("Window size must be a positive odd number");let r=new t.constructor(t.length),s=new t.constructor(e),n=Math.floor(e/2);for(let o=0;o<t.length;++o){let a=0;for(let i=-n;i<=n;++i){let l=o+i;l<0?l=Math.abs(l):l>=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function rs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function Hv(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function Xv(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 d=1;d<s[1];++d)for(let f=1;f<s[0];++f){let m=n[f-1][d-1],_=n[f-1][d],w=n[f][d-1],x,k;m<_&&m<w?(x=m,k=0):_<m&&_<w?(x=_,k=1):(x=w,k=2),n[f][d]=t[f-1][d-1]+x,o[f][d]=k}for(let d=0;d<s[1];++d)o[0][d]=2;for(let d=0;d<s[0];++d)o[d][0]=1;let a=e,i=r,l=[],u=[];for(;a>0||i>0;)switch(l.push(a-1),u.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(),u.reverse(),[l,u]}var Kv=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l<t.length;++l){let u=0,d=(l&32768)<<16,f=(l&31744)>>10,m=l&1023;if(f===31)u=d|2139095040|m<<13;else if(f===0)if(m===0)u=d;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,u=d|_<<23|m<<13}else u=d|f+112<<23|m<<13;a[0]=u,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;o<r;++o)n[o]=s[e[o]];return n}})();import*as GC from"onnxruntime-node";var dd={};Ps(dd,{InferenceSession:()=>Qp,TRACE:()=>Qi,TRACE_EVENT_BEGIN:()=>Mr,TRACE_EVENT_END:()=>Tr,TRACE_FUNC_BEGIN:()=>ls,TRACE_FUNC_END:()=>cs,Tensor:()=>Kt,default:()=>jC,env:()=>We,registerBackend:()=>is});var Kp=Object.defineProperty,mC=Object.getOwnPropertyDescriptor,hC=Object.getOwnPropertyNames,_C=Object.prototype.hasOwnProperty,gC=(t=>typeof Jr<"u"?Jr:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Jr<"u"?Jr:e)[r]}):t)(function(t){if(typeof Jr<"u")return Jr.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ye=(t,e)=>()=>(t&&(e=t(t=0)),e),Xn=(t,e)=>{for(var r in e)Kp(t,r,{get:e[r],enumerable:!0})},wC=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of hC(e))!_C.call(t,n)&&n!==r&&Kp(t,n,{get:()=>e[n],enumerable:!(s=mC(e,n))||s.enumerable});return t},Yi=t=>wC(Kp({},"__esModule",{value:!0}),t),Fn,vr,is,Yv,kk,Ek=ye(()=>{"use strict";Fn=new Map,vr=[],is=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Fn.get(t);if(s===void 0)Fn.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<vr.length;o++)if(Fn.get(vr[o]).priority<=r){vr.splice(o,0,t);return}vr.push(t)}return}throw new TypeError("not a valid backend")},Yv=async t=>{let e=Fn.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}}},kk=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 u=await Yv(l);typeof u=="string"?o.push({name:l,err:u}):(n||(n=u),n===u&&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:u}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,u)=>u==="executionProviders"?i:Reflect.get(l,u)})]}}),xC=ye(()=>{"use strict";Ek()}),Ak,yC=ye(()=>{"use strict";Ak="1.24.1"}),kp,ct,Mk=ye(()=>{"use strict";yC(),kp="warning",ct={wasm:{},webgl:{},webgpu:{},versions:{common:Ak},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}`);kp=t}},get logLevel(){return kp}},Object.defineProperty(ct,"logLevel",{enumerable:!0})}),We,bC=ye(()=>{"use strict";Mk(),We=ct}),Tk,Sk,vC=ye(()=>{"use strict";Tk=(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,u;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?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));let d=o*n,f=0,m=d,_=d*2,w=-1;a==="RGBA"?(f=0,m=d,_=d*2,w=d*3):a==="RGB"?(f=0,m=d,_=d*2):a==="RBG"&&(f=0,_=d,m=d*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let E=(t.data[f++]-u[0])*l[0],M=(t.data[m++]-u[1])*l[1],I=(t.data[_++]-u[2])*l[2],T=w===-1?255:(t.data[w++]-u[3])*l[3];s.fillStyle="rgba("+E+","+M+","+I+","+T+")",s.fillRect(k,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Sk=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,u,d;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[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,k=3,E=0,M=f,I=f*2,T=-1;i==="RGBA"?(E=0,M=f,I=f*2,T=f*3):i==="RGB"?(E=0,M=f,I=f*2):i==="RBG"&&(E=0,I=f,M=f*2),s=r.createImageData(n,o);for(let z=0;z<o*n;_+=m,w+=m,x+=m,k+=m,z++)s.data[_]=(t.data[E++]-d[0])*u[0],s.data[w]=(t.data[M++]-d[1])*u[1],s.data[x]=(t.data[I++]-d[2])*u[2],s.data[k]=T===-1?255:(t.data[T++]-d[3])*u[3]}else throw new Error("Can not access image data");return s}}),Gi,Ok,Ik,Ck,Pk,zk,kC=ye(()=>{"use strict";Yp(),Gi=(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",u=r*s,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),f=4,m=0,_=1,w=2,x=3,k=0,E=u,M=u*2,I=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?I=u*3:l==="RBG"?(k=0,M=u,E=u*2):l==="BGR"&&(M=0,E=u,k=u*2);for(let T=0;T<u;T++,m+=f,w+=f,_+=f,x+=f)d[k++]=(t[m]+a[0])/o[0],d[E++]=(t[_]+a[1])/o[1],d[M++]=(t[w]+a[2])/o[2],I!==-1&&x!==-1&&(d[I++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new Ct("float32",d,[1,4,r,s]):new Ct("float32",d,[1,3,r,s])},Ok=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=t.width,d.height=t.height;let f=u(d);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 d,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(d=e.resizedHeight,f=e.resizedWidth):(d=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=d,i.width=f,e!==void 0){let m=l();m.width=f,m.height=d;let _=u(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,d).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 d=l();d.width=t.width,d.height=t.height;let f=u(d);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=_,Gi(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((d,f)=>{let m=l(),_=u(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,d(Gi(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Gi(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Ik=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Ct({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},Ck=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Ct({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},Pk=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Ct({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},zk=(t,e,r)=>new Ct({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),os,Vn,Ep,Lk,EC=ye(()=>{"use strict";os=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Vn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ep=!1,Lk=()=>{if(!Ep){Ep=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(os.set("int64",BigInt64Array),Vn.set(BigInt64Array,"int64")),e&&(os.set("uint64",BigUint64Array),Vn.set(BigUint64Array,"uint64")),s?(os.set("float16",r),Vn.set(r,"float16")):os.set("float16",Uint16Array)}}}),Nk,$k,AC=ye(()=>{"use strict";Yp(),Nk=t=>{let e=1;for(let r=0;r<t.length;r++){let s=t[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);e*=s}return e},$k=(t,e)=>{switch(t.location){case"cpu":return new Ct(t.type,t.data,e);case"cpu-pinned":return new Ct({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Ct({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Ct({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Ct({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Ct,Yp=ye(()=>{"use strict";vC(),kC(),EC(),AC(),Ct=class{constructor(t,e,r){Lk();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=os.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=os.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=Vn.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=Nk(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 Ok(t,e)}static fromTexture(t,e){return Ik(t,e)}static fromGpuBuffer(t,e){return Ck(t,e)}static fromMLTensor(t,e){return Pk(t,e)}static fromPinnedBuffer(t,e,r){return zk(t,e,r)}toDataURL(t){return Tk(this,t)}toImageData(t){return Sk(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 $k(this,t)}}}),Kt,Rk=ye(()=>{"use strict";Yp(),Kt=Ct}),Qi,Ap,ls,cs,Mr,Tr,Uk=ye(()=>{"use strict";Mk(),Qi=(t,e)=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeStamp(`${t}::ORT::${e}`)},Ap=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n<r.length;n++){if(s&&!r[n].includes("TRACE_FUNC")){let o=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(o+=`::${e}`),Qi("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},ls=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Ap("BEGIN",t)},cs=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Ap("END",t)},Mr=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.time(`ORT::${t}`)},Tr=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeEnd(`ORT::${t}`)}}),Bk,MC=ye(()=>{"use strict";Ek(),Rk(),Uk(),Bk=class Dk{constructor(e){this.handler=e}async run(e,r,s){ls(),Mr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Kt||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 Kt)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 u of r){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);n[u]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,d=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(d.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof Kt)&&(u=!0,a=!1,n[f]=m)}if(u){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 u of this.inputNames)if(typeof e[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(a)for(let u of this.outputNames)n[u]=null;let i=await this.handler.run(e,n,o),l={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let d=i[u];d instanceof Kt?l[u]=d:l[u]=new Kt(d.type,d.data,d.dims)}return Tr("InferenceSession.run"),cs(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ls(),Mr("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 d=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>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.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>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.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(d,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await kk(a),u=await i.createInferenceSessionHandler(o,l);return Tr("InferenceSession.create"),cs(),new Dk(u)}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}}}),Qp,TC=ye(()=>{"use strict";MC(),Qp=Bk}),SC=ye(()=>{"use strict"}),OC=ye(()=>{"use strict"}),IC=ye(()=>{"use strict"}),CC=ye(()=>{"use strict"}),Fk={};Xn(Fk,{InferenceSession:()=>Qp,TRACE:()=>Qi,TRACE_EVENT_BEGIN:()=>Mr,TRACE_EVENT_END:()=>Tr,TRACE_FUNC_BEGIN:()=>ls,TRACE_FUNC_END:()=>cs,Tensor:()=>Kt,env:()=>We,registerBackend:()=>is});var us=ye(()=>{"use strict";xC(),bC(),TC(),Rk(),SC(),OC(),Uk(),IC(),CC()}),Jp=ye(()=>{"use strict"}),jk={};Xn(jk,{default:()=>Gk});var Mp,Tp,Gk,PC=ye(()=>{"use strict";nE(),ps(),Zp(),Mp="ort-wasm-proxy-worker",Tp=globalThis.self?.name===Mp,Tp&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":ed(r.wasm).then(()=>{od(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;ad(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=el(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;id(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":ld(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;cd(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(u=>u[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},pd([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":ud(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),Gk=Tp?null:t=>new Worker(t??Ot,{type:"module",name:Mp})}),qk={};Xn(qk,{default:()=>Wk});async function Qv(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(c,p)=>{c.startsWith("./")&&(c=c.substring(2)),(e.Zc||(e.Zc=new Map)).set(c,p)},e.unmountExternalData=()=>{delete e.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Me:!0}).buffer.constructor;let o=()=>{let c=p=>(...h)=>{let g=er;return h=p(...h),er!=g?new Promise((b,A)=>{Hu={resolve:b,reject:A}}):h};(()=>{for(let p of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[p]=c(e[p])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(c,p)=>{throw p},u=import.meta.url,d="";if(r||s){try{d=new URL(".",u).href}catch{}s&&(i=c=>{var p=new XMLHttpRequest;return p.open("GET",c,!1),p.responseType="arraybuffer",p.send(null),new Uint8Array(p.response)}),a=async c=>{if(C(c))return new Promise((h,g)=>{var b=new XMLHttpRequest;b.open("GET",c,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?h(b.response):g(b.status)},b.onerror=g,b.send(null)});var p=await fetch(c,{credentials:"same-origin"});if(p.ok)return p.arrayBuffer();throw Error(p.status+" : "+p.url)}}var f,m,_,w,x,k,E=console.log.bind(console),M=console.error.bind(console),I=E,T=M,z=!1,C=c=>c.startsWith("file://");function v(){yr.buffer!=V.buffer&&ue()}if(n){let c=function(p){try{var h=p.data,g=h.Uc;if(g==="load"){let b=[];self.onmessage=A=>b.push(A),k=()=>{postMessage({Uc:"loaded"});for(let A of b)c(A);self.onmessage=c};for(let A of h.ne)e[A]&&!e[A].proxy||(e[A]=(...O)=>{postMessage({Uc:"callHandler",me:A,args:O})},A=="print"&&(I=e[A]),A=="printErr"&&(T=e[A]));yr=h.we,ue(),m=h.xe,Qe(),Pi()}else if(g==="run"){(function(b){var A=(v(),P)[b+52>>>2>>>0];b=(v(),P)[b+56>>>2>>>0],a1(A,A-b),oe(A)})(h.Sc),op(h.Sc,0,0,1,0,0),W0(),qu(h.Sc),X||(jb(),X=!0);try{WA(h.te,h.ad)}catch(b){if(b!="unwind")throw b}}else h.target!=="setimmediate"&&(g==="checkMailbox"?X&&vi():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(b){throw t1(),b}};var G=c,X=!1;self.onunhandledrejection=p=>{throw p.reason||p},self.onmessage=c}var V,Q,K,Y,B,P,se,ie,S,L,R,te=!1;function ue(){var c=yr.buffer;e.HEAP8=V=new Int8Array(c),K=new Int16Array(c),e.HEAPU8=Q=new Uint8Array(c),Y=new Uint16Array(c),e.HEAP32=B=new Int32Array(c),e.HEAPU32=P=new Uint32Array(c),se=new Float32Array(c),ie=new Float64Array(c),S=new BigInt64Array(c),L=new BigUint64Array(c)}function Be(){te=!0,n?k():fr.dc()}function Ce(c){throw T(c="Aborted("+c+")"),z=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),x?.(c),c}function vt(){return{a:{sa:iT,g:VA,K:HA,f:XA,n:KA,h:YA,wa:QA,b:JA,ea:ZA,Ja:Q0,o:e2,fa:tb,Za:rb,$b:sb,bc:nb,_a:ob,Xa:ab,Qa:ib,Wa:lb,qa:cb,ac:ub,Zb:pb,Ya:db,_b:fb,db:t2,Fa:s2,Ub:n2,Sb:a2,Ea:l2,P:c2,I:u2,Tb:p2,ma:w2,Vb:x2,Ta:y2,Xb:v2,Ka:k2,Pb:E2,Ha:A2,Sa:qu,ab:M2,W:I2,r:N2,c:ju,tb:$2,y:R2,N:U2,D:B2,m:D2,t:bb,ub:F2,J:j2,V:G2,j:q2,u:W2,q:V2,l:H2,Na:X2,Oa:K2,Pa:Y2,La:Ab,Ma:Mb,Rb:Tb,fb:J2,cb:tM,$:rM,sb:sM,na:nM,bb:Z2,Y:oM,$a:aM,Yb:iM,G:Q2,ib:lM,_:cM,ra:Ti,Wb:pM,hb:uM,gb:dM,pb:xM,F:yM,va:bM,ua:vM,rb:kM,Z:EM,w:AM,ob:MM,nb:TM,mb:SM,qb:OM,lb:IM,kb:CM,jb:PM,Ua:Nb,Va:$b,Ia:Et,ga:Rb,pa:Ub,Ra:Bb,oa:Db,Eb:qT,za:RT,Fb:GT,Aa:$T,H:TT,e:pT,s:cT,x:lT,B:bT,Ib:zT,L:ET,v:fT,Ba:LT,ca:UT,ja:PT,Gb:jT,Hb:FT,Da:ST,Ca:CT,Kb:OT,O:AT,da:NT,d:dT,A:mT,k:uT,Db:WT,p:_T,z:yT,C:hT,E:gT,M:vT,Lb:MT,U:BT,ka:kT,ba:DT,Mb:xT,Nb:wT,R:IT,i:LM,a:yr,eb:xr,Jb:NM,la:$M,Q:RM,ta:UM,Ob:BM,S:DM,Ab:FM,Bb:jM,xa:GM,ha:qM,T:WM,Ga:VM,ya:HM,aa:XM,yb:KM,cc:YM,X:QM,Cb:JM,vb:ZM,wb:tT,xb:rT,ia:sT,zb:nT,Qb:oT}}}async function Qe(){function c(g,b){var A=fr=g.exports;g={};for(let[O,N]of Object.entries(A))typeof N=="function"?(A=T2(N),g[O]=A):g[O]=N;return fr=g,fr=(function(){var O=fr,N=q=>fe=>q(fe)>>>0,D=q=>()=>q()>>>0;return(O=Object.assign({},O)).ec=N(O.ec),O.Hc=D(O.Hc),O.Jc=N(O.Jc),O.vd=(q=>(fe,me)=>q(fe,me)>>>0)(O.vd),O.Ad=N(O.Ad),O.Bd=D(O.Bd),O.Fd=N(O.Fd),O})(),G0.push(fr.md),Fb=(g=fr).ec,jb=g.fc,e._OrtInit=g.gc,e._OrtGetLastError=g.hc,e._OrtCreateSessionOptions=g.ic,e._OrtAppendExecutionProvider=g.jc,e._OrtAddFreeDimensionOverride=g.kc,e._OrtAddSessionConfigEntry=g.lc,e._OrtReleaseSessionOptions=g.mc,e._OrtCreateSession=g.nc,e._OrtReleaseSession=g.oc,e._OrtGetInputOutputCount=g.pc,e._OrtGetInputOutputMetadata=g.qc,e._OrtFree=g.rc,e._OrtCreateTensor=g.sc,e._OrtGetTensorData=g.tc,e._OrtReleaseTensor=g.uc,e._OrtCreateRunOptions=g.vc,e._OrtAddRunConfigEntry=g.wc,e._OrtReleaseRunOptions=g.xc,e._OrtCreateBinding=g.yc,e._OrtBindInput=g.zc,e._OrtBindOutput=g.Ac,e._OrtClearBoundOutputs=g.Bc,e._OrtReleaseBinding=g.Cc,e._OrtRunWithBinding=g.Dc,e._OrtRun=g.Ec,e._OrtEndProfiling=g.Fc,Zu=e._OrtGetWebGpuDevice=g.Gc,Ii=g.Hc,Lt=e._free=g.Ic,Cs=e._malloc=g.Jc,Gb=e._wgpuBufferRelease=g.Kc,qb=e._wgpuCreateInstance=g.Lc,Wb=g.Mc,Vb=g.Nc,Hb=g.Oc,Xb=g.Pc,Kb=g.Qc,Yb=g.Tc,Qb=g.bd,Jb=g.cd,Zb=g.dd,ep=g.fd,tp=g.gd,rp=g.hd,sp=g.id,In=g.jd,np=g.kd,e1=g.ld,op=g.od,t1=g.pd,r1=g.qd,s1=g.rd,ap=g.sd,n1=g.td,o1=g.ud,ip=g.vd,he=g.wd,Cn=g.xd,a1=g.yd,oe=g.zd,Ci=g.Ad,ae=g.Bd,i1=g.Cd,lp=g.Dd,l1=g.Ed,c1=g.Fd,u1=g.Gd,cp=g.Hd,p1=g.Id,d1=g.Jd,f1=g.Kd,m1=g.Ld,h1=g.Md,_1=g.Nd,g1=g.Od,w1=g.Pd,x1=g.Qd,y1=g.Rd,b1=g.Sd,v1=g.Td,k1=g.Ud,E1=g.Vd,A1=g.Wd,M1=g.Yd,T1=g.Zd,S1=g._d,O1=g.$d,I1=g.be,C1=g.ce,P1=g.de,z1=g.ee,L1=g.fe,N1=g.ge,$1=g.qe,R1=g.ve,U1=g.ye,B1=g.ze,D1=g.Ae,F1=g.Be,j1=g.Ce,G1=g.De,q1=g.Ee,W1=g.Fe,V1=g.Ge,H1=g.ef,X1=g.ff,K1=g.gf,Y1=g.hf,m=b,fr}var p,h=vt();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(b,A)=>{g(c(b,A))})}):n?c(new WebAssembly.Instance(m,vt()),m):(R??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,p=await(async function(g){var b=R;if(!f&&!C(b))try{var A=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(A,g)}catch(O){T(`wasm streaming compile failed: ${O}`),T("falling back to ArrayBuffer instantiation")}return(async function(O,N){try{var D=await(async function(q){if(!f)try{var fe=await a(q);return new Uint8Array(fe)}catch{}if(q==R&&f)q=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";q=i(q)}return q})(O);return await WebAssembly.instantiate(D,N)}catch(q){T(`failed to asynchronously prepare wasm: ${q}`),Ce(q)}})(b,g)})(h),c(p.instance,p.module))}class Ze{name="ExitStatus";constructor(p){this.message=`Program terminated with exit(${p})`,this.status=p}}var rt=c=>{c.terminate(),c.onmessage=()=>{}},Me=[],xe=0,Ge=null,kt=c=>{et.length==0&&(H0(),V0(et[0]));var p=et.pop();if(!p)return 6;Sn.push(p),Xr[c.Sc]=p,p.Sc=c.Sc;var h={Uc:"run",te:c.se,ad:c.ad,Sc:c.Sc};return p.postMessage(h,c.he),0},ge=0,Le=(c,p,...h)=>{var g,b=16*h.length,A=ae(),O=Ci(b),N=O>>>3;for(g of h)typeof g=="bigint"?((v(),S)[N++>>>0]=1n,(v(),S)[N++>>>0]=g):((v(),S)[N++>>>0]=0n,(v(),ie)[N++>>>0]=g);return c=r1(c,0,b,O,p),oe(A),c};function xr(c){if(n)return Le(0,1,c);if(_=c,!(0<ge)){for(var p of Sn)rt(p);for(p of et)rt(p);et=[],Sn=[],Xr={},z=!0}l(0,new Ze(c))}function Hr(c){if(n)return Le(1,0,c);Et(c)}var Et=c=>{if(_=c,n)throw Hr(c),"unwind";xr(c)},et=[],Sn=[],G0=[],Xr={},q0=c=>{var p=c.Sc;delete Xr[p],et.push(c),Sn.splice(Sn.indexOf(c),1),c.Sc=0,s1(p)};function W0(){G0.forEach(c=>c())}var V0=c=>new Promise(p=>{c.onmessage=b=>{var A=b.data;if(b=A.Uc,A.$c&&A.$c!=Ii()){var O=Xr[A.$c];O?O.postMessage(A,A.he):T(`Internal error! Worker sent a message "${b}" to target pthread ${A.$c}, but that thread no longer exists!`)}else b==="checkMailbox"?vi():b==="spawnThread"?kt(A):b==="cleanupThread"?bi(()=>{q0(Xr[A.ue])}):b==="loaded"?(c.loaded=!0,p(c)):A.target==="setimmediate"?c.postMessage(A):b==="uncaughtException"?c.onerror(A.error):b==="callHandler"?e[A.me](...A.args):b&&T(`worker sent an unknown command ${b}`)},c.onerror=b=>{throw T(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);c.postMessage({Uc:"load",ne:g,we:yr,xe:m})});function H0(){var c=new Worker((()=>{let p=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new p("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});et.push(c)}var yr,WA=(c,p)=>{ge=0,c=cp(c,p),0<ge?_=c:ap(c)},xi=[],yi=0,wt=c=>-9007199254740992>c||9007199254740992<c?NaN:Number(c);function VA(c){var p=new Uu(c>>>=0);return(v(),V)[p.Vc+12>>>0]==0&&(X0(p,!0),yi--),K0(p,!1),xi.push(p),c1(c)}var Ms=0,HA=()=>{he(0,0);var c=xi.pop();i1(c.nd),Ms=0};function X0(c,p){p=p?1:0,(v(),V)[c.Vc+12>>>0]=p}function K0(c,p){p=p?1:0,(v(),V)[c.Vc+13>>>0]=p}class Uu{constructor(p){this.nd=p,this.Vc=p-24}}var Bu=c=>{var p=Ms;if(!p)return Cn(0),0;var h=new Uu(p);(v(),P)[h.Vc+16>>>2>>>0]=p;var g=(v(),P)[h.Vc+4>>>2>>>0];if(!g)return Cn(0),p;for(var b of c){if(b===0||b===g)break;if(l1(b,g,h.Vc+16))return Cn(b),p}return Cn(g),p};function XA(){return Bu([])}function KA(c){return Bu([c>>>0])}function YA(c,p,h,g){return Bu([c>>>0,p>>>0,h>>>0,g>>>0])}var QA=()=>{var c=xi.pop();c||Ce("no exception to throw");var p=c.nd;throw(v(),V)[c.Vc+13>>>0]==0&&(xi.push(c),K0(c,!0),X0(c,!1),yi++),lp(p),Ms=p};function JA(c,p,h){var g=new Uu(c>>>=0);throw p>>>=0,h>>>=0,(v(),P)[g.Vc+16>>>2>>>0]=0,(v(),P)[g.Vc+4>>>2>>>0]=p,(v(),P)[g.Vc+8>>>2>>>0]=h,lp(c),yi++,Ms=c}var ZA=()=>yi;function Y0(c,p,h,g){return n?Le(2,1,c,p,h,g):Q0(c,p,h,g)}function Q0(c,p,h,g){if(c>>>=0,p>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?Y0(c,p,h,g):(c={se:h,Sc:c,ad:g,he:b},n?(c.Uc="spawnThread",postMessage(c,b),0):kt(c))}function e2(c){throw Ms||=c>>>0,Ms}var J0=globalThis.TextDecoder&&new TextDecoder,Z0=(c,p,h,g)=>{if(h=p+h,g)return h;for(;c[p]&&!(p>=h);)++p;return p},eb=(c,p=0,h,g)=>{if(16<(h=Z0(c,p>>>=0,h,g))-p&&c.buffer&&J0)return J0.decode(c.buffer instanceof ArrayBuffer?c.subarray(p,h):c.slice(p,h));for(g="";p<h;){var b=c[p++];if(128&b){var A=63&c[p++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|A);else{var O=63&c[p++];65536>(b=(240&b)==224?(15&b)<<12|A<<6|O:(7&b)<<18|A<<12|O<<6|63&c[p++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},Ts=(c,p,h)=>(c>>>=0)?eb((v(),Q),c,p,h):"";function tb(c,p,h){return n?Le(3,1,c,p,h):0}function rb(c,p){if(n)return Le(4,1,c,p)}function sb(c,p){if(n)return Le(5,1,c,p)}function nb(c,p,h){if(n)return Le(6,1,c,p,h)}function ob(c,p,h){return n?Le(7,1,c,p,h):0}function ab(c,p){if(n)return Le(8,1,c,p)}function ib(c,p,h){if(n)return Le(9,1,c,p,h)}function lb(c,p,h,g){if(n)return Le(10,1,c,p,h,g)}function cb(c,p,h,g){if(n)return Le(11,1,c,p,h,g)}function ub(c,p,h,g){if(n)return Le(12,1,c,p,h,g)}function pb(c){if(n)return Le(13,1,c)}function db(c,p){if(n)return Le(14,1,c,p)}function fb(c,p,h){if(n)return Le(15,1,c,p,h)}var t2=()=>Ce(""),Zt=c=>{c>>>=0;for(var p="";;){var h=(v(),Q)[c++>>>0];if(!h)return p;p+=String.fromCharCode(h)}},Du={},Fu={},r2={},Ss=class extends Error{constructor(c){super(c),this.name="BindingError"}};function cr(c,p,h={}){return(function(g,b,A={}){var O=b.name;if(!g)throw new Ss(`type "${O}" must have a positive integer typeid pointer`);if(Fu.hasOwnProperty(g)){if(A.oe)return;throw new Ss(`Cannot register type '${O}' twice`)}Fu[g]=b,delete r2[g],Du.hasOwnProperty(g)&&(b=Du[g],delete Du[g],b.forEach(N=>N()))})(c,p,h)}var mb=(c,p,h)=>{switch(p){case 1:return h?g=>(v(),V)[g>>>0]:g=>(v(),Q)[g>>>0];case 2:return h?g=>(v(),K)[g>>>1>>>0]:g=>(v(),Y)[g>>>1>>>0];case 4:return h?g=>(v(),B)[g>>>2>>>0]:g=>(v(),P)[g>>>2>>>0];case 8:return h?g=>(v(),S)[g>>>3>>>0]:g=>(v(),L)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${p}): ${c}`)}};function s2(c,p,h,g,b){c>>>=0,h>>>=0,p=Zt(p>>>0);let A=O=>O;if(g=g===0n){let O=8*h;A=N=>BigInt.asUintN(O,N),b=A(b)}cr(c,{name:p,Rc:A,Xc:(O,N)=>(typeof N=="number"&&(N=BigInt(N)),N),Wc:mb(p,h,!g),Yc:null})}function n2(c,p,h,g){cr(c>>>=0,{name:p=Zt(p>>>0),Rc:function(b){return!!b},Xc:function(b,A){return A?h:g},Wc:function(b){return this.Rc((v(),Q)[b>>>0])},Yc:null})}var hb=[],Kr=[0,1,,1,null,1,!0,1,!1,1];function ju(c){9<(c>>>=0)&&--Kr[c+1]==0&&(Kr[c]=void 0,hb.push(c))}var zt=c=>{if(!c)throw new Ss(`Cannot use deleted val. handle = ${c}`);return Kr[c]},qt=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let p=hb.pop()||Kr.length;return Kr[p]=c,Kr[p+1]=1,p}};function Gu(c){return this.Rc((v(),P)[c>>>2>>>0])}var o2={name:"emscripten::val",Rc:c=>{var p=zt(c);return ju(c),p},Xc:(c,p)=>qt(p),Wc:Gu,Yc:null};function a2(c){return cr(c>>>0,o2)}var i2=(c,p)=>{switch(p){case 4:return function(h){return this.Rc((v(),se)[h>>>2>>>0])};case 8:return function(h){return this.Rc((v(),ie)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${p}): ${c}`)}};function l2(c,p,h){h>>>=0,cr(c>>>=0,{name:p=Zt(p>>>0),Rc:g=>g,Xc:(g,b)=>b,Wc:i2(p,h),Yc:null})}function c2(c,p,h,g,b){c>>>=0,h>>>=0,p=Zt(p>>>0);let A=N=>N;if(g===0){var O=32-8*h;A=N=>N<<O>>>O,b=A(b)}cr(c,{name:p,Rc:A,Xc:(N,D)=>D,Wc:mb(p,h,g!==0),Yc:null})}function u2(c,p,h){function g(A){var O=(v(),P)[A>>>2>>>0];return A=(v(),P)[A+4>>>2>>>0],new b((v(),V).buffer,A,O)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][p];cr(c>>>=0,{name:h=Zt(h>>>0),Rc:g,Wc:g},{oe:!0})}var ur=(c,p,h)=>{var g=(v(),Q);if(p>>>=0,0<h){var b=p;h=p+h-1;for(var A=0;A<c.length;++A){var O=c.codePointAt(A);if(127>=O){if(p>=h)break;g[p++>>>0]=O}else if(2047>=O){if(p+1>=h)break;g[p++>>>0]=192|O>>6,g[p++>>>0]=128|63&O}else if(65535>=O){if(p+2>=h)break;g[p++>>>0]=224|O>>12,g[p++>>>0]=128|O>>6&63,g[p++>>>0]=128|63&O}else{if(p+3>=h)break;g[p++>>>0]=240|O>>18,g[p++>>>0]=128|O>>12&63,g[p++>>>0]=128|O>>6&63,g[p++>>>0]=128|63&O,A++}}g[p>>>0]=0,c=p-b}else c=0;return c},pr=c=>{for(var p=0,h=0;h<c.length;++h){var g=c.charCodeAt(h);127>=g?p++:2047>=g?p+=2:55296<=g&&57343>=g?(p+=4,++h):p+=3}return p};function p2(c,p){cr(c>>>=0,{name:p=Zt(p>>>0),Rc(h){var g=(v(),P)[h>>>2>>>0];return g=Ts(h+4,g,!0),Lt(h),g},Xc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var b=typeof g=="string";if(!(b||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Ss("Cannot pass non-string to std::string");var A=b?pr(g):g.length,O=Cs(4+A+1),N=O+4;return(v(),P)[O>>>2>>>0]=A,b?ur(g,N,A+1):(v(),Q).set(g,N>>>0),h!==null&&h.push(Lt,O),O},Wc:Gu,Yc(h){Lt(h)}})}var _b=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,d2=(c,p,h)=>{if(c>>>=1,16<(p=Z0((v(),Y),c,p/2,h))-c&&_b)return _b.decode((v(),Y).slice(c,p));for(h="";c<p;++c){var g=(v(),Y)[c>>>0];h+=String.fromCharCode(g)}return h},f2=(c,p,h)=>{if(h??=2147483647,2>h)return 0;var g=p;h=(h-=2)<2*c.length?h/2:c.length;for(var b=0;b<h;++b){var A=c.charCodeAt(b);(v(),K)[p>>>1>>>0]=A,p+=2}return(v(),K)[p>>>1>>>0]=0,p-g},m2=c=>2*c.length,h2=(c,p,h)=>{var g="";c>>>=2;for(var b=0;!(b>=p/4);b++){var A=(v(),P)[c+b>>>0];if(!A&&!h)break;g+=String.fromCodePoint(A)}return g},_2=(c,p,h)=>{if(p>>>=0,h??=2147483647,4>h)return 0;var g=p;h=g+h-4;for(var b=0;b<c.length;++b){var A=c.codePointAt(b);if(65535<A&&b++,(v(),B)[p>>>2>>>0]=A,(p+=4)+4>h)break}return(v(),B)[p>>>2>>>0]=0,p-g},g2=c=>{for(var p=0,h=0;h<c.length;++h)65535<c.codePointAt(h)&&h++,p+=4;return p};function w2(c,p,h){if(c>>>=0,p>>>=0,h=Zt(h>>>=0),p===2)var g=d2,b=f2,A=m2;else g=h2,b=_2,A=g2;cr(c,{name:h,Rc:O=>{var N=(v(),P)[O>>>2>>>0];return N=g(O+4,N*p,!0),Lt(O),N},Xc:(O,N)=>{if(typeof N!="string")throw new Ss(`Cannot pass non-string to C++ string type ${h}`);var D=A(N),q=Cs(4+D+p);return(v(),P)[q>>>2>>>0]=D/p,b(N,q+4,D+p),O!==null&&O.push(Lt,q),q},Wc:Gu,Yc(O){Lt(O)}})}function x2(c,p){cr(c>>>=0,{pe:!0,name:p=Zt(p>>>0),Rc:()=>{},Xc:()=>{}})}function y2(c){op(c>>>0,!s,1,!r,131072,!1),W0()}var bi=c=>{if(!z)try{if(c(),!(0<ge))try{n?Ii()&&ap(_):Et(_)}catch(p){p instanceof Ze||p=="unwind"||l(0,p)}}catch(p){p instanceof Ze||p=="unwind"||l(0,p)}},b2=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function qu(c){c>>>=0,b2||(Atomics.waitAsync((v(),B),c>>>2,c).value.then(vi),c+=128,Atomics.store((v(),B),c>>>2,1))}var vi=()=>bi(()=>{var c=Ii();c&&(qu(c),o1())});function v2(c,p){(c>>>=0)==p>>>0?setTimeout(vi):n?postMessage({$c:c,Uc:"checkMailbox"}):(c=Xr[c])&&c.postMessage({Uc:"checkMailbox"})}var Wu=[];function k2(c,p,h,g,b){for(p>>>=0,b>>>=0,Wu.length=0,h=b>>>3,g=b+g>>>3;h<g;){var A;A=(v(),S)[h++>>>0]?(v(),S)[h++>>>0]:(v(),ie)[h++>>>0],Wu.push(A)}return(p?up[p]:aT[c])(...Wu)}var E2=()=>{ge=0};function A2(c){c>>>=0,n?postMessage({Uc:"cleanupThread",ue:c}):q0(Xr[c])}function M2(c){}var ki=c=>{try{c()}catch(p){Ce(p)}};function T2(c){var p=(...h)=>{Ei.push(c);try{return c(...h)}finally{z||(Ei.pop(),er&&br===1&&Ei.length===0&&(br=0,ge+=1,ki(X1),typeof Fibers<"u"&&Fibers.Oe()))}};return xb.set(c,p),p}var br=0,er=null,gb=0,Ei=[],Vu=new Map,wb=new Map,xb=new Map,S2=0,Hu=null,O2=[],yb=c=>(function(p){if(!z){if(br===0){var h=!1,g=!1;p((b=0)=>{if(!z&&(gb=b,h=!0,g)){br=2,ki(()=>K1(er)),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.resume(),b=!1;try{var A=(function(){var D=(v(),B)[er+8>>>2>>>0];return D=wb.get(D),D=xb.get(D),--ge,D()})()}catch(D){A=D,b=!0}var O=!1;if(!er){var N=Hu;N&&(Hu=null,(b?N.reject:N.resolve)(A),O=!0)}if(b&&!O)throw A}}),g=!0,h||(br=1,er=(function(){var b=Cs(65548),A=b+12;if((v(),P)[b>>>2>>>0]=A,(v(),P)[b+4>>>2>>>0]=A+65536,A=Ei[0],!Vu.has(A)){var O=S2++;Vu.set(A,O),wb.set(O,A)}return A=Vu.get(A),(v(),B)[b+8>>>2>>>0]=A,b})(),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.pause(),ki(()=>H1(er)))}else br===2?(br=0,ki(Y1),Lt(er),er=null,O2.forEach(bi)):Ce(`invalid state: ${br}`);return gb}})(p=>{c().then(p)});function I2(c){return c>>>=0,yb(async()=>{var p=await zt(c);return qt(p)})}var Xu=[],C2=c=>{var p=Xu.length;return Xu.push(c),p},P2=(c,p)=>{for(var h=Array(c),g=0;g<c;++g){var b=g,A=(v(),P)[p+4*g>>>2>>>0],O=Fu[A];if(O===void 0)throw c=`parameter ${g}`,A=Fb(A),p=Zt(A),Lt(A),new Ss(`${c} has unknown type ${p}`);h[b]=O}return h},z2=(c,p,h)=>{var g=[];return c=c(g,h),g.length&&((v(),P)[p>>>2>>>0]=qt(g)),c},L2={},Ai=c=>{var p=L2[c];return p===void 0?Zt(c):p};function N2(c,p,h){var[g,...b]=P2(c,p>>>0);p=g.Xc.bind(g);var A=b.map(D=>D.Wc.bind(D));c--;var O={toValue:zt};switch(c=A.map((D,q)=>{var fe=`argFromPtr${q}`;return O[fe]=D,`${fe}(args${q?"+"+8*q:""})`}),h){case 0:var N="toValue(handle)";break;case 2:N="new (toValue(handle))";break;case 3:N="";break;case 1:O.getStringOrSymbol=Ai,N="toValue(handle)[getStringOrSymbol(methodName)]"}return N+=`(${c})`,g.pe||(O.toReturnWire=p,O.emval_returnValue=z2,N=`return emval_returnValue(toReturnWire, destructorsRef, ${N})`),N=`return function (handle, methodName, destructorsRef, args) {
|
|
10
|
+
`,QI="{%- ",JI=" -%}";function ZI(t){switch(t.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return t.operator.value==="and"?1:t.operator.value==="in"||t.operator.value==="not in"?2:0}return 0}function eC(t,e=" "){let r=typeof e=="number"?" ".repeat(e):e;return Ht(t.body,0,r).replace(/\n$/,"")}function pt(...t){return QI+t.join(" ")+JI}function Ht(t,e,r){return t.map(s=>tC(s,e,r)).join(nt)}function tC(t,e,r){let s=r.repeat(e);switch(t.type){case"Program":return Ht(t.body,e,r);case"If":return rC(t,e,r);case"For":return sC(t,e,r);case"Set":return nC(t,e,r);case"Macro":return oC(t,e,r);case"Break":return s+pt("break");case"Continue":return s+pt("continue");case"CallStatement":return aC(t,e,r);case"FilterStatement":return iC(t,e,r);case"Comment":return s+"{# "+t.value+" #}";default:return s+"{{- "+ke(t)+" -}}"}}function rC(t,e,r){let s=r.repeat(e),n=[],o=t;for(;o&&(n.push({test:o.test,body:o.body}),o.alternate.length===1&&o.alternate[0].type==="If");)o=o.alternate[0];let a=s+pt("if",ke(n[0].test))+nt+Ht(n[0].body,e+1,r);for(let i=1;i<n.length;++i)a+=nt+s+pt("elif",ke(n[i].test))+nt+Ht(n[i].body,e+1,r);return o&&o.alternate.length>0&&(a+=nt+s+pt("else")+nt+Ht(o.alternate,e+1,r)),a+=nt+s+pt("endif"),a}function sC(t,e,r){let s=r.repeat(e),n="";if(t.iterable.type==="SelectExpression"){let a=t.iterable;n=`${ke(a.lhs)} if ${ke(a.test)}`}else n=ke(t.iterable);let o=s+pt("for",ke(t.loopvar),"in",n)+nt+Ht(t.body,e+1,r);return t.defaultBlock.length>0&&(o+=nt+s+pt("else")+nt+Ht(t.defaultBlock,e+1,r)),o+=nt+s+pt("endfor"),o}function nC(t,e,r){let s=r.repeat(e),n=ke(t.assignee),o=t.value?ke(t.value):"",a=s+pt("set",`${n}${t.value?" = "+o:""}`);return t.body.length===0?a:a+nt+Ht(t.body,e+1,r)+nt+s+pt("endset")}function oC(t,e,r){let s=r.repeat(e),n=t.args.map(ke).join(", ");return s+pt("macro",`${t.name.value}(${n})`)+nt+Ht(t.body,e+1,r)+nt+s+pt("endmacro")}function aC(t,e,r){let s=r.repeat(e),n=t.callerArgs&&t.callerArgs.length>0?`(${t.callerArgs.map(ke).join(", ")})`:"",o=ke(t.call),a=s+pt(`call${n}`,o)+nt;return a+=Ht(t.body,e+1,r)+nt,a+=s+pt("endcall"),a}function iC(t,e,r){let s=r.repeat(e),n=t.filter.type==="Identifier"?t.filter.value:ke(t.filter),o=s+pt("filter",n)+nt;return o+=Ht(t.body,e+1,r)+nt,o+=s+pt("endfilter"),o}function ke(t,e=-1){switch(t.type){case"SpreadExpression":return`*${ke(t.argument)}`;case"Identifier":return t.value;case"IntegerLiteral":return`${t.value}`;case"FloatLiteral":return`${t.value}`;case"StringLiteral":return JSON.stringify(t.value);case"BinaryExpression":{let r=t,s=ZI(r),n=ke(r.left,s),o=ke(r.right,s+1),a=`${n} ${r.operator.value} ${o}`;return s<e?`(${a})`:a}case"UnaryExpression":{let r=t;return r.operator.value+(r.operator.value==="not"?" ":"")+ke(r.argument,1/0)}case"CallExpression":{let r=t,s=r.args.map(ke).join(", ");return`${ke(r.callee)}(${s})`}case"MemberExpression":{let r=t,s=ke(r.object);["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(r.object.type)||(s=`(${s})`);let n=ke(r.property);return!r.computed&&r.property.type!=="Identifier"&&(n=`(${n})`),r.computed?`${s}[${n}]`:`${s}.${n}`}case"FilterExpression":{let r=t,s=ke(r.operand,1/0);return r.filter.type==="CallExpression"?`${s} | ${ke(r.filter)}`:`${s} | ${r.filter.value}`}case"SelectExpression":{let r=t;return`${ke(r.lhs)} if ${ke(r.test)}`}case"TestExpression":{let r=t;return`${ke(r.operand)} is${r.negate?" not":""} ${r.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let r=t.value.map(ke),s=t.type==="ArrayLiteral"?"[]":"()";return`${s[0]}${r.join(", ")}${s[1]}`}case"ObjectLiteral":return`{${Array.from(t.value.entries()).map(([s,n])=>`${ke(s)}: ${ke(n)}`).join(", ")}}`;case"SliceExpression":{let r=t,s=r.start?ke(r.start):"",n=r.stop?ke(r.stop):"",o=r.step?`:${ke(r.step)}`:"";return`${s}:${n}${o}`}case"KeywordArgumentExpression":{let r=t;return`${r.key.value}=${ke(r.value)}`}case"Ternary":{let r=t,s=`${ke(r.trueExpr)} if ${ke(r.condition,0)} else ${ke(r.falseExpr)}`;return e>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${t.type}`)}}var Cv=class{parsed;constructor(t){let e=gI(t,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=FI(e)}render(t){let e=new Zr;if(KI(e),t)for(let[n,o]of Object.entries(t))e.set(n,o);return new YI(e).run(this.parsed).value}format(t){return eC(this.parsed,t?.indent||" ")}};var Je=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}_call(...t){throw Error("Must implement _call method in subclass")}};function hr(t,e){t&&t(e)}function Pv(t){return Number.isInteger(t)||typeof t=="bigint"}function gp(t){return t==null||t===-1}function wp(t){let e=[],r=t;for(;Array.isArray(r);)e.push(r.length),r=r[0];return e}function dt(...t){return Array.prototype.concat.apply([],t)}function zv(...t){return t.reduce((e,r)=>e.flatMap(s=>r.map(n=>[s,n])))}function $s(t,e){return Math.abs((t+e)%(2*e)-e)}function ot(t,e){return Object.assign({},...e.map(r=>{if(t[r]!==void 0)return{[r]:t[r]}}))}function Lv(t,e){let r=0;for(let s of t)s===e&&++r;return r}import _r from"fs";import xp from"path";var lC={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"},ts=class t{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=_r.existsSync(e),this.exists){this.status=200,this.statusText="OK";let r=_r.statSync(e);this.headers.set("content-length",r.size.toString()),this.updateContentType();let s=_r.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",lC[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 _r.promises.readFile(this.filePath)).buffer}async blob(){let e=await _r.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get("content-type")})}async text(){return await _r.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Rs=class{constructor(e){this.path=e}async match(e){let r=xp.join(this.path,e),s=new ts(r);if(s.exists)return s}async put(e,r,s=void 0){let n=xp.join(this.path,e);try{let o=r.headers.get("Content-Length"),a=parseInt(o??"0"),i=0;await _r.promises.mkdir(xp.dirname(n),{recursive:!0});let l=_r.createWriteStream(n),u=r.body.getReader();for(;;){let{done:d,value:f}=await u.read();if(d)break;await new Promise((_,w)=>{l.write(f,x=>{if(x){w(x);return}_()})}),i+=f.length;let m=a?i/a*100:0;s?.({progress:m,loaded:i,total:a})}l.close()}catch(o){try{await _r.promises.unlink(n)}catch{}throw o}}};var Nv={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"},Bi=100,$v=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Un(...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 Us(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 Rv(t){return!(!$v.test(t)||t.includes("..")||t.includes("--")||t.endsWith(".git")||t.endsWith(".ipynb"))}function Uv(t,e,r){if(!r)return null;let s=Nv[t]??`Error (${t}) occurred while trying to load file`;throw Error(`${s}: "${e}".`)}async function Bv(t,e){let r=t.headers.get("Content-Length");r===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let s=parseInt(r??"0"),n=new Uint8Array(s),o=0,a=t.body.getReader();async function i(){let{done:l,value:u}=await a.read();if(l)return;let d=o+u.length;if(d>s){s=d;let m=new Uint8Array(s);m.set(n),n=m}n.set(u,o),o=d;let f=o/s*100;return e({progress:f,loaded:o,total:s}),i()}return await i(),n}async function Di(t=null){let e=null;if(De.useCustomCache){if(!De.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!De.customCache.match||!De.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");e=De.customCache}if(!e&&De.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{e=await caches.open(De.cacheKey)}catch(r){console.warn("An error occurred while opening the browser cache:",r)}}if(!e&&De.useFSCache){if(!be.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");e=new Rs(t??De.cacheDir)}return e}async function Dv(t,...e){for(let r of e)try{let s=await t.match(r);if(s)return s}catch{continue}}async function Bs(t){if(De.useFS&&!Us(t,["http:","https:","blob:"]))return new ts(t instanceof URL?t.protocol==="file:"?t.pathname:t.toString():t);if(typeof process<"u"&&process?.release?.name==="node"){let e=!!process.env?.TESTING_REMOTELY,r=De.version,s=new Headers;if(s.set("User-Agent",`transformers.js/${r}; is_ci/${e};`),Us(t,["http:","https:"],["huggingface.co","hf.co"])){let o=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;o&&s.set("Authorization",`Bearer ${o}`)}return fetch(t,{headers:s})}else return fetch(t)}function cC(t,e,r={},s=null){let n=r.revision??"main",o=Un(t,e),a=Rv(t),i=a?Un(De.localModelPath,o):o,l=Un(De.remoteHost,De.remotePathTemplate.replaceAll("{model}",t).replaceAll("{revision}",encodeURIComponent(n)),e),u=s instanceof Rs?n==="main"?o:Un(t,n,e):l;return{requestURL:o,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:a}}async function uC(t,e,r){if(t)return await Dv(t,e,r)}async function pC(t,e,r,s,n,o,a={}){if(await r.match(s)===void 0)if(o)typeof n!="string"&&await r.put(s,new Response(o,{headers:n.headers})).catch(i=>{console.warn(`Unable to add response to browser cache: ${i}.`)});else{let i=a.progress_callback?l=>hr(a.progress_callback,{status:"progress",name:t,file:e,...l}):void 0;await r.put(s,n,i)}}async function dC(t,e,r=!0,s={},n=!1,o=null){let{requestURL:a,localPath:i,remoteURL:l,proposedCacheKey:u,validModelId:d}=cC(t,e,s,o),f,m=!1,_;_=await uC(o,i,u);let w=_!==void 0;if(!w){if(De.allowLocalModels)if(Us(a,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${a}.`);if(!De.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${a}.`)}else try{_=await Bs(i),f=i}catch(M){console.warn(`Unable to load from local path "${i}": "${M}"`)}if(_===void 0||typeof _!="string"&&_.status===404){if(s.local_files_only||!De.allowRemoteModels){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${i}".`);return null}if(!d)throw Error(`Local file missing at "${i}" and download aborted due to invalid model ID "${t}".`);if(_=await Bs(l),_.status!==200)return Uv(_.status,l,r);f=u}m=o&&typeof Response<"u"&&_ instanceof Response&&_.status===200}hr(s.progress_callback,{status:"download",name:t,file:e});let x;if(!(be.IS_NODE_ENV&&n)){let E;typeof _!="string"&&(s.progress_callback?w&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(E=new Uint8Array(await _.arrayBuffer()),hr(s.progress_callback,{status:"progress",name:t,file:e,progress:100,loaded:E.length,total:E.length})):E=await Bv(_,M=>{hr(s.progress_callback,{status:"progress",name:t,file:e,...M})}):E=new Uint8Array(await _.arrayBuffer())),x=E}if(m&&f&&typeof _!="string"&&await pC(t,e,o,f,_,x,s),hr(s.progress_callback,{status:"done",name:t,file:e}),x){if(!be.IS_NODE_ENV&&n)throw new Error("Cannot return path in a browser environment.");return x}if(_ instanceof ts)return _.filePath;let k=await o?.match(f);if(k instanceof ts)return k.filePath;if(k instanceof Response)return new Uint8Array(await k.arrayBuffer());if(typeof k=="string")return k;throw new Error("Unable to get model file path or buffer.")}async function Bn(t,e,r=!0,s={},n=!1){if(!De.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!De.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}hr(s.progress_callback,{status:"initiate",name:t,file:e});let o=await Di(s?.cache_dir);return await dC(t,e,r,s,n,o)}async function yp(t,e,r=!0,s={}){let n=await Bn(t,e,r,s,!1);return n===null?null:new TextDecoder("utf-8").decode(n)}async function at(t,e,r=!0,s={}){let n=await yp(t,e,r,s);return n===null?{}:JSON.parse(n)}function jv(t,[e,r,s],[n,o],a="bilinear",i=!1){let l=o/s,u=n/r,d=new t.constructor(n*o*e),f=r*s,m=n*o;for(let _=0;_<n;++_)for(let w=0;w<o;++w){let x=_*o+w,k=(w+.5)/l-.5,E=(_+.5)/u-.5,M=Math.floor(k),I=Math.floor(E),T=Math.min(M+1,s-1),z=Math.min(I+1,r-1);M=Math.max(M,0),I=Math.max(I,0);let C=k-M,v=E-I,G=(1-C)*(1-v),X=C*(1-v),V=(1-C)*v,Q=C*v,K=I*s,Y=z*s,B=K+M,P=K+T,se=Y+M,ie=Y+T;for(let S=0;S<e;++S){let L=S*f;d[S*m+x]=G*t[L+B]+X*t[L+P]+V*t[L+se]+Q*t[L+ie]}}return d}function Gv(t,e,r){let s=new Array(r.length),n=new Array(r.length);for(let i=r.length-1,l=1;i>=0;--i)n[i]=l,s[i]=e[r[i]],l*=s[i];let o=r.map((i,l)=>n[r.indexOf(l)]),a=new t.constructor(t.length);for(let i=0;i<t.length;++i){let l=0;for(let u=e.length-1,d=i;u>=0;--u)l+=d%e[u]*o[u],d=Math.floor(d/e[u]);a[l]=t[i]}return[a,s]}function Pe(t){let e=Te(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 vp(t){let e=Te(t)[0],r=0;for(let o=0;o<t.length;++o)r+=Math.exp(t[o]-e);let s=Math.log(r);return t.map(o=>o-e-s)}function qv(t,e){let r=0;for(let s=0;s<t.length;++s)r+=t[s]*e[s];return r}function fC(t,e){let r=qv(t,e),s=Fv(t),n=Fv(e);return r/(s*n)}function Fv(t){return Math.sqrt(t.reduce((e,r)=>e+r*r,0))}function Dn(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]<e&&(e=t[s],r=s);return[e,r]}function Te(t){if(t.length===0)throw Error("Array must not be empty");let e=t[0],r=0;for(let s=1;s<t.length;++s)t[s]>e&&(e=t[s],r=s);return[e,r]}function Wv(t){return t>0&&(t&t-1)===0}var Fi=class{constructor(e){if(this.size=e|0,this.size<=1||!Wv(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let s=0;s<this.table.length;s+=2){let n=Math.PI*s/this.size;this.table[s]=Math.cos(n),this.table[s+1]=-Math.sin(n)}let r=0;for(let s=1;this.size>s;s<<=1)++r;this._width=r%2===0?r-1:r,this._bitrev=new Int32Array(1<<this._width);for(let s=0;s<this._bitrev.length;++s){this._bitrev[s]=0;for(let n=0;n<this._width;n+=2){let o=this._width-n-2;this._bitrev[s]|=(s>>>n&3)<<o}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(e,r){let s=r||new Array(e.length>>>1);for(let n=0;n<e.length;n+=2)s[n>>>1]=e[n];return s}toComplexArray(e,r){let s=r||this.createComplexArray();for(let n=0;n<s.length;n+=2)s[n]=e[n>>>1],s[n+1]=0;return s}transform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,1)}realTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._realTransform4(e,r,1)}inverseTransform(e,r){if(e===r)throw new Error("Input and output buffers must be different");this._transform4(e,r,-1);for(let s=0;s<e.length;++s)e[s]/=this.size}_transform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,u,d=this._bitrev;if(i===4)for(l=0,u=0;l<n;l+=i,++u){let m=d[u];this._singleTransform2(r,e,l,m,a)}else for(l=0,u=0;l<n;l+=i,++u){let m=d[u];this._singleTransform4(r,e,l,m,a,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let m=i>>>2;for(l=0;l<n;l+=i){let _=l+m-1;for(let w=l,x=0;w<_;w+=2,x+=a){let k=w,E=k+m,M=E+m,I=M+m,T=e[k],z=e[k+1],C=e[E],v=e[E+1],G=e[M],X=e[M+1],V=e[I],Q=e[I+1],K=f[x],Y=s*f[x+1],B=C*K-v*Y,P=C*Y+v*K,se=f[2*x],ie=s*f[2*x+1],S=G*se-X*ie,L=G*ie+X*se,R=f[3*x],te=s*f[3*x+1],ue=V*R-Q*te,Be=V*te+Q*R,Ce=T+S,vt=z+L,Qe=T-S,Ze=z-L,rt=B+ue,Me=P+Be,xe=s*(B-ue),Ge=s*(P-Be);e[k]=Ce+rt,e[k+1]=vt+Me,e[E]=Qe+Ge,e[E+1]=Ze-xe,e[M]=Ce-rt,e[M+1]=vt-Me,e[I]=Qe-Ge,e[I+1]=Ze+xe}}}}_singleTransform2(e,r,s,n,o){let a=e[n],i=e[n+1],l=e[n+o],u=e[n+o+1];r[s]=a+l,r[s+1]=i+u,r[s+2]=a-l,r[s+3]=i-u}_singleTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,u=e[n],d=e[n+1],f=e[n+o],m=e[n+o+1],_=e[n+i],w=e[n+i+1],x=e[n+l],k=e[n+l+1],E=u+_,M=d+w,I=u-_,T=d-w,z=f+x,C=m+k,v=a*(f-x),G=a*(m-k);r[s]=E+z,r[s+1]=M+C,r[s+2]=I+G,r[s+3]=T-v,r[s+4]=E-z,r[s+5]=M-C,r[s+6]=I-G,r[s+7]=T+v}_realTransform4(e,r,s){let n=this._csize,a=1<<this._width,i=n/a<<1,l,u,d=this._bitrev;if(i===4)for(l=0,u=0;l<n;l+=i,++u){let _=d[u];this._singleRealTransform2(r,e,l,_>>>1,a>>>1)}else for(l=0,u=0;l<n;l+=i,++u){let _=d[u];this._singleRealTransform4(r,e,l,_>>>1,a>>>1,s)}let f=this.table;for(a>>=2;a>=2;a>>=2){i=n/a<<1;let _=i>>>1,w=_>>>1,x=w>>>1;for(l=0;l<n;l+=i)for(let k=0,E=0;k<=x;k+=2,E+=a){let M=l+k,I=M+w,T=I+w,z=T+w,C=e[M],v=e[M+1],G=e[I],X=e[I+1],V=e[T],Q=e[T+1],K=e[z],Y=e[z+1],B=C,P=v,se=f[E],ie=s*f[E+1],S=G*se-X*ie,L=G*ie+X*se,R=f[2*E],te=s*f[2*E+1],ue=V*R-Q*te,Be=V*te+Q*R,Ce=f[3*E],vt=s*f[3*E+1],Qe=K*Ce-Y*vt,Ze=K*vt+Y*Ce,rt=B+ue,Me=P+Be,xe=B-ue,Ge=P-Be,kt=S+Qe,ge=L+Ze,Le=s*(S-Qe),xr=s*(L-Ze);if(e[M]=rt+kt,e[M+1]=Me+ge,e[I]=xe+xr,e[I+1]=Ge-Le,k===0){e[T]=rt-kt,e[T+1]=Me-ge;continue}if(k===x)continue;let Hr=l+w-k,Et=l+_-k;e[Hr]=xe-s*xr,e[Hr+1]=-Ge-s*Le,e[Et]=rt-s*kt,e[Et+1]=-Me+s*ge}}let m=n>>>1;for(let _=2;_<m;_+=2)e[n-_]=e[_],e[n-_+1]=-e[_+1]}_singleRealTransform2(e,r,s,n,o){let a=e[n],i=e[n+o];r[s]=a+i,r[s+1]=0,r[s+2]=a-i,r[s+3]=0}_singleRealTransform4(e,r,s,n,o,a){let i=o*2,l=o*3,u=e[n],d=e[n+o],f=e[n+i],m=e[n+l],_=u+f,w=u-f,x=d+m,k=a*(d-m);r[s]=_+x,r[s+1]=0,r[s+2]=w,r[s+3]=-k,r[s+4]=_-x,r[s+5]=0,r[s+6]=w,r[s+7]=k}},bp=class{constructor(e){let r=2*(e-1),s=2*(2*e-1),n=2**Math.ceil(Math.log2(s));this.bufferSize=n,this._a=r;let o=new Float64Array(s),a=new Float64Array(n);this._chirpBuffer=new Float64Array(n),this._buffer1=new Float64Array(n),this._buffer2=new Float64Array(n),this._outBuffer1=new Float64Array(n),this._outBuffer2=new Float64Array(n);let i=-2*Math.PI/e,l=Math.cos(i),u=Math.sin(i);for(let d=0;d<s>>1;++d){let f=(d+1-e)**2/2,m=Math.sqrt(l**2+u**2)**f,_=f*Math.atan2(u,l),w=2*d;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 Fi(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,u=this._slicedChirpBuffer,d=this._a;if(s)for(let f=0;f<u.length;f+=2){let m=f+1,_=f>>1,w=r[_];n[f]=w*u[f],n[m]=w*u[m]}else for(let f=0;f<u.length;f+=2){let m=f+1;n[f]=r[f]*u[f]-r[m]*u[m],n[m]=r[f]*u[m]+r[m]*u[f]}this._f.transform(a,n);for(let f=0;f<l.length;f+=2){let m=f+1;o[f]=a[f]*l[f]-a[m]*l[m],o[m]=a[f]*l[m]+a[m]*l[f]}this._f.inverseTransform(i,o);for(let f=0;f<i.length;f+=2){let m=i[f+d],_=i[f+d+1],w=u[f],x=u[f+1];e[f]=m*w-_*x,e[f+1]=m*x+_*w}}transform(e,r){this._transform(e,r,!1)}realTransform(e,r){this._transform(e,r,!0)}},ji=class{constructor(e){this.fft_length=e,this.isPowerOfTwo=Wv(e),this.isPowerOfTwo?(this.fft=new Fi(e),this.outputBufferSize=2*e):(this.fft=new bp(e),this.outputBufferSize=this.fft.bufferSize)}realTransform(e,r){this.fft.realTransform(e,r)}transform(e,r){this.fft.transform(e,r)}};function Vv(t,e){if(e%2===0||e<=0)throw new Error("Window size must be a positive odd number");let r=new t.constructor(t.length),s=new t.constructor(e),n=Math.floor(e/2);for(let o=0;o<t.length;++o){let a=0;for(let i=-n;i<=n;++i){let l=o+i;l<0?l=Math.abs(l):l>=t.length&&(l=2*(t.length-1)-l),s[a++]=t[l]}s.sort(),r[o]=s[n]}return r}function rs(t,e){let r=Math.pow(10,e);return Math.round(t*r)/r}function Hv(t){let e=Math.round(t);return Math.abs(t)%1===.5?e%2===0?e:e-1:e}function Xv(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 d=1;d<s[1];++d)for(let f=1;f<s[0];++f){let m=n[f-1][d-1],_=n[f-1][d],w=n[f][d-1],x,k;m<_&&m<w?(x=m,k=0):_<m&&_<w?(x=_,k=1):(x=w,k=2),n[f][d]=t[f-1][d-1]+x,o[f][d]=k}for(let d=0;d<s[1];++d)o[0][d]=2;for(let d=0;d<s[0];++d)o[d][0]=1;let a=e,i=r,l=[],u=[];for(;a>0||i>0;)switch(l.push(a-1),u.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(),u.reverse(),[l,u]}var Kv=(function(){let t=null;return function(e){if(!t){t=new Float32Array(65536);let o=new ArrayBuffer(4),a=new Uint32Array(o),i=new Float32Array(o);for(let l=0;l<t.length;++l){let u=0,d=(l&32768)<<16,f=(l&31744)>>10,m=l&1023;if(f===31)u=d|2139095040|m<<13;else if(f===0)if(m===0)u=d;else{let _=113;for(;(m&1024)===0;)m<<=1,--_;m&=-1025,u=d|_<<23|m<<13}else u=d|f+112<<23|m<<13;a[0]=u,t[l]=i[0]}}let r=e.length,s=t,n=new Float32Array(r);for(let o=0;o<r;++o)n[o]=s[e[o]];return n}})();import*as GC from"onnxruntime-node";var dd={};Ps(dd,{InferenceSession:()=>Qp,TRACE:()=>Qi,TRACE_EVENT_BEGIN:()=>Mr,TRACE_EVENT_END:()=>Tr,TRACE_FUNC_BEGIN:()=>ls,TRACE_FUNC_END:()=>cs,Tensor:()=>Kt,default:()=>jC,env:()=>We,registerBackend:()=>is});var Kp=Object.defineProperty,mC=Object.getOwnPropertyDescriptor,hC=Object.getOwnPropertyNames,_C=Object.prototype.hasOwnProperty,gC=(t=>typeof Jr<"u"?Jr:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof Jr<"u"?Jr:e)[r]}):t)(function(t){if(typeof Jr<"u")return Jr.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),ye=(t,e)=>()=>(t&&(e=t(t=0)),e),Xn=(t,e)=>{for(var r in e)Kp(t,r,{get:e[r],enumerable:!0})},wC=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of hC(e))!_C.call(t,n)&&n!==r&&Kp(t,n,{get:()=>e[n],enumerable:!(s=mC(e,n))||s.enumerable});return t},Yi=t=>wC(Kp({},"__esModule",{value:!0}),t),Fn,vr,is,Yv,kk,Ek=ye(()=>{"use strict";Fn=new Map,vr=[],is=(t,e,r)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let s=Fn.get(t);if(s===void 0)Fn.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<vr.length;o++)if(Fn.get(vr[o]).priority<=r){vr.splice(o,0,t);return}vr.push(t)}return}throw new TypeError("not a valid backend")},Yv=async t=>{let e=Fn.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}}},kk=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 u=await Yv(l);typeof u=="string"?o.push({name:l,err:u}):(n||(n=u),n===u&&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:u}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let i=e.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(t,{get:(l,u)=>u==="executionProviders"?i:Reflect.get(l,u)})]}}),xC=ye(()=>{"use strict";Ek()}),Ak,yC=ye(()=>{"use strict";Ak="1.24.0-dev.20251116-b39e144322"}),kp,ct,Mk=ye(()=>{"use strict";yC(),kp="warning",ct={wasm:{},webgl:{},webgpu:{},versions:{common:Ak},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}`);kp=t}},get logLevel(){return kp}},Object.defineProperty(ct,"logLevel",{enumerable:!0})}),We,bC=ye(()=>{"use strict";Mk(),We=ct}),Tk,Sk,vC=ye(()=>{"use strict";Tk=(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,u;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?u=[0,0,0,0]:typeof i.bias=="number"?u=[i.bias,i.bias,i.bias,i.bias]:(u=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(u[3]=i.bias[3]));let d=o*n,f=0,m=d,_=d*2,w=-1;a==="RGBA"?(f=0,m=d,_=d*2,w=d*3):a==="RGB"?(f=0,m=d,_=d*2):a==="RBG"&&(f=0,_=d,m=d*2);for(let x=0;x<o;x++)for(let k=0;k<n;k++){let E=(t.data[f++]-u[0])*l[0],M=(t.data[m++]-u[1])*l[1],I=(t.data[_++]-u[2])*l[2],T=w===-1?255:(t.data[w++]-u[3])*l[3];s.fillStyle="rgba("+E+","+M+","+I+","+T+")",s.fillRect(k,x,1,1)}if("toDataURL"in r)return r.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Sk=(t,e)=>{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let n,o,a;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(n=t.dims[2],o=t.dims[1],a=t.dims[3]):(n=t.dims[3],o=t.dims[2],a=t.dims[1]);let i=e!==void 0&&e.format!==void 0?e.format:"RGB",l=e?.norm,u,d;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?d=[0,0,0,0]:typeof l.bias=="number"?d=[l.bias,l.bias,l.bias,l.bias]:(d=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(d[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,k=3,E=0,M=f,I=f*2,T=-1;i==="RGBA"?(E=0,M=f,I=f*2,T=f*3):i==="RGB"?(E=0,M=f,I=f*2):i==="RBG"&&(E=0,I=f,M=f*2),s=r.createImageData(n,o);for(let z=0;z<o*n;_+=m,w+=m,x+=m,k+=m,z++)s.data[_]=(t.data[E++]-d[0])*u[0],s.data[w]=(t.data[M++]-d[1])*u[1],s.data[x]=(t.data[I++]-d[2])*u[2],s.data[k]=T===-1?255:(t.data[T++]-d[3])*u[3]}else throw new Error("Can not access image data");return s}}),Gi,Ok,Ik,Ck,Pk,zk,kC=ye(()=>{"use strict";Yp(),Gi=(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",u=r*s,d=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),f=4,m=0,_=1,w=2,x=3,k=0,E=u,M=u*2,I=-1;i==="RGB"&&(f=3,m=0,_=1,w=2,x=-1),l==="RGBA"?I=u*3:l==="RBG"?(k=0,M=u,E=u*2):l==="BGR"&&(M=0,E=u,k=u*2);for(let T=0;T<u;T++,m+=f,w+=f,_+=f,x+=f)d[k++]=(t[m]+a[0])/o[0],d[E++]=(t[_]+a[1])/o[1],d[M++]=(t[w]+a[2])/o[2],I!==-1&&x!==-1&&(d[I++]=(t[x]+a[3])/o[3]);return l==="RGBA"?new Ct("float32",d,[1,4,r,s]):new Ct("float32",d,[1,3,r,s])},Ok=async(t,e)=>{let r=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,s=typeof ImageData<"u"&&t instanceof ImageData,n=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,o=typeof t=="string",a,i=e??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=d=>typeof HTMLCanvasElement<"u"&&d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?d.getContext("2d"):null;if(r){let d=l();d.width=t.width,d.height=t.height;let f=u(d);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 d,f;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(d=e.resizedHeight,f=e.resizedWidth):(d=t.height,f=t.width),e!==void 0&&(i=e),i.format="RGBA",i.height=d,i.width=f,e!==void 0){let m=l();m.width=f,m.height=d;let _=u(m);if(_!=null)_.putImageData(t,0,0),a=_.getImageData(0,0,f,d).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 d=l();d.width=t.width,d.height=t.height;let f=u(d);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=_,Gi(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((d,f)=>{let m=l(),_=u(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,d(Gi(x.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Gi(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Ik=(t,e)=>{let{width:r,height:s,download:n,dispose:o}=e,a=[1,s,r,4];return new Ct({location:"texture",type:"float32",texture:t,dims:a,download:n,dispose:o})},Ck=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Ct({location:"gpu-buffer",type:r??"float32",gpuBuffer:t,dims:s,download:n,dispose:o})},Pk=(t,e)=>{let{dataType:r,dims:s,download:n,dispose:o}=e;return new Ct({location:"ml-tensor",type:r??"float32",mlTensor:t,dims:s,download:n,dispose:o})},zk=(t,e,r)=>new Ct({location:"cpu-pinned",type:t,data:e,dims:r??[e.length]})}),os,Vn,Ep,Lk,EC=ye(()=>{"use strict";os=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Vn=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ep=!1,Lk=()=>{if(!Ep){Ep=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;t&&(os.set("int64",BigInt64Array),Vn.set(BigInt64Array,"int64")),e&&(os.set("uint64",BigUint64Array),Vn.set(BigUint64Array,"uint64")),s?(os.set("float16",r),Vn.set(r,"float16")):os.set("float16",Uint16Array)}}}),Nk,$k,AC=ye(()=>{"use strict";Yp(),Nk=t=>{let e=1;for(let r=0;r<t.length;r++){let s=t[r];if(typeof s!="number"||!Number.isSafeInteger(s))throw new TypeError(`dims[${r}] must be an integer, got: ${s}`);if(s<0)throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${s}`);e*=s}return e},$k=(t,e)=>{switch(t.location){case"cpu":return new Ct(t.type,t.data,e);case"cpu-pinned":return new Ct({location:"cpu-pinned",data:t.data,type:t.type,dims:e});case"texture":return new Ct({location:"texture",texture:t.texture,type:t.type,dims:e});case"gpu-buffer":return new Ct({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:e});case"ml-tensor":return new Ct({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),Ct,Yp=ye(()=>{"use strict";vC(),kC(),EC(),AC(),Ct=class{constructor(t,e,r){Lk();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=os.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=os.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=Vn.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=Nk(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 Ok(t,e)}static fromTexture(t,e){return Ik(t,e)}static fromGpuBuffer(t,e){return Ck(t,e)}static fromMLTensor(t,e){return Pk(t,e)}static fromPinnedBuffer(t,e,r){return zk(t,e,r)}toDataURL(t){return Tk(this,t)}toImageData(t){return Sk(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 $k(this,t)}}}),Kt,Rk=ye(()=>{"use strict";Yp(),Kt=Ct}),Qi,Ap,ls,cs,Mr,Tr,Uk=ye(()=>{"use strict";Mk(),Qi=(t,e)=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeStamp(`${t}::ORT::${e}`)},Ap=(t,e)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n<r.length;n++){if(s&&!r[n].includes("TRACE_FUNC")){let o=`FUNC_${t}::${r[n].trim().split(" ")[1]}`;e&&(o+=`::${e}`),Qi("CPU",o);return}r[n].includes("TRACE_FUNC")&&(s=!0)}},ls=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Ap("BEGIN",t)},cs=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||Ap("END",t)},Mr=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.time(`ORT::${t}`)},Tr=t=>{(typeof ct.trace>"u"?!ct.wasm.trace:!ct.trace)||console.timeEnd(`ORT::${t}`)}}),Bk,MC=ye(()=>{"use strict";Ek(),Rk(),Uk(),Bk=class Dk{constructor(e){this.handler=e}async run(e,r,s){ls(),Mr("InferenceSession.run");let n={},o={};if(typeof e!="object"||e===null||e instanceof Kt||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 Kt)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 u of r){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);n[u]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,d=Object.getOwnPropertyNames(r);for(let f of this.outputNames)if(d.indexOf(f)!==-1){let m=r[f];(m===null||m instanceof Kt)&&(u=!0,a=!1,n[f]=m)}if(u){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 u of this.inputNames)if(typeof e[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(a)for(let u of this.outputNames)n[u]=null;let i=await this.handler.run(e,n,o),l={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let d=i[u];d instanceof Kt?l[u]=d:l[u]=new Kt(d.type,d.data,d.dims)}return Tr("InferenceSession.run"),cs(),l}async release(){return this.handler.dispose()}static async create(e,r,s,n){ls(),Mr("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 d=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>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.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>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.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(d,f,m)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await kk(a),u=await i.createInferenceSessionHandler(o,l);return Tr("InferenceSession.create"),cs(),new Dk(u)}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}}}),Qp,TC=ye(()=>{"use strict";MC(),Qp=Bk}),SC=ye(()=>{"use strict"}),OC=ye(()=>{"use strict"}),IC=ye(()=>{"use strict"}),CC=ye(()=>{"use strict"}),Fk={};Xn(Fk,{InferenceSession:()=>Qp,TRACE:()=>Qi,TRACE_EVENT_BEGIN:()=>Mr,TRACE_EVENT_END:()=>Tr,TRACE_FUNC_BEGIN:()=>ls,TRACE_FUNC_END:()=>cs,Tensor:()=>Kt,env:()=>We,registerBackend:()=>is});var us=ye(()=>{"use strict";xC(),bC(),TC(),Rk(),SC(),OC(),Uk(),IC(),CC()}),Jp=ye(()=>{"use strict"}),jk={};Xn(jk,{default:()=>Gk});var Mp,Tp,Gk,PC=ye(()=>{"use strict";nE(),ps(),Zp(),Mp="ort-wasm-proxy-worker",Tp=globalThis.self?.name===Mp,Tp&&(self.onmessage=t=>{let{type:e,in:r}=t.data;try{switch(e){case"init-wasm":ed(r.wasm).then(()=>{od(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;ad(n,s).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:s}=r,n=el(s);postMessage({type:e,out:n});break}case"create":{let{model:s,options:n}=r;id(s,n).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":ld(r),postMessage({type:e});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=r;cd(s,n,o,a,new Array(a.length).fill(null),i).then(l=>{l.some(u=>u[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:l},pd([...o,...l]))},l=>{postMessage({type:e,err:l})});break}case"end-profiling":ud(r),postMessage({type:e});break;default:}}catch(s){postMessage({type:e,err:s})}}),Gk=Tp?null:t=>new Worker(t??Ot,{type:"module",name:Mp})}),qk={};Xn(qk,{default:()=>Wk});async function Qv(t={}){var e=t,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,n=s&&self.name?.startsWith("em-pthread");e.mountExternalData=(c,p)=>{c.startsWith("./")&&(c=c.substring(2)),(e.Zc||(e.Zc=new Map)).set(c,p)},e.unmountExternalData=()=>{delete e.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Me:!0}).buffer.constructor;let o=()=>{let c=p=>(...h)=>{let g=er;return h=p(...h),er!=g?new Promise((b,A)=>{Hu={resolve:b,reject:A}}):h};(()=>{for(let p of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])e[p]=c(e[p])})(),typeof jsepRunAsync<"u"&&(e._OrtRun=jsepRunAsync(e._OrtRun),e._OrtRunWithBinding=jsepRunAsync(e._OrtRunWithBinding)),o=void 0};e.asyncInit=()=>{o?.()};var a,i,l=(c,p)=>{throw p},u=import.meta.url,d="";if(r||s){try{d=new URL(".",u).href}catch{}s&&(i=c=>{var p=new XMLHttpRequest;return p.open("GET",c,!1),p.responseType="arraybuffer",p.send(null),new Uint8Array(p.response)}),a=async c=>{if(C(c))return new Promise((h,g)=>{var b=new XMLHttpRequest;b.open("GET",c,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?h(b.response):g(b.status)},b.onerror=g,b.send(null)});var p=await fetch(c,{credentials:"same-origin"});if(p.ok)return p.arrayBuffer();throw Error(p.status+" : "+p.url)}}var f,m,_,w,x,k,E=console.log.bind(console),M=console.error.bind(console),I=E,T=M,z=!1,C=c=>c.startsWith("file://");function v(){yr.buffer!=V.buffer&&ue()}if(n){let c=function(p){try{var h=p.data,g=h.Uc;if(g==="load"){let b=[];self.onmessage=A=>b.push(A),k=()=>{postMessage({Uc:"loaded"});for(let A of b)c(A);self.onmessage=c};for(let A of h.ne)e[A]&&!e[A].proxy||(e[A]=(...O)=>{postMessage({Uc:"callHandler",me:A,args:O})},A=="print"&&(I=e[A]),A=="printErr"&&(T=e[A]));yr=h.we,ue(),m=h.xe,Qe(),Pi()}else if(g==="run"){(function(b){var A=(v(),P)[b+52>>>2>>>0];b=(v(),P)[b+56>>>2>>>0],a1(A,A-b),oe(A)})(h.Sc),op(h.Sc,0,0,1,0,0),W0(),qu(h.Sc),X||(jb(),X=!0);try{WA(h.te,h.ad)}catch(b){if(b!="unwind")throw b}}else h.target!=="setimmediate"&&(g==="checkMailbox"?X&&vi():g&&(T(`worker: received unknown command ${g}`),T(h)))}catch(b){throw t1(),b}};var G=c,X=!1;self.onunhandledrejection=p=>{throw p.reason||p},self.onmessage=c}var V,Q,K,Y,B,P,se,ie,S,L,R,te=!1;function ue(){var c=yr.buffer;e.HEAP8=V=new Int8Array(c),K=new Int16Array(c),e.HEAPU8=Q=new Uint8Array(c),Y=new Uint16Array(c),e.HEAP32=B=new Int32Array(c),e.HEAPU32=P=new Uint32Array(c),se=new Float32Array(c),ie=new Float64Array(c),S=new BigInt64Array(c),L=new BigUint64Array(c)}function Be(){te=!0,n?k():fr.dc()}function Ce(c){throw T(c="Aborted("+c+")"),z=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),x?.(c),c}function vt(){return{a:{sa:iT,g:VA,K:HA,f:XA,n:KA,h:YA,wa:QA,b:JA,ea:ZA,Ja:Q0,o:e2,fa:tb,Za:rb,$b:sb,bc:nb,_a:ob,Xa:ab,Qa:ib,Wa:lb,qa:cb,ac:ub,Zb:pb,Ya:db,_b:fb,db:t2,Fa:s2,Ub:n2,Sb:a2,Ea:l2,P:c2,J:u2,Tb:p2,ma:w2,Vb:x2,Ta:y2,Xb:v2,Ka:k2,Pb:E2,Ha:A2,Sa:qu,ab:M2,W:I2,r:N2,c:ju,tb:$2,y:R2,N:U2,D:B2,m:D2,s:bb,ub:F2,I:j2,V:G2,j:q2,u:W2,q:V2,k:H2,Na:X2,Oa:K2,Pa:Y2,La:Ab,Ma:Mb,Rb:Tb,fb:J2,cb:tM,$:rM,sb:sM,na:nM,bb:Z2,Y:oM,$a:aM,Yb:iM,G:Q2,ib:lM,_:cM,ra:Ti,Wb:pM,hb:uM,gb:dM,pb:xM,F:yM,va:bM,ua:vM,rb:kM,Z:EM,w:AM,ob:MM,nb:TM,mb:SM,qb:OM,lb:IM,kb:CM,jb:PM,Ua:Nb,Va:$b,Ia:Et,ga:Rb,pa:Ub,Ra:Bb,oa:Db,Eb:qT,za:RT,Fb:GT,Aa:$T,H:TT,e:pT,t:cT,x:lT,B:bT,Ib:zT,L:ET,v:fT,Ba:LT,ca:UT,ja:PT,Gb:jT,Hb:FT,Da:ST,Ca:CT,Kb:OT,O:AT,da:NT,d:dT,A:mT,l:uT,Db:WT,p:_T,z:yT,C:hT,E:gT,M:vT,Lb:MT,U:BT,ka:kT,ba:DT,Mb:xT,Nb:wT,R:IT,i:LM,a:yr,eb:xr,Jb:NM,la:$M,Q:RM,ta:UM,Ob:BM,S:DM,Ab:FM,Bb:jM,xa:GM,ha:qM,T:WM,Ga:VM,ya:HM,aa:XM,yb:KM,cc:YM,X:QM,Cb:JM,vb:ZM,wb:tT,xb:rT,ia:sT,zb:nT,Qb:oT}}}async function Qe(){function c(g,b){var A=fr=g.exports;g={};for(let[O,N]of Object.entries(A))typeof N=="function"?(A=T2(N),g[O]=A):g[O]=N;return fr=g,fr=(function(){var O=fr,N=q=>fe=>q(fe)>>>0,D=q=>()=>q()>>>0;return(O=Object.assign({},O)).ec=N(O.ec),O.Hc=D(O.Hc),O.Jc=N(O.Jc),O.vd=(q=>(fe,me)=>q(fe,me)>>>0)(O.vd),O.Ad=N(O.Ad),O.Bd=D(O.Bd),O.Fd=N(O.Fd),O})(),G0.push(fr.md),Fb=(g=fr).ec,jb=g.fc,e._OrtInit=g.gc,e._OrtGetLastError=g.hc,e._OrtCreateSessionOptions=g.ic,e._OrtAppendExecutionProvider=g.jc,e._OrtAddFreeDimensionOverride=g.kc,e._OrtAddSessionConfigEntry=g.lc,e._OrtReleaseSessionOptions=g.mc,e._OrtCreateSession=g.nc,e._OrtReleaseSession=g.oc,e._OrtGetInputOutputCount=g.pc,e._OrtGetInputOutputMetadata=g.qc,e._OrtFree=g.rc,e._OrtCreateTensor=g.sc,e._OrtGetTensorData=g.tc,e._OrtReleaseTensor=g.uc,e._OrtCreateRunOptions=g.vc,e._OrtAddRunConfigEntry=g.wc,e._OrtReleaseRunOptions=g.xc,e._OrtCreateBinding=g.yc,e._OrtBindInput=g.zc,e._OrtBindOutput=g.Ac,e._OrtClearBoundOutputs=g.Bc,e._OrtReleaseBinding=g.Cc,e._OrtRunWithBinding=g.Dc,e._OrtRun=g.Ec,e._OrtEndProfiling=g.Fc,Zu=e._OrtGetWebGpuDevice=g.Gc,Ii=g.Hc,Lt=e._free=g.Ic,Cs=e._malloc=g.Jc,Gb=e._wgpuBufferRelease=g.Kc,qb=e._wgpuCreateInstance=g.Lc,Wb=g.Mc,Vb=g.Nc,Hb=g.Oc,Xb=g.Pc,Kb=g.Qc,Yb=g.Tc,Qb=g.bd,Jb=g.cd,Zb=g.dd,ep=g.fd,tp=g.gd,rp=g.hd,sp=g.id,In=g.jd,np=g.kd,e1=g.ld,op=g.od,t1=g.pd,r1=g.qd,s1=g.rd,ap=g.sd,n1=g.td,o1=g.ud,ip=g.vd,he=g.wd,Cn=g.xd,a1=g.yd,oe=g.zd,Ci=g.Ad,ae=g.Bd,i1=g.Cd,lp=g.Dd,l1=g.Ed,c1=g.Fd,u1=g.Gd,cp=g.Hd,p1=g.Id,d1=g.Jd,f1=g.Kd,m1=g.Ld,h1=g.Md,_1=g.Nd,g1=g.Od,w1=g.Pd,x1=g.Qd,y1=g.Rd,b1=g.Sd,v1=g.Td,k1=g.Ud,E1=g.Vd,A1=g.Wd,M1=g.Yd,T1=g.Zd,S1=g._d,O1=g.$d,I1=g.be,C1=g.ce,P1=g.de,z1=g.ee,L1=g.fe,N1=g.ge,$1=g.qe,R1=g.ve,U1=g.ye,B1=g.ze,D1=g.Ae,F1=g.Be,j1=g.Ce,G1=g.De,q1=g.Ee,W1=g.Fe,V1=g.Ge,H1=g.ef,X1=g.ff,K1=g.gf,Y1=g.hf,m=b,fr}var p,h=vt();return e.instantiateWasm?new Promise(g=>{e.instantiateWasm(h,(b,A)=>{g(c(b,A))})}):n?c(new WebAssembly.Instance(m,vt()),m):(R??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.asyncify.wasm",d):d+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href,p=await(async function(g){var b=R;if(!f&&!C(b))try{var A=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(A,g)}catch(O){T(`wasm streaming compile failed: ${O}`),T("falling back to ArrayBuffer instantiation")}return(async function(O,N){try{var D=await(async function(q){if(!f)try{var fe=await a(q);return new Uint8Array(fe)}catch{}if(q==R&&f)q=new Uint8Array(f);else{if(!i)throw"both async and sync fetching of the wasm failed";q=i(q)}return q})(O);return await WebAssembly.instantiate(D,N)}catch(q){T(`failed to asynchronously prepare wasm: ${q}`),Ce(q)}})(b,g)})(h),c(p.instance,p.module))}class Ze{name="ExitStatus";constructor(p){this.message=`Program terminated with exit(${p})`,this.status=p}}var rt=c=>{c.terminate(),c.onmessage=()=>{}},Me=[],xe=0,Ge=null,kt=c=>{et.length==0&&(H0(),V0(et[0]));var p=et.pop();if(!p)return 6;Sn.push(p),Xr[c.Sc]=p,p.Sc=c.Sc;var h={Uc:"run",te:c.se,ad:c.ad,Sc:c.Sc};return p.postMessage(h,c.he),0},ge=0,Le=(c,p,...h)=>{var g,b=16*h.length,A=ae(),O=Ci(b),N=O>>>3;for(g of h)typeof g=="bigint"?((v(),S)[N++>>>0]=1n,(v(),S)[N++>>>0]=g):((v(),S)[N++>>>0]=0n,(v(),ie)[N++>>>0]=g);return c=r1(c,0,b,O,p),oe(A),c};function xr(c){if(n)return Le(0,1,c);if(_=c,!(0<ge)){for(var p of Sn)rt(p);for(p of et)rt(p);et=[],Sn=[],Xr={},z=!0}l(0,new Ze(c))}function Hr(c){if(n)return Le(1,0,c);Et(c)}var Et=c=>{if(_=c,n)throw Hr(c),"unwind";xr(c)},et=[],Sn=[],G0=[],Xr={},q0=c=>{var p=c.Sc;delete Xr[p],et.push(c),Sn.splice(Sn.indexOf(c),1),c.Sc=0,s1(p)};function W0(){G0.forEach(c=>c())}var V0=c=>new Promise(p=>{c.onmessage=b=>{var A=b.data;if(b=A.Uc,A.$c&&A.$c!=Ii()){var O=Xr[A.$c];O?O.postMessage(A,A.he):T(`Internal error! Worker sent a message "${b}" to target pthread ${A.$c}, but that thread no longer exists!`)}else b==="checkMailbox"?vi():b==="spawnThread"?kt(A):b==="cleanupThread"?bi(()=>{q0(Xr[A.ue])}):b==="loaded"?(c.loaded=!0,p(c)):A.target==="setimmediate"?c.postMessage(A):b==="uncaughtException"?c.onerror(A.error):b==="callHandler"?e[A.me](...A.args):b&&T(`worker sent an unknown command ${b}`)},c.onerror=b=>{throw T(`worker sent an error! ${b.filename}:${b.lineno}: ${b.message}`),b};var h,g=[];for(h of[])e.propertyIsEnumerable(h)&&g.push(h);c.postMessage({Uc:"load",ne:g,we:yr,xe:m})});function H0(){var c=new Worker((()=>{let p=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new p("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});et.push(c)}var yr,WA=(c,p)=>{ge=0,c=cp(c,p),0<ge?_=c:ap(c)},xi=[],yi=0,wt=c=>-9007199254740992>c||9007199254740992<c?NaN:Number(c);function VA(c){var p=new Uu(c>>>=0);return(v(),V)[p.Vc+12>>>0]==0&&(X0(p,!0),yi--),K0(p,!1),xi.push(p),c1(c)}var Ms=0,HA=()=>{he(0,0);var c=xi.pop();i1(c.nd),Ms=0};function X0(c,p){p=p?1:0,(v(),V)[c.Vc+12>>>0]=p}function K0(c,p){p=p?1:0,(v(),V)[c.Vc+13>>>0]=p}class Uu{constructor(p){this.nd=p,this.Vc=p-24}}var Bu=c=>{var p=Ms;if(!p)return Cn(0),0;var h=new Uu(p);(v(),P)[h.Vc+16>>>2>>>0]=p;var g=(v(),P)[h.Vc+4>>>2>>>0];if(!g)return Cn(0),p;for(var b of c){if(b===0||b===g)break;if(l1(b,g,h.Vc+16))return Cn(b),p}return Cn(g),p};function XA(){return Bu([])}function KA(c){return Bu([c>>>0])}function YA(c,p,h,g){return Bu([c>>>0,p>>>0,h>>>0,g>>>0])}var QA=()=>{var c=xi.pop();c||Ce("no exception to throw");var p=c.nd;throw(v(),V)[c.Vc+13>>>0]==0&&(xi.push(c),K0(c,!0),X0(c,!1),yi++),lp(p),Ms=p};function JA(c,p,h){var g=new Uu(c>>>=0);throw p>>>=0,h>>>=0,(v(),P)[g.Vc+16>>>2>>>0]=0,(v(),P)[g.Vc+4>>>2>>>0]=p,(v(),P)[g.Vc+8>>>2>>>0]=h,lp(c),yi++,Ms=c}var ZA=()=>yi;function Y0(c,p,h,g){return n?Le(2,1,c,p,h,g):Q0(c,p,h,g)}function Q0(c,p,h,g){if(c>>>=0,p>>>=0,h>>>=0,g>>>=0,!globalThis.SharedArrayBuffer)return 6;var b=[];return n&&b.length===0?Y0(c,p,h,g):(c={se:h,Sc:c,ad:g,he:b},n?(c.Uc="spawnThread",postMessage(c,b),0):kt(c))}function e2(c){throw Ms||=c>>>0,Ms}var J0=globalThis.TextDecoder&&new TextDecoder,Z0=(c,p,h,g)=>{if(h=p+h,g)return h;for(;c[p]&&!(p>=h);)++p;return p},eb=(c,p=0,h,g)=>{if(16<(h=Z0(c,p>>>=0,h,g))-p&&c.buffer&&J0)return J0.decode(c.buffer instanceof ArrayBuffer?c.subarray(p,h):c.slice(p,h));for(g="";p<h;){var b=c[p++];if(128&b){var A=63&c[p++];if((224&b)==192)g+=String.fromCharCode((31&b)<<6|A);else{var O=63&c[p++];65536>(b=(240&b)==224?(15&b)<<12|A<<6|O:(7&b)<<18|A<<12|O<<6|63&c[p++])?g+=String.fromCharCode(b):(b-=65536,g+=String.fromCharCode(55296|b>>10,56320|1023&b))}}else g+=String.fromCharCode(b)}return g},Ts=(c,p,h)=>(c>>>=0)?eb((v(),Q),c,p,h):"";function tb(c,p,h){return n?Le(3,1,c,p,h):0}function rb(c,p){if(n)return Le(4,1,c,p)}function sb(c,p){if(n)return Le(5,1,c,p)}function nb(c,p,h){if(n)return Le(6,1,c,p,h)}function ob(c,p,h){return n?Le(7,1,c,p,h):0}function ab(c,p){if(n)return Le(8,1,c,p)}function ib(c,p,h){if(n)return Le(9,1,c,p,h)}function lb(c,p,h,g){if(n)return Le(10,1,c,p,h,g)}function cb(c,p,h,g){if(n)return Le(11,1,c,p,h,g)}function ub(c,p,h,g){if(n)return Le(12,1,c,p,h,g)}function pb(c){if(n)return Le(13,1,c)}function db(c,p){if(n)return Le(14,1,c,p)}function fb(c,p,h){if(n)return Le(15,1,c,p,h)}var t2=()=>Ce(""),Zt=c=>{c>>>=0;for(var p="";;){var h=(v(),Q)[c++>>>0];if(!h)return p;p+=String.fromCharCode(h)}},Du={},Fu={},r2={},Ss=class extends Error{constructor(c){super(c),this.name="BindingError"}};function cr(c,p,h={}){return(function(g,b,A={}){var O=b.name;if(!g)throw new Ss(`type "${O}" must have a positive integer typeid pointer`);if(Fu.hasOwnProperty(g)){if(A.oe)return;throw new Ss(`Cannot register type '${O}' twice`)}Fu[g]=b,delete r2[g],Du.hasOwnProperty(g)&&(b=Du[g],delete Du[g],b.forEach(N=>N()))})(c,p,h)}var mb=(c,p,h)=>{switch(p){case 1:return h?g=>(v(),V)[g>>>0]:g=>(v(),Q)[g>>>0];case 2:return h?g=>(v(),K)[g>>>1>>>0]:g=>(v(),Y)[g>>>1>>>0];case 4:return h?g=>(v(),B)[g>>>2>>>0]:g=>(v(),P)[g>>>2>>>0];case 8:return h?g=>(v(),S)[g>>>3>>>0]:g=>(v(),L)[g>>>3>>>0];default:throw new TypeError(`invalid integer width (${p}): ${c}`)}};function s2(c,p,h,g,b){c>>>=0,h>>>=0,p=Zt(p>>>0);let A=O=>O;if(g=g===0n){let O=8*h;A=N=>BigInt.asUintN(O,N),b=A(b)}cr(c,{name:p,Rc:A,Xc:(O,N)=>(typeof N=="number"&&(N=BigInt(N)),N),Wc:mb(p,h,!g),Yc:null})}function n2(c,p,h,g){cr(c>>>=0,{name:p=Zt(p>>>0),Rc:function(b){return!!b},Xc:function(b,A){return A?h:g},Wc:function(b){return this.Rc((v(),Q)[b>>>0])},Yc:null})}var hb=[],Kr=[0,1,,1,null,1,!0,1,!1,1];function ju(c){9<(c>>>=0)&&--Kr[c+1]==0&&(Kr[c]=void 0,hb.push(c))}var zt=c=>{if(!c)throw new Ss(`Cannot use deleted val. handle = ${c}`);return Kr[c]},qt=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let p=hb.pop()||Kr.length;return Kr[p]=c,Kr[p+1]=1,p}};function Gu(c){return this.Rc((v(),P)[c>>>2>>>0])}var o2={name:"emscripten::val",Rc:c=>{var p=zt(c);return ju(c),p},Xc:(c,p)=>qt(p),Wc:Gu,Yc:null};function a2(c){return cr(c>>>0,o2)}var i2=(c,p)=>{switch(p){case 4:return function(h){return this.Rc((v(),se)[h>>>2>>>0])};case 8:return function(h){return this.Rc((v(),ie)[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${p}): ${c}`)}};function l2(c,p,h){h>>>=0,cr(c>>>=0,{name:p=Zt(p>>>0),Rc:g=>g,Xc:(g,b)=>b,Wc:i2(p,h),Yc:null})}function c2(c,p,h,g,b){c>>>=0,h>>>=0,p=Zt(p>>>0);let A=N=>N;if(g===0){var O=32-8*h;A=N=>N<<O>>>O,b=A(b)}cr(c,{name:p,Rc:A,Xc:(N,D)=>D,Wc:mb(p,h,g!==0),Yc:null})}function u2(c,p,h){function g(A){var O=(v(),P)[A>>>2>>>0];return A=(v(),P)[A+4>>>2>>>0],new b((v(),V).buffer,A,O)}var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][p];cr(c>>>=0,{name:h=Zt(h>>>0),Rc:g,Wc:g},{oe:!0})}var ur=(c,p,h)=>{var g=(v(),Q);if(p>>>=0,0<h){var b=p;h=p+h-1;for(var A=0;A<c.length;++A){var O=c.codePointAt(A);if(127>=O){if(p>=h)break;g[p++>>>0]=O}else if(2047>=O){if(p+1>=h)break;g[p++>>>0]=192|O>>6,g[p++>>>0]=128|63&O}else if(65535>=O){if(p+2>=h)break;g[p++>>>0]=224|O>>12,g[p++>>>0]=128|O>>6&63,g[p++>>>0]=128|63&O}else{if(p+3>=h)break;g[p++>>>0]=240|O>>18,g[p++>>>0]=128|O>>12&63,g[p++>>>0]=128|O>>6&63,g[p++>>>0]=128|63&O,A++}}g[p>>>0]=0,c=p-b}else c=0;return c},pr=c=>{for(var p=0,h=0;h<c.length;++h){var g=c.charCodeAt(h);127>=g?p++:2047>=g?p+=2:55296<=g&&57343>=g?(p+=4,++h):p+=3}return p};function p2(c,p){cr(c>>>=0,{name:p=Zt(p>>>0),Rc(h){var g=(v(),P)[h>>>2>>>0];return g=Ts(h+4,g,!0),Lt(h),g},Xc(h,g){g instanceof ArrayBuffer&&(g=new Uint8Array(g));var b=typeof g=="string";if(!(b||ArrayBuffer.isView(g)&&g.BYTES_PER_ELEMENT==1))throw new Ss("Cannot pass non-string to std::string");var A=b?pr(g):g.length,O=Cs(4+A+1),N=O+4;return(v(),P)[O>>>2>>>0]=A,b?ur(g,N,A+1):(v(),Q).set(g,N>>>0),h!==null&&h.push(Lt,O),O},Wc:Gu,Yc(h){Lt(h)}})}var _b=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,d2=(c,p,h)=>{if(c>>>=1,16<(p=Z0((v(),Y),c,p/2,h))-c&&_b)return _b.decode((v(),Y).slice(c,p));for(h="";c<p;++c){var g=(v(),Y)[c>>>0];h+=String.fromCharCode(g)}return h},f2=(c,p,h)=>{if(h??=2147483647,2>h)return 0;var g=p;h=(h-=2)<2*c.length?h/2:c.length;for(var b=0;b<h;++b){var A=c.charCodeAt(b);(v(),K)[p>>>1>>>0]=A,p+=2}return(v(),K)[p>>>1>>>0]=0,p-g},m2=c=>2*c.length,h2=(c,p,h)=>{var g="";c>>>=2;for(var b=0;!(b>=p/4);b++){var A=(v(),P)[c+b>>>0];if(!A&&!h)break;g+=String.fromCodePoint(A)}return g},_2=(c,p,h)=>{if(p>>>=0,h??=2147483647,4>h)return 0;var g=p;h=g+h-4;for(var b=0;b<c.length;++b){var A=c.codePointAt(b);if(65535<A&&b++,(v(),B)[p>>>2>>>0]=A,(p+=4)+4>h)break}return(v(),B)[p>>>2>>>0]=0,p-g},g2=c=>{for(var p=0,h=0;h<c.length;++h)65535<c.codePointAt(h)&&h++,p+=4;return p};function w2(c,p,h){if(c>>>=0,p>>>=0,h=Zt(h>>>=0),p===2)var g=d2,b=f2,A=m2;else g=h2,b=_2,A=g2;cr(c,{name:h,Rc:O=>{var N=(v(),P)[O>>>2>>>0];return N=g(O+4,N*p,!0),Lt(O),N},Xc:(O,N)=>{if(typeof N!="string")throw new Ss(`Cannot pass non-string to C++ string type ${h}`);var D=A(N),q=Cs(4+D+p);return(v(),P)[q>>>2>>>0]=D/p,b(N,q+4,D+p),O!==null&&O.push(Lt,q),q},Wc:Gu,Yc(O){Lt(O)}})}function x2(c,p){cr(c>>>=0,{pe:!0,name:p=Zt(p>>>0),Rc:()=>{},Xc:()=>{}})}function y2(c){op(c>>>0,!s,1,!r,131072,!1),W0()}var bi=c=>{if(!z)try{if(c(),!(0<ge))try{n?Ii()&&ap(_):Et(_)}catch(p){p instanceof Ze||p=="unwind"||l(0,p)}}catch(p){p instanceof Ze||p=="unwind"||l(0,p)}},b2=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function qu(c){c>>>=0,b2||(Atomics.waitAsync((v(),B),c>>>2,c).value.then(vi),c+=128,Atomics.store((v(),B),c>>>2,1))}var vi=()=>bi(()=>{var c=Ii();c&&(qu(c),o1())});function v2(c,p){(c>>>=0)==p>>>0?setTimeout(vi):n?postMessage({$c:c,Uc:"checkMailbox"}):(c=Xr[c])&&c.postMessage({Uc:"checkMailbox"})}var Wu=[];function k2(c,p,h,g,b){for(p>>>=0,b>>>=0,Wu.length=0,h=b>>>3,g=b+g>>>3;h<g;){var A;A=(v(),S)[h++>>>0]?(v(),S)[h++>>>0]:(v(),ie)[h++>>>0],Wu.push(A)}return(p?up[p]:aT[c])(...Wu)}var E2=()=>{ge=0};function A2(c){c>>>=0,n?postMessage({Uc:"cleanupThread",ue:c}):q0(Xr[c])}function M2(c){}var ki=c=>{try{c()}catch(p){Ce(p)}};function T2(c){var p=(...h)=>{Ei.push(c);try{return c(...h)}finally{z||(Ei.pop(),er&&br===1&&Ei.length===0&&(br=0,ge+=1,ki(X1),typeof Fibers<"u"&&Fibers.Oe()))}};return xb.set(c,p),p}var br=0,er=null,gb=0,Ei=[],Vu=new Map,wb=new Map,xb=new Map,S2=0,Hu=null,O2=[],yb=c=>(function(p){if(!z){if(br===0){var h=!1,g=!1;p((b=0)=>{if(!z&&(gb=b,h=!0,g)){br=2,ki(()=>K1(er)),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.resume(),b=!1;try{var A=(function(){var D=(v(),B)[er+8>>>2>>>0];return D=wb.get(D),D=xb.get(D),--ge,D()})()}catch(D){A=D,b=!0}var O=!1;if(!er){var N=Hu;N&&(Hu=null,(b?N.reject:N.resolve)(A),O=!0)}if(b&&!O)throw A}}),g=!0,h||(br=1,er=(function(){var b=Cs(65548),A=b+12;if((v(),P)[b>>>2>>>0]=A,(v(),P)[b+4>>>2>>>0]=A+65536,A=Ei[0],!Vu.has(A)){var O=S2++;Vu.set(A,O),wb.set(O,A)}return A=Vu.get(A),(v(),B)[b+8>>>2>>>0]=A,b})(),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.pause(),ki(()=>H1(er)))}else br===2?(br=0,ki(Y1),Lt(er),er=null,O2.forEach(bi)):Ce(`invalid state: ${br}`);return gb}})(p=>{c().then(p)});function I2(c){return c>>>=0,yb(async()=>{var p=await zt(c);return qt(p)})}var Xu=[],C2=c=>{var p=Xu.length;return Xu.push(c),p},P2=(c,p)=>{for(var h=Array(c),g=0;g<c;++g){var b=g,A=(v(),P)[p+4*g>>>2>>>0],O=Fu[A];if(O===void 0)throw c=`parameter ${g}`,A=Fb(A),p=Zt(A),Lt(A),new Ss(`${c} has unknown type ${p}`);h[b]=O}return h},z2=(c,p,h)=>{var g=[];return c=c(g,h),g.length&&((v(),P)[p>>>2>>>0]=qt(g)),c},L2={},Ai=c=>{var p=L2[c];return p===void 0?Zt(c):p};function N2(c,p,h){var[g,...b]=P2(c,p>>>0);p=g.Xc.bind(g);var A=b.map(D=>D.Wc.bind(D));c--;var O={toValue:zt};switch(c=A.map((D,q)=>{var fe=`argFromPtr${q}`;return O[fe]=D,`${fe}(args${q?"+"+8*q:""})`}),h){case 0:var N="toValue(handle)";break;case 2:N="new (toValue(handle))";break;case 3:N="";break;case 1:O.getStringOrSymbol=Ai,N="toValue(handle)[getStringOrSymbol(methodName)]"}return N+=`(${c})`,g.pe||(O.toReturnWire=p,O.emval_returnValue=z2,N=`return emval_returnValue(toReturnWire, destructorsRef, ${N})`),N=`return function (handle, methodName, destructorsRef, args) {
|
|
11
11
|
${N}
|
|
12
12
|
}`,h=new Function(Object.keys(O),N)(...Object.values(O)),N=`methodCaller<(${b.map(D=>D.name)}) => ${g.name}>`,C2(Object.defineProperty(h,"name",{value:N}))}function $2(c,p){return p>>>=0,(c=zt(c>>>0))==zt(p)}function R2(c){return(c>>>=0)?(c=Ai(c),qt(globalThis[c])):qt(globalThis)}function U2(c){return c=Ai(c>>>0),qt(e[c])}function B2(c,p){return p>>>=0,c=zt(c>>>0),p=zt(p),qt(c[p])}function D2(c){9<(c>>>=0)&&(Kr[c+1]+=1)}function bb(c,p,h,g,b){return Xu[c>>>0](p>>>0,h>>>0,g>>>0,b>>>0)}function F2(c,p,h,g,b){return bb(c>>>0,p>>>0,h>>>0,g>>>0,b>>>0)}function j2(){return qt([])}function G2(c){c=zt(c>>>0);for(var p=Array(c.length),h=0;h<c.length;h++)p[h]=c[h];return qt(p)}function q2(c){return qt(Ai(c>>>0))}function W2(){return qt({})}function V2(c){for(var p=zt(c>>>=0);p.length;){var h=p.pop();p.pop()(h)}ju(c)}function H2(c,p,h){p>>>=0,h>>>=0,c=zt(c>>>0),p=zt(p),h=zt(h),c[p]=h}function X2(c,p){c=wt(c),p>>>=0,c=new Date(1e3*c),(v(),B)[p>>>2>>>0]=c.getUTCSeconds(),(v(),B)[p+4>>>2>>>0]=c.getUTCMinutes(),(v(),B)[p+8>>>2>>>0]=c.getUTCHours(),(v(),B)[p+12>>>2>>>0]=c.getUTCDate(),(v(),B)[p+16>>>2>>>0]=c.getUTCMonth(),(v(),B)[p+20>>>2>>>0]=c.getUTCFullYear()-1900,(v(),B)[p+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(v(),B)[p+28>>>2>>>0]=c}var vb=c=>c%4==0&&(c%100!=0||c%400==0),kb=[0,31,60,91,121,152,182,213,244,274,305,335],Eb=[0,31,59,90,120,151,181,212,243,273,304,334];function K2(c,p){c=wt(c),p>>>=0,c=new Date(1e3*c),(v(),B)[p>>>2>>>0]=c.getSeconds(),(v(),B)[p+4>>>2>>>0]=c.getMinutes(),(v(),B)[p+8>>>2>>>0]=c.getHours(),(v(),B)[p+12>>>2>>>0]=c.getDate(),(v(),B)[p+16>>>2>>>0]=c.getMonth(),(v(),B)[p+20>>>2>>>0]=c.getFullYear()-1900,(v(),B)[p+24>>>2>>>0]=c.getDay();var h=(vb(c.getFullYear())?kb:Eb)[c.getMonth()]+c.getDate()-1|0;(v(),B)[p+28>>>2>>>0]=h,(v(),B)[p+36>>>2>>>0]=-60*c.getTimezoneOffset(),h=new Date(c.getFullYear(),6,1).getTimezoneOffset();var g=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(h!=g&&c.getTimezoneOffset()==Math.min(g,h)),(v(),B)[p+32>>>2>>>0]=c}function Y2(c){c>>>=0;var p=new Date((v(),B)[c+20>>>2>>>0]+1900,(v(),B)[c+16>>>2>>>0],(v(),B)[c+12>>>2>>>0],(v(),B)[c+8>>>2>>>0],(v(),B)[c+4>>>2>>>0],(v(),B)[c>>>2>>>0],0),h=(v(),B)[c+32>>>2>>>0],g=p.getTimezoneOffset(),b=new Date(p.getFullYear(),6,1).getTimezoneOffset(),A=new Date(p.getFullYear(),0,1).getTimezoneOffset(),O=Math.min(A,b);return 0>h?(v(),B)[c+32>>>2>>>0]=+(b!=A&&O==g):0<h!=(O==g)&&(b=Math.max(A,b),p.setTime(p.getTime()+6e4*((0<h?O:b)-g))),(v(),B)[c+24>>>2>>>0]=p.getDay(),h=(vb(p.getFullYear())?kb:Eb)[p.getMonth()]+p.getDate()-1|0,(v(),B)[c+28>>>2>>>0]=h,(v(),B)[c>>>2>>>0]=p.getSeconds(),(v(),B)[c+4>>>2>>>0]=p.getMinutes(),(v(),B)[c+8>>>2>>>0]=p.getHours(),(v(),B)[c+12>>>2>>>0]=p.getDate(),(v(),B)[c+16>>>2>>>0]=p.getMonth(),(v(),B)[c+20>>>2>>>0]=p.getYear(),c=p.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function Ab(c,p,h,g,b,A,O){return n?Le(16,1,c,p,h,g,b,A,O):-52}function Mb(c,p,h,g,b,A){if(n)return Le(17,1,c,p,h,g,b,A)}var On={},Q2=()=>performance.timeOrigin+performance.now();function Tb(c,p){if(n)return Le(18,1,c,p);if(On[c]&&(clearTimeout(On[c].id),delete On[c]),!p)return 0;var h=setTimeout(()=>{delete On[c],bi(()=>n1(c,performance.timeOrigin+performance.now()))},p);return On[c]={id:h,Ne:p},0}function J2(c,p,h,g){c>>>=0,p>>>=0,h>>>=0,g>>>=0;var b=new Date().getFullYear(),A=new Date(b,0,1).getTimezoneOffset();b=new Date(b,6,1).getTimezoneOffset();var O=Math.max(A,b);(v(),P)[c>>>2>>>0]=60*O,(v(),B)[p>>>2>>>0]=+(A!=b),c=(p=N=>{var D=Math.abs(N);return`UTC${0<=N?"-":"+"}${String(Math.floor(D/60)).padStart(2,"0")}${String(D%60).padStart(2,"0")}`})(A),p=p(b),b<A?(ur(c,h,17),ur(p,g,17)):(ur(c,g,17),ur(p,h,17))}var Z2=()=>Date.now(),eM=1;function tM(c,p,h){if(h>>>=0,!(0<=c&&3>=c))return 28;if(c===0)c=Date.now();else{if(!eM)return 52;c=performance.timeOrigin+performance.now()}return c=Math.round(1e6*c),(v(),S)[h>>>3>>>0]=BigInt(c),0}var Ku=[],Sb=(c,p)=>{Ku.length=0;for(var h;h=(v(),Q)[c++>>>0];){var g=h!=105;p+=(g&=h!=112)&&p%8?4:0,Ku.push(h==112?(v(),P)[p>>>2>>>0]:h==106?(v(),S)[p>>>3>>>0]:h==105?(v(),B)[p>>>2>>>0]:(v(),ie)[p>>>3>>>0]),p+=g?8:4}return Ku};function rM(c,p,h){return c>>>=0,p=Sb(p>>>0,h>>>0),up[c](...p)}function sM(c,p,h){return c>>>=0,p=Sb(p>>>0,h>>>0),up[c](...p)}var nM=()=>{};function oM(c,p){return T(Ts(c>>>0,p>>>0))}var aM=()=>{throw ge+=1,"unwind"};function iM(){return 4294901760}var lM=()=>1,cM=()=>navigator.hardwareConcurrency,Yr={},Ob=c=>{var p=pr(c)+1,h=Cs(p);return h&&ur(c,h,p),h},Mi=c=>{var p;return(p=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(c))?+p[1]:(p=/:(\d+):\d+(?:\)|$)/.exec(c))?2147483648|+p[1]:0},Ib=c=>{for(var p of c)(c=Mi(p))&&(Yr[c]=p)};function uM(){var c=Error().stack.toString().split(`
|
|
13
13
|
`);return c[0]=="Error"&&c.shift(),Ib(c),Yr.Xd=Mi(c[3]),Yr.re=c,Yr.Xd}function Ti(c){if(!(c=Yr[c>>>0]))return 0;var p;if(p=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(c))c=p[1];else if(p=/^\s+at (.*) \(.*\)$/.exec(c))c=p[1];else{if(!(p=/^(.+?)@/.exec(c)))return 0;c=p[1]}return Lt(Ti.ae??0),Ti.ae=Ob(c),Ti.ae}function pM(c){c>>>=0;var p=(v(),Q).length;if(c<=p||4294901760<c)return!1;for(var h=1;4>=h;h*=2){var g=p*(1+.2/h);g=Math.min(g,c+100663296);e:{g=(Math.min(4294901760,65536*Math.ceil(Math.max(c,g)/65536))-yr.buffer.byteLength+65535)/65536|0;try{yr.grow(g),ue();var b=1;break e}catch{}b=void 0}if(b)return!0}return!1}function dM(c,p,h){if(c>>>=0,p>>>=0,Yr.Xd==c)var g=Yr.re;else(g=Error().stack.toString().split(`
|
|
14
|
-
`))[0]=="Error"&&g.shift(),Ib(g);for(var b=3;g[b]&&Mi(g[b])!=c;)++b;for(c=0;c<h&&g[c+b];++c)(v(),B)[p+4*c>>>2>>>0]=Mi(g[c+b]);return c}var tr=c=>{var p=pr(c)+1,h=Ci(p);return ur(c,h,p),h},Yu=[],xt=(c,p)=>{Yu[c>>>=0]=p},rr=[],Si=[],Os=(c,p)=>{Si[c]=new Promise(h=>p.finally(()=>h(c)))},re=c=>{if(c)return Yu[c>>>0]},Oi=(c,p,h)=>{(v(),P)[c>>>2>>>0]=p,(v(),P)[c+4>>>2>>>0]=h},Cb=c=>{var p=(v(),P)[c>>>2>>>0];return c=(v(),P)[c+4>>>2>>>0],Ts(p,c)},dr=c=>{var p=(v(),P)[c>>>2>>>0];return c=(v(),P)[c+4>>>2>>>0],p?Ts(p,c):c===0?"":void 0},fM=c=>{var p=dr(c+4),h=(h=(v(),P)[c+12>>>2>>>0])?re(h):"auto";if(c+=16){var g=re((v(),P)[c+4>>>2>>>0]),b=(v(),P)[c+16>>>2>>>0],A=(v(),P)[c+20>>>2>>>0];if(b){for(var O={},N=0;N<b;++N){var D=A+24*N;O[Cb(D+4)]=(v(),ie)[D+16>>>3>>>0]}b=O}else b=void 0;c={module:g,constants:b,entryPoint:dr(c+8)}}else c=void 0;return{label:p,layout:h,compute:c}},Pb=(c,p)=>{function h(b,A){b=c[b],(v(),B)[p+A>>>2>>>0]=b}function g(b,A){b=c[b],(v(),S)[p+A>>>3>>>0]=BigInt(b)}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),g("maxUniformBufferBindingSize",64),g("maxStorageBufferBindingSize",72),h("maxVertexBuffers",88),g("maxBufferSize",96),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),c.Le!==void 0&&h("maxImmediateSize",148)},mM=[,"validation","out-of-memory","internal"],hM=[,"compatibility","core"],zb={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",327692:"chromium-experimental-unorm16-texture-formats",327693:"chromium-experimental-snorm16-texture-formats",327732:"chromium-experimental-multi-draw-indirect"},_M=[,"low-power","high-performance"],gM=[,"occlusion","timestamp"],wM={undefined:1,unknown:1,destroyed:2};function xM(c,p,h,g,b,A){p=wt(p),h=wt(h),g>>>=0,b>>>=0,A>>>=0;var O=re(c>>>0);if(c={},A){var N=(v(),P)[A+12>>>2>>>0];if(N){var D=(v(),P)[A+16>>>2>>>0];c.requiredFeatures=Array.from((v(),P).subarray(D>>>2>>>0,D+4*N>>>2>>>0),ee=>zb[ee])}var q=(v(),P)[A+20>>>2>>>0];if(q){let ee=function(Nt,st,Qr=!1){st=q+st,(st=(v(),P)[st>>>2>>>0])==4294967295||Qr&&st==0||(Re[Nt]=st)},lt=function(Nt,st){st=q+st;var Qr=(v(),P)[st>>>2>>>0],VT=(v(),P)[st+4>>>2>>>0];Qr==4294967295&&VT==4294967295||(Re[Nt]=4294967296*(v(),P)[st+4>>>2>>>0]+(v(),P)[st>>>2>>>0])};var fe=ee,me=lt,Re={};ee("maxTextureDimension1D",4),ee("maxTextureDimension2D",8),ee("maxTextureDimension3D",12),ee("maxTextureArrayLayers",16),ee("maxBindGroups",20),ee("maxBindGroupsPlusVertexBuffers",24),ee("maxDynamicUniformBuffersPerPipelineLayout",32),ee("maxDynamicStorageBuffersPerPipelineLayout",36),ee("maxSampledTexturesPerShaderStage",40),ee("maxSamplersPerShaderStage",44),ee("maxStorageBuffersPerShaderStage",48),ee("maxStorageTexturesPerShaderStage",52),ee("maxUniformBuffersPerShaderStage",56),ee("minUniformBufferOffsetAlignment",80),ee("minStorageBufferOffsetAlignment",84),lt("maxUniformBufferBindingSize",64),lt("maxStorageBufferBindingSize",72),ee("maxVertexBuffers",88),lt("maxBufferSize",96),ee("maxVertexAttributes",104),ee("maxVertexBufferArrayStride",108),ee("maxInterStageShaderVariables",112),ee("maxColorAttachments",116),ee("maxColorAttachmentBytesPerSample",120),ee("maxComputeWorkgroupStorageSize",124),ee("maxComputeInvocationsPerWorkgroup",128),ee("maxComputeWorkgroupSizeX",132),ee("maxComputeWorkgroupSizeY",136),ee("maxComputeWorkgroupSizeZ",140),ee("maxComputeWorkgroupsPerDimension",144),ee("maxImmediateSize",148,!0),c.requiredLimits=Re}(N=(v(),P)[A+24>>>2>>>0])&&(N={label:dr(N+4)},c.defaultQueue=N),c.label=dr(A+4)}ge+=1,Os(p,O.requestDevice(c).then(ee=>{--ge,xt(b,ee.queue),xt(g,ee),h&&(ge+=1,Os(h,ee.lost.then(lt=>{--ge,ee.onuncapturederror=()=>{};var Nt=ae(),st=tr(lt.message);tp(h,wM[lt.reason],st),oe(Nt)}))),ee.onuncapturederror=lt=>{var Nt=5;lt.error instanceof GPUValidationError?Nt=2:lt.error instanceof GPUOutOfMemoryError?Nt=3:lt.error instanceof GPUInternalError&&(Nt=4);var st=ae();lt=tr(lt.error.message),e1(g,Nt,lt),oe(st)},"adapterInfo"in ee||(ee.adapterInfo=O.info),np(p,1,g,0)},ee=>{--ge;var lt=ae();ee=tr(ee.message),np(p,3,g,ee),h&&tp(h,4,ee),oe(lt)}))}function yM(c){var p=re(c>>>=0),h=rr[c];if(h){for(var g=0;g<h.length;++g)h[g]();delete rr[c]}p.destroy()}var Is=()=>{var c="getMappedRange size=0 no longer means WGPU_WHOLE_MAP_SIZE";Is.ed||(Is.ed={}),Is.ed[c]||(Is.ed[c]=1,T(c))};function bM(c,p,h){p>>>=0,h>>>=0;var g=re(c>>>=0);h===0&&Is(),h==4294967295&&(h=void 0);try{var b=g.getMappedRange(p,h)}catch{return 0}var A=ip(16,b.byteLength);return(v(),Q).set(new Uint8Array(b),A>>>0),rr[c].push(()=>Lt(A)),A}function vM(c,p,h){p>>>=0,h>>>=0;var g=re(c>>>=0);h===0&&Is(),h==4294967295&&(h=void 0);try{var b=g.getMappedRange(p,h)}catch{return 0}var A=ip(16,b.byteLength);return(v(),Q).fill(0,A,b.byteLength),rr[c].push(()=>{new Uint8Array(b).set((v(),Q).subarray(A>>>0,A+b.byteLength>>>0)),Lt(A)}),A}function kM(c,p,h,g,b){c>>>=0,p=wt(p),h=wt(h),b>>>=0;var A=re(c);rr[c]=[],b==4294967295&&(b=void 0),ge+=1,Os(p,A.mapAsync(h,g>>>0,b).then(()=>{--ge,rp(p,1,0)},O=>{--ge,ae();var N=tr(O.message);rp(p,O.name==="AbortError"?4:O.name==="OperationError"?3:0,N),delete rr[c]}))}function EM(c){var p=re(c>>>=0),h=rr[c];if(h){for(var g=0;g<h.length;++g)h[g]();delete rr[c],p.unmap()}}function AM(c){delete Yu[c>>>0]}function MM(c,p,h){c>>>=0,p>>>=0,h>>>=0;var g=!!(v(),P)[p+32>>>2>>>0];p={label:dr(p+4),usage:(v(),P)[p+16>>>2>>>0],size:4294967296*(v(),P)[p+28>>>2>>>0]+(v(),P)[p+24>>>2>>>0],mappedAtCreation:g},c=re(c);try{var b=c.createBuffer(p)}catch{return!1}return xt(h,b),g&&(rr[h]=[]),!0}function TM(c,p,h,g){c>>>=0,p=wt(p),g>>>=0,h=fM(h>>>0),c=re(c),ge+=1,Os(p,c.createComputePipelineAsync(h).then(b=>{--ge,xt(g,b),ep(p,1,g,0)},b=>{--ge;var A=ae(),O=tr(b.message);ep(p,b.reason==="validation"?3:b.reason==="internal"?4:0,g,O),oe(A)}))}function SM(c,p,h){c>>>=0,p>>>=0,h>>>=0;var g=(v(),P)[p>>>2>>>0],b=(v(),P)[g+4>>>2>>>0];p={label:dr(p+4),code:""},b===2&&(p.code=Cb(g+8)),xt(h,re(c).createShaderModule(p))}var OM=c=>{(c=re(c)).onuncapturederror=null,c.destroy()};function IM(c,p){p=wt(p),c=re(c>>>0),ge+=1,Os(p,c.popErrorScope().then(h=>{--ge;var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var b=ae();h=h?tr(h.message):0,sp(p,1,g,h),oe(b)},h=>{--ge;var g=ae();h=tr(h.message),sp(p,1,5,h),oe(g)}))}function CM(c,p,h,g){if(p=wt(p),g>>>=0,h>>>=0){var b=(v(),P)[h+4>>>2>>>0];b={featureLevel:hM[b],powerPreference:_M[(v(),P)[h+8>>>2>>>0]],forceFallbackAdapter:!!(v(),P)[h+12>>>2>>>0]},(h=(v(),P)[h>>>2>>>0])!==0&&(v(),b.Qe=!!(v(),P)[h+8>>>2>>>0])}"gpu"in navigator?(ge+=1,Os(p,navigator.gpu.requestAdapter(b).then(A=>{if(--ge,A)xt(g,A),In(p,1,g,0);else{A=ae();var O=tr("WebGPU not available on this browser (requestAdapter returned null)");In(p,3,g,O),oe(A)}},A=>{--ge;var O=ae();A=tr(A.message),In(p,4,g,A),oe(O)}))):(h=ae(),b=tr("WebGPU not available on this browser (navigator.gpu is not available)"),In(p,3,g,b),oe(h))}function PM(c,p,h){return c>>>=0,p>>>=0,h>>>=0,yb(async()=>{var g=[];if(h){var b=(v(),B)[h>>>2>>>0];g.length=p+1,g[p]=new Promise(N=>setTimeout(N,b,0))}else g.length=p;for(var A=0;A<p;++A){var O=4294967296*(v(),P)[c+8*A+4>>>2>>>0]+(v(),P)[c+8*A>>>2>>>0];if(!(O in Si))return O;g[A]=Si[O]}return g=await Promise.race(g),delete Si[g],g})}var Qu,Ju={},Lb=()=>{if(!Qu){var c,p={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in Ju)Ju[c]===void 0?delete p[c]:p[c]=Ju[c];var h=[];for(c in p)h.push(`${c}=${p[c]}`);Qu=h}return Qu};function Nb(c,p){if(n)return Le(19,1,c,p);c>>>=0,p>>>=0;var h,g=0,b=0;for(h of Lb()){var A=p+g;(v(),P)[c+b>>>2>>>0]=A,g+=ur(h,A,1/0)+1,b+=4}return 0}function $b(c,p){if(n)return Le(20,1,c,p);c>>>=0,p>>>=0;var h=Lb();for(var g of((v(),P)[c>>>2>>>0]=h.length,c=0,h))c+=pr(g)+1;return(v(),P)[p>>>2>>>0]=c,0}function Rb(c){return n?Le(21,1,c):52}function Ub(c,p,h,g){return n?Le(22,1,c,p,h,g):52}function Bb(c,p,h,g){return n?Le(23,1,c,p,h,g):70}var zM=[null,[],[]];function Db(c,p,h,g){if(n)return Le(24,1,c,p,h,g);p>>>=0,h>>>=0,g>>>=0;for(var b=0,A=0;A<h;A++){var O=(v(),P)[p>>>2>>>0],N=(v(),P)[p+4>>>2>>>0];p+=8;for(var D=0;D<N;D++){var q=c,fe=(v(),Q)[O+D>>>0],me=zM[q];fe===0||fe===10?((q===1?I:T)(eb(me)),me.length=0):me.push(fe)}b+=N}return(v(),P)[g>>>2>>>0]=b,0}function LM(c){return c>>>0}function NM(c,p){return Pb(re(c>>>0).limits,p>>>0),1}function $M(c,p){return re(c>>>0).features.has(zb[p])}function RM(c){return BigInt(re(c>>>0).size)}function UM(c){return BigInt(re(c>>>0).usage)}function BM(c,p){if(c>>>=0,p>>>=0){var h=dr(p+4);h={label:h,timestampWrites:p=(p=(v(),P)[p+12>>>2>>>0])!==0?{querySet:re((v(),P)[p+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),P)[p+8>>>2>>>0],endOfPassWriteIndex:(v(),P)[p+12>>>2>>>0]}:void 0}}return c=re(c),p=Kb(0),xt(p,c.beginComputePass(h)),p}function DM(c,p,h,g,b,A){h=wt(h),b=wt(b),A=wt(A),re(c>>>0).copyBufferToBuffer(re(p>>>0),h,re(g>>>0),b,A)}function FM(c){c=re(c>>>0);var p=Hb(0);return xt(p,c.finish()),p}function jM(c,p,h,g,b,A){A=wt(A),re(c>>>0).resolveQuerySet(re(p>>>0),h,g,re(b>>>0),A)}function GM(c,p,h,g){re(c>>>0).dispatchWorkgroups(p,h,g)}function qM(c,p,h){h=wt(h),re(c>>>0).dispatchWorkgroupsIndirect(re(p>>>0),h)}function WM(c){re(c>>>0).end()}function VM(c,p,h,g,b){g>>>=0,b>>>=0,c=re(c>>>0),h=re(h>>>0),g==0?c.setBindGroup(p,h):c.setBindGroup(p,h,(v(),P),b>>>2,g)}function HM(c,p){re(c>>>0).setPipeline(re(p>>>0))}function XM(c,p,h){re(c>>>0).Pe(re(p>>>0),h)}function KM(c,p){c=re(c>>>0);var h=Vb(0);return xt(h,c.getBindGroupLayout(p)),h}function YM(c,p){c>>>=0;var h=dr(4+(p>>>=0)),g=re((v(),P)[p+12>>>2>>>0]),b=(v(),P)[p+16>>>2>>>0];p=(v(),P)[p+20>>>2>>>0];for(var A=[],O=0;O<b;++O){var N=A,D=N.push,q=p+40*O,fe=(v(),P)[q+8>>>2>>>0],me=(v(),P)[q+32>>>2>>>0],Re=(v(),P)[q+36>>>2>>>0],ee=(v(),P)[q+4>>>2>>>0];fe?(me=q+24,(me=(v(),P)[me>>>2>>>0]+4294967296*(v(),B)[me+4>>>2>>>0])==-1&&(me=void 0),q={binding:ee,resource:{buffer:re(fe),offset:4294967296*(v(),P)[q+4+16>>>2>>>0]+(v(),P)[q+16>>>2>>>0],size:me}}):q=me?{binding:ee,resource:re(me)}:{binding:ee,resource:re(Re)},D.call(N,q)}return h={label:h,layout:g,entries:A},c=re(c),g=Wb(0),xt(g,c.createBindGroup(h)),g}function QM(c,p){var h;return c>>>=0,(p>>>=0)&&(h={label:dr(p+4)}),c=re(c),p=Xb(0),xt(p,c.createCommandEncoder(h)),p}function JM(c,p){c>>>=0,p>>>=0,p={type:gM[(v(),P)[p+12>>>2>>>0]],count:(v(),P)[p+16>>>2>>>0]},c=re(c);var h=Yb(0);return xt(h,c.createQuerySet(p)),h}function ZM(c,p){c=re(c>>>0).adapterInfo,p>>>=0,(v(),B)[p+52>>>2>>>0]=c.subgroupMinSize,(v(),B)[p+56>>>2>>>0]=c.subgroupMaxSize;var h=Ob(c.vendor+c.architecture+c.device+c.description),g=pr(c.vendor);return Oi(p+4,h,g),h+=g,g=pr(c.architecture),Oi(p+12,h,g),h+=g,g=pr(c.device),Oi(p+20,h,g),Oi(p+28,h+g,pr(c.description)),(v(),B)[p+36>>>2>>>0]=2,c=c.isFallbackAdapter?3:4,(v(),B)[p+40>>>2>>>0]=c,(v(),B)[p+44>>>2>>>0]=0,(v(),B)[p+48>>>2>>>0]=0,1}var eT={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-snorm16-texture-formats":327693,"chromium-experimental-multi-draw-indirect":327732};function tT(c,p){p>>>=0,c=re(c>>>0);var h=Cs(4*c.features.size),g=0,b=0;c.features.forEach(A=>{0<=(A=eT[A])&&((v(),B)[h+g>>>2>>>0]=A,g+=4,b++)}),(v(),P)[p+4>>>2>>>0]=h,(v(),P)[p>>>2>>>0]=b}function rT(c,p){return Pb(re(c>>>0).limits,p>>>0),1}function sT(c,p){re(c>>>0).pushErrorScope(mM[p])}function nT(c,p,h){p>>>=0,h>>>=0,c=re(c>>>0),p=Array.from((v(),B).subarray(h>>>2>>>0,h+4*p>>>2>>>0),g=>re(g)),c.submit(p)}function oT(c,p,h,g,b){h=wt(h),g>>>=0,b>>>=0,c=re(c>>>0),p=re(p>>>0),g=(v(),Q).subarray(g>>>0,g+b>>>0),c.writeBuffer(p,h,g,0,b)}n||(function(){for(var c=e.numThreads-1;c--;)H0();Me.push(async()=>{var p=(async function(){if(!n)return Promise.all(et.map(V0))})();xe++,await p,--xe==0&&Ge&&(p=Ge,Ge=null,p())})})(),n||(yr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ue()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ae(),e.stackRestore=c=>oe(c),e.stackAlloc=c=>Ci(c),e.setValue=function(c,p,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(v(),V)[c>>>0]=p;break;case"i16":(v(),K)[c>>>1>>>0]=p;break;case"i32":(v(),B)[c>>>2>>>0]=p;break;case"i64":(v(),S)[c>>>3>>>0]=BigInt(p);break;case"float":(v(),se)[c>>>2>>>0]=p;break;case"double":(v(),ie)[c>>>3>>>0]=p;break;case"*":(v(),P)[c>>>2>>>0]=p;break;default:Ce(`invalid type for setValue: ${h}`)}},e.getValue=function(c,p="i8"){switch(p.endsWith("*")&&(p="*"),p){case"i1":case"i8":return(v(),V)[c>>>0];case"i16":return(v(),K)[c>>>1>>>0];case"i32":return(v(),B)[c>>>2>>>0];case"i64":return(v(),S)[c>>>3>>>0];case"float":return(v(),se)[c>>>2>>>0];case"double":return(v(),ie)[c>>>3>>>0];case"*":return(v(),P)[c>>>2>>>0];default:Ce(`invalid type for getValue: ${p}`)}},e.UTF8ToString=Ts,e.stringToUTF8=ur,e.lengthBytesUTF8=pr;var Fb,jb,Zu,Ii,Lt,Cs,Gb,qb,Wb,Vb,Hb,Xb,Kb,Yb,Qb,Jb,Zb,ep,tp,rp,sp,In,np,e1,op,t1,r1,s1,ap,n1,o1,ip,he,Cn,a1,oe,Ci,ae,i1,lp,l1,c1,u1,cp,p1,d1,f1,m1,h1,_1,g1,w1,x1,y1,b1,v1,k1,E1,A1,M1,T1,S1,O1,I1,C1,P1,z1,L1,N1,$1,R1,U1,B1,D1,F1,j1,G1,q1,W1,V1,H1,X1,K1,Y1,fr,aT=[xr,Hr,Y0,tb,rb,sb,nb,ob,ab,ib,lb,cb,ub,pb,db,fb,Ab,Mb,Tb,Nb,$b,Rb,Ub,Bb,Db],up={1111036:(c,p,h,g,b)=>{if(e===void 0||!e.Zc)return 1;if((c=Ts(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=e.Zc.get(c)))return 2;if(p=Number(p>>>0),h=Number(h>>>0),g=Number(g>>>0),p+h>c.byteLength)return 3;try{let A=c.subarray(p,p+h);switch(b){case 0:(v(),Q).set(A,g>>>0);break;case 1:e.ie?e.ie(g,A):e.Ke(g,A);break;default:return 4}return 0}catch{return 4}},1111860:(c,p,h)=>{e.ke(c,(v(),Q).subarray(p>>>0,p+h>>>0))},1111924:()=>e.Ie(),1111966:c=>{e.je(c)},1112003:()=>typeof wasmOffsetConverter<"u"};function iT(){return typeof wasmOffsetConverter<"u"}function lT(c,p,h,g){var b=ae();try{return w1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function cT(c,p,h){var g=ae();try{return h1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function uT(c,p,h){var g=ae();try{u1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function pT(c,p){var h=ae();try{return cp(c,p)}catch(g){if(oe(h),g!==g+0)throw g;he(1,0)}}function dT(c){var p=ae();try{p1(c)}catch(h){if(oe(p),h!==h+0)throw h;he(1,0)}}function fT(c,p,h,g,b,A,O){var N=ae();try{return m1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function mT(c,p){var h=ae();try{x1(c,p)}catch(g){if(oe(h),g!==g+0)throw g;he(1,0)}}function hT(c,p,h,g,b,A){var O=ae();try{d1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function _T(c,p,h,g){var b=ae();try{g1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function gT(c,p,h,g,b,A,O){var N=ae();try{b1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function wT(c,p,h,g,b,A,O){var N=ae();try{v1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function xT(c,p,h,g,b,A,O,N){var D=ae();try{P1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function yT(c,p,h,g,b){var A=ae();try{f1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function bT(c,p,h,g,b){var A=ae();try{return y1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function vT(c,p,h,g,b,A,O,N){var D=ae();try{z1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function kT(c,p,h,g,b,A,O,N,D,q,fe,me){var Re=ae();try{k1(c,p,h,g,b,A,O,N,D,q,fe,me)}catch(ee){if(oe(Re),ee!==ee+0)throw ee;he(1,0)}}function ET(c,p,h,g,b,A){var O=ae();try{return I1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function AT(c,p,h){var g=ae();try{return T1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;return he(1,0),0n}}function MT(c,p,h,g,b,A,O,N,D){var q=ae();try{_1(c,p,h,g,b,A,O,N,D)}catch(fe){if(oe(q),fe!==fe+0)throw fe;he(1,0)}}function TT(c){var p=ae();try{return A1(c)}catch(h){if(oe(p),h!==h+0)throw h;he(1,0)}}function ST(c,p,h){var g=ae();try{return L1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function OT(c,p){var h=ae();try{return V1(c,p)}catch(g){if(oe(h),g!==g+0)throw g;return he(1,0),0n}}function IT(c,p,h,g,b){var A=ae();try{N1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function CT(c){var p=ae();try{return E1(c)}catch(h){if(oe(p),h!==h+0)throw h;return he(1,0),0n}}function PT(c,p,h,g,b,A){var O=ae();try{return U1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function zT(c,p,h,g,b,A){var O=ae();try{return B1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function LT(c,p,h,g,b,A,O,N){var D=ae();try{return C1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function NT(c,p,h,g,b){var A=ae();try{return D1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;return he(1,0),0n}}function $T(c,p,h,g){var b=ae();try{return F1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function RT(c,p,h,g){var b=ae();try{return j1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function UT(c,p,h,g,b,A,O,N,D,q,fe,me){var Re=ae();try{return G1(c,p,h,g,b,A,O,N,D,q,fe,me)}catch(ee){if(oe(Re),ee!==ee+0)throw ee;he(1,0)}}function BT(c,p,h,g,b,A,O,N,D,q,fe){var me=ae();try{$1(c,p,h,g,b,A,O,N,D,q,fe)}catch(Re){if(oe(me),Re!==Re+0)throw Re;he(1,0)}}function DT(c,p,h,g,b,A,O,N,D,q,fe,me,Re,ee,lt,Nt){var st=ae();try{R1(c,p,h,g,b,A,O,N,D,q,fe,me,Re,ee,lt,Nt)}catch(Qr){if(oe(st),Qr!==Qr+0)throw Qr;he(1,0)}}function FT(c,p,h,g){var b=ae();try{return q1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function jT(c,p,h,g,b){var A=ae();try{return W1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function GT(c,p,h){var g=ae();try{return M1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function qT(c,p,h){var g=ae();try{return S1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function WT(c,p,h,g){var b=ae();try{O1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function Pi(){if(0<xe)Ge=Pi;else if(n)w?.(e),Be();else{for(var c=Me;0<c.length;)c.shift()(e);0<xe?Ge=Pi:(e.calledRun=!0,z||(Be(),w?.(e)))}}return n||(fr=await Qe(),Pi()),e.PTR_SIZE=4,e.webgpuInit=c=>{let p=new WeakMap,h,g,b=1;e.webgpuRegisterDevice=N=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(N){var D=p.get(N);if(!D){let q=((fe,me=0)=>{var Re=Zb(me);return me=Jb(me,Re),xt(Re,fe.queue),xt(me,fe),me})(N,D=qb(0));D=[b++,D,q],p.set(N,D)}return h=N,g=D[0],D}h=void 0,g=0};let A=new Map;e.webgpuOnCreateSession=N=>{if(g!==void 0){var D=g;if(g=void 0,N){let q=Zu(D);A.set(N,q),D===0&&c(h??re(q))}h=void 0}},e.webgpuOnReleaseSession=N=>{A.delete(N)};let O=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(N,D,q)=>{if(q)return N[O]=[q,NaN],q;if(q=N[O])return q[1]++,q[0];if((D=A.get(D))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return D=((fe,me=0)=>(fe.mapState!="pending"||Ce(),me=Qb(me,fe.mapState=="mapped"?3:1),xt(me,fe),fe.mapState=="mapped"&&(rr[me]=[]),me))(N,D),N[O]=[D,1],D},e.webgpuUnregisterBuffer=N=>{let D=N[O];if(!D)throw Error("Buffer is not registered");D[1]--,D[1]===0&&(Gb(D[0]),delete N[O])},e.webgpuGetBuffer=N=>re(N),e.webgpuCreateDownloader=(N,D,q)=>{if((q=A.get(q))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let fe=re(q),me=16*Math.ceil(Number(D)/16);return async()=>{let Re=fe.createBuffer({size:me,usage:9});try{let ee=fe.createCommandEncoder();return ee.copyBufferToBuffer(N,0,Re,0,me),fe.queue.submit([ee.finish()]),await Re.mapAsync(GPUMapMode.READ),Re.getMappedRange().slice(0,D)}finally{Re.destroy()}}},e.ie=(N,D)=>{var q=D.buffer;let fe=D.byteOffset,me=D.byteLength;if(D=16*Math.ceil(Number(me)/16),N=re(N),!h){var Re=Zu(g);h=re(Re)}let ee=(Re=h.createBuffer({mappedAtCreation:!0,size:D,usage:6})).getMappedRange();new Uint8Array(ee).set(new Uint8Array(q,fe,me)),Re.unmap(),(q=h.createCommandEncoder()).copyBufferToBuffer(Re,0,N,0,D),h.queue.submit([q.finish()]),Re.destroy()}},e.webnnInit=c=>{let p=c[0];[e.Ie,e.je,e.webnnEnsureTensor,e.ke,e.webnnDownloadTensor,e.He,e.webnnEnableTraceEvent]=c.slice(1),e.webnnReleaseTensorId=e.je,e.webnnUploadTensor=e.ke,e.webnnRegisterMLContext=e.He,e.webnnOnRunStart=h=>p.onRunStart(h),e.webnnOnRunEnd=p.onRunEnd.bind(p),e.webnnOnReleaseSession=h=>{p.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>p.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,b,A)=>p.registerMLTensor(h,g,b,A),e.webnnCreateMLContext=h=>p.createMLContext(h),e.webnnRegisterMLConstant=(h,g,b,A,O,N)=>p.registerMLConstant(h,g,b,A,O,e.Zc,N),e.webnnRegisterGraphInput=p.registerGraphInput.bind(p),e.webnnIsGraphInput=p.isGraphInput.bind(p),e.webnnRegisterGraphOutput=p.registerGraphOutput.bind(p),e.webnnIsGraphOutput=p.isGraphOutput.bind(p),e.webnnCreateTemporaryTensor=p.createTemporaryTensor.bind(p),e.webnnIsGraphInputOutputTypeSupported=p.isGraphInputOutputTypeSupported.bind(p)},te?e:new Promise((c,p)=>{w=c,x=p})}var Wk,Jv,zC=ye(()=>{"use strict";Wk=Qv,Jv=globalThis.self?.name?.startsWith("em-pthread"),Jv&&Qv()}),Sp,qp,Zv,Ot,Vk,qi,ek,tk,Op,rk,Ip,Hk,Cp,Xk,Zp=ye(()=>{"use strict";Jp(),Sp=typeof location>"u"?void 0:location.origin,qp=import.meta.url>"file:"&&import.meta.url<"file;",Zv=()=>{if(qp){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Sp).href}return import.meta.url},Ot=Zv(),Vk=()=>{if(Ot&&!Ot.startsWith("blob:"))return Ot.substring(0,Ot.lastIndexOf("/")+1)},qi=(t,e)=>{try{let r=e??Ot;return(r?new URL(t,r):new URL(t)).origin===Sp}catch{return!1}},ek=(t,e)=>{let r=e??Ot;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},tk=(t,e)=>`${e??"./"}${t}`,Op=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},rk=async t=>(await import(t)).default,Ip=(PC(),Yi(jk)).default,Hk=async()=>{if(!Ot)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(qi(Ot))return[void 0,Ip()];let t=await Op(Ot);return[t,Ip(t)]},Cp=(zC(),Yi(qk)).default,Xk=async(t,e,r,s)=>{let n=Cp&&!(t||e);if(n)if(Ot)n=qi(Ot);else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Cp];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??ek(o,e),i=r&&a&&!qi(a,e),l=i?await Op(a):a??tk(o,e);return[i?l:void 0,await rk(l)]}}}),Pp,Wi,jn,zp,sk,nk,ok,ed,Ue,ps=ye(()=>{"use strict";Zp(),Wi=!1,jn=!1,zp=!1,sk=()=>{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}},nk=()=>{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}},ok=()=>{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}},ed=async t=>{if(Wi)return Promise.resolve();if(jn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(zp)throw new Error("previous call to 'initializeWebAssembly()' failed.");jn=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!ok())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!nk())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=sk();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,u=l?.href??l,d=t.wasmBinary,[f,m]=await Xk(i,o,r>1,!!d||!!u),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,k)=>{let E={numThreads:r};if(d)E.wasmBinary=d;else if(u||o)E.locateFile=M=>u??o+M;else if(i&&i.indexOf("blob:")!==0)E.locateFile=M=>new URL(M,i).href;else if(f){let M=Vk();M&&(E.locateFile=I=>M+I)}m(E).then(M=>{jn=!1,Wi=!0,Pp=M,x(),f&&URL.revokeObjectURL(f)},M=>{jn=!1,zp=!0,k(M)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ue=()=>{if(Wi&&Pp)return Pp;throw new Error("WebAssembly is not initialized yet.")}}),It,Ji,Oe,td=ye(()=>{"use strict";ps(),It=(t,e)=>{let r=Ue(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Ji=(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")Ji(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Oe=t=>{let e=Ue(),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)}}}),Kk,LC=ye(()=>{"use strict";ps(),td(),Kk=t=>{let e=Ue(),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=It(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Oe("Can't create run options."),t?.extra!==void 0&&Ji(t.extra,"",new WeakSet,(a,i)=>{let l=It(a,s),u=It(i,s);e._OrtAddRunConfigEntry(r,l,u)!==0&&Oe(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),ak,ik,lk,Vi,kr,ck,Yk,NC=ye(()=>{"use strict";ps(),td(),ak=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}`)}},ik=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},lk=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)},Vi=(t,e,r,s)=>{let n=It(e,s),o=It(r,s);Ue()._OrtAddSessionConfigEntry(t,n,o)!==0&&Oe(`Can't set a session config entry: ${e} - ${r}.`)},kr=(t,e,r,s)=>{let n=It(e,s),o=It(r,s);t.push([n,o])},ck=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&Vi(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&&kr(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&kr(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];kr(a,"forceCpuNodeNames",x.join(`
|
|
15
|
-
`),r)}_.validationMode&&kr(a,"validationMode",_.validationMode,r)}let m=Ue().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;kr(a,"deviceId",_.toString(),r),kr(a,"webgpuInstance",w.toString(),r),kr(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=It(o,r),l=a.length,u=0,d=0;if(l>0){u=Ue()._malloc(l*Ue().PTR_SIZE),r.push(u),d=Ue()._malloc(l*Ue().PTR_SIZE),r.push(d);for(let f=0;f<l;f++)Ue().setValue(u+f*Ue().PTR_SIZE,a[f][0],"*"),Ue().setValue(d+f*Ue().PTR_SIZE,a[f][1],"*")}await Ue()._OrtAppendExecutionProvider(t,i,u,d,l)!==0&&Oe(`Can't append execution provider: ${o}.`)}},Yk=async t=>{let e=Ue(),r=0,s=[],n=t||{};lk(n);try{let o=ak(n.graphOptimizationLevel??"all"),a=ik(n.executionMode??"sequential"),i=typeof n.logId=="string"?It(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 u=n.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let d=typeof n.optimizedModelFilePath=="string"?It(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,u,d),r===0&&Oe("Can't create session options."),n.executionProviders&&await ck(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Vi(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 _=It(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&Oe(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&Ji(n.extra,"",new WeakSet,(f,m)=>{Vi(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Oe("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),as,Ki,Fs,Hn,Zi,rd,sd,Wp,js=ye(()=>{"use strict";as=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}`)}},Ki=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}`)}},Fs=(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},Hn=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Zi=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}`)}},rd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",sd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Wp=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}`)}}}),nd,Qk=ye(()=>{"use strict";Jp(),nd=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 u=l.byteLength;new Uint8Array(o,a,u).set(l),a+=u}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),Jk,$C=ye(()=>{"use strict";js(),Jk=(t,e)=>new(Hn(e))(t)}),uk,pk,dk,fk,Zk,mk,_t,eE=ye(()=>{"use strict";js(),uk=["V","I","W","E","F"],pk=(t,e)=>{console.log(`[${uk[t]},${new Date().toISOString()}]${e}`)},Zk=(t,e)=>{dk=t,fk=e},mk=(t,e)=>{let r=Zi(t),s=Zi(dk);r>=s&&pk(r,typeof e=="function"?e():e)},_t=(...t)=>{fk&&mk(...t)}}),Lp,Vp,Np,hk,$p,_k,Rp,Up,Bp,gk,tE,RC=ye(()=>{"use strict";js(),eE(),Lp=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Vp=(t,e)=>{if(e==="int32")return t;let r=Lp.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(Hn(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i<n;i++){let l=o[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},Np=(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}`)}},hk=1,$p=()=>hk++,_k=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Rp=(t,e)=>{let r=Lp.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},Up=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 Rp(this.dataType,this.tensorShape)}destroy(){_t("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=Np(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},Bp=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=_k.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);_t("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!==Rp(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=Vp(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 _t("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?Np(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()}},gk=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=$p();return this.tensorTrackersById.set(t,new Bp(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){_t("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){_t("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=$p(),a=new Up({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new Bp(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[u,d]of this.freeTensors.entries())if(d.canReuseTensor(i,e,r)){_t("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(u,1)[0];return f.sessionId=t,f}_t("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 Up({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)}},tE=(...t)=>new gk(...t)}),rE={};Xn(rE,{WebNNBackend:()=>sE});var Gn,wk,sE,UC=ye(()=>{"use strict";js(),ps(),$C(),RC(),eE(),Gn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),wk=(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])},sE=class{constructor(t){this.tensorManager=tE(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,Zk(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){_t("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){_t("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)_t("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=>wk(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){_t("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Gn.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){_t("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Gn.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(!Ue().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");_t("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 Jk(r,e)}}registerMLTensor(t,e,r,s){let n=Gn.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return _t("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(e,e+r).buffer,d;switch(n.dataType){case"float32":d=new Float32Array(u);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":d=new Int32Array(u);break;case"uint32":d=new Uint32Array(u);break;case"int64":if(a){let f=Vp(new Uint8Array(u),"int64");d=new Int32Array(f.buffer),n.dataType="int32"}else d=new BigInt64Array(u);break;case"uint64":d=new BigUint64Array(u);break;case"int8":d=new Int8Array(u);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return _t("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,d)}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=Gn.get(as(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),xk,od,ad,Er,yk,Dp,el,id,ld,Fp,cd,ud,pd,nE=ye(()=>{"use strict";us(),LC(),NC(),js(),ps(),td(),Qk(),xk=(t,e)=>{Ue()._OrtInit(t,e)!==0&&Oe("Can't initialize onnxruntime.")},od=async t=>{xk(t.wasm.numThreads,Zi(t.logLevel))},ad=async(t,e)=>{Ue().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"&&Ue().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(UC(),Yi(rE)).WebNNBackend(t);Ue().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])}},Er=new Map,yk=t=>{let e=Ue(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Oe("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},Dp=(t,e)=>{let r=Ue(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Oe("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let u=r.HEAPU32[n/4+1],d=[];for(let f=0;f<u;f++){let m=Number(r.getValue(n+8+f*o,"*"));d.push(m!==0?r.UTF8ToString(m):Number(r.getValue(n+8+(f+u)*o,"*")))}return[i,l,d]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},el=t=>{let e=Ue(),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]},id=async(t,e)=>{let r,s,n=Ue();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=el(t);let o=0,a=0,i=0,l=[],u=[],d=[];try{if([a,l]=await Yk(e),e?.externalData&&n.mountExternalData){let T=[];for(let z of e.externalData){let C=typeof z=="string"?z:z.path;T.push(nd(typeof z=="string"?z:z.data).then(v=>{n.mountExternalData(C,v)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let z=T,C=z?.context,v=z?.gpuDevice,G=z?.deviceType,X=z?.powerPreference;C?n.currentContext=C:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:G,powerPreference:X})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Oe("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=yk(o),_=!!e?.enableGraphCapture,w=[],x=[],k=[],E=[],M=[];for(let T=0;T<f;T++){let[z,C,v]=Dp(o,T);z===0&&Oe("Can't get an input name."),u.push(z);let G=n.UTF8ToString(z);w.push(G),k.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Ki(C),shape:v})}for(let T=0;T<m;T++){let[z,C,v]=Dp(o,T+f);z===0&&Oe("Can't get an output name."),d.push(z);let G=n.UTF8ToString(z);x.push(G),E.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Ki(C),shape:v});{if(_&&e?.preferredOutputLocation===void 0){M.push("gpu-buffer");continue}let X=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[G]??"cpu",V=n.webnnIsGraphOutput;if(X==="cpu"&&V&&V(o,G)){M.push("ml-tensor-cpu-output");continue}if(X!=="cpu"&&X!=="cpu-pinned"&&X!=="gpu-buffer"&&X!=="ml-tensor")throw new Error(`Not supported preferred output location: ${X}.`);if(_&&X!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${X}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);M.push(X)}}let I=null;return M.some(T=>T==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Oe("Can't create IO binding."),I={handle:i,outputPreferredLocations:M,outputPreferredLocationsEncoded:M.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>Wp(T))}),Er.set(o,[o,u,d,I,_,!1]),[o,w,x,k,E]}catch(f){throw u.forEach(m=>n._OrtFree(m)),d.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Oe("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Oe("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Oe("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},ld=t=>{let e=Ue(),r=Er.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Oe("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Oe("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Oe("Can't release session."),Er.delete(t)},Fp=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=Ue(),l=i.PTR_SIZE,u=t[0],d=t[1],f=t[3],m=f,_,w;if(u==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let E=t[2].gpuBuffer;w=Fs(as(u),d);{let M=i.webgpuRegisterBuffer;if(!M)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=M(E,s)}}else if(f==="ml-tensor"){let E=t[2].mlTensor;w=Fs(as(u),d);let M=i.webnnRegisterMLTensor;if(!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=M(s,E,as(u),d)}else{let E=t[2];if(Array.isArray(E)){w=l*E.length,_=i._malloc(w),r.push(_);for(let M=0;M<E.length;M++){if(typeof E[M]!="string")throw new TypeError(`tensor data at index ${M} is not a string`);i.setValue(_+M*l,It(E[M],r),"*")}}else{let M=i.webnnIsGraphInput,I=i.webnnIsGraphOutput;if(u!=="string"&&M&&I){let T=i.UTF8ToString(n);if(M(s,T)||I(s,T)){let z=as(u);w=Fs(z,d),m="ml-tensor";let C=i.webnnCreateTemporaryTensor,v=i.webnnUploadTensor;if(!C||!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let G=await C(s,z,d);v(G,new Uint8Array(E.buffer,E.byteOffset,E.byteLength)),_=G}else w=E.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),_)}else w=E.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),_)}}let x=i.stackSave(),k=i.stackAlloc(4*d.length);try{d.forEach((M,I)=>i.setValue(k+I*l,M,l===4?"i32":"i64"));let E=i._OrtCreateTensor(as(u),_,w,k,d.length,Wp(m));E===0&&Oe(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(E)}finally{i.stackRestore(x)}},cd=async(t,e,r,s,n,o)=>{let a=Ue(),i=a.PTR_SIZE,l=Er.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let u=l[0],d=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,k=s.length,E=0,M=[],I=[],T=[],z=[],C=[],v=a.stackSave(),G=a.stackAlloc(x*i),X=a.stackAlloc(x*i),V=a.stackAlloc(k*i),Q=a.stackAlloc(k*i);try{[E,M]=Kk(o),Mr("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)await Fp(r[P],I,z,t,d[e[P]],e[P],_);for(let P=0;P<k;P++)await Fp(n[P],T,z,t,f[s[P]],x+s[P],_);Tr("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)a.setValue(G+P*i,I[P],"*"),a.setValue(X+P*i,d[e[P]],"*");for(let P=0;P<k;P++)a.setValue(V+P*i,T[P],"*"),a.setValue(Q+P*i,f[s[P]],"*");if(m&&!w){let{handle:P,outputPreferredLocations:se,outputPreferredLocationsEncoded:ie}=m;if(d.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${d.length}).`);Mr("wasm bindInputsOutputs");for(let S=0;S<x;S++){let L=e[S];await a._OrtBindInput(P,d[L],I[S])!==0&&Oe(`Can't bind input[${S}] for session=${t}.`)}for(let S=0;S<k;S++){let L=s[S];n[S]?.[3]?(C.push(T[S]),a._OrtBindOutput(P,f[L],T[S],0)!==0&&Oe(`Can't bind pre-allocated output[${S}] for session=${t}.`)):a._OrtBindOutput(P,f[L],0,ie[L])!==0&&Oe(`Can't bind output[${S}] to ${se[S]} for session=${t}.`)}Tr("wasm bindInputsOutputs"),Er.set(t,[u,d,f,m,_,!0])}a.jsepOnRunStart?.(u),a.webnnOnRunStart?.(u);let K;m?K=await a._OrtRunWithBinding(u,m.handle,k,V,E):K=await a._OrtRun(u,X,G,x,Q,k,V,E),K!==0&&Oe("failed to call OrtRun().");let Y=[],B=[];Mr("wasm ProcessOutputTensor");for(let P=0;P<k;P++){let se=Number(a.getValue(V+P*i,"*"));if(se===T[P]||C.includes(T[P])){Y.push(n[P]),se!==T[P]&&a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.");continue}let ie=a.stackSave(),S=a.stackAlloc(4*i),L=!1,R,te=0;try{a._OrtGetTensorData(se,S,S+i,S+2*i,S+3*i)!==0&&Oe(`Can't access output tensor data on index ${P}.`);let ue=i===4?"i32":"i64",Be=Number(a.getValue(S,ue));te=a.getValue(S+i,"*");let Ce=a.getValue(S+i*2,"*"),vt=Number(a.getValue(S+i*3,ue)),Qe=[];for(let Me=0;Me<vt;Me++)Qe.push(Number(a.getValue(Ce+Me*i,ue)));a._OrtFree(Ce)!==0&&Oe("Can't free memory for tensor dims.");let Ze=Qe.reduce((Me,xe)=>Me*xe,1);R=Ki(Be);let rt=m?.outputPreferredLocations[s[P]];if(R==="string"){if(rt==="gpu-buffer"||rt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let xe=0;xe<Ze;xe++){let Ge=a.getValue(te+xe*i,"*"),kt=a.getValue(te+(xe+1)*i,"*"),ge=xe===Ze-1?void 0:kt-Ge;Me.push(a.UTF8ToString(Ge,ge))}Y.push([R,Qe,Me,"cpu"])}else if(rt==="gpu-buffer"&&Ze>0){let Me=a.webgpuGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=Me(te),Ge=Fs(Be,Ze);if(Ge===void 0||!rd(R))throw new Error(`Unsupported data type: ${R}`);L=!0;{a.webgpuRegisterBuffer(xe,t,te);let kt=a.webgpuCreateDownloader(xe,Ge,t);Y.push([R,Qe,{gpuBuffer:xe,download:async()=>{let ge=await kt();return new(Hn(R))(ge)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.")}},"gpu-buffer"])}}else if(rt==="ml-tensor"&&Ze>0){let Me=a.webnnEnsureTensor,xe=a.webnnIsGraphInputOutputTypeSupported;if(!Me||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Fs(Be,Ze)===void 0||!sd(R))throw new Error(`Unsupported data type: ${R}`);if(!xe(t,R,!1))throw new Error(`preferredLocation "ml-tensor" for ${R} output is not supported by current WebNN Context.`);let Ge=await Me(t,te,Be,Qe,!1);L=!0,Y.push([R,Qe,{mlTensor:Ge,download:a.webnnCreateMLTensorDownloader(te,R),dispose:()=>{a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(rt==="ml-tensor-cpu-output"&&Ze>0){let Me=a.webnnCreateMLTensorDownloader(te,R)(),xe=Y.length;L=!0,B.push((async()=>{let Ge=[xe,await Me];return a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se),Ge})()),Y.push([R,Qe,[],"cpu"])}else{let Me=Hn(R),xe=new Me(Ze);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(a.HEAPU8.subarray(te,te+xe.byteLength)),Y.push([R,Qe,xe,"cpu"])}}finally{a.stackRestore(ie),R==="string"&&te&&a._free(te),L||a._OrtReleaseTensor(se)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Oe("Can't clear bound outputs."),Er.set(t,[u,d,f,m,_,!1]));for(let[P,se]of await Promise.all(B))Y[P][2]=se;return Tr("wasm ProcessOutputTensor"),Y}finally{a.webnnOnRunEnd?.(u),a.stackRestore(v),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),n.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),I.forEach(K=>a._OrtReleaseTensor(K)),T.forEach(K=>a._OrtReleaseTensor(K)),z.forEach(K=>a._free(K)),E!==0&&a._OrtReleaseRunOptions(E),M.forEach(K=>a._free(K))}},ud=t=>{let e=Ue(),r=Er.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Oe("Can't get an profile file name."),e._OrtFree(n)},pd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Ar,Ut,Ds,qn,Wn,Hi,jp,Xi,ss,ns,bk,oE,aE,iE,lE,cE,uE,pE,dE=ye(()=>{"use strict";us(),nE(),ps(),Zp(),Ar=()=>!!We.wasm.proxy&&typeof document<"u",Ds=!1,qn=!1,Wn=!1,Xi=new Map,ss=(t,e)=>{let r=Xi.get(t);r?r.push(e):Xi.set(t,[e])},ns=()=>{if(Ds||!qn||Wn||!Ut)throw new Error("worker not ready")},bk=t=>{switch(t.data.type){case"init-wasm":Ds=!1,t.data.err?(Wn=!0,jp[1](t.data.err)):(qn=!0,jp[0]()),Hi&&(URL.revokeObjectURL(Hi),Hi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Xi.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},oE=async()=>{if(!qn){if(Ds)throw new Error("multiple calls to 'initWasm()' detected.");if(Wn)throw new Error("previous call to 'initWasm()' failed.");if(Ds=!0,Ar())return new Promise((t,e)=>{Ut?.terminate(),Hk().then(([r,s])=>{try{Ut=s,Ut.onerror=o=>e(o),Ut.onmessage=bk,jp=[t,e];let n={type:"init-wasm",in:We};!n.in.wasm.wasmPaths&&(r||qp)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Ut.postMessage(n),Hi=r}catch(n){e(n)}},e)});try{await ed(We.wasm),await od(We),qn=!0}catch(t){throw Wn=!0,t}finally{Ds=!1}}},aE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:We}};Ut.postMessage(s)});await ad(We,t)},iE=async t=>Ar()?(ns(),new Promise((e,r)=>{ss("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Ut.postMessage(s,[t.buffer])})):el(t),lE=async(t,e)=>{if(Ar()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ns(),new Promise((r,s)=>{ss("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Ut.postMessage(n,o)})}else return id(t,e)},cE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("release",[e,r]);let s={type:"release",in:t};Ut.postMessage(s)});ld(t)},uE=async(t,e,r,s,n,o)=>{if(Ar()){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)=>{ss("run",[a,i]);let l=r,u={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Ut.postMessage(u,pd(l))})}else return cd(t,e,r,s,n,o)},pE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Ut.postMessage(s)});ud(t)}}),Gp,vk,fE,BC=ye(()=>{"use strict";us(),dE(),js(),Jp(),Qk(),Gp=(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()}`)}},vk=t=>{switch(t[3]){case"cpu":return new Kt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!rd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Kt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!sd(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Kt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},fE=class{async fetchModelAndCopyToWasmMemory(t){return iE(await nd(t))}async loadModel(t,e){ls();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await lE(r,e),cs()}async dispose(){return cE(this.sessionId)}async run(t,e,r){ls();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)=>Gp(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?Gp(f,()=>`output "${this.outputNames[a[m]]}"`):null),u=await uE(this.sessionId,n,i,a,l,r),d={};for(let f=0;f<u.length;f++)d[this.outputNames[a[f]]]=o[f]??vk(u[f]);return cs(),d}startProfiling(){}endProfiling(){pE(this.sessionId)}}}),mE={};Xn(mE,{OnnxruntimeWebAssemblyBackend:()=>Xp,initializeFlags:()=>Hp,wasmBackend:()=>hE});var Hp,Xp,hE,DC=ye(()=>{"use strict";us(),dE(),BC(),Hp=()=>{(typeof We.wasm.initTimeout!="number"||We.wasm.initTimeout<0)&&(We.wasm.initTimeout=0);let t=We.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.`),We.wasm.simd=!1),typeof We.wasm.proxy!="boolean"&&(We.wasm.proxy=!1),typeof We.wasm.trace!="boolean"&&(We.wasm.trace=!1),typeof We.wasm.numThreads!="number"||!Number.isInteger(We.wasm.numThreads)||We.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)We.wasm.numThreads=1;else{let e=typeof navigator>"u"?gC("node:os").cpus().length:navigator.hardwareConcurrency;We.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Xp=class{async init(t){Hp(),await oE(),await aE(t)}async createInferenceSessionHandler(t,e){let r=new fE;return await r.loadModel(t,e),r}},hE=new Xp});us();us();us();var FC="1.24.1",jC=Fk;{let t=(DC(),Yi(mE)).wasmBackend;is("webgpu",t,5),is("webnn",t,5),is("cpu",t,10),is("wasm",t,10)}Object.defineProperty(We.versions,"web",{value:FC,enumerable:!0});async function _E(t){let e=t.split("/").pop(),r;try{if(r=await Di(),r){let n=await r.match(t);if(n)return n}}catch(n){console.warn(`Failed to load ${e} from cache:`,n)}let s=await fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){console.warn(`Failed to cache ${e}:`,n)}return s}async function gE(t){let e=await _E(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return console.warn("Failed to read WASM binary:",r),null}}async function wE(t){let e=await _E(t);if(!e||typeof e=="string")return null;try{let r=await e.text(),s=t.split("/").slice(0,-1).join("/");r=r.replace(/import\.meta\.url/g,`"${s}"`);let n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return console.warn("Failed to read WASM binary:",r),null}}function fd(t){return Us(t,["blob:"])}function md(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}import{Tensor as AE}from"onnxruntime-common";var qC=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"}}),WC=["verbose","info","warning","error","fatal"],vE=4,Bt=[],hd,qs,xE=Symbol.for("onnxruntime");if(xE in globalThis)qs=globalThis[xE];else if(be.IS_NODE_ENV){switch(qs=GC,process.platform){case"win32":Bt.push("dml");break;case"linux":process.arch==="x64"&&Bt.push("cuda");break;case"darwin":Bt.push("coreml");break}Bt.push("webgpu"),Bt.push("cpu"),hd=["cpu"]}else qs=dd,be.IS_WEBNN_AVAILABLE&&Bt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),be.IS_WEBGPU_AVAILABLE&&Bt.push("webgpu"),Bt.push("wasm"),hd=["wasm"];var VC=qs.InferenceSession;function kE(t=null){if(!t)return hd;switch(t){case"auto":return Bt;case"gpu":return Bt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Bt.includes(t))return[qC[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Bt.join(", ")}.`)}var EE=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV,yE=Promise.resolve(),Gs=null;async function HC(){return Gs||(De.useWasmCache&&typeof ft?.wasm?.wasmPaths=="object"&&ft?.wasm?.wasmPaths?.wasm&&ft?.wasm?.wasmPaths?.mjs?(Gs=(async()=>{let e=ft.wasm.wasmPaths;await Promise.all([e.wasm&&!fd(e.wasm)?(async()=>{try{let r=await gE(md(e.wasm));r&&(ft.wasm.wasmBinary=r)}catch(r){console.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!fd(e.mjs)?(async()=>{try{let r=await wE(md(e.mjs));r&&(ft.wasm.wasmPaths.mjs=r)}catch(r){console.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),Gs):(Gs=Promise.resolve(),Gs))}async function tl(t,e,r){await HC();let s=()=>VC.create(t,{logSeverityLevel:vE,...e}),n=await(EE?yE=yE.then(s):s());return n.config=r,n}var bE=Promise.resolve();async function rl(t,e){let r=()=>t.run(e);return await(EE?bE=bE.then(r):r())}function sl(t){return t instanceof qs.Tensor}var ft=qs?.env;ft.logLevel=WC[vE];if(ft?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&ft.versions?.web&&!ft.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${ft.versions.web}/dist/`;ft.wasm.wasmPaths=be.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}ft.wasm.proxy=!1}ft?.webgpu&&(ft.webgpu.powerPreference="high-performance");function Kn(){return ft?.wasm?.proxy}De.backends.onnx=ft;var Sr=async(t,e,r)=>{let s=await tl(new Uint8Array(t),e);return(async n=>{let o=Kn(),a=Object.fromEntries(Object.entries(n).map(([l,u])=>[l,(o?u.clone():u).ort_tensor])),i=await rl(s,a);return Array.isArray(r)?r.map(l=>new U(i[l])):new U(i[r])})},nr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Sr([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=Sr([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=Sr([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=Sr([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=Sr([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=Sr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Sr([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=Sr([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 ME=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"});var TE=(function(){let t;return async function(){if(t===void 0)if(!be.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),mt=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),_d=Object.freeze({[ME.wasm]:mt.q8}),gd=Object.freeze({[mt.fp32]:"",[mt.fp16]:"_fp16",[mt.int8]:"_int8",[mt.uint8]:"_uint8",[mt.q8]:"_quantized",[mt.q4]:"_q4",[mt.q4f16]:"_q4f16",[mt.bnb4]:"_bnb4"}),Ws=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 U=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 sl(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new AE(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n<e;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(e){let[r,...s]=this.dims;if(e=or(e,r),s.length>0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;s<r.length;++s)if(r[s]==e)return s;return-1}_subarray(e,r,s){let n=e*r,o=(e+1)*r,a="subarray"in this.data?this.data.subarray(n,o):this.data.slice(n,o);return new t(this.type,a,s)}item(){let e=this.data;if(e.length!==1)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return XC(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=1/(1+Math.exp(-e[r]));return this}map(e){return this.clone().map_(e)}map_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]=e(r[s],s,r);return this}mul(e){return this.clone().mul_(e)}mul_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]-=e;return this}clone(){return new t(this.type,this.data.slice(),this.dims.slice())}slice(...e){let r=[],s=[];for(let d=0;d<this.dims.length;++d){let f=e[d];if(f==null)s.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof f=="number")f=or(f,this.dims[d],d),s.push([f,f+1]);else if(Array.isArray(f)&&f.length===2){let[m,_]=f;if(m=m===null?0:or(m,this.dims[d],d,!1),_=_===null?this.dims[d]:or(_,this.dims[d],d,!1),m>_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[d])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([d,f])=>f-d),o=n.reduce((d,f)=>d*f),a=this.data,i=new a.constructor(o),l=this.stride(),u=!0;for(let d=1;d<n.length;++d)if(s[d][0]!==0||s[d][1]!==this.dims[d]){u=!1;break}if(u){let d=s[0][0]*l[0],f=s[0][1]*l[0];if(ArrayBuffer.isView(a))i.set(a.subarray(d,f));else if(Array.isArray(a)){let m=a.slice(d,f);for(let _=0;_<m.length;++_)i[_]=m[_]}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<o;++d){let f=0;for(let m=n.length-1,_=d;m>=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[d]=a[f]}return new t(this.type,i,r)}permute(...e){return KC(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=(u,d)=>u+d**e;if(r===null){let u=n.reduce(o,0)**(1/e);return new t(this.type,[u],[])}let[a,i,l]=Yn(o,this,r,s);if(e!==1)for(let u=0;u<i.length;++u)i[u]=i[u]**(1/e);return new t(a,i,l)}normalize_(e=2,r=1){r=or(r,this.dims.length);let s=this.norm(e,r,!0),n=this.data,o=s.data;for(let a=0;a<n.length;++a){let i=0;for(let l=this.dims.length-1,u=a,d=1;l>=0;--l){let f=this.dims[l];if(l!==r){let m=u%f;i+=m*d,d*=this.dims[l]}u=Math.floor(u/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return wd(this.dims)}squeeze(e=null){return new t(this.type,this.data,SE(this.dims,e))}squeeze_(e=null){return this.dims=SE(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,OE(this.dims,e))}unsqueeze_(e){return this.dims=OE(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;n<e.length;++n)if(e[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}let s=this.data;if(r!==-1){let n=e.reduce((o,a,i)=>i!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=-e[r];return this}neg(){return this.clone().neg_()}gt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>e?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]<e?1:0;return new t("bool",r,this.dims)}clamp_(e,r){let s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],e),r);return this}clamp(e,r){return this.clone().clamp_(e,r)}round_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=Math.round(e[r]);return this}round(){return this.clone().round_()}mean(e=null,r=!1){return al(this,e,r)}min(e=null,r=!1){if(e===null){let a=Dn(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Yn((a,i)=>Math.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Te(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Yn((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=Dn(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=Te(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${e.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(e.every(d=>d===1)){if(e.length===this.dims.length)return this.clone();let d=e.length-this.dims.length,f=Array(d).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((d,f)=>d*e[f]),o=n.reduce((d,f)=>d*f,1),a=this.data,i=new a.constructor(o),l=wd(s),u=wd(n);for(let d=0;d<o;++d){let f=d,m=0;for(let _=0;_<n.length;++_){let w=Math.floor(f/u[_]);f=f%u[_];let x=w%s[_];m+=x*l[_]}i[d]=a[m]}return new t(this.type,i,n)}tile(...e){if(e.length<this.dims.length){let r=this.dims.length-e.length;e=Array(r).fill(1).concat(e)}return this.repeat(...e)}to(e){if(this.type===e)return this;if(!Ws.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);let r,s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(e);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=o=>BigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,Kv(this.data),this.dims);return new t(e,Ws[e].from(this.data,r),this.dims)}};function XC(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.length<e[o]?l.push(i):a.push([i]),a},[[]]);return n[0]}function KC(t,e){let[r,s]=Gv(t.data,t.dims,e);return new U(t.type,r,s)}function xd(t,[e,r],s="bilinear",n=!1){let o=t.dims.at(-3)??1,a=t.dims.at(-2),i=t.dims.at(-1),l=jv(t.data,[o,a,i],[e,r],s,n);return new U(t.type,l,[o,e,r])}async function Dt(t,{size:e=null,mode:r="bilinear"}={}){if(t.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!e)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(e.length===2)s=[...t.dims.slice(0,2),...e];else if(e.length===3)s=[t.dims[0],...e];else if(e.length===4)s=e;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await nr.nearest_interpolate_4d;else if(r==="bilinear")n=await nr.bilinear_interpolate_4d;else if(r==="bicubic")n=await nr.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new U("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function IE(t,e){return await(await nr.matmul)({a:t,b:e})}async function QN(t,e){return await(await nr.rfft)({x:t,a:e})}async function Yt(t,e){let r=await nr.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new U("int64",[BigInt(e)],[1])})}var nl=t=>new U("int64",t,[t.length]);async function ol(t,e,r,s,n){return await(await nr.slice)({x:t,s:nl(e),e:nl(r),a:nl(s),t:nl(n??new Array(s.length).fill(1))})}function CE(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,u=0;for(let d=0;d<a;++d){let f=d*l*i;for(let m=0;m<l;++m){let _=0,w=0,x=d*i,k=f+m;for(let M=0;M<i;++M){let I=Number(s[x+M]);w+=I,_+=r[k+M*l]*I}let E=_/w;o[u++]=E}}return new U(t.type,o,n)}function JN(t,e,{eps:r=1e-5}={}){if(t.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[s,n]=t.dims;if(e.length!==1&&e[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[o,a]=yd(t,1,0,!0),i=o.data,l=a.data,u=t.data,d=new u.constructor(u.length);for(let f=0;f<s;++f){let m=f*n;for(let _=0;_<n;++_){let w=m+_;d[w]=(u[w]-l[f])/(i[f]+r)}}return new U(t.type,d,t.dims)}function SE(t,e){return t=t.slice(),e===null?t=t.filter(r=>r!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function OE(t,e){return e=or(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function or(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=or(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i<t.length;++i){let{data:l,dims:u}=t[i];for(let d=0;d<l.length;++d){let f=0;for(let m=u.length-1,_=d,w=1;m>=0;--m){let x=u[m],k=_%x;m===e&&(k+=a),f+=k*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[d]}a+=u[e]}}return new U(o,n,r)}function Ft(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function Yn(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=or(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 u=0;u<o.length;++u){let d=0;for(let f=a.length-1,m=u,_=1;f>=0;--f){let w=a[f];if(f!==r){let x=m%w;d+=x*_,_*=i[f]}m=Math.floor(m/w)}l[d]=t(l[d],o[u],u,d)}return s||i.splice(r,1),[e.type,l,i]}function yd(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((E,M)=>E+M,0)/n.length,w=Math.sqrt(n.reduce((E,M)=>E+(M-_)**2,0)/(n.length-r)),x=new U(t.type,[_],[]);return[new U(t.type,[w],[]),x]}e=or(e,o.length);let a=al(t,e,s),i=a.data,[l,u,d]=Yn((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;m<u.length;++m)u[m]=Math.sqrt(u[m]/(o[e]-r));return[new U(l,u,d),a]}function al(t,e=null,r=!1){let s=t.dims,n=t.data;if(e===null){let l=n.reduce((u,d)=>u+d,0);return new U(t.type,[l/n.length],[])}e=or(e,s.length);let[o,a,i]=Yn((l,u)=>l+u,t,e,r);if(s[e]!==1)for(let l=0;l<a.length;++l)a[l]/=s[e];return new U(o,a,i)}function wd(t){let e=new Array(t.length);for(let r=t.length-1,s=1;r>=0;--r)e[r]=s,s*=t[r];return e}function bd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new U(r,new s(n).fill(e),t)}function Ve(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return bd(t,e,r,s)}function Qn(t,e){return Ve(t.dims,e)}function it(t){return bd(t,1n,"int64",BigInt64Array)}function il(t){return it(t.dims)}function vd(t){return bd(t,0n,"int64",BigInt64Array)}function kd(t){return vd(t.dims)}function ZN(t){let e=t.reduce((r,s)=>r*s,1);return new U("float32",Float32Array.from({length:e},()=>Math.random()),t)}function PE(t){let e=t.reduce((s,n)=>s*n,1),r=new Float32Array(e);for(let s=0;s<e;s+=2){let n=1-Math.random(),o=Math.random(),a=Math.sqrt(-2*Math.log(n)),i=2*Math.PI*o;r[s]=a*Math.cos(i),s+1<e&&(r[s+1]=a*Math.sin(i))}return new U("float32",r,t)}function zE(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i<o.length;++i){let l=o[i]>0?1:0,u=Math.floor(i/8),d=i%8;a[u]|=l<<7-d,r&&d===0&&(a[u]-=128)}return new U(s,a,[t.dims[0],t.dims[1]/8])}async function Ed(t,e){return await Promise.all([at(t,"tokenizer.json",!0,e),at(t,"tokenizer_config.json",!0,e)])}function Ad(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 YC=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function QC(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?dt(t[n],i):dt(i,t[n])}}function JC(t,e){for(let r of Object.keys(t))t[r].length=e}function ds(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 ZC(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var j=class extends Je{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new xv(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=ds(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=ds(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=ds(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=ds(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=ds(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=ds(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=ZC(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 Ed(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,{text_pair:r=null,add_special_tokens:s=!0,padding:n=!1,truncation:o=null,max_length:a=null,return_tensor:i=!0,return_token_type_ids:l=null}={}){let u=Array.isArray(e),d;if(u){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");d=e.map((m,_)=>this._encode_plus(m,{text_pair:r[_],add_special_tokens:s,return_token_type_ids:l}))}else d=e.map(m=>this._encode_plus(m,{add_special_tokens:s,return_token_type_ids:l}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");d=[this._encode_plus(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:l})]}if(a===null?a=this.model_max_length:o===null&&(n===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),a=this.model_max_length):n===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),n===!0&&(a=Math.min(Te(d.map(m=>m.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),n||o)for(let m=0;m<d.length;++m)d[m].input_ids.length!==a&&(d[m].input_ids.length>a?o&&JC(d[m],a):n&&QC(d[m],a,_=>_==="input_ids"?this.pad_token_id:0,this.padding_side));let f={};if(i){if(!(n&&o)&&d.some(_=>{for(let w of Object.keys(_))if(_[w].length!==d[0][w]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[d.length,d[0].input_ids.length];for(let _ of Object.keys(d[0]))f[_]=new U("int64",BigInt64Array.from(d.flatMap(w=>w[_]).map(BigInt)),m)}else{for(let m of Object.keys(d[0]))f[m]=d.map(_=>_[m]);if(!u)for(let m of Object.keys(f))f[m]=f[m][0]}return f}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof U&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof U&&(e=Ad(e)),!Array.isArray(e)||e.length===0||!Pv(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,{tools:r=null,documents:s=null,chat_template:n=null,add_generation_prompt:o=!1,tokenize:a=!0,padding:i=!1,truncation:l=!1,max_length:u=null,return_tensor:d=!0,return_dict:f=!0,tokenizer_kwargs:m={},..._}={}){if(n=this.get_chat_template({chat_template:n,tools:r}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let w=this._compiled_template_cache.get(n);w===void 0&&(w=new Cv(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let E of YC){let M=ds(this.config,E);M&&(x[E]=M)}let k=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,..._});if(a){let E=this._call(k,{add_special_tokens:!1,padding:i,truncation:l,max_length:u,return_tensor:d,...m});return f?E:E.input_ids}return k}};function Vs(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var gf={};Ps(gf,{AlbertTokenizer:()=>Md,AutoTokenizer:()=>J,BartTokenizer:()=>Td,BertTokenizer:()=>Sd,BlenderbotSmallTokenizer:()=>Od,BlenderbotTokenizer:()=>Id,BloomTokenizer:()=>Cd,CLIPTokenizer:()=>zd,CamembertTokenizer:()=>Pd,CodeGenTokenizer:()=>Nd,CodeLlamaTokenizer:()=>Ld,CohereTokenizer:()=>$d,ConvBertTokenizer:()=>Rd,DebertaTokenizer:()=>Bd,DebertaV2Tokenizer:()=>Ud,DistilBertTokenizer:()=>Dd,ElectraTokenizer:()=>Fd,EsmTokenizer:()=>jd,FalconTokenizer:()=>Gd,GPT2Tokenizer:()=>Vd,GPTNeoXTokenizer:()=>Wd,GemmaTokenizer:()=>qd,HerbertTokenizer:()=>Hd,LlamaTokenizer:()=>Xd,M2M100Tokenizer:()=>Kd,MBart50Tokenizer:()=>Qd,MBartTokenizer:()=>Jn,MPNetTokenizer:()=>ef,MarianTokenizer:()=>Yd,MgpstrTokenizer:()=>Jd,MobileBertTokenizer:()=>Zd,NllbTokenizer:()=>tf,NougatTokenizer:()=>rf,PreTrainedTokenizer:()=>j,Qwen2Tokenizer:()=>sf,RoFormerTokenizer:()=>of,RobertaTokenizer:()=>nf,SiglipTokenizer:()=>af,SpeechT5Tokenizer:()=>lf,SqueezeBertTokenizer:()=>cf,T5Tokenizer:()=>uf,TokenizersBackend:()=>j,VitsTokenizer:()=>df,Wav2Vec2CTCTokenizer:()=>ff,WhisperTokenizer:()=>mf,XLMRobertaTokenizer:()=>hf,XLMTokenizer:()=>_f});var Md=class extends j{return_token_type_ids=!0};var Td=class extends j{};var Sd=class extends j{return_token_type_ids=!0};var Od=class extends j{};var Id=class extends j{};var Cd=class extends j{};var Pd=class extends j{};var zd=class extends j{};var Ld=class extends j{};var Nd=class extends j{};var $d=class extends j{};var Rd=class extends j{return_token_type_ids=!0};var Ud=class extends j{return_token_type_ids=!0};var Bd=class extends j{return_token_type_ids=!0};var Dd=class extends j{};var Fd=class extends j{return_token_type_ids=!0};var jd=class extends j{};var Gd=class extends j{};var qd=class extends j{};var Wd=class extends j{};var Vd=class extends j{};var Hd=class extends j{return_token_type_ids=!0};var Xd=class extends j{padding_side="left"};var Kd=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var Yd=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||console.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),dt([n],super._encode_text(o))}}};var Jn=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var Qd=class extends Jn{};var Jd=class extends j{};var Zd=class extends j{return_token_type_ids=!0};var ef=class extends j{};var tf=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var rf=class extends j{};var sf=class extends j{};var nf=class extends j{};var of=class extends j{return_token_type_ids=!0};var af=class extends j{};var lf=class extends j{};var cf=class extends j{return_token_type_ids=!0};var uf=class extends j{};var pf=class extends $t{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},df=class extends j{constructor(e,r){super(e,r),this._tokenizer.decoder=new pf({type:"VitsDecoder"})}};var ff=class extends j{};var LE=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],Zn=new Map(LE),eP=new Map([...LE.map(([t,e])=>[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function NE(t){t=t.toLowerCase();let e=eP.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Zn.has(t))e=t;else{let n=t.length===2?Zn.keys():Zn.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var tP="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",$E=new RegExp(`^[${tP}]+$`,"gu"),mf=class extends j{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let u=[],d=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],k=[],E=!1,M=null,I=new Set(this.all_special_ids);for(let C of e){let v=C.tokens,G=i?C.token_timestamps:null,X=null,V=m;if("stride"in C){let[Y,B,P]=C.stride;if(f-=B,M=Y-P,B&&(V=B/n+m),P)for(let se=v.length-1;se>=0;--se){let ie=Number(v[se]);if(ie>=m){if(X!==null&&(ie-m)*n<M)break;X=ie}}}let Q=[],K=[];for(let Y=0;Y<v.length;++Y){let B=Number(v[Y]);if(I.has(B)){let P=this.decode([B]),se=Zn.get(P.slice(2,-2));if(se!==void 0){if(a!==null&&se!==a&&!r){x.push(Q);let ie=this.findLongestCommonSequence(x)[0],S=this.decode(ie);d.text=S,u.push(d),x=[],Q=[],d=l()}a=d.language=se}}else if(B>=m&&B<=w){let P=(B-m)*n+f,se=rs(P,2);if(X!==null&&B>=X)E=!0;else if(E||x.length>0&&B<V)E=!1;else if(d.timestamp[0]===null)d.timestamp[0]=se;else if(se!==d.timestamp[0]){d.timestamp[1]=se,x.push(Q),i&&k.push(K);let[ie,S]=this.findLongestCommonSequence(x,k),L=this.decode(ie);d.text=L,i&&(d.words=this.collateWordTimestamps(ie,S,a)),u.push(d),x=[],Q=[],k=[],K=[],d=l()}}else if(Q.push(B),i){let P=rs(G[Y]+f,2),se;if(Y+1<G.length){se=rs(G[Y+1]+f,2);let ie=this.decode([B]);$E.test(ie)&&(se=rs(Math.min(P+n,se),2))}else se=null;K.push([P,se])}}if("stride"in C){let[Y,B,P]=C.stride;f+=Y-P}Q.length>0?(x.push(Q),i&&k.push(K)):x.every(Y=>Y.length===0)&&(d=l(),x=[],Q=[],k=[],K=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[C,v]=this.findLongestCommonSequence(x,k),G=this.decode(C);d.text=G,i&&(d.words=this.collateWordTimestamps(C,v,a)),u.push(d)}let T=Object.create(null),z=u.map(C=>C.text).join("");if(r||s){for(let C=0;C<u.length;++C){let v=u[C];r||delete v.timestamp,s||delete v.language}if(i){let C=[];for(let v of u)for(let G of v.words)C.push(G);T={chunks:C}}else T={chunks:u}}return[z,T]}findLongestCommonSequence(e,r=null){let s=e[0],n=s.length,o=[],a=Array.isArray(r)&&r.length>0,i=a?[]:null,l=a?r[0]:null;for(let u=1;u<e.length;++u){let d=e[u],f=0,m=[n,n,0,0],_=d.length;for(let T=1;T<n+_;++T){let z=Math.max(0,n-T),C=Math.min(n,n+_-T),v=s.slice(z,C),G=Math.max(0,T-n),X=Math.min(_,T),V=d.slice(G,X);if(v.length!==V.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let Q;a?Q=v.filter((B,P)=>B===V[P]&&l[z+P]<=r[u][G+P]).length:Q=v.filter((B,P)=>B===V[P]).length;let K=T/1e4,Y=Q/T+K;Q>1&&Y>f&&(f=Y,m=[z,C,G,X])}let[w,x,k,E]=m,M=Math.floor((x+w)/2),I=Math.floor((E+k)/2);o.push(...s.slice(0,M)),s=d.slice(I),n=s.length,a&&(i.push(...l.slice(0,M)),l=r[u].slice(I))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l<n.length;++l){let u=a[l];i.push({text:n[l],timestamp:[r[u.at(0)][0],r[u.at(-1)][1]]})}return i}combineTokensIntoWords(e,r,s=`"'\u201C\xA1\xBF([{-`,n=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){r=r??"english";let o,a,i;return["chinese","japanese","thai","lao","myanmar"].includes(r)?[o,a,i]=this.splitTokensOnUnicode(e):[o,a,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(o,a,i,s,n)}decode(e,r){let s;return r?.decode_with_timestamps?(e instanceof U&&(e=Ad(e)),s=this.decodeWithTimestamps(e,r)):s=super.decode(e,r),s}decodeWithTimestamps(e,r){let s=r?.time_precision??.02,n=this.all_special_ids.at(-1)+1,o=[[]];for(let a of e)if(a=Number(a),a>=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],u=0;for(let d=0;d<e.length;++d){let f=e[d];i.push(f),l.push(d);let m=this.decode(i,{decode_with_timestamps:!0});(!m.includes(s)||r[u+m.indexOf(s)]===s)&&(n.push(m),o.push(i),a.push(l),i=[],l=[],u+=m.length)}return[n,o,a]}splitTokensOnSpaces(e){let[r,s,n]=this.splitTokensOnUnicode(e),o=[],a=[],i=[];for(let l=0;l<r.length;++l){let u=r[l],d=s[l],f=n[l],m=d[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=u.startsWith(" "),w=u.trim(),x=$E.test(w);if(m||_||x||o.length===0)o.push(u),a.push(d),i.push(f);else{let k=o.length-1;o[k]+=u,a[k].push(...d),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),u=a.length-2,d=a.length-1;for(;u>=0;)a[u].startsWith(" ")&&n.includes(a[u].trim())?(a[d]=a[u]+a[d],i[d]=dt(i[u],i[d]),l[d]=dt(l[u],l[d]),a[u]="",i[u]=[],l[u]=[]):d=u,--u;for(u=0,d=1;d<a.length;)!a[u].endsWith(" ")&&o.includes(a[d])?(a[u]+=a[d],i[u]=dt(i[u],i[d]),l[u]=dt(l[u],l[d]),a[d]="",i[d]=[],l[d]=[]):u=d,++d;return[a.filter(f=>f),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var hf=class extends j{};var _f=class extends j{return_token_type_ids=!0;constructor(e,r){super(e,r),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var J=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Ed(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),u=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",d=gf[u];return d||(console.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),d=j),new d(i,l)}};var Hs="https://github.com/huggingface/transformers.js/issues/new/choose";var eo="preprocessor_config.json",Xs=eo,RE="processor_config.json",UE="chat_template.jinja";var ne=class extends Je{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?at(e,RE,!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?yp(e,UE,!0,r):null]);return new this(s,n,o)}};var Cl={};Ps(Cl,{ChatterboxProcessor:()=>Pf,Florence2Processor:()=>km,Gemma3nProcessor:()=>Em,GroundingDinoProcessor:()=>Am,Idefics3Processor:()=>Sl,JinaCLIPProcessor:()=>Tm,LlavaProcessor:()=>Sm,MgpstrProcessor:()=>Om,MoonshineProcessor:()=>Im,OwlViTProcessor:()=>Cm,PaliGemmaProcessor:()=>Pm,Phi3VProcessor:()=>zm,PixtralProcessor:()=>Lm,Processor:()=>ne,PyAnnoteProcessor:()=>Nm,Qwen2VLProcessor:()=>$m,Sam2Processor:()=>Ol,Sam2VideoProcessor:()=>Rm,SamProcessor:()=>io,SmolVLMProcessor:()=>Sl,SpeechT5Processor:()=>Um,UltravoxProcessor:()=>Bm,VLChatProcessor:()=>Mm,VoxtralProcessor:()=>Dm,Wav2Vec2Processor:()=>Fm,Wav2Vec2ProcessorWithLM:()=>jm,WhisperProcessor:()=>Gm});var Ne=class extends Je{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await at(e,eo,!0,r);return new this(s)}};function He(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var oo={};Ps(oo,{ASTFeatureExtractor:()=>yf,ChatterboxFeatureExtractor:()=>bf,ClapFeatureExtractor:()=>vf,DacFeatureExtractor:()=>so,EncodecFeatureExtractor:()=>ro,FeatureExtractor:()=>Ne,Gemma3nAudioFeatureExtractor:()=>kf,MoonshineFeatureExtractor:()=>Ef,ParakeetFeatureExtractor:()=>Af,PyAnnoteFeatureExtractor:()=>no,SeamlessM4TFeatureExtractor:()=>Mf,SnacFeatureExtractor:()=>Tf,SpeechT5FeatureExtractor:()=>Sf,Wav2Vec2FeatureExtractor:()=>Of,WeSpeakerFeatureExtractor:()=>If,WhisperFeatureExtractor:()=>Cf});import rP from"fs";import{Readable as sP}from"stream";import{pipeline as nP}from"stream/promises";async function ll(t,e){if(be.IS_BROWSER_ENV){if(be.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(be.IS_FS_AVAILABLE){let r=e.stream(),s=sP.fromWeb(r),n=rP.createWriteStream(t);await nP(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function xf(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 Bs(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&console.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let u=0;u<n.length;++u)o[u]=a*(i[u]+l[u])/2}else o=n.getChannelData(0);return o}function FE(t,e){if(t<1)return new Float64Array;if(t===1)return new Float64Array([1]);let r=1-e,s=2*Math.PI/(t-1),n=new Float64Array(t);for(let o=0;o<t;++o)n[o]=e-r*Math.cos(o*s);return n}function BE(t){return FE(t,.5)}function oP(t){return FE(t,.54)}var aP={htk:t=>2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function wf(t,e="htk"){let r=aP[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 iP={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 lP(t,e="htk"){let r=iP[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 cP(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<e.length;++l)i[l]=e[l]-t[a]}let n=e.length-2,o=Array.from({length:n},()=>new Array(t.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<n;++l){let u=-i[l]/r[l],d=i[l+2]/r[l+1];o[l][a]=Math.max(0,Math.min(u,d))}}return o}function DE(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+s*o)}function yt(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=wf(r,a),u=wf(s,a),d=DE(l,u,e+2),f=lP(d,a),m;if(i){let w=n/((t-1)*2);m=wf(Float64Array.from({length:t},(x,k)=>k*w),a),f=d}else m=DE(0,Math.floor(n/2),t);let _=cP(m,f);if(o!==null&&o==="slaney")for(let w=0;w<e;++w){let x=_[w],k=2/(f[w+2]-f[w]);for(let E=0;E<t;++E)x[E]*=k}return _}function uP(t,e,r){let s=new t.constructor(t.length+e+r),n=t.length-1;for(let o=0;o<t.length;++o)s[e+o]=t[o];for(let o=1;o<=e;++o)s[e-o]=t[$s(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[$s(n-o,n)];return s}function jE(t,e,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);let o=Math.log10(r);for(let a=0;a<t.length;++a)t[a]=e*Math.log10(Math.max(s,t[a])-o);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");let a=Te(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function pP(t,e=1,r=1e-5,s=null){return jE(t,20,e,r,s)}function dP(t,e=1,r=1e-10,s=null){return jE(t,10,e,r,s)}async function At(t,e,r,s,{fft_length:n=null,power:o=1,center:a=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:u=null,preemphasis_htk_flavor:d=!0,mel_filters:f=null,mel_floor:m=1e-10,log_mel:_=null,reference:w=1,min_value:x=1e-10,db_range:k=null,remove_dc_offset:E=null,min_num_frames:M=null,max_num_frames:I=null,do_pad:T=!0,transpose:z=!1,mel_offset:C=0}={}){let v=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(v!==r)throw new Error(`Length of the window (${v}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a)switch(i){case"reflect":{let L=Math.floor((n-1)/2)+1;t=uP(t,L,L);break}case"constant":{let L=Math.floor(n/2),R=new t.constructor(t.length+2*L);R.set(t,L),t=R;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let G=Math.floor(1+Math.floor((t.length-r)/s));M!==null&&G<M&&(G=M);let X=l?Math.floor(n/2)+1:n,V=G,Q=G;I!==null&&(I>G?T&&(Q=I):Q=V=I);let K=new ji(n),Y=new Float64Array(n),B=new Float64Array(K.outputBufferSize),P=new Float32Array(X*Q);for(let L=0;L<V;++L){let R=L*s,te=Math.min(t.length-R,r);te!==r&&Y.fill(0,0,r);for(let ue=0;ue<te;++ue)Y[ue]=t[R+ue];if(E){let ue=0;for(let Ce=0;Ce<te;++Ce)ue+=Y[Ce];let Be=ue/te;for(let Ce=0;Ce<te;++Ce)Y[Ce]-=Be}if(u!==null){for(let ue=te-1;ue>=1;--ue)Y[ue]-=u*Y[ue-1];Y[0]*=1-u}for(let ue=0;ue<e.length;++ue)Y[ue]*=e[ue];K.realTransform(B,Y);for(let ue=0;ue<X;++ue){let Be=ue<<1;P[ue*Q+L]=B[Be]**2+B[Be+1]**2}}if(o!==null&&o!==2){let L=o/2;for(let R=0;R<P.length;++R)P[R]**=L}let se=f.length,ie=await IE(new U("float32",f.flat(),[se,X]),new U("float32",P,[X,Q]));z&&(ie=ie.transpose(1,0));let S=ie.data;for(let L=0;L<S.length;++L)S[L]=C+Math.max(m,S[L]);if(o!==null&&_!==null){let L=Math.min(S.length,V*se);switch(_){case"log":for(let R=0;R<L;++R)S[R]=Math.log(S[R]);break;case"log10":for(let R=0;R<L;++R)S[R]=Math.log10(S[R]);break;case"dB":if(o===1)pP(S,w,x,k);else if(o===2)dP(S,w,x,k);else throw new Error(`Cannot use log_mel option '${_}' with power ${o}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${_}'`)}}return ie}function Mt(t,e,{periodic:r=!0,frame_length:s=null,center:n=!0}={}){let o=r?t+1:t,a;switch(e){case"boxcar":a=new Float64Array(o).fill(1);break;case"hann":case"hann_window":a=BE(o);break;case"hamming":a=oP(o);break;case"povey":a=BE(o).map(i=>Math.pow(i,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);return a}function fP(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return cl(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),cl(n,8,"WAVE"),cl(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),cl(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function cl(t,e,r){for(let s=0;s<r.length;++s)t.setUint8(e+s,r.charCodeAt(s))}var to=class{constructor(e,r){this.audio=e,this.sampling_rate=r}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((n,o)=>n+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),fP(e,this.sampling_rate)}async save(e){return ll(e,this.toBlob())}};var yf=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){He(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o<n.length;++o)n[o]=(n[o]-this.mean)/s}return{input_values:r.unsqueeze_(0)}}};var ro=class extends Ne{async _call(e){He(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=this.config.feature_size;if(e.length%r!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${r}).`);let s=[1,r,e.length/r];return{input_values:new U("float32",e,s)}}};var bf=class extends Ne{async _call(e){He(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new U("float32",e,r)}}};var vf=class extends Ne{constructor(e){super(e),this.mel_filters=yt(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=yt(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=Mt(this.config.fft_window_size,"hann")}async _get_input_mel(e,r,s,n){let o,a=!1,i=e.length-r;if(i>0)if(s==="rand_trunc"){a=!0;let l=Math.floor(Math.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let u=e.length;u<r;u+=e.length)l.set(e.subarray(0,Math.min(e.length,r-u)),u);else if(n==="repeatpad")for(let u=e.length;u<-i;u+=e.length)l.set(e,u);e=l}if(s==="fusion")throw new Error(`Truncation strategy "${s}" not implemented`);o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return o.unsqueeze_(0)}async _extract_fbank_features(e,r,s=null){return At(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:r,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:r=null}={}){return He(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,r??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}};var so=class extends ro{};var kf=class extends Ne{constructor(e){super(e);let{fft_length:r,feature_size:s,min_frequency:n,max_frequency:o,sampling_rate:a,frame_length:i}=this.config,l=yt(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=Mt(i,"hann")}async _extract_fbank_features(e,r){return At(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:r=48e4,truncation:s=!0,padding:n=!0,pad_to_multiple_of:o=128}={}){if(He(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>r&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,u=new Float64Array(e.length+l);u.set(e),this.config.padding_value!==0&&u.fill(this.config.padding_value,e.length),e=u}let a=await this._extract_fbank_features(e,this.config.max_length),i=Ve([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Ef=class extends Ne{async _call(e){He(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new U("float32",e,r)}}};var mP=1e-5,Af=class extends Ne{constructor(e){super(e),this.config.mel_filters??=yt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let r=Mt(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let s=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(r,s)}async _extract_fbank_features(e){let r=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=r*e[n-1];return await At(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){He(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f<s;++f){let m=f*a;for(let _=0;_<a;++_){let w=n[m+_];i[_]+=w,l[_]+=w*w}}let u=s>1?s-1:1;for(let f=0;f<a;++f){let m=i[f]/s,_=(l[f]-s*m*m)/u,x=1/(Math.sqrt(_)+mP);for(let k=0;k<s;++k){let E=k*a+f;n[E]=(n[E]-m)*x}}let d=new BigInt64Array(o);return d.fill(1n,0,s),{input_features:r.unsqueeze_(0),attention_mask:new U("int64",d,[1,o])}}};var no=class extends Ne{async _call(e){He(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new U("float32",e,r)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,r){let s=r/this.samples_to_frames(r)/this.config.sampling_rate,n=[];for(let o of e.tolist()){let a=[],i=-1;for(let l=0;l<o.length;++l){let u=Pe(o[l]),[d,f]=Te(u),[m,_]=[l,l+1];f!==i?(i=f,a.push({id:f,start:m,end:_,score:d})):(a.at(-1).end=_,a.at(-1).score+=d)}n.push(a.map(({id:l,start:u,end:d,score:f})=>({id:l,start:u*s,end:d*s,confidence:f/(d-u)})))}return n}};var Mf=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){He(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let E=0;E<x;++E){let M=0;for(let C=0;C<w;++C)M+=k[C*x+E];let I=M/w,T=0;for(let C=0;C<w;++C)T+=(k[C*x+E]-I)**2;T/=w-1;let z=Math.sqrt(T+1e-7);for(let C=0;C<w;++C){let v=C*x+E;k[v]=(k[v]-I)/z}}}let i;if(r){let[w,x]=a.dims,k=a.data,E=w%s;if(E>0){let M=new Float32Array(x*(w+E));M.set(k),M.fill(this.config.padding_value,k.length);let I=w+E;a=new U(a.type,M,[I,x]),o&&(i=new U("int64",new BigInt64Array(I),[1,I]),i.data.fill(1n,0,w))}}let[l,u]=a.dims,d=this.config.stride;if(l%d!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${d}).`);let m=a.view(1,Math.floor(l/d),u*d),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let E=1,M=0;E<l;E+=d,++M)x[M]=k[E]}else x.fill(1n);_.attention_mask=new U("int64",x,[1,w])}return _}};var Tf=class extends so{};var Sf=class extends Ne{};var Of=class extends Ne{_zero_mean_unit_var_norm(e){let s=e.reduce((o,a)=>o+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){He(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new U("float32",r,s),attention_mask:new U("int64",new BigInt64Array(r.length).fill(1n),s)}}};var If=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(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),At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){He(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;l<o;++l){let u=l*a*i,d=l*i;for(let f=0;f<a;++f){let m=u+f*i;for(let _=0;_<i;++_)n[m+_]-=s[d+_]}}}return{input_features:r}}};var Cf=class extends Ne{constructor(e){super(e),this.config.mel_filters??=yt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=Mt(this.config.n_fft,"hann")}async _extract_fbank_features(e){let r=await At(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)}),s=r.data,n=Te(s)[0];for(let o=0;o<s.length;++o)s[o]=(Math.max(s[o],n-8)+4)/4;return r}async _call(e,{max_length:r=null}={}){He(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var tt=class{static async from_pretrained(e,r={}){let s=await at(e,eo,!0,r),n=s.feature_extractor_type,o=oo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Hs}.`);return new o(s)}};var Pf=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};import zf from"sharp";var fs,GE,Or,Qt=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV;if(Qt)fs=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},Or=self.createImageBitmap,GE=self.ImageData;else if(zf)Or=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Xe(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var hP={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_P=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Xe=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!Qt)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 Bs(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(Qt){let r=await Or(e),s=fs(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=zf(await e.arrayBuffer());return await Or(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r<this.data.length;r+=this.channels){let n=this.data[r],o=this.data[r+1],a=this.data[r+2];e[s++]=Math.round(.2989*n+.587*o+.114*a)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2],e[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${e.channels}`);let r=this.data,s=e.data,n=this.width*this.height;if(this.channels===3){let o=new Uint8ClampedArray(n*4);for(let a=0,i=0,l=0;a<n;++a)o[l++]=r[i++],o[l++]=r[i++],o[l++]=r[i++],o[l++]=s[a];return this._update(o,this.width,this.height,4)}else if(this.channels===4){for(let o=0;o<n;++o)r[4*o+3]=s[o];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(e,r,{resample:s=2}={}){if(this.width===e&&this.height===r)return this;let n=hP[s]??s,o=gp(e),a=gp(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),Qt){let i=this.channels,l=this.toCanvas(),u=fs(e,r).getContext("2d");return u.drawImage(l,0,0,e,r),new t(u.getImageData(0,0,e,r).data,e,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(console.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([e/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:e,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await Or(i)}}async pad([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),e===0&&r===0&&s===0&&n===0)return this;if(Qt){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,u=fs(i,l).getContext("2d");return u.drawImage(a,0,0,this.width,this.height,e,s,this.width,this.height),new t(u.getImageData(0,0,i,l).data,i,l,4).convert(o)}else{let o=this.toSharp().extend({left:e,right:r,top:s,bottom:n});return await Or(o)}}async crop([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),e===0&&r===0&&s===this.width-1&&n===this.height-1)return this;let o=s-e+1,a=n-r+1;if(Qt){let i=this.channels,l=this.toCanvas(),u=fs(o,a).getContext("2d");return u.drawImage(l,e,r,o,a,0,0,o,a),new t(u.getImageData(0,0,o,a).data,o,a,4).convert(i)}else{let i=this.toSharp().extract({left:e,top:r,width:o,height:a});return await Or(i)}}async center_crop(e,r){if(this.width===e&&this.height===r)return this;let s=(this.width-e)/2,n=(this.height-r)/2;if(Qt){let o=this.channels,a=this.toCanvas(),i=fs(e,r).getContext("2d"),l=0,u=0,d=0,f=0;return s>=0?l=s:d=-s,n>=0?u=n:f=-n,i.drawImage(a,l,u,e,r,d,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],u=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):u=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:u,top:i,width:e,height:r})}return await Or(o)}}async toBlob(e="image/png",r=1){if(!Qt)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 U("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(!Qt)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=fs(e.width,e.height),s=new GE(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;l<a;++l){let u=n*l;for(let d=0;d<n;++d)i[d][l]=e[u+d]}return i.map(l=>new t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(Qt){if(be.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=_P.get(r)??"image/png",n=await this.toBlob(s);return ll(e,n)}else if(be.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(Qt)throw new Error("toSharp() is only supported in server-side environments.");return zf(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},gP=Xe.read.bind(Xe);function qE(t,e,r=0,s=null){let n=t/e,o=Hv(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function Lf([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function Nf([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Ir(t,e=.5,r=null,s=!1){let n=t.logits,o=t.pred_boxes,[a,i,l]=n.dims;if(r!==null&&r.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let d=0;d<a;++d){let f=r!==null?r[d]:null,m={boxes:[],classes:[],scores:[]},_=n[d],w=o[d];for(let x=0;x<i;++x){let k=_[x],E=[],M;if(s){M=k.sigmoid().data;for(let I=0;I<M.length;++I)M[I]>e&&E.push(I)}else{let I=Te(k.data)[1];if(I===l-1||(M=Pe(k.data),M[I]<e))continue;E.push(I)}for(let I of E){let T=w[x].data;T=Nf(T),f!==null&&(T=T.map((z,C)=>z*f[(C+1)%2])),m.boxes.push(T),m.classes.push(I),m.scores.push(M[I])}}u.push(m)}return u}function ul(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;o<s;++o){let a=e!==null?e[o]:null,i=r[o];a!==null&&(i=xd(i,a,"bilinear",!1));let[l,u]=a??i.dims.slice(-2),d=new U("int32",new Int32Array(l*u),[l,u]),f=i[0].data,m=d.data;for(let x=1;x<i.dims[0];++x){let k=i[x].data;for(let E=0;E<k.length;++E)k[E]>f[E]&&(f[E]=k[E],m[E]=x)}let _=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let k=m[x];_[k]=k}let w=_.filter(x=>x!==void 0);n.push({segmentation:d,labels:w})}return n}function wP(t,e,r,s){let n=[],o=[],a=[];for(let i=0;i<t.dims[0];++i){let l=t[i],u=e[i],d=Te(l.data)[1];if(d===s)continue;let m=Pe(l.data)[d];m>r&&(n.push(u),o.push(m),a.push(d))}return[n,o,a]}function xP(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let d=0;d<t.length;++d)t[d]===r&&(o.push(d),++a),l[d]>=s&&++i;let u=a>0&&i>0;return u&&(u=a/i>n),[u,o]}function yP(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,u=new U("int32",new Int32Array(i*l),[i,l]),d=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=xd(t[x],a,"bilinear",!1);let f=new Int32Array(t[0].data.length),m=new Float32Array(t[0].data.length);for(let x=0;x<t.length;++x){let k=e[x],E=t[x].data;for(let M=0;M<E.length;++M)E[M]*=k,E[M]>m[M]&&(f[M]=x,m[M]=E[M])}let _=0,w=u.data;for(let x=0;x<r.length;++x){let k=r[x],[E,M]=xP(f,t,x,s,n);if(E){++_;for(let I of M)w[I]=_;d.push({id:_,label_id:k,score:e[x]})}}return[u,d]}function bP(t,e,r=28,s=3136,n=784*1280){if(t<r||e<r)throw new Error(`height:${t} or width:${e} must be larger than factor:${r}`);if(Math.max(t,e)/Math.min(t,e)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let o=Math.round(t/r)*r,a=Math.round(e/r)*r;if(o*a>n){let i=Math.sqrt(t*e/n);o=Math.floor(t/i/r)*r,a=Math.floor(e/i/r)*r}else if(o*a<s){let i=Math.sqrt(s/(t*e));o=Math.ceil(t*i/r)*r,a=Math.ceil(e*i/r)*r}return[o,a]}function pl(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);let a=t.class_queries_logits??t.logits,l=(t.masks_queries_logits??t.pred_masks).sigmoid(),[u,d,f]=a.dims;if(f-=1,o!==null&&o.length!==u)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let m=[];for(let _=0;_<u;++_){let w=o!==null?o[_]:null,x=a[_],k=l[_],[E,M,I]=wP(x,k,e,f);if(I.length===0){let[C,v]=w??k.dims.slice(-2),G=new U("int32",new Int32Array(C*v).fill(-1),[C,v]);m.push({segmentation:G,segments_info:[]});continue}let[T,z]=yP(E,M,I,r,s,n,w);m.push({segmentation:T,segments_info:z})}return m}function dl(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var W=class extends Je{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,r,s=2){let n=e.height,o=e.width,a=r.height,i=r.width,l=Math.min(n,a),u=Math.min(o,i);return l===n&&u===o?e:(n>o?u=Math.floor(o*l/n):o>n&&(l=Math.floor(n*u/o)),await e.resize(u,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=Dn(s.data)[0],a=Te(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,u=s.height,d=0,f=0,m=s.data;for(let _=0;_<s.height;++_){let w=_*s.width;for(let x=0;x<s.width;++x)(m[w+x]-n)/a<i&&(l=Math.min(l,x),u=Math.min(u,_),d=Math.max(d,x),f=Math.max(f,_))}return e=await e.crop([l,u,d,f]),e}pad_image(e,r,s,{mode:n="constant",center:o=!1,constant_values:a=0}={}){let[i,l,u]=r,d,f;if(typeof s=="number"?(d=s,f=s):s==="square"?d=f=Math.max(i,l):(d=s.width,f=s.height),d!==l||f!==i){let m=new Float32Array(d*f*u);if(Array.isArray(a))for(let x=0;x<m.length;++x)m[x]=a[x%u];else a!==0&&m.fill(a);let[_,w]=o?[Math.floor((d-l)/2),Math.floor((f-i)/2)]:[0,0];for(let x=0;x<i;++x){let k=(x+w)*d,E=x*l;for(let M=0;M<l;++M){let I=(k+M+_)*u,T=(E+M)*u;for(let z=0;z<u;++z)m[I+z]=e[T+z]}}if(n==="symmetric"){if(o)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let x=i-1,k=l-1;for(let E=0;E<f;++E){let M=E*d,I=$s(E,x)*l;for(let T=0;T<d;++T){if(E<i&&T<l)continue;let z=(M+T)*u,C=(I+$s(T,k))*u;for(let v=0;v<u;++v)m[z+v]=e[C+v]}}}e=m,r=[f,d,u]}return[e,r]}rescale(e){for(let r=0;r<e.length;++r)e[r]=this.rescale_factor*e[r]}get_resize_output_image_size(e,r){let[s,n]=e.size,o,a;if(this.do_thumbnail){let{height:i,width:l}=r;o=Math.min(i,l)}else Number.isInteger(r)?(o=r,a=this.config.max_size??o):r!==void 0&&(o=r.shortest_edge,a=r.longest_edge);if(o!==void 0||a!==void 0){let i=o===void 0?1:Math.max(o/s,o/n),l=s*i,u=n*i,d=a===void 0?1:Math.min(a/l,a/u),f=Math.floor(Number((l*d).toFixed(2))),m=Math.floor(Number((u*d).toFixed(2)));return this.size_divisibility!==void 0&&([f,m]=Lf([f,m],this.size_divisibility)),[f,m]}else if(r!==void 0&&r.width!==void 0&&r.height!==void 0){let i=r.width,l=r.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let u=l/n,d=i/s;Math.abs(1-d)<Math.abs(1-u)?u=d:d=u,l=qE(u*n,this.config.ensure_multiple_of),i=qE(d*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return Lf([s,n],this.size_divisibility);if(this.min_pixels!==void 0&&this.max_pixels!==void 0){let i=this.config.patch_size*this.config.merge_size;return bP(n,s,i,this.min_pixels,this.max_pixels)}else throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(r)}`)}}async resize(e){let[r,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(r,s,{resample:this.resample})}async preprocess(e,{do_normalize:r=null,do_pad:s=null,do_convert_rgb:n=null,do_convert_grayscale:o=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[i,l]=e.size;if(n??this.do_convert_rgb?e=e.rgb():o&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,w;Number.isInteger(this.crop_size)?(_=this.crop_size,w=this.crop_size):(_=this.crop_size.width,w=this.crop_size.height),e=await e.center_crop(_,w)}let u=[e.height,e.width],d=Float32Array.from(e.data),f=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(d),r??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let w=this.image_std;if(Array.isArray(this.image_std)||(w=new Array(e.channels).fill(w)),_.length!==e.channels||w.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${w.length}) must match the number of channels in the image (${e.channels}).`);for(let x=0;x<d.length;x+=e.channels)for(let k=0;k<e.channels;++k)d[x+k]=(d[x+k]-_[k])/w[k]}if(s??this.do_pad){if(this.pad_size)[d,f]=this.pad_image(d,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let[_,w]=Lf([f[1],f[0]],this.size_divisibility);[d,f]=this.pad_image(d,f,{width:_,height:w})}}if(a??this.do_flip_channel_order){if(f[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<d.length;_+=3){let w=d[_];d[_]=d[_+2],d[_+2]=w}}let m=new U("float32",d,f).permute(2,0,1);return{original_size:[l,i],reshaped_input_size:u,pixel_values:m}}async _call(e,...r){Array.isArray(e)||(e=[e]);let s=await Promise.all(e.map(o=>this.preprocess(o)));return{pixel_values:Ft(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await at(e,Xs,!0,r);return new this(s)}};var Zs={};Ps(Zs,{BeitFeatureExtractor:()=>$f,BitImageProcessor:()=>Rf,CLIPFeatureExtractor:()=>Bf,CLIPImageProcessor:()=>fl,ChineseCLIPFeatureExtractor:()=>Uf,ConvNextFeatureExtractor:()=>Df,ConvNextImageProcessor:()=>ml,DINOv3ViTImageProcessor:()=>Gf,DPTFeatureExtractor:()=>Wf,DPTImageProcessor:()=>gl,DeiTFeatureExtractor:()=>Ff,DeiTImageProcessor:()=>hl,DetrFeatureExtractor:()=>jf,DetrImageProcessor:()=>_l,DonutFeatureExtractor:()=>qf,DonutImageProcessor:()=>Ks,EfficientNetImageProcessor:()=>Vf,GLPNFeatureExtractor:()=>Hf,GroundingDinoImageProcessor:()=>Xf,Idefics3ImageProcessor:()=>wl,ImageFeatureExtractor:()=>W,ImageProcessor:()=>W,JinaCLIPImageProcessor:()=>Yf,LlavaOnevisionImageProcessor:()=>Qf,Mask2FormerImageProcessor:()=>Zf,MaskFormerFeatureExtractor:()=>Jf,MaskFormerImageProcessor:()=>Ys,MobileNetV1FeatureExtractor:()=>em,MobileNetV1ImageProcessor:()=>xl,MobileNetV2FeatureExtractor:()=>tm,MobileNetV2ImageProcessor:()=>yl,MobileNetV3FeatureExtractor:()=>rm,MobileNetV3ImageProcessor:()=>bl,MobileNetV4FeatureExtractor:()=>sm,MobileNetV4ImageProcessor:()=>vl,MobileViTFeatureExtractor:()=>nm,MobileViTImageProcessor:()=>kl,NougatImageProcessor:()=>om,OwlViTFeatureExtractor:()=>am,OwlViTImageProcessor:()=>Qs,Owlv2ImageProcessor:()=>im,Phi3VImageProcessor:()=>um,PixtralImageProcessor:()=>pm,PvtImageProcessor:()=>dm,Qwen2VLImageProcessor:()=>fm,RTDetrImageProcessor:()=>mm,Sam2ImageProcessor:()=>ao,Sam3ImageProcessor:()=>ao,SamImageProcessor:()=>ao,SapiensFeatureExtractor:()=>hm,SapiensImageProcessor:()=>El,SegformerFeatureExtractor:()=>_m,SegformerImageProcessor:()=>Al,SiglipImageProcessor:()=>gm,SmolVLMImageProcessor:()=>wl,Swin2SRImageProcessor:()=>wm,VLMImageProcessor:()=>Kf,ViTFeatureExtractor:()=>xm,ViTImageProcessor:()=>Ml,VitMatteImageProcessor:()=>ym,VitPoseImageProcessor:()=>bm,YolosFeatureExtractor:()=>vm,YolosImageProcessor:()=>Tl});var $f=class extends W{};var Rf=class extends W{};var Uf=class extends W{};var fl=class extends W{},Bf=class extends fl{};var ml=class extends W{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}},Df=class extends ml{};var hl=class extends W{},Ff=class extends hl{};var _l=class extends W{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ve(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Ir(...e)}post_process_panoptic_segmentation(...e){return pl(...e)}post_process_instance_segmentation(...e){return dl(...e)}},jf=class extends _l{};var Gf=class extends W{};var Ks=class extends W{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 u=this.image_std;Array.isArray(u)||(u=new Array(i).fill(l));let d=l.map((f,m)=>-f/u[m]);return super.pad_image(e,r,s,{center:!0,constant_values:d,...n})}},qf=class extends Ks{};var gl=class extends W{},Wf=class extends gl{};var Vf=class extends W{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 Hf=class extends W{};var Xf=class extends W{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=it([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var wl=class extends W{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=[],u=[];for(let E of n){let M=await Promise.all(E.map(z=>this.preprocess(z)));l.push(...M.map(z=>z.original_size)),u.push(...M.map(z=>z.reshaped_input_size)),M.forEach(z=>z.pixel_values.unsqueeze_(0));let{longest_edge:I}=this.max_image_size,T;if(r??this.do_image_splitting){let z=new Array(M.length),C=new Array(M.length);T=await Promise.all(M.map(async(v,G)=>{let X=this.get_resize_for_vision_encoder(v.pixel_values,I),V=await Dt(v.pixel_values,{size:[X.height,X.width]}),{frames:Q,num_splits_h:K,num_splits_w:Y}=await this.split_image(V,this.max_image_size);return z[G]=K,C[G]=Y,Ee(Q,0)})),a.push(z),i.push(C)}else{let z=[I,I];T=await Promise.all(M.map(C=>Dt(C.pixel_values,{size:z}))),a.push(new Array(M.length).fill(0)),i.push(new Array(M.length).fill(0))}o.push(Ee(T,0))}let d=o.length,[f,m,_,w]=o[0].dims,x,k;if(d===1)x=o[0].unsqueeze_(0),k=Ve([d,f,_,w],!0);else{let E=Math.max(...o.map(T=>T.dims.at(0)));k=Ve([d,E,_,w],!0);let M=k.data,I=E*_*w;for(let T=0;T<d;++T){let z=o[T].dims[0];if(z<E){o[T]=Ee([o[T],Ve([E-z,m,_,w],0)],0);let C=T*I+z*_*w,v=(T+1)*I;M.fill(!1,C,v)}}x=Ft(o,0)}return{pixel_values:x,pixel_attention_mask:k,original_sizes:l,reshaped_input_sizes:u,...s?{rows:a,cols:i}:{}}}async split_image(e,{longest_edge:r}){let s=r,n=r,o=[],[a,i]=e.dims.slice(-2),l=0,u=0;if(a>s||i>n){l=Math.ceil(a/s),u=Math.ceil(i/n);let d=Math.ceil(a/l),f=Math.ceil(i/u);for(let w=0;w<l;++w)for(let x=0;x<u;++x){let k,E,M,I;w===l-1?(E=a-d,I=a):(E=w*d,I=(w+1)*d),x===u-1?(k=i-f,M=i):(k=x*f,M=(x+1)*f);let C=await ol(e,[E,k],[I,M],[2,3]);o.push(C)}let m=s,_=n;(a!==m||i!==_)&&(e=await Dt(e,{size:[m,_]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:u}}};var Kf=class extends W{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(r=>r*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var Yf=class extends W{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};var Qf=class extends W{};var Ys=class extends W{post_process_panoptic_segmentation(...e){return pl(...e)}post_process_instance_segmentation(...e){return dl(...e)}},Jf=class extends Ys{};var Zf=class extends Ys{};var xl=class extends W{},em=class extends xl{};var yl=class extends W{},tm=class extends yl{};var bl=class extends W{},rm=class extends bl{};var vl=class extends W{},sm=class extends vl{};var kl=class extends W{},nm=class extends kl{};var om=class extends Ks{};var Qs=class extends W{post_process_object_detection(...e){return Ir(...e)}},am=class extends Qs{};var im=class extends Qs{};var Pt=336,vP=[2,3],{ceil:lm,floor:Js,sqrt:cm}=Math,um=class extends W{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 Js((Js(r/Pt)*Js(e/Pt)+1)*s+1+(Js(r/Pt)+1)*cm(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),u=Math.floor(l/a);return[l,u]}pad_image(e,r,s,n={}){let[o,a]=r,i=Pt*lm(o/Pt),l=Pt*lm(a/Pt),u=[1,1,1].map((d,f)=>(d-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:u,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||cm(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 Dt(m,{size:[Pt,Pt],mode:"bicubic"});if(r>0){let k=[],E=cm(r),M=Js(w/E),I=Js(_/E);for(let z=0;z<E;++z)for(let C=0;C<E;++C){let v,G,X,V;z===E-1?(G=_-I,V=_):(G=z*I,V=(z+1)*I),C===E-1?(v=w-M,X=w):(v=C*M,X=(C+1)*M);let Y=await ol(m,[G,v],[V,X],vP);k.push(Y)}let T=await Dt(Ee(k,0),{size:[Pt,Pt],mode:"bicubic"});i.push(Ee([x,T],0))}else i.push(x)}let l=Ft(i,0),u=a.map(m=>m.map(_=>Pt*lm(_/Pt))),d=new U("int64",u.flat(),[s,2]),f=u.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:d,num_img_tokens:f}}};var pm=class extends W{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:u,spatial_merge_size:d}=this.config;if(!d)throw new Error("config must contain 'spatial_merge_size'");let f=u*d,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var dm=class extends W{};var fm=class extends W{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:u}=this.config;a.dims[0]===1&&(a=Ee(Array.from({length:i},()=>a),0));let d=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/u),_=Math.floor(a.dims[3]/u),w=a.view(d,i,f,Math.floor(m/l),l,u,Math.floor(_/l),l,u).permute(0,3,6,4,7,2,1,5,8).view(d*m*_,f*i*u*u),x=new U("int64",[d,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var mm=class extends W{post_process_object_detection(...e){return Ir(...e)}};var ao=class extends W{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=wp(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){let[i,l]=r[a],[u,d]=s[a],f=[d/l,u/i];for(let m=0;m<e[a].length;++m)for(let _=0;_<e[a][m].length;++_)for(let w=0;w<e[a][m][_].length;++w)e[a][m][_][w]*=f[w%2]}return new U("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=wp(e);if(s.length===2)s=[1,...s],e=[e];else if(s.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(s.some((n,o)=>n!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new U("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 u=0;u<r.length;++u){let d=r[u],f=s[u],m=await Dt(e[u],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,f[0]],[0,f[1]]),m=await Dt(m,{mode:"bilinear",size:d}),o){let _=m.data,w=new Uint8Array(_.length);for(let x=0;x<_.length;++x)_[x]>n&&(w[x]=1);m=new U("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 El=class extends W{post_process_semantic_segmentation(...e){return ul(...e)}},hm=class extends El{};var Al=class extends W{post_process_semantic_segmentation(...e){return ul(...e)}},_m=class extends Al{};var gm=class extends W{};var wm=class extends W{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 Ml=class extends W{},xm=class extends Ml{};var ym=class extends W{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:Ft(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 bm=class extends W{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,u=[];for(let d=0;d<o;++d){let f=n[d],m=r[d],_=[];for(let w=0;w<m.length;++w){let x=m[w],k=[],E=[],M=[],I=x.at(-2)/l,T=x.at(-1)/i;for(let z=0;z<f.length;++z){let[C,v]=[0,0],G=0,X=-1/0,V=f[z];for(let K=0;K<V.length;++K){let Y=V[K];for(let B=0;B<Y.length;++B){let P=Y[B];G+=P,X=Math.max(X,P),C+=(B+.5)*P,v+=K*P}}if(s!=null&&X<s)continue;let Q=[I*C/G,T*v/G];k.push(Q),M.push(z),E.push(X)}_.push({bbox:x,scores:E,labels:M,keypoints:k})}u.push(_)}return u}};var Tl=class extends W{post_process_object_detection(...e){return Ir(...e)}},vm=class extends Tl{};var $e=class{static async from_pretrained(e,r={}){let s=await at(e,Xs,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=Zs[n?.replace(/Fast$/,"")];return o||(n!==void 0&&console.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Hs}.`),o=W),new o(s)}};var km=class extends ne{static tokenizer_class=J;static image_processor_class=$e;constructor(e,r,s){super(e,r,s);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:o,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(o??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],u=[];for(let[d,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),u.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:u};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 Em=class extends ne{static image_processor_class=$e;static feature_extractor_class=tt;static tokenizer_class=J;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:u,image_token:d,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
|
|
14
|
+
`))[0]=="Error"&&g.shift(),Ib(g);for(var b=3;g[b]&&Mi(g[b])!=c;)++b;for(c=0;c<h&&g[c+b];++c)(v(),B)[p+4*c>>>2>>>0]=Mi(g[c+b]);return c}var tr=c=>{var p=pr(c)+1,h=Ci(p);return ur(c,h,p),h},Yu=[],xt=(c,p)=>{Yu[c>>>=0]=p},rr=[],Si=[],Os=(c,p)=>{Si[c]=new Promise(h=>p.finally(()=>h(c)))},re=c=>{if(c)return Yu[c>>>0]},Oi=(c,p,h)=>{(v(),P)[c>>>2>>>0]=p,(v(),P)[c+4>>>2>>>0]=h},Cb=c=>{var p=(v(),P)[c>>>2>>>0];return c=(v(),P)[c+4>>>2>>>0],Ts(p,c)},dr=c=>{var p=(v(),P)[c>>>2>>>0];return c=(v(),P)[c+4>>>2>>>0],p?Ts(p,c):c===0?"":void 0},fM=c=>{var p=dr(c+4),h=(h=(v(),P)[c+12>>>2>>>0])?re(h):"auto";if(c+=16){var g=re((v(),P)[c+4>>>2>>>0]),b=(v(),P)[c+16>>>2>>>0],A=(v(),P)[c+20>>>2>>>0];if(b){for(var O={},N=0;N<b;++N){var D=A+24*N;O[Cb(D+4)]=(v(),ie)[D+16>>>3>>>0]}b=O}else b=void 0;c={module:g,constants:b,entryPoint:dr(c+8)}}else c=void 0;return{label:p,layout:h,compute:c}},Pb=(c,p)=>{function h(b,A){b=c[b],(v(),B)[p+A>>>2>>>0]=b}function g(b,A){b=c[b],(v(),S)[p+A>>>3>>>0]=BigInt(b)}h("maxTextureDimension1D",4),h("maxTextureDimension2D",8),h("maxTextureDimension3D",12),h("maxTextureArrayLayers",16),h("maxBindGroups",20),h("maxBindGroupsPlusVertexBuffers",24),h("maxBindingsPerBindGroup",28),h("maxDynamicUniformBuffersPerPipelineLayout",32),h("maxDynamicStorageBuffersPerPipelineLayout",36),h("maxSampledTexturesPerShaderStage",40),h("maxSamplersPerShaderStage",44),h("maxStorageBuffersPerShaderStage",48),h("maxStorageTexturesPerShaderStage",52),h("maxUniformBuffersPerShaderStage",56),h("minUniformBufferOffsetAlignment",80),h("minStorageBufferOffsetAlignment",84),g("maxUniformBufferBindingSize",64),g("maxStorageBufferBindingSize",72),h("maxVertexBuffers",88),g("maxBufferSize",96),h("maxVertexAttributes",104),h("maxVertexBufferArrayStride",108),h("maxInterStageShaderVariables",112),h("maxColorAttachments",116),h("maxColorAttachmentBytesPerSample",120),h("maxComputeWorkgroupStorageSize",124),h("maxComputeInvocationsPerWorkgroup",128),h("maxComputeWorkgroupSizeX",132),h("maxComputeWorkgroupSizeY",136),h("maxComputeWorkgroupSizeZ",140),h("maxComputeWorkgroupsPerDimension",144),c.Le!==void 0&&h("maxImmediateSize",148)},mM=[,"validation","out-of-memory","internal"],hM=[,"compatibility","core"],zb={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",327692:"chromium-experimental-unorm16-texture-formats",327693:"chromium-experimental-snorm16-texture-formats",327732:"chromium-experimental-multi-draw-indirect"},_M=[,"low-power","high-performance"],gM=[,"occlusion","timestamp"],wM={undefined:1,unknown:1,destroyed:2};function xM(c,p,h,g,b,A){p=wt(p),h=wt(h),g>>>=0,b>>>=0,A>>>=0;var O=re(c>>>0);if(c={},A){var N=(v(),P)[A+12>>>2>>>0];if(N){var D=(v(),P)[A+16>>>2>>>0];c.requiredFeatures=Array.from((v(),P).subarray(D>>>2>>>0,D+4*N>>>2>>>0),ee=>zb[ee])}var q=(v(),P)[A+20>>>2>>>0];if(q){let ee=function(Nt,st,Qr=!1){st=q+st,(st=(v(),P)[st>>>2>>>0])==4294967295||Qr&&st==0||(Re[Nt]=st)},lt=function(Nt,st){st=q+st;var Qr=(v(),P)[st>>>2>>>0],VT=(v(),P)[st+4>>>2>>>0];Qr==4294967295&&VT==4294967295||(Re[Nt]=4294967296*(v(),P)[st+4>>>2>>>0]+(v(),P)[st>>>2>>>0])};var fe=ee,me=lt,Re={};ee("maxTextureDimension1D",4),ee("maxTextureDimension2D",8),ee("maxTextureDimension3D",12),ee("maxTextureArrayLayers",16),ee("maxBindGroups",20),ee("maxBindGroupsPlusVertexBuffers",24),ee("maxDynamicUniformBuffersPerPipelineLayout",32),ee("maxDynamicStorageBuffersPerPipelineLayout",36),ee("maxSampledTexturesPerShaderStage",40),ee("maxSamplersPerShaderStage",44),ee("maxStorageBuffersPerShaderStage",48),ee("maxStorageTexturesPerShaderStage",52),ee("maxUniformBuffersPerShaderStage",56),ee("minUniformBufferOffsetAlignment",80),ee("minStorageBufferOffsetAlignment",84),lt("maxUniformBufferBindingSize",64),lt("maxStorageBufferBindingSize",72),ee("maxVertexBuffers",88),lt("maxBufferSize",96),ee("maxVertexAttributes",104),ee("maxVertexBufferArrayStride",108),ee("maxInterStageShaderVariables",112),ee("maxColorAttachments",116),ee("maxColorAttachmentBytesPerSample",120),ee("maxComputeWorkgroupStorageSize",124),ee("maxComputeInvocationsPerWorkgroup",128),ee("maxComputeWorkgroupSizeX",132),ee("maxComputeWorkgroupSizeY",136),ee("maxComputeWorkgroupSizeZ",140),ee("maxComputeWorkgroupsPerDimension",144),ee("maxImmediateSize",148,!0),c.requiredLimits=Re}(N=(v(),P)[A+24>>>2>>>0])&&(N={label:dr(N+4)},c.defaultQueue=N),c.label=dr(A+4)}ge+=1,Os(p,O.requestDevice(c).then(ee=>{--ge,xt(b,ee.queue),xt(g,ee),h&&(ge+=1,Os(h,ee.lost.then(lt=>{--ge,ee.onuncapturederror=()=>{};var Nt=ae(),st=tr(lt.message);tp(h,wM[lt.reason],st),oe(Nt)}))),ee.onuncapturederror=lt=>{var Nt=5;lt.error instanceof GPUValidationError?Nt=2:lt.error instanceof GPUOutOfMemoryError?Nt=3:lt.error instanceof GPUInternalError&&(Nt=4);var st=ae();lt=tr(lt.error.message),e1(g,Nt,lt),oe(st)},"adapterInfo"in ee||(ee.adapterInfo=O.info),np(p,1,g,0)},ee=>{--ge;var lt=ae();ee=tr(ee.message),np(p,3,g,ee),h&&tp(h,4,ee),oe(lt)}))}function yM(c){var p=re(c>>>=0),h=rr[c];if(h){for(var g=0;g<h.length;++g)h[g]();delete rr[c]}p.destroy()}var Is=()=>{var c="getMappedRange size=0 no longer means WGPU_WHOLE_MAP_SIZE";Is.ed||(Is.ed={}),Is.ed[c]||(Is.ed[c]=1,T(c))};function bM(c,p,h){p>>>=0,h>>>=0;var g=re(c>>>=0);h===0&&Is(),h==4294967295&&(h=void 0);try{var b=g.getMappedRange(p,h)}catch{return 0}var A=ip(16,b.byteLength);return(v(),Q).set(new Uint8Array(b),A>>>0),rr[c].push(()=>Lt(A)),A}function vM(c,p,h){p>>>=0,h>>>=0;var g=re(c>>>=0);h===0&&Is(),h==4294967295&&(h=void 0);try{var b=g.getMappedRange(p,h)}catch{return 0}var A=ip(16,b.byteLength);return(v(),Q).fill(0,A,b.byteLength),rr[c].push(()=>{new Uint8Array(b).set((v(),Q).subarray(A>>>0,A+b.byteLength>>>0)),Lt(A)}),A}function kM(c,p,h,g,b){c>>>=0,p=wt(p),h=wt(h),b>>>=0;var A=re(c);rr[c]=[],b==4294967295&&(b=void 0),ge+=1,Os(p,A.mapAsync(h,g>>>0,b).then(()=>{--ge,rp(p,1,0)},O=>{--ge,ae();var N=tr(O.message);rp(p,O.name==="AbortError"?4:O.name==="OperationError"?3:0,N),delete rr[c]}))}function EM(c){var p=re(c>>>=0),h=rr[c];if(h){for(var g=0;g<h.length;++g)h[g]();delete rr[c],p.unmap()}}function AM(c){delete Yu[c>>>0]}function MM(c,p,h){c>>>=0,p>>>=0,h>>>=0;var g=!!(v(),P)[p+32>>>2>>>0];p={label:dr(p+4),usage:(v(),P)[p+16>>>2>>>0],size:4294967296*(v(),P)[p+28>>>2>>>0]+(v(),P)[p+24>>>2>>>0],mappedAtCreation:g},c=re(c);try{var b=c.createBuffer(p)}catch{return!1}return xt(h,b),g&&(rr[h]=[]),!0}function TM(c,p,h,g){c>>>=0,p=wt(p),g>>>=0,h=fM(h>>>0),c=re(c),ge+=1,Os(p,c.createComputePipelineAsync(h).then(b=>{--ge,xt(g,b),ep(p,1,g,0)},b=>{--ge;var A=ae(),O=tr(b.message);ep(p,b.reason==="validation"?3:b.reason==="internal"?4:0,g,O),oe(A)}))}function SM(c,p,h){c>>>=0,p>>>=0,h>>>=0;var g=(v(),P)[p>>>2>>>0],b=(v(),P)[g+4>>>2>>>0];p={label:dr(p+4),code:""},b===2&&(p.code=Cb(g+8)),xt(h,re(c).createShaderModule(p))}var OM=c=>{(c=re(c)).onuncapturederror=null,c.destroy()};function IM(c,p){p=wt(p),c=re(c>>>0),ge+=1,Os(p,c.popErrorScope().then(h=>{--ge;var g=5;h?h instanceof GPUValidationError?g=2:h instanceof GPUOutOfMemoryError?g=3:h instanceof GPUInternalError&&(g=4):g=1;var b=ae();h=h?tr(h.message):0,sp(p,1,g,h),oe(b)},h=>{--ge;var g=ae();h=tr(h.message),sp(p,1,5,h),oe(g)}))}function CM(c,p,h,g){if(p=wt(p),g>>>=0,h>>>=0){var b=(v(),P)[h+4>>>2>>>0];b={featureLevel:hM[b],powerPreference:_M[(v(),P)[h+8>>>2>>>0]],forceFallbackAdapter:!!(v(),P)[h+12>>>2>>>0]},(h=(v(),P)[h>>>2>>>0])!==0&&(v(),b.Qe=!!(v(),P)[h+8>>>2>>>0])}"gpu"in navigator?(ge+=1,Os(p,navigator.gpu.requestAdapter(b).then(A=>{if(--ge,A)xt(g,A),In(p,1,g,0);else{A=ae();var O=tr("WebGPU not available on this browser (requestAdapter returned null)");In(p,3,g,O),oe(A)}},A=>{--ge;var O=ae();A=tr(A.message),In(p,4,g,A),oe(O)}))):(h=ae(),b=tr("WebGPU not available on this browser (navigator.gpu is not available)"),In(p,3,g,b),oe(h))}function PM(c,p,h){return c>>>=0,p>>>=0,h>>>=0,yb(async()=>{var g=[];if(h){var b=(v(),B)[h>>>2>>>0];g.length=p+1,g[p]=new Promise(N=>setTimeout(N,b,0))}else g.length=p;for(var A=0;A<p;++A){var O=4294967296*(v(),P)[c+8*A+4>>>2>>>0]+(v(),P)[c+8*A>>>2>>>0];if(!(O in Si))return O;g[A]=Si[O]}return g=await Promise.race(g),delete Si[g],g})}var Qu,Ju={},Lb=()=>{if(!Qu){var c,p={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in Ju)Ju[c]===void 0?delete p[c]:p[c]=Ju[c];var h=[];for(c in p)h.push(`${c}=${p[c]}`);Qu=h}return Qu};function Nb(c,p){if(n)return Le(19,1,c,p);c>>>=0,p>>>=0;var h,g=0,b=0;for(h of Lb()){var A=p+g;(v(),P)[c+b>>>2>>>0]=A,g+=ur(h,A,1/0)+1,b+=4}return 0}function $b(c,p){if(n)return Le(20,1,c,p);c>>>=0,p>>>=0;var h=Lb();for(var g of((v(),P)[c>>>2>>>0]=h.length,c=0,h))c+=pr(g)+1;return(v(),P)[p>>>2>>>0]=c,0}function Rb(c){return n?Le(21,1,c):52}function Ub(c,p,h,g){return n?Le(22,1,c,p,h,g):52}function Bb(c,p,h,g){return n?Le(23,1,c,p,h,g):70}var zM=[null,[],[]];function Db(c,p,h,g){if(n)return Le(24,1,c,p,h,g);p>>>=0,h>>>=0,g>>>=0;for(var b=0,A=0;A<h;A++){var O=(v(),P)[p>>>2>>>0],N=(v(),P)[p+4>>>2>>>0];p+=8;for(var D=0;D<N;D++){var q=c,fe=(v(),Q)[O+D>>>0],me=zM[q];fe===0||fe===10?((q===1?I:T)(eb(me)),me.length=0):me.push(fe)}b+=N}return(v(),P)[g>>>2>>>0]=b,0}function LM(c){return c>>>0}function NM(c,p){return Pb(re(c>>>0).limits,p>>>0),1}function $M(c,p){return re(c>>>0).features.has(zb[p])}function RM(c){return BigInt(re(c>>>0).size)}function UM(c){return BigInt(re(c>>>0).usage)}function BM(c,p){if(c>>>=0,p>>>=0){var h=dr(p+4);h={label:h,timestampWrites:p=(p=(v(),P)[p+12>>>2>>>0])!==0?{querySet:re((v(),P)[p+4>>>2>>>0]),beginningOfPassWriteIndex:(v(),P)[p+8>>>2>>>0],endOfPassWriteIndex:(v(),P)[p+12>>>2>>>0]}:void 0}}return c=re(c),p=Kb(0),xt(p,c.beginComputePass(h)),p}function DM(c,p,h,g,b,A){h=wt(h),b=wt(b),A=wt(A),re(c>>>0).copyBufferToBuffer(re(p>>>0),h,re(g>>>0),b,A)}function FM(c){c=re(c>>>0);var p=Hb(0);return xt(p,c.finish()),p}function jM(c,p,h,g,b,A){A=wt(A),re(c>>>0).resolveQuerySet(re(p>>>0),h,g,re(b>>>0),A)}function GM(c,p,h,g){re(c>>>0).dispatchWorkgroups(p,h,g)}function qM(c,p,h){h=wt(h),re(c>>>0).dispatchWorkgroupsIndirect(re(p>>>0),h)}function WM(c){re(c>>>0).end()}function VM(c,p,h,g,b){g>>>=0,b>>>=0,c=re(c>>>0),h=re(h>>>0),g==0?c.setBindGroup(p,h):c.setBindGroup(p,h,(v(),P),b>>>2,g)}function HM(c,p){re(c>>>0).setPipeline(re(p>>>0))}function XM(c,p,h){re(c>>>0).Pe(re(p>>>0),h)}function KM(c,p){c=re(c>>>0);var h=Vb(0);return xt(h,c.getBindGroupLayout(p)),h}function YM(c,p){c>>>=0;var h=dr(4+(p>>>=0)),g=re((v(),P)[p+12>>>2>>>0]),b=(v(),P)[p+16>>>2>>>0];p=(v(),P)[p+20>>>2>>>0];for(var A=[],O=0;O<b;++O){var N=A,D=N.push,q=p+40*O,fe=(v(),P)[q+8>>>2>>>0],me=(v(),P)[q+32>>>2>>>0],Re=(v(),P)[q+36>>>2>>>0],ee=(v(),P)[q+4>>>2>>>0];fe?(me=q+24,(me=(v(),P)[me>>>2>>>0]+4294967296*(v(),B)[me+4>>>2>>>0])==-1&&(me=void 0),q={binding:ee,resource:{buffer:re(fe),offset:4294967296*(v(),P)[q+4+16>>>2>>>0]+(v(),P)[q+16>>>2>>>0],size:me}}):q=me?{binding:ee,resource:re(me)}:{binding:ee,resource:re(Re)},D.call(N,q)}return h={label:h,layout:g,entries:A},c=re(c),g=Wb(0),xt(g,c.createBindGroup(h)),g}function QM(c,p){var h;return c>>>=0,(p>>>=0)&&(h={label:dr(p+4)}),c=re(c),p=Xb(0),xt(p,c.createCommandEncoder(h)),p}function JM(c,p){c>>>=0,p>>>=0,p={type:gM[(v(),P)[p+12>>>2>>>0]],count:(v(),P)[p+16>>>2>>>0]},c=re(c);var h=Yb(0);return xt(h,c.createQuerySet(p)),h}function ZM(c,p){c=re(c>>>0).adapterInfo,p>>>=0,(v(),B)[p+52>>>2>>>0]=c.subgroupMinSize,(v(),B)[p+56>>>2>>>0]=c.subgroupMaxSize;var h=Ob(c.vendor+c.architecture+c.device+c.description),g=pr(c.vendor);return Oi(p+4,h,g),h+=g,g=pr(c.architecture),Oi(p+12,h,g),h+=g,g=pr(c.device),Oi(p+20,h,g),Oi(p+28,h+g,pr(c.description)),(v(),B)[p+36>>>2>>>0]=2,c=c.isFallbackAdapter?3:4,(v(),B)[p+40>>>2>>>0]=c,(v(),B)[p+44>>>2>>>0]=0,(v(),B)[p+48>>>2>>>0]=0,1}var eT={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-snorm16-texture-formats":327693,"chromium-experimental-multi-draw-indirect":327732};function tT(c,p){p>>>=0,c=re(c>>>0);var h=Cs(4*c.features.size),g=0,b=0;c.features.forEach(A=>{0<=(A=eT[A])&&((v(),B)[h+g>>>2>>>0]=A,g+=4,b++)}),(v(),P)[p+4>>>2>>>0]=h,(v(),P)[p>>>2>>>0]=b}function rT(c,p){return Pb(re(c>>>0).limits,p>>>0),1}function sT(c,p){re(c>>>0).pushErrorScope(mM[p])}function nT(c,p,h){p>>>=0,h>>>=0,c=re(c>>>0),p=Array.from((v(),B).subarray(h>>>2>>>0,h+4*p>>>2>>>0),g=>re(g)),c.submit(p)}function oT(c,p,h,g,b){h=wt(h),g>>>=0,b>>>=0,c=re(c>>>0),p=re(p>>>0),g=(v(),Q).subarray(g>>>0,g+b>>>0),c.writeBuffer(p,h,g,0,b)}n||(function(){for(var c=e.numThreads-1;c--;)H0();Me.push(async()=>{var p=(async function(){if(!n)return Promise.all(et.map(V0))})();xe++,await p,--xe==0&&Ge&&(p=Ge,Ge=null,p())})})(),n||(yr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ue()),e.wasmBinary&&(f=e.wasmBinary),e.stackSave=()=>ae(),e.stackRestore=c=>oe(c),e.stackAlloc=c=>Ci(c),e.setValue=function(c,p,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":(v(),V)[c>>>0]=p;break;case"i16":(v(),K)[c>>>1>>>0]=p;break;case"i32":(v(),B)[c>>>2>>>0]=p;break;case"i64":(v(),S)[c>>>3>>>0]=BigInt(p);break;case"float":(v(),se)[c>>>2>>>0]=p;break;case"double":(v(),ie)[c>>>3>>>0]=p;break;case"*":(v(),P)[c>>>2>>>0]=p;break;default:Ce(`invalid type for setValue: ${h}`)}},e.getValue=function(c,p="i8"){switch(p.endsWith("*")&&(p="*"),p){case"i1":case"i8":return(v(),V)[c>>>0];case"i16":return(v(),K)[c>>>1>>>0];case"i32":return(v(),B)[c>>>2>>>0];case"i64":return(v(),S)[c>>>3>>>0];case"float":return(v(),se)[c>>>2>>>0];case"double":return(v(),ie)[c>>>3>>>0];case"*":return(v(),P)[c>>>2>>>0];default:Ce(`invalid type for getValue: ${p}`)}},e.UTF8ToString=Ts,e.stringToUTF8=ur,e.lengthBytesUTF8=pr;var Fb,jb,Zu,Ii,Lt,Cs,Gb,qb,Wb,Vb,Hb,Xb,Kb,Yb,Qb,Jb,Zb,ep,tp,rp,sp,In,np,e1,op,t1,r1,s1,ap,n1,o1,ip,he,Cn,a1,oe,Ci,ae,i1,lp,l1,c1,u1,cp,p1,d1,f1,m1,h1,_1,g1,w1,x1,y1,b1,v1,k1,E1,A1,M1,T1,S1,O1,I1,C1,P1,z1,L1,N1,$1,R1,U1,B1,D1,F1,j1,G1,q1,W1,V1,H1,X1,K1,Y1,fr,aT=[xr,Hr,Y0,tb,rb,sb,nb,ob,ab,ib,lb,cb,ub,pb,db,fb,Ab,Mb,Tb,Nb,$b,Rb,Ub,Bb,Db],up={1116828:(c,p,h,g,b)=>{if(e===void 0||!e.Zc)return 1;if((c=Ts(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=e.Zc.get(c)))return 2;if(p=Number(p>>>0),h=Number(h>>>0),g=Number(g>>>0),p+h>c.byteLength)return 3;try{let A=c.subarray(p,p+h);switch(b){case 0:(v(),Q).set(A,g>>>0);break;case 1:e.ie?e.ie(g,A):e.Ke(g,A);break;default:return 4}return 0}catch{return 4}},1117652:(c,p,h)=>{e.ke(c,(v(),Q).subarray(p>>>0,p+h>>>0))},1117716:()=>e.Ie(),1117758:c=>{e.je(c)},1117795:()=>typeof wasmOffsetConverter<"u"};function iT(){return typeof wasmOffsetConverter<"u"}function lT(c,p,h,g){var b=ae();try{return w1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function cT(c,p,h){var g=ae();try{return h1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function uT(c,p,h){var g=ae();try{u1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function pT(c,p){var h=ae();try{return cp(c,p)}catch(g){if(oe(h),g!==g+0)throw g;he(1,0)}}function dT(c){var p=ae();try{p1(c)}catch(h){if(oe(p),h!==h+0)throw h;he(1,0)}}function fT(c,p,h,g,b,A,O){var N=ae();try{return m1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function mT(c,p){var h=ae();try{x1(c,p)}catch(g){if(oe(h),g!==g+0)throw g;he(1,0)}}function hT(c,p,h,g,b,A){var O=ae();try{d1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function _T(c,p,h,g){var b=ae();try{g1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function gT(c,p,h,g,b,A,O){var N=ae();try{b1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function wT(c,p,h,g,b,A,O){var N=ae();try{v1(c,p,h,g,b,A,O)}catch(D){if(oe(N),D!==D+0)throw D;he(1,0)}}function xT(c,p,h,g,b,A,O,N){var D=ae();try{P1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function yT(c,p,h,g,b){var A=ae();try{f1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function bT(c,p,h,g,b){var A=ae();try{return y1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function vT(c,p,h,g,b,A,O,N){var D=ae();try{z1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function kT(c,p,h,g,b,A,O,N,D,q,fe,me){var Re=ae();try{k1(c,p,h,g,b,A,O,N,D,q,fe,me)}catch(ee){if(oe(Re),ee!==ee+0)throw ee;he(1,0)}}function ET(c,p,h,g,b,A){var O=ae();try{return I1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function AT(c,p,h){var g=ae();try{return T1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;return he(1,0),0n}}function MT(c,p,h,g,b,A,O,N,D){var q=ae();try{_1(c,p,h,g,b,A,O,N,D)}catch(fe){if(oe(q),fe!==fe+0)throw fe;he(1,0)}}function TT(c){var p=ae();try{return A1(c)}catch(h){if(oe(p),h!==h+0)throw h;he(1,0)}}function ST(c,p,h){var g=ae();try{return L1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function OT(c,p){var h=ae();try{return V1(c,p)}catch(g){if(oe(h),g!==g+0)throw g;return he(1,0),0n}}function IT(c,p,h,g,b){var A=ae();try{N1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function CT(c){var p=ae();try{return E1(c)}catch(h){if(oe(p),h!==h+0)throw h;return he(1,0),0n}}function PT(c,p,h,g,b,A){var O=ae();try{return U1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function zT(c,p,h,g,b,A){var O=ae();try{return B1(c,p,h,g,b,A)}catch(N){if(oe(O),N!==N+0)throw N;he(1,0)}}function LT(c,p,h,g,b,A,O,N){var D=ae();try{return C1(c,p,h,g,b,A,O,N)}catch(q){if(oe(D),q!==q+0)throw q;he(1,0)}}function NT(c,p,h,g,b){var A=ae();try{return D1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;return he(1,0),0n}}function $T(c,p,h,g){var b=ae();try{return F1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function RT(c,p,h,g){var b=ae();try{return j1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function UT(c,p,h,g,b,A,O,N,D,q,fe,me){var Re=ae();try{return G1(c,p,h,g,b,A,O,N,D,q,fe,me)}catch(ee){if(oe(Re),ee!==ee+0)throw ee;he(1,0)}}function BT(c,p,h,g,b,A,O,N,D,q,fe){var me=ae();try{$1(c,p,h,g,b,A,O,N,D,q,fe)}catch(Re){if(oe(me),Re!==Re+0)throw Re;he(1,0)}}function DT(c,p,h,g,b,A,O,N,D,q,fe,me,Re,ee,lt,Nt){var st=ae();try{R1(c,p,h,g,b,A,O,N,D,q,fe,me,Re,ee,lt,Nt)}catch(Qr){if(oe(st),Qr!==Qr+0)throw Qr;he(1,0)}}function FT(c,p,h,g){var b=ae();try{return q1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function jT(c,p,h,g,b){var A=ae();try{return W1(c,p,h,g,b)}catch(O){if(oe(A),O!==O+0)throw O;he(1,0)}}function GT(c,p,h){var g=ae();try{return M1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function qT(c,p,h){var g=ae();try{return S1(c,p,h)}catch(b){if(oe(g),b!==b+0)throw b;he(1,0)}}function WT(c,p,h,g){var b=ae();try{O1(c,p,h,g)}catch(A){if(oe(b),A!==A+0)throw A;he(1,0)}}function Pi(){if(0<xe)Ge=Pi;else if(n)w?.(e),Be();else{for(var c=Me;0<c.length;)c.shift()(e);0<xe?Ge=Pi:(e.calledRun=!0,z||(Be(),w?.(e)))}}return n||(fr=await Qe(),Pi()),e.PTR_SIZE=4,e.webgpuInit=c=>{let p=new WeakMap,h,g,b=1;e.webgpuRegisterDevice=N=>{if(g!==void 0)throw Error("another WebGPU EP inference session is being created.");if(N){var D=p.get(N);if(!D){let q=((fe,me=0)=>{var Re=Zb(me);return me=Jb(me,Re),xt(Re,fe.queue),xt(me,fe),me})(N,D=qb(0));D=[b++,D,q],p.set(N,D)}return h=N,g=D[0],D}h=void 0,g=0};let A=new Map;e.webgpuOnCreateSession=N=>{if(g!==void 0){var D=g;if(g=void 0,N){let q=Zu(D);A.set(N,q),D===0&&c(h??re(q))}h=void 0}},e.webgpuOnReleaseSession=N=>{A.delete(N)};let O=Symbol("gpuBufferMetadata");e.webgpuRegisterBuffer=(N,D,q)=>{if(q)return N[O]=[q,NaN],q;if(q=N[O])return q[1]++,q[0];if((D=A.get(D))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return D=((fe,me=0)=>(fe.mapState!="pending"||Ce(),me=Qb(me,fe.mapState=="mapped"?3:1),xt(me,fe),fe.mapState=="mapped"&&(rr[me]=[]),me))(N,D),N[O]=[D,1],D},e.webgpuUnregisterBuffer=N=>{let D=N[O];if(!D)throw Error("Buffer is not registered");D[1]--,D[1]===0&&(Gb(D[0]),delete N[O])},e.webgpuGetBuffer=N=>re(N),e.webgpuCreateDownloader=(N,D,q)=>{if((q=A.get(q))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let fe=re(q),me=16*Math.ceil(Number(D)/16);return async()=>{let Re=fe.createBuffer({size:me,usage:9});try{let ee=fe.createCommandEncoder();return ee.copyBufferToBuffer(N,0,Re,0,me),fe.queue.submit([ee.finish()]),await Re.mapAsync(GPUMapMode.READ),Re.getMappedRange().slice(0,D)}finally{Re.destroy()}}},e.ie=(N,D)=>{var q=D.buffer;let fe=D.byteOffset,me=D.byteLength;if(D=16*Math.ceil(Number(me)/16),N=re(N),!h){var Re=Zu(g);h=re(Re)}let ee=(Re=h.createBuffer({mappedAtCreation:!0,size:D,usage:6})).getMappedRange();new Uint8Array(ee).set(new Uint8Array(q,fe,me)),Re.unmap(),(q=h.createCommandEncoder()).copyBufferToBuffer(Re,0,N,0,D),h.queue.submit([q.finish()]),Re.destroy()}},e.webnnInit=c=>{let p=c[0];[e.Ie,e.je,e.webnnEnsureTensor,e.ke,e.webnnDownloadTensor,e.He,e.webnnEnableTraceEvent]=c.slice(1),e.webnnReleaseTensorId=e.je,e.webnnUploadTensor=e.ke,e.webnnRegisterMLContext=e.He,e.webnnOnRunStart=h=>p.onRunStart(h),e.webnnOnRunEnd=p.onRunEnd.bind(p),e.webnnOnReleaseSession=h=>{p.onReleaseSession(h)},e.webnnCreateMLTensorDownloader=(h,g)=>p.createMLTensorDownloader(h,g),e.webnnRegisterMLTensor=(h,g,b,A)=>p.registerMLTensor(h,g,b,A),e.webnnCreateMLContext=h=>p.createMLContext(h),e.webnnRegisterMLConstant=(h,g,b,A,O,N)=>p.registerMLConstant(h,g,b,A,O,e.Zc,N),e.webnnRegisterGraphInput=p.registerGraphInput.bind(p),e.webnnIsGraphInput=p.isGraphInput.bind(p),e.webnnRegisterGraphOutput=p.registerGraphOutput.bind(p),e.webnnIsGraphOutput=p.isGraphOutput.bind(p),e.webnnCreateTemporaryTensor=p.createTemporaryTensor.bind(p),e.webnnIsGraphInputOutputTypeSupported=p.isGraphInputOutputTypeSupported.bind(p)},te?e:new Promise((c,p)=>{w=c,x=p})}var Wk,Jv,zC=ye(()=>{"use strict";Wk=Qv,Jv=globalThis.self?.name?.startsWith("em-pthread"),Jv&&Qv()}),Sp,qp,Zv,Ot,Vk,qi,ek,tk,Op,rk,Ip,Hk,Cp,Xk,Zp=ye(()=>{"use strict";Jp(),Sp=typeof location>"u"?void 0:location.origin,qp=import.meta.url>"file:"&&import.meta.url<"file;",Zv=()=>{if(qp){let t=URL;return new URL(new t("ort.webgpu.bundle.min.mjs",import.meta.url).href,Sp).href}return import.meta.url},Ot=Zv(),Vk=()=>{if(Ot&&!Ot.startsWith("blob:"))return Ot.substring(0,Ot.lastIndexOf("/")+1)},qi=(t,e)=>{try{let r=e??Ot;return(r?new URL(t,r):new URL(t)).origin===Sp}catch{return!1}},ek=(t,e)=>{let r=e??Ot;try{return(r?new URL(t,r):new URL(t)).href}catch{return}},tk=(t,e)=>`${e??"./"}${t}`,Op=async t=>{let e=await(await fetch(t,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},rk=async t=>(await import(t)).default,Ip=(PC(),Yi(jk)).default,Hk=async()=>{if(!Ot)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(qi(Ot))return[void 0,Ip()];let t=await Op(Ot);return[t,Ip(t)]},Cp=(zC(),Yi(qk)).default,Xk=async(t,e,r,s)=>{let n=Cp&&!(t||e);if(n)if(Ot)n=qi(Ot);else if(s&&!r)n=!0;else throw new Error("cannot determine the script source URL.");if(n)return[void 0,Cp];{let o="ort-wasm-simd-threaded.asyncify.mjs",a=t??ek(o,e),i=r&&a&&!qi(a,e),l=i?await Op(a):a??tk(o,e);return[i?l:void 0,await rk(l)]}}}),Pp,Wi,jn,zp,sk,nk,ok,ed,Ue,ps=ye(()=>{"use strict";Zp(),Wi=!1,jn=!1,zp=!1,sk=()=>{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}},nk=()=>{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}},ok=()=>{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}},ed=async t=>{if(Wi)return Promise.resolve();if(jn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(zp)throw new Error("previous call to 'initializeWebAssembly()' failed.");jn=!0;let e=t.initTimeout,r=t.numThreads;if(t.simd!==!1){if(t.simd==="relaxed"){if(!ok())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!nk())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=sk();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,u=l?.href??l,d=t.wasmBinary,[f,m]=await Xk(i,o,r>1,!!d||!!u),_=!1,w=[];if(e>0&&w.push(new Promise(x=>{setTimeout(()=>{_=!0,x()},e)})),w.push(new Promise((x,k)=>{let E={numThreads:r};if(d)E.wasmBinary=d;else if(u||o)E.locateFile=M=>u??o+M;else if(i&&i.indexOf("blob:")!==0)E.locateFile=M=>new URL(M,i).href;else if(f){let M=Vk();M&&(E.locateFile=I=>M+I)}m(E).then(M=>{jn=!1,Wi=!0,Pp=M,x(),f&&URL.revokeObjectURL(f)},M=>{jn=!1,zp=!0,k(M)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ue=()=>{if(Wi&&Pp)return Pp;throw new Error("WebAssembly is not initialized yet.")}}),It,Ji,Oe,td=ye(()=>{"use strict";ps(),It=(t,e)=>{let r=Ue(),s=r.lengthBytesUTF8(t)+1,n=r._malloc(s);return r.stringToUTF8(t,n,s),e.push(n),n},Ji=(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")Ji(o,a+".",r,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Oe=t=>{let e=Ue(),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)}}}),Kk,LC=ye(()=>{"use strict";ps(),td(),Kk=t=>{let e=Ue(),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=It(t.tag,s)),r=e._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),r===0&&Oe("Can't create run options."),t?.extra!==void 0&&Ji(t.extra,"",new WeakSet,(a,i)=>{let l=It(a,s),u=It(i,s);e._OrtAddRunConfigEntry(r,l,u)!==0&&Oe(`Can't set a run config entry: ${a} - ${i}.`)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseRunOptions(r),s.forEach(a=>e._free(a)),o}}}),ak,ik,lk,Vi,kr,ck,Yk,NC=ye(()=>{"use strict";ps(),td(),ak=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}`)}},ik=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},lk=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)},Vi=(t,e,r,s)=>{let n=It(e,s),o=It(r,s);Ue()._OrtAddSessionConfigEntry(t,n,o)!==0&&Oe(`Can't set a session config entry: ${e} - ${r}.`)},kr=(t,e,r,s)=>{let n=It(e,s),o=It(r,s);t.push([n,o])},ck=async(t,e,r)=>{let s=e.executionProviders;for(let n of s){let o=typeof n=="string"?n:n.name,a=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let f=n?.deviceType;f&&Vi(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&&kr(a,"enableGraphCapture","1",r),typeof _.preferredLayout=="string"&&kr(a,"preferredLayout",_.preferredLayout,r),_.forceCpuNodeNames){let x=Array.isArray(_.forceCpuNodeNames)?_.forceCpuNodeNames:[_.forceCpuNodeNames];kr(a,"forceCpuNodeNames",x.join(`
|
|
15
|
+
`),r)}_.validationMode&&kr(a,"validationMode",_.validationMode,r)}let m=Ue().webgpuRegisterDevice(f);if(m){let[_,w,x]=m;kr(a,"deviceId",_.toString(),r),kr(a,"webgpuInstance",w.toString(),r),kr(a,"webgpuDevice",x.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=It(o,r),l=a.length,u=0,d=0;if(l>0){u=Ue()._malloc(l*Ue().PTR_SIZE),r.push(u),d=Ue()._malloc(l*Ue().PTR_SIZE),r.push(d);for(let f=0;f<l;f++)Ue().setValue(u+f*Ue().PTR_SIZE,a[f][0],"*"),Ue().setValue(d+f*Ue().PTR_SIZE,a[f][1],"*")}await Ue()._OrtAppendExecutionProvider(t,i,u,d,l)!==0&&Oe(`Can't append execution provider: ${o}.`)}},Yk=async t=>{let e=Ue(),r=0,s=[],n=t||{};lk(n);try{let o=ak(n.graphOptimizationLevel??"all"),a=ik(n.executionMode??"sequential"),i=typeof n.logId=="string"?It(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 u=n.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let d=typeof n.optimizedModelFilePath=="string"?It(n.optimizedModelFilePath,s):0;if(r=e._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,u,d),r===0&&Oe("Can't create session options."),n.executionProviders&&await ck(r,n,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Vi(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 _=It(f,s);e._OrtAddFreeDimensionOverride(r,_,m)!==0&&Oe(`Can't set a free dimension override: ${f} - ${m}.`)}return n.extra!==void 0&&Ji(n.extra,"",new WeakSet,(f,m)=>{Vi(r,f,m,s)}),[r,s]}catch(o){throw r!==0&&e._OrtReleaseSessionOptions(r)!==0&&Oe("Can't release session options."),s.forEach(a=>e._free(a)),o}}}),as,Ki,Fs,Hn,Zi,rd,sd,Wp,js=ye(()=>{"use strict";as=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}`)}},Ki=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}`)}},Fs=(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},Hn=t=>{switch(t){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}},Zi=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}`)}},rd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",sd=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint64"||t==="int8"||t==="uint8"||t==="bool"||t==="uint4"||t==="int4",Wp=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}`)}}}),nd,Qk=ye(()=>{"use strict";Jp(),nd=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 u=l.byteLength;new Uint8Array(o,a,u).set(l),a+=u}return new Uint8Array(o,0,s)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),Jk,$C=ye(()=>{"use strict";js(),Jk=(t,e)=>new(Hn(e))(t)}),uk,pk,dk,fk,Zk,mk,_t,eE=ye(()=>{"use strict";js(),uk=["V","I","W","E","F"],pk=(t,e)=>{console.log(`[${uk[t]},${new Date().toISOString()}]${e}`)},Zk=(t,e)=>{dk=t,fk=e},mk=(t,e)=>{let r=Zi(t),s=Zi(dk);r>=s&&pk(r,typeof e=="function"?e():e)},_t=(...t)=>{fk&&mk(...t)}}),Lp,Vp,Np,hk,$p,_k,Rp,Up,Bp,gk,tE,RC=ye(()=>{"use strict";js(),eE(),Lp=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Vp=(t,e)=>{if(e==="int32")return t;let r=Lp.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(Hn(e))(t.buffer,t.byteOffset,n);switch(e){case"int64":case"uint64":{let a=new Int32Array(n);for(let i=0;i<n;i++){let l=o[i];if(l>2147483647n||l<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");a[i]=Number(l)}return new Uint8Array(a.buffer)}case"int8":case"uint8":case"uint32":{if(e==="uint32"&&o.some(i=>i>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let a=Int32Array.from(o,Number);return new Uint8Array(a.buffer)}default:throw new Error(`Unsupported data conversion from ${e} to 'int32'`)}},Np=(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}`)}},hk=1,$p=()=>hk++,_k=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Rp=(t,e)=>{let r=Lp.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},Up=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 Rp(this.dataType,this.tensorShape)}destroy(){_t("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=Np(new Uint8Array(e),this.dataType);if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(r);return}else return r.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,e,r){return this.mlContext===t&&this.dataType===e&&this.tensorShape.length===r.length&&this.tensorShape.every((s,n)=>s===r[n])}setIsDataConverted(t){this.isDataConverted=t}},Bp=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=_k.get(e),!a||o?.input.dataTypes.includes(a))throw new Error(`WebNN backend does not support data type: ${e}`);_t("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!==Rp(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=Vp(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 _t("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?Np(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()}},gk=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=$p();return this.tensorTrackersById.set(t,new Bp(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){_t("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){_t("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=$p(),a=new Up({sessionId:t,context:n,tensor:e,dataType:r,shape:s});return this.tensorTrackersById.set(o,new Bp(this,a)),this.externalTensors.add(a),o}async getCachedTensor(t,e,r,s,n,o,a){let i=this.getMLContext(t);for(let[u,d]of this.freeTensors.entries())if(d.canReuseTensor(i,e,r)){_t("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, ${a?`fallbackDataType: ${a},`:""} shape: ${r}`);let f=this.freeTensors.splice(u,1)[0];return f.sessionId=t,f}_t("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 Up({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)}},tE=(...t)=>new gk(...t)}),rE={};Xn(rE,{WebNNBackend:()=>sE});var Gn,wk,sE,UC=ye(()=>{"use strict";js(),ps(),$C(),RC(),eE(),Gn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),wk=(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])},sE=class{constructor(t){this.tensorManager=tE(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,Zk(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){_t("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){_t("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let e=this.temporarySessionTensorIds.get(t);if(e){for(let r of e)_t("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=>wk(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){_t("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,e,r,s,n){let o=Gn.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){_t("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${r}}`);let s=Gn.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(!Ue().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");_t("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 Jk(r,e)}}registerMLTensor(t,e,r,s){let n=Gn.get(r);if(!n)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.registerTensor(t,e,n,s);return _t("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(t,e,r,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=t;t.startsWith("./")&&(i=t.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} not found in preloaded files.`);if(e+r>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(e,e+r).buffer,d;switch(n.dataType){case"float32":d=new Float32Array(u);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":d=new Int32Array(u);break;case"uint32":d=new Uint32Array(u);break;case"int64":if(a){let f=Vp(new Uint8Array(u),"int64");d=new Int32Array(f.buffer),n.dataType="int32"}else d=new BigInt64Array(u);break;case"uint64":d=new BigUint64Array(u);break;case"int8":d=new Int8Array(u);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return _t("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,d)}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=Gn.get(as(e)),n=this.mlOpSupportLimitsBySessionId.get(t);return typeof s>"u"?!1:r?!!n?.input.dataTypes.includes(s):!!n?.output.dataTypes.includes(s)}flush(){}}}),xk,od,ad,Er,yk,Dp,el,id,ld,Fp,cd,ud,pd,nE=ye(()=>{"use strict";us(),LC(),NC(),js(),ps(),td(),Qk(),xk=(t,e)=>{Ue()._OrtInit(t,e)!==0&&Oe("Can't initialize onnxruntime.")},od=async t=>{xk(t.wasm.numThreads,Zi(t.logLevel))},ad=async(t,e)=>{Ue().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"&&Ue().webgpuInit(s=>{t.webgpu.device=s}),e==="webnn"){let s=new(UC(),Yi(rE)).WebNNBackend(t);Ue().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])}},Er=new Map,yk=t=>{let e=Ue(),r=e.stackSave();try{let s=e.PTR_SIZE,n=e.stackAlloc(2*s);e._OrtGetInputOutputCount(t,n,n+s)!==0&&Oe("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(e.getValue(n,o)),Number(e.getValue(n+s,o))]}finally{e.stackRestore(r)}},Dp=(t,e)=>{let r=Ue(),s=r.stackSave(),n=0;try{let o=r.PTR_SIZE,a=r.stackAlloc(2*o);r._OrtGetInputOutputMetadata(t,e,a,a+o)!==0&&Oe("Can't get session input/output metadata.");let i=Number(r.getValue(a,"*"));n=Number(r.getValue(a+o,"*"));let l=r.HEAP32[n/4];if(l===0)return[i,0];let u=r.HEAPU32[n/4+1],d=[];for(let f=0;f<u;f++){let m=Number(r.getValue(n+8+f*o,"*"));d.push(m!==0?r.UTF8ToString(m):Number(r.getValue(n+8+(f+u)*o,"*")))}return[i,l,d]}finally{r.stackRestore(s),n!==0&&r._OrtFree(n)}},el=t=>{let e=Ue(),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]},id=async(t,e)=>{let r,s,n=Ue();Array.isArray(t)?[r,s]=t:t.buffer===n.HEAPU8.buffer?[r,s]=[t.byteOffset,t.byteLength]:[r,s]=el(t);let o=0,a=0,i=0,l=[],u=[],d=[];try{if([a,l]=await Yk(e),e?.externalData&&n.mountExternalData){let T=[];for(let z of e.externalData){let C=typeof z=="string"?z:z.path;T.push(nd(typeof z=="string"?z:z.data).then(v=>{n.mountExternalData(C,v)}))}await Promise.all(T)}for(let T of e?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let z=T,C=z?.context,v=z?.gpuDevice,G=z?.deviceType,X=z?.powerPreference;C?n.currentContext=C:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:G,powerPreference:X})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(r,s,a),n.webgpuOnCreateSession?.(o),o===0&&Oe("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[f,m]=yk(o),_=!!e?.enableGraphCapture,w=[],x=[],k=[],E=[],M=[];for(let T=0;T<f;T++){let[z,C,v]=Dp(o,T);z===0&&Oe("Can't get an input name."),u.push(z);let G=n.UTF8ToString(z);w.push(G),k.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Ki(C),shape:v})}for(let T=0;T<m;T++){let[z,C,v]=Dp(o,T+f);z===0&&Oe("Can't get an output name."),d.push(z);let G=n.UTF8ToString(z);x.push(G),E.push(C===0?{name:G,isTensor:!1}:{name:G,isTensor:!0,type:Ki(C),shape:v});{if(_&&e?.preferredOutputLocation===void 0){M.push("gpu-buffer");continue}let X=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[G]??"cpu",V=n.webnnIsGraphOutput;if(X==="cpu"&&V&&V(o,G)){M.push("ml-tensor-cpu-output");continue}if(X!=="cpu"&&X!=="cpu-pinned"&&X!=="gpu-buffer"&&X!=="ml-tensor")throw new Error(`Not supported preferred output location: ${X}.`);if(_&&X!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${X}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);M.push(X)}}let I=null;return M.some(T=>T==="gpu-buffer"||T==="ml-tensor"||T==="ml-tensor-cpu-output")&&(i=n._OrtCreateBinding(o),i===0&&Oe("Can't create IO binding."),I={handle:i,outputPreferredLocations:M,outputPreferredLocationsEncoded:M.map(T=>T==="ml-tensor-cpu-output"?"ml-tensor":T).map(T=>Wp(T))}),Er.set(o,[o,u,d,I,_,!1]),[o,w,x,k,E]}catch(f){throw u.forEach(m=>n._OrtFree(m)),d.forEach(m=>n._OrtFree(m)),i!==0&&n._OrtReleaseBinding(i)!==0&&Oe("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Oe("Can't release session."),f}finally{n._free(r),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&Oe("Can't release session options."),l.forEach(f=>n._free(f)),n.unmountExternalData?.()}},ld=t=>{let e=Ue(),r=Er.get(t);if(!r)throw new Error(`cannot release session. invalid session id: ${t}`);let[s,n,o,a,i]=r;a&&(i&&e._OrtClearBoundOutputs(a.handle)!==0&&Oe("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&Oe("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),n.forEach(l=>e._OrtFree(l)),o.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(s)!==0&&Oe("Can't release session."),Er.delete(t)},Fp=async(t,e,r,s,n,o,a=!1)=>{if(!t){e.push(0);return}let i=Ue(),l=i.PTR_SIZE,u=t[0],d=t[1],f=t[3],m=f,_,w;if(u==="string"&&(f==="gpu-buffer"||f==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&f!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(f==="gpu-buffer"){let E=t[2].gpuBuffer;w=Fs(as(u),d);{let M=i.webgpuRegisterBuffer;if(!M)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=M(E,s)}}else if(f==="ml-tensor"){let E=t[2].mlTensor;w=Fs(as(u),d);let M=i.webnnRegisterMLTensor;if(!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=M(s,E,as(u),d)}else{let E=t[2];if(Array.isArray(E)){w=l*E.length,_=i._malloc(w),r.push(_);for(let M=0;M<E.length;M++){if(typeof E[M]!="string")throw new TypeError(`tensor data at index ${M} is not a string`);i.setValue(_+M*l,It(E[M],r),"*")}}else{let M=i.webnnIsGraphInput,I=i.webnnIsGraphOutput;if(u!=="string"&&M&&I){let T=i.UTF8ToString(n);if(M(s,T)||I(s,T)){let z=as(u);w=Fs(z,d),m="ml-tensor";let C=i.webnnCreateTemporaryTensor,v=i.webnnUploadTensor;if(!C||!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let G=await C(s,z,d);v(G,new Uint8Array(E.buffer,E.byteOffset,E.byteLength)),_=G}else w=E.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),_)}else w=E.byteLength,_=i._malloc(w),r.push(_),i.HEAPU8.set(new Uint8Array(E.buffer,E.byteOffset,w),_)}}let x=i.stackSave(),k=i.stackAlloc(4*d.length);try{d.forEach((M,I)=>i.setValue(k+I*l,M,l===4?"i32":"i64"));let E=i._OrtCreateTensor(as(u),_,w,k,d.length,Wp(m));E===0&&Oe(`Can't create tensor for input/output. session=${s}, index=${o}.`),e.push(E)}finally{i.stackRestore(x)}},cd=async(t,e,r,s,n,o)=>{let a=Ue(),i=a.PTR_SIZE,l=Er.get(t);if(!l)throw new Error(`cannot run inference. invalid session id: ${t}`);let u=l[0],d=l[1],f=l[2],m=l[3],_=l[4],w=l[5],x=e.length,k=s.length,E=0,M=[],I=[],T=[],z=[],C=[],v=a.stackSave(),G=a.stackAlloc(x*i),X=a.stackAlloc(x*i),V=a.stackAlloc(k*i),Q=a.stackAlloc(k*i);try{[E,M]=Kk(o),Mr("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)await Fp(r[P],I,z,t,d[e[P]],e[P],_);for(let P=0;P<k;P++)await Fp(n[P],T,z,t,f[s[P]],x+s[P],_);Tr("wasm prepareInputOutputTensor");for(let P=0;P<x;P++)a.setValue(G+P*i,I[P],"*"),a.setValue(X+P*i,d[e[P]],"*");for(let P=0;P<k;P++)a.setValue(V+P*i,T[P],"*"),a.setValue(Q+P*i,f[s[P]],"*");if(m&&!w){let{handle:P,outputPreferredLocations:se,outputPreferredLocationsEncoded:ie}=m;if(d.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${d.length}).`);Mr("wasm bindInputsOutputs");for(let S=0;S<x;S++){let L=e[S];await a._OrtBindInput(P,d[L],I[S])!==0&&Oe(`Can't bind input[${S}] for session=${t}.`)}for(let S=0;S<k;S++){let L=s[S];n[S]?.[3]?(C.push(T[S]),a._OrtBindOutput(P,f[L],T[S],0)!==0&&Oe(`Can't bind pre-allocated output[${S}] for session=${t}.`)):a._OrtBindOutput(P,f[L],0,ie[L])!==0&&Oe(`Can't bind output[${S}] to ${se[S]} for session=${t}.`)}Tr("wasm bindInputsOutputs"),Er.set(t,[u,d,f,m,_,!0])}a.jsepOnRunStart?.(u),a.webnnOnRunStart?.(u);let K;m?K=await a._OrtRunWithBinding(u,m.handle,k,V,E):K=await a._OrtRun(u,X,G,x,Q,k,V,E),K!==0&&Oe("failed to call OrtRun().");let Y=[],B=[];Mr("wasm ProcessOutputTensor");for(let P=0;P<k;P++){let se=Number(a.getValue(V+P*i,"*"));if(se===T[P]||C.includes(T[P])){Y.push(n[P]),se!==T[P]&&a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.");continue}let ie=a.stackSave(),S=a.stackAlloc(4*i),L=!1,R,te=0;try{a._OrtGetTensorData(se,S,S+i,S+2*i,S+3*i)!==0&&Oe(`Can't access output tensor data on index ${P}.`);let ue=i===4?"i32":"i64",Be=Number(a.getValue(S,ue));te=a.getValue(S+i,"*");let Ce=a.getValue(S+i*2,"*"),vt=Number(a.getValue(S+i*3,ue)),Qe=[];for(let Me=0;Me<vt;Me++)Qe.push(Number(a.getValue(Ce+Me*i,ue)));a._OrtFree(Ce)!==0&&Oe("Can't free memory for tensor dims.");let Ze=Qe.reduce((Me,xe)=>Me*xe,1);R=Ki(Be);let rt=m?.outputPreferredLocations[s[P]];if(R==="string"){if(rt==="gpu-buffer"||rt==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let xe=0;xe<Ze;xe++){let Ge=a.getValue(te+xe*i,"*"),kt=a.getValue(te+(xe+1)*i,"*"),ge=xe===Ze-1?void 0:kt-Ge;Me.push(a.UTF8ToString(Ge,ge))}Y.push([R,Qe,Me,"cpu"])}else if(rt==="gpu-buffer"&&Ze>0){let Me=a.webgpuGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=Me(te),Ge=Fs(Be,Ze);if(Ge===void 0||!rd(R))throw new Error(`Unsupported data type: ${R}`);L=!0;{a.webgpuRegisterBuffer(xe,t,te);let kt=a.webgpuCreateDownloader(xe,Ge,t);Y.push([R,Qe,{gpuBuffer:xe,download:async()=>{let ge=await kt();return new(Hn(R))(ge)},dispose:()=>{a._OrtReleaseTensor(se)!==0&&Oe("Can't release tensor.")}},"gpu-buffer"])}}else if(rt==="ml-tensor"&&Ze>0){let Me=a.webnnEnsureTensor,xe=a.webnnIsGraphInputOutputTypeSupported;if(!Me||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Fs(Be,Ze)===void 0||!sd(R))throw new Error(`Unsupported data type: ${R}`);if(!xe(t,R,!1))throw new Error(`preferredLocation "ml-tensor" for ${R} output is not supported by current WebNN Context.`);let Ge=await Me(t,te,Be,Qe,!1);L=!0,Y.push([R,Qe,{mlTensor:Ge,download:a.webnnCreateMLTensorDownloader(te,R),dispose:()=>{a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se)}},"ml-tensor"])}else if(rt==="ml-tensor-cpu-output"&&Ze>0){let Me=a.webnnCreateMLTensorDownloader(te,R)(),xe=Y.length;L=!0,B.push((async()=>{let Ge=[xe,await Me];return a.webnnReleaseTensorId(te),a._OrtReleaseTensor(se),Ge})()),Y.push([R,Qe,[],"cpu"])}else{let Me=Hn(R),xe=new Me(Ze);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(a.HEAPU8.subarray(te,te+xe.byteLength)),Y.push([R,Qe,xe,"cpu"])}}finally{a.stackRestore(ie),R==="string"&&te&&a._free(te),L||a._OrtReleaseTensor(se)}}m&&!_&&(a._OrtClearBoundOutputs(m.handle)!==0&&Oe("Can't clear bound outputs."),Er.set(t,[u,d,f,m,_,!1]));for(let[P,se]of await Promise.all(B))Y[P][2]=se;return Tr("wasm ProcessOutputTensor"),Y}finally{a.webnnOnRunEnd?.(u),a.stackRestore(v),r.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),n.forEach(K=>{K&&K[3]==="gpu-buffer"&&a.webgpuUnregisterBuffer(K[2].gpuBuffer)}),I.forEach(K=>a._OrtReleaseTensor(K)),T.forEach(K=>a._OrtReleaseTensor(K)),z.forEach(K=>a._free(K)),E!==0&&a._OrtReleaseRunOptions(E),M.forEach(K=>a._free(K))}},ud=t=>{let e=Ue(),r=Er.get(t);if(!r)throw new Error("invalid session id");let s=r[0],n=e._OrtEndProfiling(s);n===0&&Oe("Can't get an profile file name."),e._OrtFree(n)},pd=t=>{let e=[];for(let r of t){let s=r[2];!Array.isArray(s)&&"buffer"in s&&e.push(s.buffer)}return e}}),Ar,Ut,Ds,qn,Wn,Hi,jp,Xi,ss,ns,bk,oE,aE,iE,lE,cE,uE,pE,dE=ye(()=>{"use strict";us(),nE(),ps(),Zp(),Ar=()=>!!We.wasm.proxy&&typeof document<"u",Ds=!1,qn=!1,Wn=!1,Xi=new Map,ss=(t,e)=>{let r=Xi.get(t);r?r.push(e):Xi.set(t,[e])},ns=()=>{if(Ds||!qn||Wn||!Ut)throw new Error("worker not ready")},bk=t=>{switch(t.data.type){case"init-wasm":Ds=!1,t.data.err?(Wn=!0,jp[1](t.data.err)):(qn=!0,jp[0]()),Hi&&(URL.revokeObjectURL(Hi),Hi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=Xi.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}default:}},oE=async()=>{if(!qn){if(Ds)throw new Error("multiple calls to 'initWasm()' detected.");if(Wn)throw new Error("previous call to 'initWasm()' failed.");if(Ds=!0,Ar())return new Promise((t,e)=>{Ut?.terminate(),Hk().then(([r,s])=>{try{Ut=s,Ut.onerror=o=>e(o),Ut.onmessage=bk,jp=[t,e];let n={type:"init-wasm",in:We};!n.in.wasm.wasmPaths&&(r||qp)&&(n.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm",import.meta.url).href}),Ut.postMessage(n),Hi=r}catch(n){e(n)}},e)});try{await ed(We.wasm),await od(We),qn=!0}catch(t){throw Wn=!0,t}finally{Ds=!1}}},aE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("init-ep",[e,r]);let s={type:"init-ep",in:{epName:t,env:We}};Ut.postMessage(s)});await ad(We,t)},iE=async t=>Ar()?(ns(),new Promise((e,r)=>{ss("copy-from",[e,r]);let s={type:"copy-from",in:{buffer:t}};Ut.postMessage(s,[t.buffer])})):el(t),lE=async(t,e)=>{if(Ar()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ns(),new Promise((r,s)=>{ss("create",[r,s]);let n={type:"create",in:{model:t,options:{...e}}},o=[];t instanceof Uint8Array&&o.push(t.buffer),Ut.postMessage(n,o)})}else return id(t,e)},cE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("release",[e,r]);let s={type:"release",in:t};Ut.postMessage(s)});ld(t)},uE=async(t,e,r,s,n,o)=>{if(Ar()){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)=>{ss("run",[a,i]);let l=r,u={type:"run",in:{sessionId:t,inputIndices:e,inputs:l,outputIndices:s,options:o}};Ut.postMessage(u,pd(l))})}else return cd(t,e,r,s,n,o)},pE=async t=>{if(Ar())return ns(),new Promise((e,r)=>{ss("end-profiling",[e,r]);let s={type:"end-profiling",in:t};Ut.postMessage(s)});ud(t)}}),Gp,vk,fE,BC=ye(()=>{"use strict";us(),dE(),js(),Jp(),Qk(),Gp=(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()}`)}},vk=t=>{switch(t[3]){case"cpu":return new Kt(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!rd(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:n}=t[2];return Kt.fromGpuBuffer(r,{dataType:e,dims:t[1],download:s,dispose:n})}case"ml-tensor":{let e=t[0];if(!sd(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:n}=t[2];return Kt.fromMLTensor(r,{dataType:e,dims:t[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${t[3]}`)}},fE=class{async fetchModelAndCopyToWasmMemory(t){return iE(await nd(t))}async loadModel(t,e){ls();let r;typeof t=="string"?r=await this.fetchModelAndCopyToWasmMemory(t):r=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await lE(r,e),cs()}async dispose(){return cE(this.sessionId)}async run(t,e,r){ls();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)=>Gp(f,()=>`input "${this.inputNames[n[m]]}"`)),l=o.map((f,m)=>f?Gp(f,()=>`output "${this.outputNames[a[m]]}"`):null),u=await uE(this.sessionId,n,i,a,l,r),d={};for(let f=0;f<u.length;f++)d[this.outputNames[a[f]]]=o[f]??vk(u[f]);return cs(),d}startProfiling(){}endProfiling(){pE(this.sessionId)}}}),mE={};Xn(mE,{OnnxruntimeWebAssemblyBackend:()=>Xp,initializeFlags:()=>Hp,wasmBackend:()=>hE});var Hp,Xp,hE,DC=ye(()=>{"use strict";us(),dE(),BC(),Hp=()=>{(typeof We.wasm.initTimeout!="number"||We.wasm.initTimeout<0)&&(We.wasm.initTimeout=0);let t=We.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.`),We.wasm.simd=!1),typeof We.wasm.proxy!="boolean"&&(We.wasm.proxy=!1),typeof We.wasm.trace!="boolean"&&(We.wasm.trace=!1),typeof We.wasm.numThreads!="number"||!Number.isInteger(We.wasm.numThreads)||We.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)We.wasm.numThreads=1;else{let e=typeof navigator>"u"?gC("node:os").cpus().length:navigator.hardwareConcurrency;We.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Xp=class{async init(t){Hp(),await oE(),await aE(t)}async createInferenceSessionHandler(t,e){let r=new fE;return await r.loadModel(t,e),r}},hE=new Xp});us();us();us();var FC="1.25.0-dev.20260209-a3749f1353",jC=Fk;{let t=(DC(),Yi(mE)).wasmBackend;is("webgpu",t,5),is("webnn",t,5),is("cpu",t,10),is("wasm",t,10)}Object.defineProperty(We.versions,"web",{value:FC,enumerable:!0});async function _E(t){let e=t.split("/").pop(),r;try{if(r=await Di(),r){let n=await r.match(t);if(n)return n}}catch(n){console.warn(`Failed to load ${e} from cache:`,n)}let s=await fetch(t);if(!s.ok)throw new Error(`Failed to fetch ${e}: ${s.status} ${s.statusText}`);if(r)try{await r.put(t,s.clone())}catch(n){console.warn(`Failed to cache ${e}:`,n)}return s}async function gE(t){let e=await _E(t);if(!e||typeof e=="string")return null;try{return await e.arrayBuffer()}catch(r){return console.warn("Failed to read WASM binary:",r),null}}async function wE(t){let e=await _E(t);if(!e||typeof e=="string")return null;try{let r=await e.text(),s=t.split("/").slice(0,-1).join("/");r=r.replace(/import\.meta\.url/g,`"${s}"`);let n=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(n)}catch(r){return console.warn("Failed to read WASM binary:",r),null}}function fd(t){return Us(t,["blob:"])}function md(t){let e;if(typeof location<"u"&&location.href)e=location.href;else if(typeof import.meta<"u"&&import.meta.url)e=import.meta.url;else return t;return new URL(t,e).href}import{Tensor as AE}from"onnxruntime-common";var qC=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"}}),WC=["verbose","info","warning","error","fatal"],vE=4,Bt=[],hd,qs,xE=Symbol.for("onnxruntime");if(xE in globalThis)qs=globalThis[xE];else if(be.IS_NODE_ENV){switch(qs=GC,process.platform){case"win32":Bt.push("dml");break;case"linux":process.arch==="x64"&&Bt.push("cuda");break;case"darwin":Bt.push("coreml");break}Bt.push("webgpu"),Bt.push("cpu"),hd=["cpu"]}else qs=dd,be.IS_WEBNN_AVAILABLE&&Bt.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),be.IS_WEBGPU_AVAILABLE&&Bt.push("webgpu"),Bt.push("wasm"),hd=["wasm"];var VC=qs.InferenceSession;function kE(t=null){if(!t)return hd;switch(t){case"auto":return Bt;case"gpu":return Bt.filter(e=>["webgpu","cuda","dml","webnn-gpu"].includes(e))}if(Bt.includes(t))return[qC[t]??t];throw new Error(`Unsupported device: "${t}". Should be one of: ${Bt.join(", ")}.`)}var EE=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV,yE=Promise.resolve(),Gs=null;async function HC(){return Gs||(De.useWasmCache&&typeof ft?.wasm?.wasmPaths=="object"&&ft?.wasm?.wasmPaths?.wasm&&ft?.wasm?.wasmPaths?.mjs?(Gs=(async()=>{let e=ft.wasm.wasmPaths;await Promise.all([e.wasm&&!fd(e.wasm)?(async()=>{try{let r=await gE(md(e.wasm));r&&(ft.wasm.wasmBinary=r)}catch(r){console.warn("Failed to pre-load WASM binary:",r)}})():Promise.resolve(),e.mjs&&!fd(e.mjs)?(async()=>{try{let r=await wE(md(e.mjs));r&&(ft.wasm.wasmPaths.mjs=r)}catch(r){console.warn("Failed to pre-load WASM factory:",r)}})():Promise.resolve()])})(),Gs):(Gs=Promise.resolve(),Gs))}async function tl(t,e,r){await HC();let s=()=>VC.create(t,{logSeverityLevel:vE,...e}),n=await(EE?yE=yE.then(s):s());return n.config=r,n}var bE=Promise.resolve();async function rl(t,e){let r=()=>t.run(e);return await(EE?bE=bE.then(r):r())}function sl(t){return t instanceof qs.Tensor}var ft=qs?.env;ft.logLevel=WC[vE];if(ft?.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&ft.versions?.web&&!ft.wasm.wasmPaths){let t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${ft.versions.web}/dist/`;ft.wasm.wasmPaths=be.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}ft.wasm.proxy=!1}ft?.webgpu&&(ft.webgpu.powerPreference="high-performance");function Kn(){return ft?.wasm?.proxy}De.backends.onnx=ft;var Sr=async(t,e,r)=>{let s=await tl(new Uint8Array(t),e);return(async n=>{let o=Kn(),a=Object.fromEntries(Object.entries(n).map(([l,u])=>[l,(o?u.clone():u).ort_tensor])),i=await rl(s,a);return Array.isArray(r)?r.map(l=>new U(i[l])):new U(i[r])})},nr=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Sr([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=Sr([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=Sr([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=Sr([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=Sr([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=Sr([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=Sr([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=Sr([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 ME=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"});var TE=(function(){let t;return async function(){if(t===void 0)if(!be.IS_WEBGPU_AVAILABLE)t=!1;else try{t=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{t=!1}return t}})(),mt=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),_d=Object.freeze({[ME.wasm]:mt.q8}),gd=Object.freeze({[mt.fp32]:"",[mt.fp16]:"_fp16",[mt.int8]:"_int8",[mt.uint8]:"_uint8",[mt.q8]:"_quantized",[mt.q4]:"_q4",[mt.q4f16]:"_q4f16",[mt.bnb4]:"_bnb4"}),Ws=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 U=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 sl(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new AE(e[0],e[1],e[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let n=Number(s);if(Number.isInteger(n))return r._getitem(n)}return r[s]},set:(r,s,n)=>r[s]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...r]=this.dims;if(r.length>0){let s=r.reduce((n,o)=>n*o);for(let n=0;n<e;++n)yield this._subarray(n,s,r)}else yield*this.data}_getitem(e){let[r,...s]=this.dims;if(e=or(e,r),s.length>0){let n=s.reduce((o,a)=>o*a);return this._subarray(e,n,s)}else return new t(this.type,[this.data[e]],s)}indexOf(e){let r=this.data;for(let s=0;s<r.length;++s)if(r[s]==e)return s;return-1}_subarray(e,r,s){let n=e*r,o=(e+1)*r,a="subarray"in this.data?this.data.subarray(n,o):this.data.slice(n,o);return new t(this.type,a,s)}item(){let e=this.data;if(e.length!==1)throw new Error(`a Tensor with ${e.length} elements cannot be converted to Scalar`);return e[0]}tolist(){return XC(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=1/(1+Math.exp(-e[r]));return this}map(e){return this.clone().map_(e)}map_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]=e(r[s],s,r);return this}mul(e){return this.clone().mul_(e)}mul_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]*=e;return this}div(e){return this.clone().div_(e)}div_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]/=e;return this}add(e){return this.clone().add_(e)}add_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]+=e;return this}sub(e){return this.clone().sub_(e)}sub_(e){let r=this.data;for(let s=0;s<r.length;++s)r[s]-=e;return this}clone(){return new t(this.type,this.data.slice(),this.dims.slice())}slice(...e){let r=[],s=[];for(let d=0;d<this.dims.length;++d){let f=e[d];if(f==null)s.push([0,this.dims[d]]),r.push(this.dims[d]);else if(typeof f=="number")f=or(f,this.dims[d],d),s.push([f,f+1]);else if(Array.isArray(f)&&f.length===2){let[m,_]=f;if(m=m===null?0:or(m,this.dims[d],d,!1),_=_===null?this.dims[d]:or(_,this.dims[d],d,!1),m>_)throw new Error(`Invalid slice: ${f}`);let w=[Math.max(m,0),Math.min(_,this.dims[d])];s.push(w),r.push(w[1]-w[0])}else throw new Error(`Invalid slice: ${f}`)}let n=s.map(([d,f])=>f-d),o=n.reduce((d,f)=>d*f),a=this.data,i=new a.constructor(o),l=this.stride(),u=!0;for(let d=1;d<n.length;++d)if(s[d][0]!==0||s[d][1]!==this.dims[d]){u=!1;break}if(u){let d=s[0][0]*l[0],f=s[0][1]*l[0];if(ArrayBuffer.isView(a))i.set(a.subarray(d,f));else if(Array.isArray(a)){let m=a.slice(d,f);for(let _=0;_<m.length;++_)i[_]=m[_]}else throw new Error("Unsupported data type for slicing")}else for(let d=0;d<o;++d){let f=0;for(let m=n.length-1,_=d;m>=0;--m){let w=n[m];f+=(_%w+s[m][0])*l[m],_=Math.floor(_/w)}i[d]=a[f]}return new t(this.type,i,r)}permute(...e){return KC(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=(u,d)=>u+d**e;if(r===null){let u=n.reduce(o,0)**(1/e);return new t(this.type,[u],[])}let[a,i,l]=Yn(o,this,r,s);if(e!==1)for(let u=0;u<i.length;++u)i[u]=i[u]**(1/e);return new t(a,i,l)}normalize_(e=2,r=1){r=or(r,this.dims.length);let s=this.norm(e,r,!0),n=this.data,o=s.data;for(let a=0;a<n.length;++a){let i=0;for(let l=this.dims.length-1,u=a,d=1;l>=0;--l){let f=this.dims[l];if(l!==r){let m=u%f;i+=m*d,d*=this.dims[l]}u=Math.floor(u/f)}n[a]/=o[i]}return this}normalize(e=2,r=1){return this.clone().normalize_(e,r)}stride(){return wd(this.dims)}squeeze(e=null){return new t(this.type,this.data,SE(this.dims,e))}squeeze_(e=null){return this.dims=SE(this.dims,e),this}unsqueeze(e){return new t(this.type,this.data,OE(this.dims,e))}unsqueeze_(e){return this.dims=OE(this.dims,e),this}flatten_(e=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,e),n=this.dims.slice(e,r+1),o=this.dims.slice(r+1);return this.dims=[...s,n.reduce((a,i)=>a*i,1),...o],this}flatten(e=0,r=-1){return this.clone().flatten_(e,r)}view(...e){let r=-1;for(let n=0;n<e.length;++n)if(e[n]===-1){if(r!==-1)throw new Error("Only one dimension can be inferred");r=n}let s=this.data;if(r!==-1){let n=e.reduce((o,a,i)=>i!==r?o*a:o,1);e[r]=s.length/n}return new t(this.type,s,e)}neg_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=-e[r];return this}neg(){return this.clone().neg_()}gt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]>e?1:0;return new t("bool",r,this.dims)}lt(e){let r=new Uint8Array(this.data.length),s=this.data;for(let n=0;n<s.length;++n)r[n]=s[n]<e?1:0;return new t("bool",r,this.dims)}clamp_(e,r){let s=this.data;for(let n=0;n<s.length;++n)s[n]=Math.min(Math.max(s[n],e),r);return this}clamp(e,r){return this.clone().clamp_(e,r)}round_(){let e=this.data;for(let r=0;r<e.length;++r)e[r]=Math.round(e[r]);return this}round(){return this.clone().round_()}mean(e=null,r=!1){return al(this,e,r)}min(e=null,r=!1){if(e===null){let a=Dn(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Yn((a,i)=>Math.min(a,i),this,e,r,1/0);return new t(s,n,o)}max(e=null,r=!1){if(e===null){let a=Te(this.data)[0];return new t(this.type,[a],[])}let[s,n,o]=Yn((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=Dn(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=Te(this.data)[1];return new t("int64",[BigInt(s)],[])}repeat(...e){if(e.length<this.dims.length)throw new Error(`Number of dimensions of repeat dims (${e.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(e.every(d=>d===1)){if(e.length===this.dims.length)return this.clone();let d=e.length-this.dims.length,f=Array(d).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((d,f)=>d*e[f]),o=n.reduce((d,f)=>d*f,1),a=this.data,i=new a.constructor(o),l=wd(s),u=wd(n);for(let d=0;d<o;++d){let f=d,m=0;for(let _=0;_<n.length;++_){let w=Math.floor(f/u[_]);f=f%u[_];let x=w%s[_];m+=x*l[_]}i[d]=a[m]}return new t(this.type,i,n)}tile(...e){if(e.length<this.dims.length){let r=this.dims.length-e.length;e=Array(r).fill(1).concat(e)}return this.repeat(...e)}to(e){if(this.type===e)return this;if(!Ws.hasOwnProperty(e))throw new Error(`Unsupported type: ${e}`);let r,s=["int64","uint64"].includes(this.type),n=["int64","uint64"].includes(e);if(s&&!n)r=Number;else if(!s&&n)["float16","float32","float64"].includes(this.type)?r=o=>BigInt(Math.floor(o)):r=BigInt;else if(this.type==="float16"&&e=="float32"&&this.data instanceof Uint16Array)return new t(e,Kv(this.data),this.dims);return new t(e,Ws[e].from(this.data,r),this.dims)}};function XC(t,e){let r=t.length,s=e.reduce((o,a)=>o*a);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${e})`);let n=t;for(let o=e.length-1;o>=0;o--)n=n.reduce((a,i)=>{let l=a[a.length-1];return l.length<e[o]?l.push(i):a.push([i]),a},[[]]);return n[0]}function KC(t,e){let[r,s]=Gv(t.data,t.dims,e);return new U(t.type,r,s)}function xd(t,[e,r],s="bilinear",n=!1){let o=t.dims.at(-3)??1,a=t.dims.at(-2),i=t.dims.at(-1),l=jv(t.data,[o,a,i],[e,r],s,n);return new U(t.type,l,[o,e,r])}async function Dt(t,{size:e=null,mode:r="bilinear"}={}){if(t.dims.length!==4)throw new Error("`interpolate_4d` currently only supports 4D input.");if(!e)throw new Error("`interpolate_4d` requires a `size` argument.");let s;if(e.length===2)s=[...t.dims.slice(0,2),...e];else if(e.length===3)s=[t.dims[0],...e];else if(e.length===4)s=e;else throw new Error("`size` must be of length 2, 3, or 4.");let n;if(r==="nearest")n=await nr.nearest_interpolate_4d;else if(r==="bilinear")n=await nr.bilinear_interpolate_4d;else if(r==="bicubic")n=await nr.bicubic_interpolate_4d;else throw new Error(`Unsupported mode: ${r}`);let o=new U("int64",new BigInt64Array(s.map(BigInt)),[s.length]);return await n({x:t,s:o})}async function IE(t,e){return await(await nr.matmul)({a:t,b:e})}async function QN(t,e){return await(await nr.rfft)({x:t,a:e})}async function Yt(t,e){let r=await nr.top_k;return e==null?e=t.dims.at(-1):e=Math.min(e,t.dims.at(-1)),await r({x:t,k:new U("int64",[BigInt(e)],[1])})}var nl=t=>new U("int64",t,[t.length]);async function ol(t,e,r,s,n){return await(await nr.slice)({x:t,s:nl(e),e:nl(r),a:nl(s),t:nl(n??new Array(s.length).fill(1))})}function CE(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,u=0;for(let d=0;d<a;++d){let f=d*l*i;for(let m=0;m<l;++m){let _=0,w=0,x=d*i,k=f+m;for(let M=0;M<i;++M){let I=Number(s[x+M]);w+=I,_+=r[k+M*l]*I}let E=_/w;o[u++]=E}}return new U(t.type,o,n)}function JN(t,e,{eps:r=1e-5}={}){if(t.dims.length!==2)throw new Error("`layer_norm` currently only supports 2D input.");let[s,n]=t.dims;if(e.length!==1&&e[0]!==n)throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.");let[o,a]=yd(t,1,0,!0),i=o.data,l=a.data,u=t.data,d=new u.constructor(u.length);for(let f=0;f<s;++f){let m=f*n;for(let _=0;_<n;++_){let w=m+_;d[w]=(u[w]-l[f])/(i[f]+r)}}return new U(t.type,d,t.dims)}function SE(t,e){return t=t.slice(),e===null?t=t.filter(r=>r!==1):typeof e=="number"?t[e]===1&&t.splice(e,1):Array.isArray(e)&&(t=t.filter((r,s)=>r!==1||!e.includes(s))),t}function OE(t,e){return e=or(e,t.length+1),t=t.slice(),t.splice(e,0,1),t}function or(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=or(e,t[0].dims.length);let r=t[0].dims.slice();r[e]=t.reduce((a,i)=>a+i.dims[e],0);let s=r.reduce((a,i)=>a*i,1),n=new t[0].data.constructor(s),o=t[0].type;if(e===0){let a=0;for(let i of t){let l=i.data;n.set(l,a),a+=l.length}}else{let a=0;for(let i=0;i<t.length;++i){let{data:l,dims:u}=t[i];for(let d=0;d<l.length;++d){let f=0;for(let m=u.length-1,_=d,w=1;m>=0;--m){let x=u[m],k=_%x;m===e&&(k+=a),f+=k*w,w*=r[m],_=Math.floor(_/x)}n[f]=l[d]}a+=u[e]}}return new U(o,n,r)}function Ft(t,e=0){return Ee(t.map(r=>r.unsqueeze(e)),e)}function Yn(t,e,r,s=!1,n=null){let o=e.data,a=e.dims;r=or(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 u=0;u<o.length;++u){let d=0;for(let f=a.length-1,m=u,_=1;f>=0;--f){let w=a[f];if(f!==r){let x=m%w;d+=x*_,_*=i[f]}m=Math.floor(m/w)}l[d]=t(l[d],o[u],u,d)}return s||i.splice(r,1),[e.type,l,i]}function yd(t,e=null,r=1,s=!1){let n=t.data,o=t.dims;if(e===null){let _=n.reduce((E,M)=>E+M,0)/n.length,w=Math.sqrt(n.reduce((E,M)=>E+(M-_)**2,0)/(n.length-r)),x=new U(t.type,[_],[]);return[new U(t.type,[w],[]),x]}e=or(e,o.length);let a=al(t,e,s),i=a.data,[l,u,d]=Yn((m,_,w,x)=>m+(_-i[x])**2,t,e,s);for(let m=0;m<u.length;++m)u[m]=Math.sqrt(u[m]/(o[e]-r));return[new U(l,u,d),a]}function al(t,e=null,r=!1){let s=t.dims,n=t.data;if(e===null){let l=n.reduce((u,d)=>u+d,0);return new U(t.type,[l/n.length],[])}e=or(e,s.length);let[o,a,i]=Yn((l,u)=>l+u,t,e,r);if(s[e]!==1)for(let l=0;l<a.length;++l)a[l]/=s[e];return new U(o,a,i)}function wd(t){let e=new Array(t.length);for(let r=t.length-1,s=1;r>=0;--r)e[r]=s,s*=t[r];return e}function bd(t,e,r,s){let n=t.reduce((o,a)=>o*a,1);return new U(r,new s(n).fill(e),t)}function Ve(t,e){let r,s;if(typeof e=="number")r="float32",s=Float32Array;else if(typeof e=="bigint")r="int64",s=BigInt64Array;else if(typeof e=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof e}`);return bd(t,e,r,s)}function Qn(t,e){return Ve(t.dims,e)}function it(t){return bd(t,1n,"int64",BigInt64Array)}function il(t){return it(t.dims)}function vd(t){return bd(t,0n,"int64",BigInt64Array)}function kd(t){return vd(t.dims)}function ZN(t){let e=t.reduce((r,s)=>r*s,1);return new U("float32",Float32Array.from({length:e},()=>Math.random()),t)}function PE(t){let e=t.reduce((s,n)=>s*n,1),r=new Float32Array(e);for(let s=0;s<e;s+=2){let n=1-Math.random(),o=Math.random(),a=Math.sqrt(-2*Math.log(n)),i=2*Math.PI*o;r[s]=a*Math.cos(i),s+1<e&&(r[s+1]=a*Math.sin(i))}return new U("float32",r,t)}function zE(t,e){if(t.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(t.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(e))throw new Error("The precision must be either 'binary' or 'ubinary'");let r=e==="binary",s=r?"int8":"uint8",n=r?Int8Array:Uint8Array,o=t.data,a=new n(o.length/8);for(let i=0;i<o.length;++i){let l=o[i]>0?1:0,u=Math.floor(i/8),d=i%8;a[u]|=l<<7-d,r&&d===0&&(a[u]-=128)}return new U(s,a,[t.dims[0],t.dims[1]/8])}async function Ed(t,e){return await Promise.all([at(t,"tokenizer.json",!0,e),at(t,"tokenizer_config.json",!0,e)])}function Ad(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 YC=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function QC(t,e,r,s){for(let n of Object.keys(t)){let o=e-t[n].length,a=r(n),i=new Array(o).fill(a);t[n]=s==="right"?dt(t[n],i):dt(i,t[n])}}function JC(t,e){for(let r of Object.keys(t))t[r].length=e}function ds(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 ZC(t){let e=[];for(let r of t.get_added_tokens_decoder().values())r.special&&e.push(r);return e}var j=class extends Je{return_token_type_ids=!1;padding_side="right";constructor(e,r){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=r,this._tokenizer=new xv(e,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=ds(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=ds(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=ds(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=ds(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=ds(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=ds(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=ZC(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 Ed(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a});return new this(...i)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(r=>this._tokenizer.token_to_id(r))}_call(e,{text_pair:r=null,add_special_tokens:s=!0,padding:n=!1,truncation:o=null,max_length:a=null,return_tensor:i=!0,return_token_type_ids:l=null}={}){let u=Array.isArray(e),d;if(u){if(e.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(e.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");d=e.map((m,_)=>this._encode_plus(m,{text_pair:r[_],add_special_tokens:s,return_token_type_ids:l}))}else d=e.map(m=>this._encode_plus(m,{add_special_tokens:s,return_token_type_ids:l}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");d=[this._encode_plus(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:l})]}if(a===null?a=this.model_max_length:o===null&&(n===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),a=this.model_max_length):n===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),n===!0&&(a=Math.min(Te(d.map(m=>m.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),n||o)for(let m=0;m<d.length;++m)d[m].input_ids.length!==a&&(d[m].input_ids.length>a?o&&JC(d[m],a):n&&QC(d[m],a,_=>_==="input_ids"?this.pad_token_id:0,this.padding_side));let f={};if(i){if(!(n&&o)&&d.some(_=>{for(let w of Object.keys(_))if(_[w].length!==d[0][w]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let m=[d.length,d[0].input_ids.length];for(let _ of Object.keys(d[0]))f[_]=new U("int64",BigInt64Array.from(d.flatMap(w=>w[_]).map(BigInt)),m)}else{for(let m of Object.keys(d[0]))f[m]=d.map(_=>_[m]);if(!u)for(let m of Object.keys(f))f[m]=f[m][0]}return f}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){let{ids:o,attention_mask:a,token_type_ids:i}=this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n??this.return_token_type_ids});return{input_ids:o,attention_mask:a,...i?{token_type_ids:i}:{}}}tokenize(e,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(e,{text_pair:r,add_special_tokens:s})}encode(e,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:n=null}={}){return this._tokenizer.encode(e,{text_pair:r,add_special_tokens:s,return_token_type_ids:n}).ids}batch_decode(e,r={}){return e instanceof U&&(e=e.tolist()),e.map(s=>this.decode(s,r))}decode(e,r={}){if(e instanceof U&&(e=Ad(e)),!Array.isArray(e)||e.length===0||!Pv(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,r)}decode_single(e,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(e,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:e=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){let s=this.chat_template;if(e!==null&&Object.hasOwn(s,e))e=s[e];else if(e===null)if(r!==null&&"tool_use"in s)e=s.tool_use;else if("default"in s)e=s.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(s).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,{tools:r=null,documents:s=null,chat_template:n=null,add_generation_prompt:o=!1,tokenize:a=!0,padding:i=!1,truncation:l=!1,max_length:u=null,return_tensor:d=!0,return_dict:f=!0,tokenizer_kwargs:m={},..._}={}){if(n=this.get_chat_template({chat_template:n,tools:r}),typeof n!="string")throw Error(`chat_template must be a string, but got ${typeof n}`);let w=this._compiled_template_cache.get(n);w===void 0&&(w=new Cv(n),this._compiled_template_cache.set(n,w));let x=Object.create(null);for(let E of YC){let M=ds(this.config,E);M&&(x[E]=M)}let k=w.render({messages:e,add_generation_prompt:o,tools:r,documents:s,...x,..._});if(a){let E=this._call(k,{add_special_tokens:!1,padding:i,truncation:l,max_length:u,return_tensor:d,...m});return f?E:E.input_ids}return k}};function Vs(t,e,r,s){if(!("language_codes"in t)||!Array.isArray(t.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in t)||!(t.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in t)||typeof t.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let n=s.src_lang,o=s.tgt_lang;if(!t.language_codes.includes(o))throw new Error(`Target language code "${o}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);if(n!==void 0){if(!t.language_codes.includes(n))throw new Error(`Source language code "${n}" is not valid. Must be one of: {${t.language_codes.join(", ")}}`);for(let a of t._tokenizer.post_processor.config.single)if("SpecialToken"in a&&t.languageRegex.test(a.SpecialToken.id)){a.SpecialToken.id=t.lang_to_token(n);break}}return s.forced_bos_token_id=t._tokenizer.token_to_id(t.lang_to_token(o)),t._call(e,r)}var gf={};Ps(gf,{AlbertTokenizer:()=>Md,AutoTokenizer:()=>J,BartTokenizer:()=>Td,BertTokenizer:()=>Sd,BlenderbotSmallTokenizer:()=>Od,BlenderbotTokenizer:()=>Id,BloomTokenizer:()=>Cd,CLIPTokenizer:()=>zd,CamembertTokenizer:()=>Pd,CodeGenTokenizer:()=>Nd,CodeLlamaTokenizer:()=>Ld,CohereTokenizer:()=>$d,ConvBertTokenizer:()=>Rd,DebertaTokenizer:()=>Bd,DebertaV2Tokenizer:()=>Ud,DistilBertTokenizer:()=>Dd,ElectraTokenizer:()=>Fd,EsmTokenizer:()=>jd,FalconTokenizer:()=>Gd,GPT2Tokenizer:()=>Vd,GPTNeoXTokenizer:()=>Wd,GemmaTokenizer:()=>qd,HerbertTokenizer:()=>Hd,LlamaTokenizer:()=>Xd,M2M100Tokenizer:()=>Kd,MBart50Tokenizer:()=>Qd,MBartTokenizer:()=>Jn,MPNetTokenizer:()=>ef,MarianTokenizer:()=>Yd,MgpstrTokenizer:()=>Jd,MobileBertTokenizer:()=>Zd,NllbTokenizer:()=>tf,NougatTokenizer:()=>rf,PreTrainedTokenizer:()=>j,Qwen2Tokenizer:()=>sf,RoFormerTokenizer:()=>of,RobertaTokenizer:()=>nf,SiglipTokenizer:()=>af,SpeechT5Tokenizer:()=>lf,SqueezeBertTokenizer:()=>cf,T5Tokenizer:()=>uf,TokenizersBackend:()=>j,VitsTokenizer:()=>df,Wav2Vec2CTCTokenizer:()=>ff,WhisperTokenizer:()=>mf,XLMRobertaTokenizer:()=>hf,XLMTokenizer:()=>_f});var Md=class extends j{return_token_type_ids=!0};var Td=class extends j{};var Sd=class extends j{return_token_type_ids=!0};var Od=class extends j{};var Id=class extends j{};var Cd=class extends j{};var Pd=class extends j{};var zd=class extends j{};var Ld=class extends j{};var Nd=class extends j{};var $d=class extends j{};var Rd=class extends j{return_token_type_ids=!0};var Ud=class extends j{return_token_type_ids=!0};var Bd=class extends j{return_token_type_ids=!0};var Dd=class extends j{};var Fd=class extends j{return_token_type_ids=!0};var jd=class extends j{};var Gd=class extends j{};var qd=class extends j{};var Wd=class extends j{};var Vd=class extends j{};var Hd=class extends j{return_token_type_ids=!0};var Xd=class extends j{padding_side="left"};var Kd=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s.slice(2,-2)),this.lang_to_token=s=>`__${s}__`}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var Yd=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(s=>this.languageRegex.test(s)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[r,...s]=e.trim().split(this.languageRegex);if(s.length===0)return super._encode_text(r);if(s.length===2){let[n,o]=s;return this.supported_language_codes.includes(n)||console.warn(`Unsupported language code "${n}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),dt([n],super._encode_text(o))}}};var Jn=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)).map(s=>s),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var Qd=class extends Jn{};var Jd=class extends j{};var Zd=class extends j{return_token_type_ids=!0};var ef=class extends j{};var tf=class extends j{constructor(e,r){super(e,r),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(s=>this.languageRegex.test(s)),this.lang_to_token=s=>s}_build_translation_inputs(e,r,s){return Vs(this,e,r,s)}};var rf=class extends j{};var sf=class extends j{};var nf=class extends j{};var of=class extends j{return_token_type_ids=!0};var af=class extends j{};var lf=class extends j{};var cf=class extends j{return_token_type_ids=!0};var uf=class extends j{};var pf=class extends $t{decode_chain(e){let r="";for(let s=1;s<e.length;s+=2)r+=e[s];return[r]}},df=class extends j{constructor(e,r){super(e,r),this._tokenizer.decoder=new pf({type:"VitsDecoder"})}};var ff=class extends j{};var LE=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],Zn=new Map(LE),eP=new Map([...LE.map(([t,e])=>[e,t]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function NE(t){t=t.toLowerCase();let e=eP.get(t);if(e===void 0){let r=t.match(/^<\|([a-z]{2})\|>$/);if(r&&(t=r[1]),Zn.has(t))e=t;else{let n=t.length===2?Zn.keys():Zn.values();throw new Error(`Language "${t}" is not supported. Must be one of: ${JSON.stringify(Array.from(n))}`)}}return e}var tP="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",$E=new RegExp(`^[${tP}]+$`,"gu"),mf=class extends j{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:r=!1,return_language:s=!1,time_precision:n=null,force_full_sequences:o=!0}={}){if(n===null)throw Error("Must specify time_precision");let a=null,i=r==="word";function l(){return{language:a,timestamp:[null,null],text:""}}let u=[],d=l(),f=0,m=this.timestamp_begin,w=m+1500,x=[],k=[],E=!1,M=null,I=new Set(this.all_special_ids);for(let C of e){let v=C.tokens,G=i?C.token_timestamps:null,X=null,V=m;if("stride"in C){let[Y,B,P]=C.stride;if(f-=B,M=Y-P,B&&(V=B/n+m),P)for(let se=v.length-1;se>=0;--se){let ie=Number(v[se]);if(ie>=m){if(X!==null&&(ie-m)*n<M)break;X=ie}}}let Q=[],K=[];for(let Y=0;Y<v.length;++Y){let B=Number(v[Y]);if(I.has(B)){let P=this.decode([B]),se=Zn.get(P.slice(2,-2));if(se!==void 0){if(a!==null&&se!==a&&!r){x.push(Q);let ie=this.findLongestCommonSequence(x)[0],S=this.decode(ie);d.text=S,u.push(d),x=[],Q=[],d=l()}a=d.language=se}}else if(B>=m&&B<=w){let P=(B-m)*n+f,se=rs(P,2);if(X!==null&&B>=X)E=!0;else if(E||x.length>0&&B<V)E=!1;else if(d.timestamp[0]===null)d.timestamp[0]=se;else if(se!==d.timestamp[0]){d.timestamp[1]=se,x.push(Q),i&&k.push(K);let[ie,S]=this.findLongestCommonSequence(x,k),L=this.decode(ie);d.text=L,i&&(d.words=this.collateWordTimestamps(ie,S,a)),u.push(d),x=[],Q=[],k=[],K=[],d=l()}}else if(Q.push(B),i){let P=rs(G[Y]+f,2),se;if(Y+1<G.length){se=rs(G[Y+1]+f,2);let ie=this.decode([B]);$E.test(ie)&&(se=rs(Math.min(P+n,se),2))}else se=null;K.push([P,se])}}if("stride"in C){let[Y,B,P]=C.stride;f+=Y-P}Q.length>0?(x.push(Q),i&&k.push(K)):x.every(Y=>Y.length===0)&&(d=l(),x=[],Q=[],k=[],K=[])}if(x.length>0){if(o&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[C,v]=this.findLongestCommonSequence(x,k),G=this.decode(C);d.text=G,i&&(d.words=this.collateWordTimestamps(C,v,a)),u.push(d)}let T=Object.create(null),z=u.map(C=>C.text).join("");if(r||s){for(let C=0;C<u.length;++C){let v=u[C];r||delete v.timestamp,s||delete v.language}if(i){let C=[];for(let v of u)for(let G of v.words)C.push(G);T={chunks:C}}else T={chunks:u}}return[z,T]}findLongestCommonSequence(e,r=null){let s=e[0],n=s.length,o=[],a=Array.isArray(r)&&r.length>0,i=a?[]:null,l=a?r[0]:null;for(let u=1;u<e.length;++u){let d=e[u],f=0,m=[n,n,0,0],_=d.length;for(let T=1;T<n+_;++T){let z=Math.max(0,n-T),C=Math.min(n,n+_-T),v=s.slice(z,C),G=Math.max(0,T-n),X=Math.min(_,T),V=d.slice(G,X);if(v.length!==V.length)throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let Q;a?Q=v.filter((B,P)=>B===V[P]&&l[z+P]<=r[u][G+P]).length:Q=v.filter((B,P)=>B===V[P]).length;let K=T/1e4,Y=Q/T+K;Q>1&&Y>f&&(f=Y,m=[z,C,G,X])}let[w,x,k,E]=m,M=Math.floor((x+w)/2),I=Math.floor((E+k)/2);o.push(...s.slice(0,M)),s=d.slice(I),n=s.length,a&&(i.push(...l.slice(0,M)),l=r[u].slice(I))}return o.push(...s),a?(i.push(...l),[o,i]):[o,[]]}collateWordTimestamps(e,r,s){let[n,o,a]=this.combineTokensIntoWords(e,s),i=[];for(let l=0;l<n.length;++l){let u=a[l];i.push({text:n[l],timestamp:[r[u.at(0)][0],r[u.at(-1)][1]]})}return i}combineTokensIntoWords(e,r,s=`"'\u201C\xA1\xBF([{-`,n=`"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`){r=r??"english";let o,a,i;return["chinese","japanese","thai","lao","myanmar"].includes(r)?[o,a,i]=this.splitTokensOnUnicode(e):[o,a,i]=this.splitTokensOnSpaces(e),this.mergePunctuations(o,a,i,s,n)}decode(e,r){let s;return r?.decode_with_timestamps?(e instanceof U&&(e=Ad(e)),s=this.decodeWithTimestamps(e,r)):s=super.decode(e,r),s}decodeWithTimestamps(e,r){let s=r?.time_precision??.02,n=this.all_special_ids.at(-1)+1,o=[[]];for(let a of e)if(a=Number(a),a>=n){let i=((a-n)*s).toFixed(2);o.push(`<|${i}|>`),o.push([])}else o[o.length-1].push(a);return o=o.map(a=>typeof a=="string"?a:super.decode(a,r)),o.join("")}splitTokensOnUnicode(e){let r=this.decode(e,{decode_with_timestamps:!0}),s="\uFFFD",n=[],o=[],a=[],i=[],l=[],u=0;for(let d=0;d<e.length;++d){let f=e[d];i.push(f),l.push(d);let m=this.decode(i,{decode_with_timestamps:!0});(!m.includes(s)||r[u+m.indexOf(s)]===s)&&(n.push(m),o.push(i),a.push(l),i=[],l=[],u+=m.length)}return[n,o,a]}splitTokensOnSpaces(e){let[r,s,n]=this.splitTokensOnUnicode(e),o=[],a=[],i=[];for(let l=0;l<r.length;++l){let u=r[l],d=s[l],f=n[l],m=d[0]>=this._tokenizer.token_to_id("<|endoftext|>"),_=u.startsWith(" "),w=u.trim(),x=$E.test(w);if(m||_||x||o.length===0)o.push(u),a.push(d),i.push(f);else{let k=o.length-1;o[k]+=u,a[k].push(...d),i[k].push(...f)}}return[o,a,i]}mergePunctuations(e,r,s,n,o){let a=structuredClone(e),i=structuredClone(r),l=structuredClone(s),u=a.length-2,d=a.length-1;for(;u>=0;)a[u].startsWith(" ")&&n.includes(a[u].trim())?(a[d]=a[u]+a[d],i[d]=dt(i[u],i[d]),l[d]=dt(l[u],l[d]),a[u]="",i[u]=[],l[u]=[]):d=u,--u;for(u=0,d=1;d<a.length;)!a[u].endsWith(" ")&&o.includes(a[d])?(a[u]+=a[d],i[u]=dt(i[u],i[d]),l[u]=dt(l[u],l[d]),a[d]="",i[d]=[],l[d]=[]):u=d,++d;return[a.filter(f=>f),i.filter(f=>f.length>0),l.filter(f=>f.length>0)]}};var hf=class extends j{};var _f=class extends j{return_token_type_ids=!0;constructor(e,r){super(e,r),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}};var J=class{static async from_pretrained(e,{progress_callback:r=null,config:s=null,cache_dir:n=null,local_files_only:o=!1,revision:a="main"}={}){let[i,l]=await Ed(e,{progress_callback:r,config:s,cache_dir:n,local_files_only:o,revision:a}),u=l.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",d=gf[u];return d||(console.warn(`Unknown tokenizer class "${u}", attempting to construct from base class.`),d=j),new d(i,l)}};var Hs="https://github.com/huggingface/transformers.js/issues/new/choose";var eo="preprocessor_config.json",Xs=eo,RE="processor_config.json",UE="chat_template.jinja";var ne=class extends Je{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,r,s){super(),this.config=e,this.components=r,this.chat_template=s}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,r={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...r})}batch_decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...e)}async _call(e,...r){for(let s of[this.image_processor,this.feature_extractor,this.tokenizer])if(s)return s(e,...r);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,r={}){let[s,n,o]=await Promise.all([this.uses_processor_config?at(e,RE,!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?yp(e,UE,!0,r):null]);return new this(s,n,o)}};var Cl={};Ps(Cl,{ChatterboxProcessor:()=>Pf,Florence2Processor:()=>km,Gemma3nProcessor:()=>Em,GroundingDinoProcessor:()=>Am,Idefics3Processor:()=>Sl,JinaCLIPProcessor:()=>Tm,LlavaProcessor:()=>Sm,MgpstrProcessor:()=>Om,MoonshineProcessor:()=>Im,OwlViTProcessor:()=>Cm,PaliGemmaProcessor:()=>Pm,Phi3VProcessor:()=>zm,PixtralProcessor:()=>Lm,Processor:()=>ne,PyAnnoteProcessor:()=>Nm,Qwen2VLProcessor:()=>$m,Sam2Processor:()=>Ol,Sam2VideoProcessor:()=>Rm,SamProcessor:()=>io,SmolVLMProcessor:()=>Sl,SpeechT5Processor:()=>Um,UltravoxProcessor:()=>Bm,VLChatProcessor:()=>Mm,VoxtralProcessor:()=>Dm,Wav2Vec2Processor:()=>Fm,Wav2Vec2ProcessorWithLM:()=>jm,WhisperProcessor:()=>Gm});var Ne=class extends Je{constructor(e){super(),this.config=e}static async from_pretrained(e,r={}){let s=await at(e,eo,!0,r);return new this(s)}};function He(t,e){if(!(t instanceof Float32Array||t instanceof Float64Array))throw new Error(`${e} expects input to be a Float32Array or a Float64Array, but got ${t?.constructor?.name??typeof t} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var oo={};Ps(oo,{ASTFeatureExtractor:()=>yf,ChatterboxFeatureExtractor:()=>bf,ClapFeatureExtractor:()=>vf,DacFeatureExtractor:()=>so,EncodecFeatureExtractor:()=>ro,FeatureExtractor:()=>Ne,Gemma3nAudioFeatureExtractor:()=>kf,MoonshineFeatureExtractor:()=>Ef,ParakeetFeatureExtractor:()=>Af,PyAnnoteFeatureExtractor:()=>no,SeamlessM4TFeatureExtractor:()=>Mf,SnacFeatureExtractor:()=>Tf,SpeechT5FeatureExtractor:()=>Sf,Wav2Vec2FeatureExtractor:()=>Of,WeSpeakerFeatureExtractor:()=>If,WhisperFeatureExtractor:()=>Cf});import rP from"fs";import{Readable as sP}from"stream";import{pipeline as nP}from"stream/promises";async function ll(t,e){if(be.IS_BROWSER_ENV){if(be.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");let r=URL.createObjectURL(e),s=document.createElement("a");s.href=r,s.download=t,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(be.IS_FS_AVAILABLE){let r=e.stream(),s=sP.fromWeb(r),n=rP.createWriteStream(t);await nP(s,n)}else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function xf(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 Bs(t)).arrayBuffer(),s=new AudioContext({sampleRate:e});typeof e>"u"&&console.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);let n=await s.decodeAudioData(r),o;if(n.numberOfChannels===2){let a=Math.sqrt(2),i=n.getChannelData(0),l=n.getChannelData(1);o=new Float32Array(i.length);for(let u=0;u<n.length;++u)o[u]=a*(i[u]+l[u])/2}else o=n.getChannelData(0);return o}function FE(t,e){if(t<1)return new Float64Array;if(t===1)return new Float64Array([1]);let r=1-e,s=2*Math.PI/(t-1),n=new Float64Array(t);for(let o=0;o<t;++o)n[o]=e-r*Math.cos(o*s);return n}function BE(t){return FE(t,.5)}function oP(t){return FE(t,.54)}var aP={htk:t=>2595*Math.log10(1+t/700),kaldi:t=>1127*Math.log(1+t/700),slaney:(t,e=1e3,r=15,s=27/Math.log(6.4))=>t>=e?r+Math.log(t/e)*s:3*t/200};function wf(t,e="htk"){let r=aP[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 iP={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 lP(t,e="htk"){let r=iP[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 cP(t,e){let r=Float64Array.from({length:e.length-1},(a,i)=>e[i+1]-e[i]),s=Array.from({length:t.length},()=>new Array(e.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<e.length;++l)i[l]=e[l]-t[a]}let n=e.length-2,o=Array.from({length:n},()=>new Array(t.length));for(let a=0;a<t.length;++a){let i=s[a];for(let l=0;l<n;++l){let u=-i[l]/r[l],d=i[l+2]/r[l+1];o[l][a]=Math.max(0,Math.min(u,d))}}return o}function DE(t,e,r){let s=(e-t)/(r-1);return Float64Array.from({length:r},(n,o)=>t+s*o)}function yt(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=wf(r,a),u=wf(s,a),d=DE(l,u,e+2),f=lP(d,a),m;if(i){let w=n/((t-1)*2);m=wf(Float64Array.from({length:t},(x,k)=>k*w),a),f=d}else m=DE(0,Math.floor(n/2),t);let _=cP(m,f);if(o!==null&&o==="slaney")for(let w=0;w<e;++w){let x=_[w],k=2/(f[w+2]-f[w]);for(let E=0;E<t;++E)x[E]*=k}return _}function uP(t,e,r){let s=new t.constructor(t.length+e+r),n=t.length-1;for(let o=0;o<t.length;++o)s[e+o]=t[o];for(let o=1;o<=e;++o)s[e-o]=t[$s(o,n)];for(let o=1;o<=r;++o)s[n+e+o]=t[$s(n-o,n)];return s}function jE(t,e,r,s,n){if(r<=0)throw new Error("reference must be greater than zero");if(s<=0)throw new Error("min_value must be greater than zero");r=Math.max(s,r);let o=Math.log10(r);for(let a=0;a<t.length;++a)t[a]=e*Math.log10(Math.max(s,t[a])-o);if(n!==null){if(n<=0)throw new Error("db_range must be greater than zero");let a=Te(t)[0]-n;for(let i=0;i<t.length;++i)t[i]=Math.max(t[i],a)}return t}function pP(t,e=1,r=1e-5,s=null){return jE(t,20,e,r,s)}function dP(t,e=1,r=1e-10,s=null){return jE(t,10,e,r,s)}async function At(t,e,r,s,{fft_length:n=null,power:o=1,center:a=!0,pad_mode:i="reflect",onesided:l=!0,preemphasis:u=null,preemphasis_htk_flavor:d=!0,mel_filters:f=null,mel_floor:m=1e-10,log_mel:_=null,reference:w=1,min_value:x=1e-10,db_range:k=null,remove_dc_offset:E=null,min_num_frames:M=null,max_num_frames:I=null,do_pad:T=!0,transpose:z=!1,mel_offset:C=0}={}){let v=e.length;if(n===null&&(n=r),r>n)throw Error(`frame_length (${r}) may not be larger than fft_length (${n})`);if(v!==r)throw new Error(`Length of the window (${v}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(o===null&&f!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!d)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(a)switch(i){case"reflect":{let L=Math.floor((n-1)/2)+1;t=uP(t,L,L);break}case"constant":{let L=Math.floor(n/2),R=new t.constructor(t.length+2*L);R.set(t,L),t=R;break}default:throw new Error(`pad_mode="${i}" not implemented yet.`)}let G=Math.floor(1+Math.floor((t.length-r)/s));M!==null&&G<M&&(G=M);let X=l?Math.floor(n/2)+1:n,V=G,Q=G;I!==null&&(I>G?T&&(Q=I):Q=V=I);let K=new ji(n),Y=new Float64Array(n),B=new Float64Array(K.outputBufferSize),P=new Float32Array(X*Q);for(let L=0;L<V;++L){let R=L*s,te=Math.min(t.length-R,r);te!==r&&Y.fill(0,0,r);for(let ue=0;ue<te;++ue)Y[ue]=t[R+ue];if(E){let ue=0;for(let Ce=0;Ce<te;++Ce)ue+=Y[Ce];let Be=ue/te;for(let Ce=0;Ce<te;++Ce)Y[Ce]-=Be}if(u!==null){for(let ue=te-1;ue>=1;--ue)Y[ue]-=u*Y[ue-1];Y[0]*=1-u}for(let ue=0;ue<e.length;++ue)Y[ue]*=e[ue];K.realTransform(B,Y);for(let ue=0;ue<X;++ue){let Be=ue<<1;P[ue*Q+L]=B[Be]**2+B[Be+1]**2}}if(o!==null&&o!==2){let L=o/2;for(let R=0;R<P.length;++R)P[R]**=L}let se=f.length,ie=await IE(new U("float32",f.flat(),[se,X]),new U("float32",P,[X,Q]));z&&(ie=ie.transpose(1,0));let S=ie.data;for(let L=0;L<S.length;++L)S[L]=C+Math.max(m,S[L]);if(o!==null&&_!==null){let L=Math.min(S.length,V*se);switch(_){case"log":for(let R=0;R<L;++R)S[R]=Math.log(S[R]);break;case"log10":for(let R=0;R<L;++R)S[R]=Math.log10(S[R]);break;case"dB":if(o===1)pP(S,w,x,k);else if(o===2)dP(S,w,x,k);else throw new Error(`Cannot use log_mel option '${_}' with power ${o}`);break;default:throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${_}'`)}}return ie}function Mt(t,e,{periodic:r=!0,frame_length:s=null,center:n=!0}={}){let o=r?t+1:t,a;switch(e){case"boxcar":a=new Float64Array(o).fill(1);break;case"hann":case"hann_window":a=BE(o);break;case"hamming":a=oP(o);break;case"povey":a=BE(o).map(i=>Math.pow(i,.85));break;default:throw new Error(`Unknown window type ${e}.`)}if(r&&(a=a.subarray(0,t)),s===null)return a;if(t>s)throw new Error(`Length of the window (${t}) may not be larger than frame_length (${s})`);return a}function fP(t,e){let r=t.reduce((o,a)=>o+a.length,0),s=new ArrayBuffer(44),n=new DataView(s);return cl(n,0,"RIFF"),n.setUint32(4,36+r*4,!0),cl(n,8,"WAVE"),cl(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),cl(n,36,"data"),n.setUint32(40,r*4,!0),new Blob([s,...t.map(o=>o.buffer)],{type:"audio/wav"})}function cl(t,e,r){for(let s=0;s<r.length;++s)t.setUint8(e+s,r.charCodeAt(s))}var to=class{constructor(e,r){this.audio=e,this.sampling_rate=r}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let e=this.audio.reduce((n,o)=>n+o.length,0),r=new Float32Array(e),s=0;for(let n of this.audio)r.set(n,s),s+=n.length;return r}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),fP(e,this.sampling_rate)}async save(e){return ll(e,this.toBlob())}};var yf=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,r){return At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e){He(e,"ASTFeatureExtractor");let r=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let s=this.std*2,n=r.data;for(let o=0;o<n.length;++o)n[o]=(n[o]-this.mean)/s}return{input_values:r.unsqueeze_(0)}}};var ro=class extends Ne{async _call(e){He(e,"EncodecFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=this.config.feature_size;if(e.length%r!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${r}).`);let s=[1,r,e.length/r];return{input_values:new U("float32",e,s)}}};var bf=class extends Ne{async _call(e){He(e,"ChatterboxFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new U("float32",e,r)}}};var vf=class extends Ne{constructor(e){super(e),this.mel_filters=yt(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=yt(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=Mt(this.config.fft_window_size,"hann")}async _get_input_mel(e,r,s,n){let o,a=!1,i=e.length-r;if(i>0)if(s==="rand_trunc"){a=!0;let l=Math.floor(Math.random()*(i+1));e=e.subarray(l,l+r),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${s}" not implemented`);else{if(i<0){let l=new Float64Array(r);if(l.set(e),n==="repeat")for(let u=e.length;u<r;u+=e.length)l.set(e.subarray(0,Math.min(e.length,r-u)),u);else if(n==="repeatpad")for(let u=e.length;u<-i;u+=e.length)l.set(e,u);e=l}if(s==="fusion")throw new Error(`Truncation strategy "${s}" not implemented`);o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}return o.unsqueeze_(0)}async _extract_fbank_features(e,r,s=null){return At(e,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:r,log_mel:"dB",max_num_frames:s,do_pad:!1,transpose:!0})}async _call(e,{max_length:r=null}={}){return He(e,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(e,r??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}};var so=class extends ro{};var kf=class extends Ne{constructor(e){super(e);let{fft_length:r,feature_size:s,min_frequency:n,max_frequency:o,sampling_rate:a,frame_length:i}=this.config,l=yt(Math.floor(1+r/2),s,n,o,a,null,"htk",!1);this.mel_filters=l,this.window=Mt(i,"hann")}async _extract_fbank_features(e,r){return At(e,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(e,{max_length:r=48e4,truncation:s=!0,padding:n=!0,pad_to_multiple_of:o=128}={}){if(He(e,"Gemma3nAudioFeatureExtractor"),s&&e.length>r&&(e=e.slice(0,r)),n&&e.length%o!==0){let l=o-e.length%o,u=new Float64Array(e.length+l);u.set(e),this.config.padding_value!==0&&u.fill(this.config.padding_value,e.length),e=u}let a=await this._extract_fbank_features(e,this.config.max_length),i=Ve([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:i}}};var Ef=class extends Ne{async _call(e){He(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,e.length];return{input_values:new U("float32",e,r)}}};var mP=1e-5,Af=class extends Ne{constructor(e){super(e),this.config.mel_filters??=yt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let r=Mt(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let s=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(r,s)}async _extract_fbank_features(e){let r=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=r*e[n-1];return await At(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){He(e,"ParakeetFeatureExtractor");let r=await this._extract_fbank_features(e),s=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),n=r.data;n.fill(0,s*r.dims[1]);let[o,a]=r.dims,i=new Float64Array(a),l=new Float64Array(a);for(let f=0;f<s;++f){let m=f*a;for(let _=0;_<a;++_){let w=n[m+_];i[_]+=w,l[_]+=w*w}}let u=s>1?s-1:1;for(let f=0;f<a;++f){let m=i[f]/s,_=(l[f]-s*m*m)/u,x=1/(Math.sqrt(_)+mP);for(let k=0;k<s;++k){let E=k*a+f;n[E]=(n[E]-m)*x}}let d=new BigInt64Array(o);return d.fill(1n,0,s),{input_features:r.unsqueeze_(0),attention_mask:new U("int64",d,[1,o])}}};var no=class extends Ne{async _call(e){He(e,"PyAnnoteFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=[1,1,e.length];return{input_values:new U("float32",e,r)}}samples_to_frames(e){return(e-this.config.offset)/this.config.step}post_process_speaker_diarization(e,r){let s=r/this.samples_to_frames(r)/this.config.sampling_rate,n=[];for(let o of e.tolist()){let a=[],i=-1;for(let l=0;l<o.length;++l){let u=Pe(o[l]),[d,f]=Te(u),[m,_]=[l,l+1];f!==i?(i=f,a.push({id:f,start:m,end:_,score:d})):(a.at(-1).end=_,a.at(-1).score+=d)}n.push(a.map(({id:l,start:u,end:d,score:f})=>({id:l,start:u*s,end:d*s,confidence:f/(d-u)})))}return n}};var Mf=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(400,"povey",{periodic:!1})}async _extract_fbank_features(e,r){return e=e.map(s=>s*32768),At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:r,transpose:!0})}async _call(e,{padding:r=!0,pad_to_multiple_of:s=2,do_normalize_per_mel_bins:n=!0,return_attention_mask:o=!0}={}){He(e,"SeamlessM4TFeatureExtractor");let a=await this._extract_fbank_features(e,this.config.max_length);if(n){let[w,x]=a.dims,k=a.data;for(let E=0;E<x;++E){let M=0;for(let C=0;C<w;++C)M+=k[C*x+E];let I=M/w,T=0;for(let C=0;C<w;++C)T+=(k[C*x+E]-I)**2;T/=w-1;let z=Math.sqrt(T+1e-7);for(let C=0;C<w;++C){let v=C*x+E;k[v]=(k[v]-I)/z}}}let i;if(r){let[w,x]=a.dims,k=a.data,E=w%s;if(E>0){let M=new Float32Array(x*(w+E));M.set(k),M.fill(this.config.padding_value,k.length);let I=w+E;a=new U(a.type,M,[I,x]),o&&(i=new U("int64",new BigInt64Array(I),[1,I]),i.data.fill(1n,0,w))}}let[l,u]=a.dims,d=this.config.stride;if(l%d!==0)throw new Error(`The number of frames (${l}) must be a multiple of the stride (${d}).`);let m=a.view(1,Math.floor(l/d),u*d),_={input_features:m};if(o){let w=m.dims[1],x=new BigInt64Array(w);if(i){let k=i.data;for(let E=1,M=0;E<l;E+=d,++M)x[M]=k[E]}else x.fill(1n);_.attention_mask=new U("int64",x,[1,w])}return _}};var Tf=class extends so{};var Sf=class extends Ne{};var Of=class extends Ne{_zero_mean_unit_var_norm(e){let s=e.reduce((o,a)=>o+a,0)/e.length,n=e.reduce((o,a)=>o+(a-s)**2,0)/e.length;return e.map(o=>(o-s)/Math.sqrt(n+1e-7))}async _call(e){He(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let r=e;this.config.do_normalize&&(r=this._zero_mean_unit_var_norm(r));let s=[1,r.length];return{input_values:new U("float32",r,s),attention_mask:new U("int64",new BigInt64Array(r.length).fill(1n),s)}}};var If=class extends Ne{constructor(e){super(e);let r=this.config.sampling_rate,s=yt(257,this.config.num_mel_bins,20,Math.floor(r/2),r,null,"kaldi",!0);this.mel_filters=s,this.window=Mt(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),At(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){He(e,"WeSpeakerFeatureExtractor");let r=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let s=r.mean(1).data,n=r.data,[o,a,i]=r.dims;for(let l=0;l<o;++l){let u=l*a*i,d=l*i;for(let f=0;f<a;++f){let m=u+f*i;for(let _=0;_<i;++_)n[m+_]-=s[d+_]}}}return{input_features:r}}};var Cf=class extends Ne{constructor(e){super(e),this.config.mel_filters??=yt(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=Mt(this.config.n_fft,"hann")}async _extract_fbank_features(e){let r=await At(e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(e.length/this.config.hop_length),this.config.nb_max_frames)}),s=r.data,n=Te(s)[0];for(let o=0;o<s.length;++o)s[o]=(Math.max(s[o],n-8)+4)/4;return r}async _call(e,{max_length:r=null}={}){He(e,"WhisperFeatureExtractor");let s,n=r??this.config.n_samples;return e.length>n?(e.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),s=e.slice(0,n)):(s=new Float32Array(n),s.set(e)),{input_features:(await this._extract_fbank_features(s)).unsqueeze_(0)}}};var tt=class{static async from_pretrained(e,r={}){let s=await at(e,eo,!0,r),n=s.feature_extractor_type,o=oo[n];if(!o)throw new Error(`Unknown feature_extractor_type: '${n}'. Please report this at ${Hs}.`);return new o(s)}};var Pf=class extends ne{static tokenizer_class=J;static feature_extractor_class=tt;async _call(e,r=null){let s=this.tokenizer(e),n=r?await this.feature_extractor(r):{};return{...s,...n}}};import zf from"sharp";var fs,GE,Or,Qt=be.IS_BROWSER_ENV||be.IS_WEBWORKER_ENV;if(Qt)fs=(t,e)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(t,e)},Or=self.createImageBitmap,GE=self.ImageData;else if(zf)Or=async t=>{let r=(await t.metadata()).channels,{data:s,info:n}=await t.rotate().raw().toBuffer({resolveWithObject:!0}),o=new Xe(new Uint8ClampedArray(s),n.width,n.height,n.channels);return r!==void 0&&r!==n.channels&&o.convert(r),o};else throw new Error("Unable to load image processing library.");var hP={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_P=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Xe=class t{constructor(e,r,s,n){this.data=e,this.width=r,this.height=s,this.channels=n}get size(){return[this.width,this.height]}static async read(e){if(e instanceof t)return e;if(typeof e=="string"||e instanceof URL)return await this.fromURL(e);if(e instanceof Blob)return await this.fromBlob(e);if(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)return this.fromCanvas(e);throw new Error(`Unsupported input type: ${typeof e}`)}static fromCanvas(e){if(!Qt)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 Bs(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(Qt){let r=await Or(e),s=fs(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=zf(await e.arrayBuffer());return await Or(r)}}static fromTensor(e,r="CHW"){if(e.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${e.dims.length} dimensions.`);if(r==="CHW")e=e.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(e.data instanceof Uint8ClampedArray||e.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${e.type}`);switch(e.dims[2]){case 1:case 2:case 3:case 4:return new t(e.data,e.dims[1],e.dims[0],e.dims[2]);default:throw new Error(`Unsupported number of channels: ${e.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r<this.data.length;r+=this.channels){let n=this.data[r],o=this.data[r+1],a=this.data[r+2];e[s++]=Math.round(.2989*n+.587*o+.114*a)}break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let e=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r];break;case 4:for(let r=0,s=0;r<this.data.length;r+=4)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2];break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let e=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let r=0,s=0;r<this.data.length;++r)e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=this.data[r],e[s++]=255;break;case 3:for(let r=0,s=0;r<this.data.length;r+=3)e[s++]=this.data[r],e[s++]=this.data[r+1],e[s++]=this.data[r+2],e[s++]=255;break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(e,this.width,this.height,4)}putAlpha(e){if(e.width!==this.width||e.height!==this.height)throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${e.width}x${e.height}`);if(e.channels!==1)throw new Error(`Expected mask to have 1 channel, but got ${e.channels}`);let r=this.data,s=e.data,n=this.width*this.height;if(this.channels===3){let o=new Uint8ClampedArray(n*4);for(let a=0,i=0,l=0;a<n;++a)o[l++]=r[i++],o[l++]=r[i++],o[l++]=r[i++],o[l++]=s[a];return this._update(o,this.width,this.height,4)}else if(this.channels===4){for(let o=0;o<n;++o)r[4*o+3]=s[o];return this}throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(e,r,{resample:s=2}={}){if(this.width===e&&this.height===r)return this;let n=hP[s]??s,o=gp(e),a=gp(r);if(o&&a)return this;if(o?e=r/this.height*this.width:a&&(r=e/this.width*this.height),Qt){let i=this.channels,l=this.toCanvas(),u=fs(e,r).getContext("2d");return u.drawImage(l,0,0,e,r),new t(u.getImageData(0,0,e,r).data,e,r,4).convert(i)}else{let i=this.toSharp();switch(n){case"box":case"hamming":(n==="box"||n==="hamming")&&(console.warn(`Resampling method ${n} is not yet supported. Using bilinear instead.`),n="bilinear");case"nearest":case"bilinear":case"bicubic":i=i.affine([e/this.width,0,0,r/this.height],{interpolator:n});break;case"lanczos":i=i.resize({width:e,height:r,fit:"fill",kernel:"lanczos3"});break;default:throw new Error(`Resampling method ${n} is not supported.`)}return await Or(i)}}async pad([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.max(s,0),n=Math.max(n,0),e===0&&r===0&&s===0&&n===0)return this;if(Qt){let o=this.channels,a=this.toCanvas(),i=this.width+e+r,l=this.height+s+n,u=fs(i,l).getContext("2d");return u.drawImage(a,0,0,this.width,this.height,e,s,this.width,this.height),new t(u.getImageData(0,0,i,l).data,i,l,4).convert(o)}else{let o=this.toSharp().extend({left:e,right:r,top:s,bottom:n});return await Or(o)}}async crop([e,r,s,n]){if(e=Math.max(e,0),r=Math.max(r,0),s=Math.min(s,this.width-1),n=Math.min(n,this.height-1),e===0&&r===0&&s===this.width-1&&n===this.height-1)return this;let o=s-e+1,a=n-r+1;if(Qt){let i=this.channels,l=this.toCanvas(),u=fs(o,a).getContext("2d");return u.drawImage(l,e,r,o,a,0,0,o,a),new t(u.getImageData(0,0,o,a).data,o,a,4).convert(i)}else{let i=this.toSharp().extract({left:e,top:r,width:o,height:a});return await Or(i)}}async center_crop(e,r){if(this.width===e&&this.height===r)return this;let s=(this.width-e)/2,n=(this.height-r)/2;if(Qt){let o=this.channels,a=this.toCanvas(),i=fs(e,r).getContext("2d"),l=0,u=0,d=0,f=0;return s>=0?l=s:d=-s,n>=0?u=n:f=-n,i.drawImage(a,l,u,e,r,d,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],u=0;s<0?(l[0]=Math.floor(-s),l[1]=e-this.width-l[0]):u=Math.floor(s),o=o.extend({top:a[0],bottom:a[1],left:l[0],right:l[1]}).extract({left:u,top:i,width:e,height:r})}return await Or(o)}}async toBlob(e="image/png",r=1){if(!Qt)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 U("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(!Qt)throw new Error("toCanvas() is only supported in browser environments.");let e=this.clone().rgba(),r=fs(e.width,e.height),s=new GE(e.data,e.width,e.height);return r.getContext("2d").putImageData(s,0,0),r}split(){let{data:e,width:r,height:s,channels:n}=this,o=e.constructor,a=e.length/n,i=Array.from({length:n},()=>new o(a));for(let l=0;l<a;++l){let u=n*l;for(let d=0;d<n;++d)i[d][l]=e[u+d]}return i.map(l=>new t(l,r,s,1))}_update(e,r,s,n=null){return this.data=e,this.width=r,this.height=s,n!==null&&(this.channels=n),this}clone(){return new t(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(Qt){if(be.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");let r=e.split(".").pop().toLowerCase(),s=_P.get(r)??"image/png",n=await this.toBlob(s);return ll(e,n)}else if(be.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(Qt)throw new Error("toSharp() is only supported in server-side environments.");return zf(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},gP=Xe.read.bind(Xe);function qE(t,e,r=0,s=null){let n=t/e,o=Hv(n)*e;return s!==null&&o>s&&(o=Math.floor(n)*e),o<r&&(o=Math.ceil(n)*e),o}function Lf([t,e],r){return[Math.max(Math.floor(t/r),1)*r,Math.max(Math.floor(e/r),1)*r]}function Nf([t,e,r,s]){return[t-r/2,e-s/2,t+r/2,e+s/2]}function Ir(t,e=.5,r=null,s=!1){let n=t.logits,o=t.pred_boxes,[a,i,l]=n.dims;if(r!==null&&r.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let d=0;d<a;++d){let f=r!==null?r[d]:null,m={boxes:[],classes:[],scores:[]},_=n[d],w=o[d];for(let x=0;x<i;++x){let k=_[x],E=[],M;if(s){M=k.sigmoid().data;for(let I=0;I<M.length;++I)M[I]>e&&E.push(I)}else{let I=Te(k.data)[1];if(I===l-1||(M=Pe(k.data),M[I]<e))continue;E.push(I)}for(let I of E){let T=w[x].data;T=Nf(T),f!==null&&(T=T.map((z,C)=>z*f[(C+1)%2])),m.boxes.push(T),m.classes.push(I),m.scores.push(M[I])}}u.push(m)}return u}function ul(t,e=null){let r=t.logits,s=r.dims[0];if(e!==null&&e.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let n=[];for(let o=0;o<s;++o){let a=e!==null?e[o]:null,i=r[o];a!==null&&(i=xd(i,a,"bilinear",!1));let[l,u]=a??i.dims.slice(-2),d=new U("int32",new Int32Array(l*u),[l,u]),f=i[0].data,m=d.data;for(let x=1;x<i.dims[0];++x){let k=i[x].data;for(let E=0;E<k.length;++E)k[E]>f[E]&&(f[E]=k[E],m[E]=x)}let _=new Array(i.dims[0]);for(let x=0;x<m.length;++x){let k=m[x];_[k]=k}let w=_.filter(x=>x!==void 0);n.push({segmentation:d,labels:w})}return n}function wP(t,e,r,s){let n=[],o=[],a=[];for(let i=0;i<t.dims[0];++i){let l=t[i],u=e[i],d=Te(l.data)[1];if(d===s)continue;let m=Pe(l.data)[d];m>r&&(n.push(u),o.push(m),a.push(d))}return[n,o,a]}function xP(t,e,r,s=.5,n=.8){let o=[],a=0,i=0,l=e[r].data;for(let d=0;d<t.length;++d)t[d]===r&&(o.push(d),++a),l[d]>=s&&++i;let u=a>0&&i>0;return u&&(u=a/i>n),[u,o]}function yP(t,e,r,s,n,o=null,a=null){let[i,l]=a??t[0].dims,u=new U("int32",new Int32Array(i*l),[i,l]),d=[];if(a!==null)for(let x=0;x<t.length;++x)t[x]=xd(t[x],a,"bilinear",!1);let f=new Int32Array(t[0].data.length),m=new Float32Array(t[0].data.length);for(let x=0;x<t.length;++x){let k=e[x],E=t[x].data;for(let M=0;M<E.length;++M)E[M]*=k,E[M]>m[M]&&(f[M]=x,m[M]=E[M])}let _=0,w=u.data;for(let x=0;x<r.length;++x){let k=r[x],[E,M]=xP(f,t,x,s,n);if(E){++_;for(let I of M)w[I]=_;d.push({id:_,label_id:k,score:e[x]})}}return[u,d]}function bP(t,e,r=28,s=3136,n=784*1280){if(t<r||e<r)throw new Error(`height:${t} or width:${e} must be larger than factor:${r}`);if(Math.max(t,e)/Math.min(t,e)>200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(t,e)/Math.min(t,e)}`);let o=Math.round(t/r)*r,a=Math.round(e/r)*r;if(o*a>n){let i=Math.sqrt(t*e/n);o=Math.floor(t/i/r)*r,a=Math.floor(e/i/r)*r}else if(o*a<s){let i=Math.sqrt(s/(t*e));o=Math.ceil(t*i/r)*r,a=Math.ceil(e*i/r)*r}return[o,a]}function pl(t,e=.5,r=.5,s=.8,n=null,o=null){n===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),n=new Set);let a=t.class_queries_logits??t.logits,l=(t.masks_queries_logits??t.pred_masks).sigmoid(),[u,d,f]=a.dims;if(f-=1,o!==null&&o.length!==u)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let m=[];for(let _=0;_<u;++_){let w=o!==null?o[_]:null,x=a[_],k=l[_],[E,M,I]=wP(x,k,e,f);if(I.length===0){let[C,v]=w??k.dims.slice(-2),G=new U("int32",new Int32Array(C*v).fill(-1),[C,v]);m.push({segmentation:G,segments_info:[]});continue}let[T,z]=yP(E,M,I,r,s,n,w);m.push({segmentation:T,segments_info:z})}return m}function dl(t,e=.5,r=null){throw new Error("`post_process_instance_segmentation` is not yet implemented.")}var W=class extends Je{constructor(e){super(),this.image_mean=e.image_mean??e.mean,this.image_std=e.image_std??e.std,this.resample=e.resample??2,this.do_rescale=e.do_rescale??!0,this.rescale_factor=e.rescale_factor??1/255,this.do_normalize=e.do_normalize,this.do_thumbnail=e.do_thumbnail,this.size=e.size??e.image_size,this.do_resize=e.do_resize??this.size!==void 0,this.size_divisibility=e.size_divisibility??e.size_divisor,this.do_center_crop=e.do_center_crop,this.crop_size=e.crop_size,this.do_convert_rgb=e.do_convert_rgb??!0,this.do_crop_margin=e.do_crop_margin,this.pad_size=e.pad_size,this.do_pad=e.do_pad,this.min_pixels=e.min_pixels,this.max_pixels=e.max_pixels,this.do_pad&&!this.pad_size&&this.size&&this.size.width!==void 0&&this.size.height!==void 0&&(this.pad_size=this.size),this.do_flip_channel_order=e.do_flip_channel_order??!1,this.config=e}async thumbnail(e,r,s=2){let n=e.height,o=e.width,a=r.height,i=r.width,l=Math.min(n,a),u=Math.min(o,i);return l===n&&u===o?e:(n>o?u=Math.floor(o*l/n):o>n&&(l=Math.floor(n*u/o)),await e.resize(u,l,{resample:s}))}async crop_margin(e,r=200){let s=e.clone().grayscale(),n=Dn(s.data)[0],a=Te(s.data)[0]-n;if(a===0)return e;let i=r/255,l=s.width,u=s.height,d=0,f=0,m=s.data;for(let _=0;_<s.height;++_){let w=_*s.width;for(let x=0;x<s.width;++x)(m[w+x]-n)/a<i&&(l=Math.min(l,x),u=Math.min(u,_),d=Math.max(d,x),f=Math.max(f,_))}return e=await e.crop([l,u,d,f]),e}pad_image(e,r,s,{mode:n="constant",center:o=!1,constant_values:a=0}={}){let[i,l,u]=r,d,f;if(typeof s=="number"?(d=s,f=s):s==="square"?d=f=Math.max(i,l):(d=s.width,f=s.height),d!==l||f!==i){let m=new Float32Array(d*f*u);if(Array.isArray(a))for(let x=0;x<m.length;++x)m[x]=a[x%u];else a!==0&&m.fill(a);let[_,w]=o?[Math.floor((d-l)/2),Math.floor((f-i)/2)]:[0,0];for(let x=0;x<i;++x){let k=(x+w)*d,E=x*l;for(let M=0;M<l;++M){let I=(k+M+_)*u,T=(E+M)*u;for(let z=0;z<u;++z)m[I+z]=e[T+z]}}if(n==="symmetric"){if(o)throw new Error("`center` padding is not supported when `mode` is set to `symmetric`.");let x=i-1,k=l-1;for(let E=0;E<f;++E){let M=E*d,I=$s(E,x)*l;for(let T=0;T<d;++T){if(E<i&&T<l)continue;let z=(M+T)*u,C=(I+$s(T,k))*u;for(let v=0;v<u;++v)m[z+v]=e[C+v]}}}e=m,r=[f,d,u]}return[e,r]}rescale(e){for(let r=0;r<e.length;++r)e[r]=this.rescale_factor*e[r]}get_resize_output_image_size(e,r){let[s,n]=e.size,o,a;if(this.do_thumbnail){let{height:i,width:l}=r;o=Math.min(i,l)}else Number.isInteger(r)?(o=r,a=this.config.max_size??o):r!==void 0&&(o=r.shortest_edge,a=r.longest_edge);if(o!==void 0||a!==void 0){let i=o===void 0?1:Math.max(o/s,o/n),l=s*i,u=n*i,d=a===void 0?1:Math.min(a/l,a/u),f=Math.floor(Number((l*d).toFixed(2))),m=Math.floor(Number((u*d).toFixed(2)));return this.size_divisibility!==void 0&&([f,m]=Lf([f,m],this.size_divisibility)),[f,m]}else if(r!==void 0&&r.width!==void 0&&r.height!==void 0){let i=r.width,l=r.height;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let u=l/n,d=i/s;Math.abs(1-d)<Math.abs(1-u)?u=d:d=u,l=qE(u*n,this.config.ensure_multiple_of),i=qE(d*s,this.config.ensure_multiple_of)}return[i,l]}else{if(this.size_divisibility!==void 0)return Lf([s,n],this.size_divisibility);if(this.min_pixels!==void 0&&this.max_pixels!==void 0){let i=this.config.patch_size*this.config.merge_size;return bP(n,s,i,this.min_pixels,this.max_pixels)}else throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(r)}`)}}async resize(e){let[r,s]=this.get_resize_output_image_size(e,this.size);return await e.resize(r,s,{resample:this.resample})}async preprocess(e,{do_normalize:r=null,do_pad:s=null,do_convert_rgb:n=null,do_convert_grayscale:o=null,do_flip_channel_order:a=null}={}){this.do_crop_margin&&(e=await this.crop_margin(e));let[i,l]=e.size;if(n??this.do_convert_rgb?e=e.rgb():o&&(e=e.grayscale()),this.do_resize&&(e=await this.resize(e)),this.do_thumbnail&&(e=await this.thumbnail(e,this.size,this.resample)),this.do_center_crop){let _,w;Number.isInteger(this.crop_size)?(_=this.crop_size,w=this.crop_size):(_=this.crop_size.width,w=this.crop_size.height),e=await e.center_crop(_,w)}let u=[e.height,e.width],d=Float32Array.from(e.data),f=[e.height,e.width,e.channels];if(this.do_rescale&&this.rescale(d),r??this.do_normalize){let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(e.channels).fill(_));let w=this.image_std;if(Array.isArray(this.image_std)||(w=new Array(e.channels).fill(w)),_.length!==e.channels||w.length!==e.channels)throw new Error(`When set to arrays, the length of \`image_mean\` (${_.length}) and \`image_std\` (${w.length}) must match the number of channels in the image (${e.channels}).`);for(let x=0;x<d.length;x+=e.channels)for(let k=0;k<e.channels;++k)d[x+k]=(d[x+k]-_[k])/w[k]}if(s??this.do_pad){if(this.pad_size)[d,f]=this.pad_image(d,[e.height,e.width,e.channels],this.pad_size);else if(this.size_divisibility){let[_,w]=Lf([f[1],f[0]],this.size_divisibility);[d,f]=this.pad_image(d,f,{width:_,height:w})}}if(a??this.do_flip_channel_order){if(f[2]!==3)throw new Error("Flipping channel order is only supported for RGB images.");for(let _=0;_<d.length;_+=3){let w=d[_];d[_]=d[_+2],d[_+2]=w}}let m=new U("float32",d,f).permute(2,0,1);return{original_size:[l,i],reshaped_input_size:u,pixel_values:m}}async _call(e,...r){Array.isArray(e)||(e=[e]);let s=await Promise.all(e.map(o=>this.preprocess(o)));return{pixel_values:Ft(s.map(o=>o.pixel_values),0),original_sizes:s.map(o=>o.original_size),reshaped_input_sizes:s.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,r={}){let s=await at(e,Xs,!0,r);return new this(s)}};var Zs={};Ps(Zs,{BeitFeatureExtractor:()=>$f,BitImageProcessor:()=>Rf,CLIPFeatureExtractor:()=>Bf,CLIPImageProcessor:()=>fl,ChineseCLIPFeatureExtractor:()=>Uf,ConvNextFeatureExtractor:()=>Df,ConvNextImageProcessor:()=>ml,DINOv3ViTImageProcessor:()=>Gf,DPTFeatureExtractor:()=>Wf,DPTImageProcessor:()=>gl,DeiTFeatureExtractor:()=>Ff,DeiTImageProcessor:()=>hl,DetrFeatureExtractor:()=>jf,DetrImageProcessor:()=>_l,DonutFeatureExtractor:()=>qf,DonutImageProcessor:()=>Ks,EfficientNetImageProcessor:()=>Vf,GLPNFeatureExtractor:()=>Hf,GroundingDinoImageProcessor:()=>Xf,Idefics3ImageProcessor:()=>wl,ImageFeatureExtractor:()=>W,ImageProcessor:()=>W,JinaCLIPImageProcessor:()=>Yf,LlavaOnevisionImageProcessor:()=>Qf,Mask2FormerImageProcessor:()=>Zf,MaskFormerFeatureExtractor:()=>Jf,MaskFormerImageProcessor:()=>Ys,MobileNetV1FeatureExtractor:()=>em,MobileNetV1ImageProcessor:()=>xl,MobileNetV2FeatureExtractor:()=>tm,MobileNetV2ImageProcessor:()=>yl,MobileNetV3FeatureExtractor:()=>rm,MobileNetV3ImageProcessor:()=>bl,MobileNetV4FeatureExtractor:()=>sm,MobileNetV4ImageProcessor:()=>vl,MobileViTFeatureExtractor:()=>nm,MobileViTImageProcessor:()=>kl,NougatImageProcessor:()=>om,OwlViTFeatureExtractor:()=>am,OwlViTImageProcessor:()=>Qs,Owlv2ImageProcessor:()=>im,Phi3VImageProcessor:()=>um,PixtralImageProcessor:()=>pm,PvtImageProcessor:()=>dm,Qwen2VLImageProcessor:()=>fm,RTDetrImageProcessor:()=>mm,Sam2ImageProcessor:()=>ao,Sam3ImageProcessor:()=>ao,SamImageProcessor:()=>ao,SapiensFeatureExtractor:()=>hm,SapiensImageProcessor:()=>El,SegformerFeatureExtractor:()=>_m,SegformerImageProcessor:()=>Al,SiglipImageProcessor:()=>gm,SmolVLMImageProcessor:()=>wl,Swin2SRImageProcessor:()=>wm,VLMImageProcessor:()=>Kf,ViTFeatureExtractor:()=>xm,ViTImageProcessor:()=>Ml,VitMatteImageProcessor:()=>ym,VitPoseImageProcessor:()=>bm,YolosFeatureExtractor:()=>vm,YolosImageProcessor:()=>Tl});var $f=class extends W{};var Rf=class extends W{};var Uf=class extends W{};var fl=class extends W{},Bf=class extends fl{};var ml=class extends W{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}},Df=class extends ml{};var hl=class extends W{},Ff=class extends hl{};var _l=class extends W{async _call(e){let r=await super._call(e),s=[r.pixel_values.dims[0],64,64],n=Ve(s,1n);return{...r,pixel_mask:n}}post_process_object_detection(...e){return Ir(...e)}post_process_panoptic_segmentation(...e){return pl(...e)}post_process_instance_segmentation(...e){return dl(...e)}},jf=class extends _l{};var Gf=class extends W{};var Ks=class extends W{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 u=this.image_std;Array.isArray(u)||(u=new Array(i).fill(l));let d=l.map((f,m)=>-f/u[m]);return super.pad_image(e,r,s,{center:!0,constant_values:d,...n})}},qf=class extends Ks{};var gl=class extends W{},Wf=class extends gl{};var Vf=class extends W{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 Hf=class extends W{};var Xf=class extends W{async _call(e){let r=await super._call(e),s=r.pixel_values.dims,n=it([s[0],s[2],s[3]]);return{...r,pixel_mask:n}}};var wl=class extends W{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=[],u=[];for(let E of n){let M=await Promise.all(E.map(z=>this.preprocess(z)));l.push(...M.map(z=>z.original_size)),u.push(...M.map(z=>z.reshaped_input_size)),M.forEach(z=>z.pixel_values.unsqueeze_(0));let{longest_edge:I}=this.max_image_size,T;if(r??this.do_image_splitting){let z=new Array(M.length),C=new Array(M.length);T=await Promise.all(M.map(async(v,G)=>{let X=this.get_resize_for_vision_encoder(v.pixel_values,I),V=await Dt(v.pixel_values,{size:[X.height,X.width]}),{frames:Q,num_splits_h:K,num_splits_w:Y}=await this.split_image(V,this.max_image_size);return z[G]=K,C[G]=Y,Ee(Q,0)})),a.push(z),i.push(C)}else{let z=[I,I];T=await Promise.all(M.map(C=>Dt(C.pixel_values,{size:z}))),a.push(new Array(M.length).fill(0)),i.push(new Array(M.length).fill(0))}o.push(Ee(T,0))}let d=o.length,[f,m,_,w]=o[0].dims,x,k;if(d===1)x=o[0].unsqueeze_(0),k=Ve([d,f,_,w],!0);else{let E=Math.max(...o.map(T=>T.dims.at(0)));k=Ve([d,E,_,w],!0);let M=k.data,I=E*_*w;for(let T=0;T<d;++T){let z=o[T].dims[0];if(z<E){o[T]=Ee([o[T],Ve([E-z,m,_,w],0)],0);let C=T*I+z*_*w,v=(T+1)*I;M.fill(!1,C,v)}}x=Ft(o,0)}return{pixel_values:x,pixel_attention_mask:k,original_sizes:l,reshaped_input_sizes:u,...s?{rows:a,cols:i}:{}}}async split_image(e,{longest_edge:r}){let s=r,n=r,o=[],[a,i]=e.dims.slice(-2),l=0,u=0;if(a>s||i>n){l=Math.ceil(a/s),u=Math.ceil(i/n);let d=Math.ceil(a/l),f=Math.ceil(i/u);for(let w=0;w<l;++w)for(let x=0;x<u;++x){let k,E,M,I;w===l-1?(E=a-d,I=a):(E=w*d,I=(w+1)*d),x===u-1?(k=i-f,M=i):(k=x*f,M=(x+1)*f);let C=await ol(e,[E,k],[I,M],[2,3]);o.push(C)}let m=s,_=n;(a!==m||i!==_)&&(e=await Dt(e,{size:[m,_]}))}return o.push(e),{frames:o,num_splits_h:l,num_splits_w:u}}};var Kf=class extends W{constructor(e){super({do_pad:!0,pad_size:{width:e.image_size,height:e.image_size},...e}),this.constant_values=this.config.background_color.map(r=>r*this.rescale_factor)}pad_image(e,r,s,n){return super.pad_image(e,r,s,{constant_values:this.constant_values,center:!0,...n})}};var Yf=class extends W{constructor(e){let{resize_mode:r,fill_color:s,interpolation:n,size:o,...a}=e,i=r==="squash"?{width:o,height:o}:r==="shortest"?{shortest_edge:o}:{longest_edge:o},l=n==="bicubic"?3:2;super({...a,size:i,resample:l,do_center_crop:!0,crop_size:o,do_normalize:!0})}};var Qf=class extends W{};var Ys=class extends W{post_process_panoptic_segmentation(...e){return pl(...e)}post_process_instance_segmentation(...e){return dl(...e)}},Jf=class extends Ys{};var Zf=class extends Ys{};var xl=class extends W{},em=class extends xl{};var yl=class extends W{},tm=class extends yl{};var bl=class extends W{},rm=class extends bl{};var vl=class extends W{},sm=class extends vl{};var kl=class extends W{},nm=class extends kl{};var om=class extends Ks{};var Qs=class extends W{post_process_object_detection(...e){return Ir(...e)}},am=class extends Qs{};var im=class extends Qs{};var Pt=336,vP=[2,3],{ceil:lm,floor:Js,sqrt:cm}=Math,um=class extends W{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 Js((Js(r/Pt)*Js(e/Pt)+1)*s+1+(Js(r/Pt)+1)*cm(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),u=Math.floor(l/a);return[l,u]}pad_image(e,r,s,n={}){let[o,a]=r,i=Pt*lm(o/Pt),l=Pt*lm(a/Pt),u=[1,1,1].map((d,f)=>(d-this.image_mean[f])/this.image_std[f]);return super.pad_image(e,r,{width:l,height:i},{center:!0,constant_values:u,...n})}async _call(e,{num_crops:r=null}={}){if(this._num_crops=r??=this.config.num_crops,r<4||cm(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 Dt(m,{size:[Pt,Pt],mode:"bicubic"});if(r>0){let k=[],E=cm(r),M=Js(w/E),I=Js(_/E);for(let z=0;z<E;++z)for(let C=0;C<E;++C){let v,G,X,V;z===E-1?(G=_-I,V=_):(G=z*I,V=(z+1)*I),C===E-1?(v=w-M,X=w):(v=C*M,X=(C+1)*M);let Y=await ol(m,[G,v],[V,X],vP);k.push(Y)}let T=await Dt(Ee(k,0),{size:[Pt,Pt],mode:"bicubic"});i.push(Ee([x,T],0))}else i.push(x)}let l=Ft(i,0),u=a.map(m=>m.map(_=>Pt*lm(_/Pt))),d=new U("int64",u.flat(),[s,2]),f=u.map(([m,_])=>this.calc_num_image_tokens_from_image_size(_,m));return{pixel_values:l,original_sizes:o,reshaped_input_sizes:a,image_sizes:d,num_img_tokens:f}}};var pm=class extends W{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:u,spatial_merge_size:d}=this.config;if(!d)throw new Error("config must contain 'spatial_merge_size'");let f=u*d,m=Math.floor((i-1)/f)+1,_=Math.floor((l-1)/f)+1;return[m*f,_*f]}};var dm=class extends W{};var fm=class extends W{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:u}=this.config;a.dims[0]===1&&(a=Ee(Array.from({length:i},()=>a),0));let d=a.dims[0]/i,f=a.dims[1],m=Math.floor(a.dims[2]/u),_=Math.floor(a.dims[3]/u),w=a.view(d,i,f,Math.floor(m/l),l,u,Math.floor(_/l),l,u).permute(0,3,6,4,7,2,1,5,8).view(d*m*_,f*i*u*u),x=new U("int64",[d,m,_],[1,3]);return{pixel_values:w,image_grid_thw:x,original_sizes:n,reshaped_input_sizes:o}}};var mm=class extends W{post_process_object_detection(...e){return Ir(...e)}};var ao=class extends W{reshape_input_points(e,r,s,n=!1){e=structuredClone(e);let o=wp(e);if(o.length===3)n||(o=[1,...o]),e=[e];else if(o.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let a=0;a<e.length;++a){let[i,l]=r[a],[u,d]=s[a],f=[d/l,u/i];for(let m=0;m<e[a].length;++m)for(let _=0;_<e[a][m].length;++_)for(let w=0;w<e[a][m][_].length;++w)e[a][m][_][w]*=f[w%2]}return new U("float32",Float32Array.from(e.flat(1/0)),o)}add_input_labels(e,r){let s=wp(e);if(s.length===2)s=[1,...s],e=[e];else if(s.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(s.some((n,o)=>n!==r.dims[o]))throw Error(`The first ${s.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new U("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 u=0;u<r.length;++u){let d=r[u],f=s[u],m=await Dt(e[u],{mode:"bilinear",size:l});if(m=m.slice(null,null,[0,f[0]],[0,f[1]]),m=await Dt(m,{mode:"bilinear",size:d}),o){let _=m.data,w=new Uint8Array(_.length);for(let x=0;x<_.length;++x)_[x]>n&&(w[x]=1);m=new U("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 El=class extends W{post_process_semantic_segmentation(...e){return ul(...e)}},hm=class extends El{};var Al=class extends W{post_process_semantic_segmentation(...e){return ul(...e)}},_m=class extends Al{};var gm=class extends W{};var wm=class extends W{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 Ml=class extends W{},xm=class extends Ml{};var ym=class extends W{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:Ft(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 bm=class extends W{post_process_pose_estimation(e,r,{threshold:s=null}={}){let n=e.tolist(),[o,a,i,l]=e.dims,u=[];for(let d=0;d<o;++d){let f=n[d],m=r[d],_=[];for(let w=0;w<m.length;++w){let x=m[w],k=[],E=[],M=[],I=x.at(-2)/l,T=x.at(-1)/i;for(let z=0;z<f.length;++z){let[C,v]=[0,0],G=0,X=-1/0,V=f[z];for(let K=0;K<V.length;++K){let Y=V[K];for(let B=0;B<Y.length;++B){let P=Y[B];G+=P,X=Math.max(X,P),C+=(B+.5)*P,v+=K*P}}if(s!=null&&X<s)continue;let Q=[I*C/G,T*v/G];k.push(Q),M.push(z),E.push(X)}_.push({bbox:x,scores:E,labels:M,keypoints:k})}u.push(_)}return u}};var Tl=class extends W{post_process_object_detection(...e){return Ir(...e)}},vm=class extends Tl{};var $e=class{static async from_pretrained(e,r={}){let s=await at(e,Xs,!0,r),n=s.image_processor_type??s.feature_extractor_type,o=Zs[n?.replace(/Fast$/,"")];return o||(n!==void 0&&console.warn(`Image processor type '${n}' not found, assuming base ImageProcessor. Please report this at ${Hs}.`),o=W),new o(s)}};var km=class extends ne{static tokenizer_class=J;static image_processor_class=$e;constructor(e,r,s){super(e,r,s);let{tasks_answer_post_processing_type:n,task_prompts_without_inputs:o,task_prompts_with_input:a}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(n??{})),this.task_prompts_without_inputs=new Map(Object.entries(o??{})),this.task_prompts_with_input=new Map(Object.entries(a??{})),this.regexes={quad_boxes:/(.+?)<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm,bboxes:/([^<]+)?<loc_(\d+)><loc_(\d+)><loc_(\d+)><loc_(\d+)>/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);let r=[];for(let s of e)if(this.task_prompts_without_inputs.has(s))r.push(this.task_prompts_without_inputs.get(s));else{for(let[n,o]of this.task_prompts_with_input)if(s.includes(n)){r.push(o.replaceAll("{input}",s).replaceAll(n,""));break}r.length!==e.length&&r.push(s)}return r}post_process_generation(e,r,s){let n=this.tasks_answer_post_processing_type.get(r)??"pure_text";e=e.replaceAll("<s>","").replaceAll("</s>","");let o;switch(n){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let a=n==="ocr"?"quad_boxes":"bboxes",i=e.matchAll(this.regexes[a]),l=[],u=[];for(let[d,f,...m]of i)l.push(f?f.trim():l.at(-1)??""),u.push(m.map((_,w)=>(Number(_)+.5)/this.size_per_bin*s[w%2]));o={labels:l,[a]:u};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 Em=class extends ne{static image_processor_class=$e;static feature_extractor_class=tt;static tokenizer_class=J;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,r,s){super(e,r,s),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:n,boa_token:o,audio_token:a,eoa_token:i,image_token_id:l,boi_token:u,image_token:d,eoi_token:f}=this.tokenizer.config;this.audio_token_id=n,this.boa_token=o,this.audio_token=a;let m=a.repeat(this.audio_seq_length);this.full_audio_sequence=`
|
|
16
16
|
|
|
17
17
|
${o}${m}${i}
|
|
18
18
|
|