diff --git "a/dist/assets/index-C0ilSO9I.js" "b/dist/assets/index-C0ilSO9I.js" new file mode 100644--- /dev/null +++ "b/dist/assets/index-C0ilSO9I.js" @@ -0,0 +1,154 @@ +var dE=Object.defineProperty;var fE=(e,n,r)=>n in e?dE(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var L=(e,n,r)=>fE(e,typeof n!="symbol"?n+"":n,r);(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const c of o)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&s(u)}).observe(document,{childList:!0,subtree:!0});function r(o){const c={};return o.integrity&&(c.integrity=o.integrity),o.referrerPolicy&&(c.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?c.credentials="include":o.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function s(o){if(o.ep)return;o.ep=!0;const c=r(o);fetch(o.href,c)}})();var jm={exports:{}},vu={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ub;function hE(){if(ub)return vu;ub=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(s,o,c){var u=null;if(c!==void 0&&(u=""+c),o.key!==void 0&&(u=""+o.key),"key"in o){c={};for(var d in o)d!=="key"&&(c[d]=o[d])}else c=o;return o=c.ref,{$$typeof:e,type:s,key:u,ref:o!==void 0?o:null,props:c}}return vu.Fragment=n,vu.jsx=r,vu.jsxs=r,vu}var db;function pE(){return db||(db=1,jm.exports=hE()),jm.exports}var _e=pE(),Vm={exports:{}},je={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var fb;function mE(){if(fb)return je;fb=1;var e=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),w=Symbol.iterator;function b(F){return F===null||typeof F!="object"?null:(F=w&&F[w]||F["@@iterator"],typeof F=="function"?F:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,O={};function z(F,H,ue){this.props=F,this.context=H,this.refs=O,this.updater=ue||S}z.prototype.isReactComponent={},z.prototype.setState=function(F,H){if(typeof F!="object"&&typeof F!="function"&&F!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,F,H,"setState")},z.prototype.forceUpdate=function(F){this.updater.enqueueForceUpdate(this,F,"forceUpdate")};function D(){}D.prototype=z.prototype;function P(F,H,ue){this.props=F,this.context=H,this.refs=O,this.updater=ue||S}var j=P.prototype=new D;j.constructor=P,E(j,z.prototype),j.isPureReactComponent=!0;var G=Array.isArray;function K(){}var k={H:null,A:null,T:null,S:null},ce=Object.prototype.hasOwnProperty;function oe(F,H,ue){var de=ue.ref;return{$$typeof:e,type:F,key:H,ref:de!==void 0?de:null,props:ue}}function he(F,H){return oe(F.type,H,F.props)}function me(F){return typeof F=="object"&&F!==null&&F.$$typeof===e}function pe(F){var H={"=":"=0",":":"=2"};return"$"+F.replace(/[=:]/g,function(ue){return H[ue]})}var ne=/\/+/g;function ee(F,H){return typeof F=="object"&&F!==null&&F.key!=null?pe(""+F.key):H.toString(36)}function Me(F){switch(F.status){case"fulfilled":return F.value;case"rejected":throw F.reason;default:switch(typeof F.status=="string"?F.then(K,K):(F.status="pending",F.then(function(H){F.status==="pending"&&(F.status="fulfilled",F.value=H)},function(H){F.status==="pending"&&(F.status="rejected",F.reason=H)})),F.status){case"fulfilled":return F.value;case"rejected":throw F.reason}}throw F}function V(F,H,ue,de,be){var Oe=typeof F;(Oe==="undefined"||Oe==="boolean")&&(F=null);var Ne=!1;if(F===null)Ne=!0;else switch(Oe){case"bigint":case"string":case"number":Ne=!0;break;case"object":switch(F.$$typeof){case e:case n:Ne=!0;break;case g:return Ne=F._init,V(Ne(F._payload),H,ue,de,be)}}if(Ne)return be=be(F),Ne=de===""?"."+ee(F,0):de,G(be)?(ue="",Ne!=null&&(ue=Ne.replace(ne,"$&/")+"/"),V(be,H,ue,"",function(ht){return ht})):be!=null&&(me(be)&&(be=he(be,ue+(be.key==null||F&&F.key===be.key?"":(""+be.key).replace(ne,"$&/")+"/")+Ne)),H.push(be)),1;Ne=0;var at=de===""?".":de+":";if(G(F))for(var Qe=0;Qe>>1,te=V[R];if(0>>1;Ro(ue,I))deo(be,ue)?(V[R]=be,V[de]=I,R=de):(V[R]=ue,V[H]=I,R=H);else if(deo(be,I))V[R]=be,V[de]=I,R=de;else break e}}return W}function o(V,W){var I=V.sortIndex-W.sortIndex;return I!==0?I:V.id-W.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var c=performance;e.unstable_now=function(){return c.now()}}else{var u=Date,d=u.now();e.unstable_now=function(){return u.now()-d}}var h=[],p=[],g=1,y=null,w=3,b=!1,S=!1,E=!1,O=!1,z=typeof setTimeout=="function"?setTimeout:null,D=typeof clearTimeout=="function"?clearTimeout:null,P=typeof setImmediate<"u"?setImmediate:null;function j(V){for(var W=r(p);W!==null;){if(W.callback===null)s(p);else if(W.startTime<=V)s(p),W.sortIndex=W.expirationTime,n(h,W);else break;W=r(p)}}function G(V){if(E=!1,j(V),!S)if(r(h)!==null)S=!0,K||(K=!0,pe());else{var W=r(p);W!==null&&Me(G,W.startTime-V)}}var K=!1,k=-1,ce=5,oe=-1;function he(){return O?!0:!(e.unstable_now()-oeV&&he());){var R=y.callback;if(typeof R=="function"){y.callback=null,w=y.priorityLevel;var te=R(y.expirationTime<=V);if(V=e.unstable_now(),typeof te=="function"){y.callback=te,j(V),W=!0;break t}y===r(h)&&s(h),j(V)}else s(h);y=r(h)}if(y!==null)W=!0;else{var F=r(p);F!==null&&Me(G,F.startTime-V),W=!1}}break e}finally{y=null,w=I,b=!1}W=void 0}}finally{W?pe():K=!1}}}var pe;if(typeof P=="function")pe=function(){P(me)};else if(typeof MessageChannel<"u"){var ne=new MessageChannel,ee=ne.port2;ne.port1.onmessage=me,pe=function(){ee.postMessage(null)}}else pe=function(){z(me,0)};function Me(V,W){k=z(function(){V(e.unstable_now())},W)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(V){V.callback=null},e.unstable_forceFrameRate=function(V){0>V||125R?(V.sortIndex=I,n(p,V),r(h)===null&&V===r(p)&&(E?(D(k),k=-1):E=!0,Me(G,I-R))):(V.sortIndex=te,n(h,V),S||b||(S=!0,K||(K=!0,pe()))),V},e.unstable_shouldYield=he,e.unstable_wrapCallback=function(V){var W=w;return function(){var I=w;w=W;try{return V.apply(this,arguments)}finally{w=I}}}})(Hm)),Hm}var mb;function gE(){return mb||(mb=1,$m.exports=_E()),$m.exports}var Ym={exports:{}},An={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var _b;function vE(){if(_b)return An;_b=1;var e=bg();function n(h){var p="https://react.dev/errors/"+h;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(n){console.error(n)}}return e(),Ym.exports=vE(),Ym.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var vb;function wE(){if(vb)return yu;vb=1;var e=gE(),n=bg(),r=yE();function s(t){var a="https://react.dev/errors/"+t;if(1te||(t.current=R[te],R[te]=null,te--)}function ue(t,a){te++,R[te]=t.current,t.current=a}var de=F(null),be=F(null),Oe=F(null),Ne=F(null);function at(t,a){switch(ue(Oe,a),ue(be,t),ue(de,null),a.nodeType){case 9:case 11:t=(t=a.documentElement)&&(t=t.namespaceURI)?N0(t):0;break;default:if(t=a.tagName,a=a.namespaceURI)a=N0(a),t=D0(a,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}H(de),ue(de,t)}function Qe(){H(de),H(be),H(Oe)}function ht(t){t.memoizedState!==null&&ue(Ne,t);var a=de.current,i=D0(a,t.type);a!==i&&(ue(be,t),ue(de,i))}function Ct(t){be.current===t&&(H(de),H(be)),Ne.current===t&&(H(Ne),pu._currentValue=I)}var Ue,ze;function Ye(t){if(Ue===void 0)try{throw Error()}catch(i){var a=i.stack.trim().match(/\n( *(at )?)/);Ue=a&&a[1]||"",ze=-1)":-1f||B[l]!==Q[f]){var re=` +`+B[l].replace(" at new "," at ");return t.displayName&&re.includes("")&&(re=re.replace("",t.displayName)),re}while(1<=l&&0<=f);break}}}finally{Ht=!1,Error.prepareStackTrace=i}return(i=t?t.displayName||t.name:"")?Ye(i):""}function xt(t,a){switch(t.tag){case 26:case 27:case 5:return Ye(t.type);case 16:return Ye("Lazy");case 13:return t.child!==a&&a!==null?Ye("Suspense Fallback"):Ye("Suspense");case 19:return Ye("SuspenseList");case 0:case 15:return Rt(t.type,!1);case 11:return Rt(t.type.render,!1);case 1:return Rt(t.type,!0);case 31:return Ye("Activity");default:return""}}function _s(t){try{var a="",i=null;do a+=xt(t,i),i=t,t=t.return;while(t);return a}catch(l){return` +Error generating stack: `+l.message+` +`+l.stack}}var so=Object.prototype.hasOwnProperty,Ra=e.unstable_scheduleCallback,io=e.unstable_cancelCallback,ad=e.unstable_shouldYield,rd=e.unstable_requestPaint,Mn=e.unstable_now,cr=e.unstable_getCurrentPriorityLevel,sd=e.unstable_ImmediatePriority,di=e.unstable_UserBlockingPriority,Fr=e.unstable_NormalPriority,fn=e.unstable_LowPriority,id=e.unstable_IdlePriority,gs=e.log,Qh=e.unstable_setDisableYieldValue,vs=null,xn=null;function _a(t){if(typeof gs=="function"&&Qh(t),xn&&typeof xn.setStrictMode=="function")try{xn.setStrictMode(vs,t)}catch{}}var hn=Math.clz32?Math.clz32:Kh,Wh=Math.log,Zh=Math.LN2;function Kh(t){return t>>>=0,t===0?32:31-(Wh(t)/Zh|0)|0}var oo=256,lo=262144,co=4194304;function ur(t){var a=t&42;if(a!==0)return a;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function fi(t,a,i){var l=t.pendingLanes;if(l===0)return 0;var f=0,m=t.suspendedLanes,T=t.pingedLanes;t=t.warmLanes;var A=l&134217727;return A!==0?(l=A&~m,l!==0?f=ur(l):(T&=A,T!==0?f=ur(T):i||(i=A&~t,i!==0&&(f=ur(i))))):(A=l&~m,A!==0?f=ur(A):T!==0?f=ur(T):i||(i=l&~t,i!==0&&(f=ur(i)))),f===0?0:a!==0&&a!==f&&(a&m)===0&&(m=f&-f,i=a&-a,m>=i||m===32&&(i&4194048)!==0)?a:f}function hi(t,a){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&a)===0}function od(t,a){switch(t){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Vl(){var t=co;return co<<=1,(co&62914560)===0&&(co=4194304),t}function uo(t){for(var a=[],i=0;31>i;i++)a.push(t);return a}function ga(t,a){t.pendingLanes|=a,a!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function ld(t,a,i,l,f,m){var T=t.pendingLanes;t.pendingLanes=i,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=i,t.entangledLanes&=i,t.errorRecoveryDisabledLanes&=i,t.shellSuspendCounter=0;var A=t.entanglements,B=t.expirationTimes,Q=t.hiddenUpdates;for(i=T&~i;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var np=/[\n"\\]/g;function jn(t){return t.replace(np,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Wl(t,a,i,l,f,m,T,A){t.name="",T!=null&&typeof T!="function"&&typeof T!="symbol"&&typeof T!="boolean"?t.type=T:t.removeAttribute("type"),a!=null?T==="number"?(a===0&&t.value===""||t.value!=a)&&(t.value=""+Ut(a)):t.value!==""+Ut(a)&&(t.value=""+Ut(a)):T!=="submit"&&T!=="reset"||t.removeAttribute("value"),a!=null?Zl(t,T,Ut(a)):i!=null?Zl(t,T,Ut(i)):l!=null&&t.removeAttribute("value"),f==null&&m!=null&&(t.defaultChecked=!!m),f!=null&&(t.checked=f&&typeof f!="function"&&typeof f!="symbol"),A!=null&&typeof A!="function"&&typeof A!="symbol"&&typeof A!="boolean"?t.name=""+Ut(A):t.removeAttribute("name")}function fd(t,a,i,l,f,m,T,A){if(m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"&&(t.type=m),a!=null||i!=null){if(!(m!=="submit"&&m!=="reset"||a!=null)){yo(t);return}i=i!=null?""+Ut(i):"",a=a!=null?""+Ut(a):i,A||a===t.value||(t.value=a),t.defaultValue=a}l=l??f,l=typeof l!="function"&&typeof l!="symbol"&&!!l,t.checked=A?t.checked:!!l,t.defaultChecked=!!l,T!=null&&typeof T!="function"&&typeof T!="symbol"&&typeof T!="boolean"&&(t.name=T),yo(t)}function Zl(t,a,i){a==="number"&&wo(t.ownerDocument)===t||t.defaultValue===""+i||(t.defaultValue=""+i)}function ws(t,a,i,l){if(t=t.options,a){a={};for(var f=0;f"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),tc=!1;if(wa)try{var Ur={};Object.defineProperty(Ur,"passive",{get:function(){tc=!0}}),window.addEventListener("test",Ur,Ur),window.removeEventListener("test",Ur,Ur)}catch{tc=!1}var hr=null,xo=null,To=null;function So(){if(To)return To;var t,a=xo,i=a.length,l,f="value"in hr?hr.value:hr.textContent,m=f.length;for(t=0;t=bi),Mi=" ",cc=!1;function Td(t,a){switch(t){case"keyup":return Mp.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function xi(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ss=!1;function xp(t,a){switch(t){case"compositionend":return xi(a);case"keypress":return a.which!==32?null:(cc=!0,Mi);case"textInput":return t=a.data,t===Mi&&cc?null:t;default:return null}}function Ma(t,a){if(Ss)return t==="compositionend"||!oc&&Td(t,a)?(t=So(),To=xo=hr=null,Ss=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:i,offset:a-t};t=l}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=Ad(i)}}function kd(t,a){return t&&a?t===a?!0:t&&t.nodeType===3?!1:a&&a.nodeType===3?kd(t,a.parentNode):"contains"in t?t.contains(a):t.compareDocumentPosition?!!(t.compareDocumentPosition(a)&16):!1:!1}function Od(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var a=wo(t.document);a instanceof t.HTMLIFrameElement;){try{var i=typeof a.contentWindow.location.href=="string"}catch{i=!1}if(i)t=a.contentWindow;else break;a=wo(t.document)}return a}function pc(t){var a=t&&t.nodeName&&t.nodeName.toLowerCase();return a&&(a==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||a==="textarea"||t.contentEditable==="true")}var kp=wa&&"documentMode"in document&&11>=document.documentMode,Es=null,mc=null,Si=null,_c=!1;function zd(t,a,i){var l=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;_c||Es==null||Es!==wo(l)||(l=Es,"selectionStart"in l&&pc(l)?l={start:l.selectionStart,end:l.selectionEnd}:(l=(l.ownerDocument&&l.ownerDocument.defaultView||window).getSelection(),l={anchorNode:l.anchorNode,anchorOffset:l.anchorOffset,focusNode:l.focusNode,focusOffset:l.focusOffset}),Si&&Ti(Si,l)||(Si=l,l=_f(mc,"onSelect"),0>=T,f-=T,aa=1<<32-hn(a)+f|i<qe?(et=Se,Se=null):et=Se.sibling;var it=Z($,Se,X[qe],ie);if(it===null){Se===null&&(Se=et);break}t&&Se&&it.alternate===null&&a($,Se),U=m(it,U,qe),st===null?ke=it:st.sibling=it,st=it,Se=et}if(qe===X.length)return i($,Se),Xe&&Ea($,qe),ke;if(Se===null){for(;qeqe?(et=Se,Se=null):et=Se.sibling;var Zs=Z($,Se,it.value,ie);if(Zs===null){Se===null&&(Se=et);break}t&&Se&&Zs.alternate===null&&a($,Se),U=m(Zs,U,qe),st===null?ke=Zs:st.sibling=Zs,st=Zs,Se=et}if(it.done)return i($,Se),Xe&&Ea($,qe),ke;if(Se===null){for(;!it.done;qe++,it=X.next())it=le($,it.value,ie),it!==null&&(U=m(it,U,qe),st===null?ke=it:st.sibling=it,st=it);return Xe&&Ea($,qe),ke}for(Se=l(Se);!it.done;qe++,it=X.next())it=ae(Se,$,qe,it.value,ie),it!==null&&(t&&it.alternate!==null&&Se.delete(it.key===null?qe:it.key),U=m(it,U,qe),st===null?ke=it:st.sibling=it,st=it);return t&&Se.forEach(function(uE){return a($,uE)}),Xe&&Ea($,qe),ke}function wt($,U,X,ie){if(typeof X=="object"&&X!==null&&X.type===E&&X.key===null&&(X=X.props.children),typeof X=="object"&&X!==null){switch(X.$$typeof){case b:e:{for(var ke=X.key;U!==null;){if(U.key===ke){if(ke=X.type,ke===E){if(U.tag===7){i($,U.sibling),ie=f(U,X.props.children),ie.return=$,$=ie;break e}}else if(U.elementType===ke||typeof ke=="object"&&ke!==null&&ke.$$typeof===ce&&Mr(ke)===U.type){i($,U.sibling),ie=f(U,X.props),Ls(ie,X),ie.return=$,$=ie;break e}i($,U);break}else a($,U);U=U.sibling}X.type===E?(ie=qr(X.props.children,$.mode,ie,X.key),ie.return=$,$=ie):(ie=Fo(X.type,X.key,X.props,null,$.mode,ie),Ls(ie,X),ie.return=$,$=ie)}return T($);case S:e:{for(ke=X.key;U!==null;){if(U.key===ke)if(U.tag===4&&U.stateNode.containerInfo===X.containerInfo&&U.stateNode.implementation===X.implementation){i($,U.sibling),ie=f(U,X.children||[]),ie.return=$,$=ie;break e}else{i($,U);break}else a($,U);U=U.sibling}ie=Ec(X,$.mode,ie),ie.return=$,$=ie}return T($);case ce:return X=Mr(X),wt($,U,X,ie)}if(Me(X))return xe($,U,X,ie);if(pe(X)){if(ke=pe(X),typeof ke!="function")throw Error(s(150));return X=ke.call(X),Le($,U,X,ie)}if(typeof X.then=="function")return wt($,U,Oi(X),ie);if(X.$$typeof===P)return wt($,U,Ei($,X),ie);zi($,X)}return typeof X=="string"&&X!==""||typeof X=="number"||typeof X=="bigint"?(X=""+X,U!==null&&U.tag===6?(i($,U.sibling),ie=f(U,X),ie.return=$,$=ie):(i($,U),ie=Sc(X,$.mode,ie),ie.return=$,$=ie),T($)):i($,U)}return function($,U,X,ie){try{zs=0;var ke=wt($,U,X,ie);return Zr=null,ke}catch(Se){if(Se===Wr||Se===Ci)throw Se;var st=Dn(29,Se,null,$.mode);return st.lanes=ie,st.return=$,st}finally{}}}var Tr=Ic(!0),Gc=Ic(!1),Ya=!1;function Ho(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Yo(t,a){t=t.updateQueue,a.updateQueue===t&&(a.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Xa(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Qa(t,a,i){var l=t.updateQueue;if(l===null)return null;if(l=l.shared,(ct&2)!==0){var f=l.pending;return f===null?a.next=a:(a.next=f.next,f.next=a),l.pending=a,a=Do(t),Fd(t,null,i),a}return No(t,l,a,i),Do(t)}function Ns(t,a,i){if(a=a.updateQueue,a!==null&&(a=a.shared,(i&4194048)!==0)){var l=a.lanes;l&=t.pendingLanes,i|=l,a.lanes=i,$l(t,i)}}function ia(t,a){var i=t.updateQueue,l=t.alternate;if(l!==null&&(l=l.updateQueue,i===l)){var f=null,m=null;if(i=i.firstBaseUpdate,i!==null){do{var T={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};m===null?f=m=T:m=m.next=T,i=i.next}while(i!==null);m===null?f=m=a:m=m.next=a}else f=m=a;i={baseState:l.baseState,firstBaseUpdate:f,lastBaseUpdate:m,shared:l.shared,callbacks:l.callbacks},t.updateQueue=i;return}t=i.lastBaseUpdate,t===null?i.firstBaseUpdate=a:t.next=a,i.lastBaseUpdate=a}var jc=!1;function Kr(){if(jc){var t=Qr;if(t!==null)throw t}}function Li(t,a,i,l){jc=!1;var f=t.updateQueue;Ya=!1;var m=f.firstBaseUpdate,T=f.lastBaseUpdate,A=f.shared.pending;if(A!==null){f.shared.pending=null;var B=A,Q=B.next;B.next=null,T===null?m=Q:T.next=Q,T=B;var re=t.alternate;re!==null&&(re=re.updateQueue,A=re.lastBaseUpdate,A!==T&&(A===null?re.firstBaseUpdate=Q:A.next=Q,re.lastBaseUpdate=B))}if(m!==null){var le=f.baseState;T=0,re=Q=B=null,A=m;do{var Z=A.lane&-536870913,ae=Z!==A.lane;if(ae?(Je&Z)===Z:(l&Z)===Z){Z!==0&&Z===Xr&&(jc=!0),re!==null&&(re=re.next={lane:0,tag:A.tag,payload:A.payload,callback:null,next:null});e:{var xe=t,Le=A;Z=a;var wt=i;switch(Le.tag){case 1:if(xe=Le.payload,typeof xe=="function"){le=xe.call(wt,le,Z);break e}le=xe;break e;case 3:xe.flags=xe.flags&-65537|128;case 0:if(xe=Le.payload,Z=typeof xe=="function"?xe.call(wt,le,Z):xe,Z==null)break e;le=y({},le,Z);break e;case 2:Ya=!0}}Z=A.callback,Z!==null&&(t.flags|=64,ae&&(t.flags|=8192),ae=f.callbacks,ae===null?f.callbacks=[Z]:ae.push(Z))}else ae={lane:Z,tag:A.tag,payload:A.payload,callback:A.callback,next:null},re===null?(Q=re=ae,B=le):re=re.next=ae,T|=Z;if(A=A.next,A===null){if(A=f.shared.pending,A===null)break;ae=A,A=ae.next,ae.next=null,f.lastBaseUpdate=ae,f.shared.pending=null}}while(!0);re===null&&(B=le),f.baseState=B,f.firstBaseUpdate=Q,f.lastBaseUpdate=re,m===null&&(f.shared.lanes=0),Gs|=T,t.lanes=T,t.memoizedState=le}}function jd(t,a){if(typeof t!="function")throw Error(s(191,t));t.call(a)}function Vd(t,a){var i=t.callbacks;if(i!==null)for(t.callbacks=null,t=0;tm?m:8;var T=V.T,A={};V.T=A,Ip(t,!1,a,i);try{var B=f(),Q=V.S;if(Q!==null&&Q(A,B),B!==null&&typeof B=="object"&&typeof B.then=="function"){var re=Gd(B,l);Zc(t,a,re,ca(t))}else Zc(t,a,l,ca(t))}catch(le){Zc(t,a,{then:function(){},status:"rejected",reason:le},ca())}finally{W.p=m,T!==null&&A.types!==null&&(T.types=A.types),V.T=T}}function sS(){}function Rp(t,a,i,l){if(t.tag!==5)throw Error(s(476));var f=sw(t).queue;rw(t,f,a,I,i===null?sS:function(){return iw(t),i(l)})}function sw(t){var a=t.memoizedState;if(a!==null)return a;a={memoizedState:I,baseState:I,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:v,lastRenderedState:I},next:null};var i={};return a.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:v,lastRenderedState:i},next:null},t.memoizedState=a,t=t.alternate,t!==null&&(t.memoizedState=a),a}function iw(t){var a=sw(t);a.next===null&&(a=t.alternate.memoizedState),Zc(t,a.next.queue,{},ca())}function Up(){return Xt(pu)}function ow(){return Bt().memoizedState}function lw(){return Bt().memoizedState}function iS(t){for(var a=t.return;a!==null;){switch(a.tag){case 24:case 3:var i=ca();t=Xa(i);var l=Qa(a,t,i);l!==null&&(Qn(l,a,i),Ns(l,a,i)),a={cache:jo()},t.payload=a;return}a=a.return}}function oS(t,a,i){var l=ca();i={lane:l,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},Wd(t)?uw(a,i):(i=xc(t,a,i,l),i!==null&&(Qn(i,t,l),dw(i,a,l)))}function cw(t,a,i){var l=ca();Zc(t,a,i,l)}function Zc(t,a,i,l){var f={lane:l,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(Wd(t))uw(a,f);else{var m=t.alternate;if(t.lanes===0&&(m===null||m.lanes===0)&&(m=a.lastRenderedReducer,m!==null))try{var T=a.lastRenderedState,A=m(T,i);if(f.hasEagerState=!0,f.eagerState=A,Kt(A,T))return No(t,a,f,0),bt===null&&Lo(),!1}catch{}finally{}if(i=xc(t,a,f,l),i!==null)return Qn(i,t,l),dw(i,a,l),!0}return!1}function Ip(t,a,i,l){if(l={lane:2,revertLane:vm(),gesture:null,action:l,hasEagerState:!1,eagerState:null,next:null},Wd(t)){if(a)throw Error(s(479))}else a=xc(t,i,l,2),a!==null&&Qn(a,t,2)}function Wd(t){var a=t.alternate;return t===Ie||a!==null&&a===Ie}function uw(t,a){Fs=Wo=!0;var i=t.pending;i===null?a.next=a:(a.next=i.next,i.next=a),t.pending=a}function dw(t,a,i){if((i&4194048)!==0){var l=a.lanes;l&=t.pendingLanes,i|=l,a.lanes=i,$l(t,i)}}var Kc={readContext:Xt,use:Di,useCallback:kt,useContext:kt,useEffect:kt,useImperativeHandle:kt,useLayoutEffect:kt,useInsertionEffect:kt,useMemo:kt,useReducer:kt,useRef:kt,useState:kt,useDebugValue:kt,useDeferredValue:kt,useTransition:kt,useSyncExternalStore:kt,useId:kt,useHostTransitionStatus:kt,useFormState:kt,useActionState:kt,useOptimistic:kt,useMemoCache:kt,useCacheRefresh:kt};Kc.useEffectEvent=kt;var fw={readContext:Xt,use:Di,useCallback:function(t,a){return gn().memoizedState=[t,a===void 0?null:a],t},useContext:Xt,useEffect:Qy,useImperativeHandle:function(t,a,i){i=i!=null?i.concat([t]):null,Xd(4194308,4,Jy.bind(null,a,t),i)},useLayoutEffect:function(t,a){return Xd(4194308,4,t,a)},useInsertionEffect:function(t,a){Xd(4,2,t,a)},useMemo:function(t,a){var i=gn();a=a===void 0?null:a;var l=t();if(Jr){_a(!0);try{t()}finally{_a(!1)}}return i.memoizedState=[l,a],l},useReducer:function(t,a,i){var l=gn();if(i!==void 0){var f=i(a);if(Jr){_a(!0);try{i(a)}finally{_a(!1)}}}else f=a;return l.memoizedState=l.baseState=f,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:f},l.queue=t,t=t.dispatch=oS.bind(null,Ie,t),[l.memoizedState,t]},useRef:function(t){var a=gn();return t={current:t},a.memoizedState=t},useState:function(t){t=ge(t);var a=t.queue,i=cw.bind(null,Ie,a);return a.dispatch=i,[t.memoizedState,i]},useDebugValue:Bp,useDeferredValue:function(t,a){var i=gn();return Pp(i,t,a)},useTransition:function(){var t=ge(!1);return t=rw.bind(null,Ie,t.queue,!0,!1),gn().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,a,i){var l=Ie,f=gn();if(Xe){if(i===void 0)throw Error(s(407));i=i()}else{if(i=a(),bt===null)throw Error(s(349));(Je&127)!==0||q(l,a,i)}f.memoizedState=i;var m={value:i,getSnapshot:a};return f.queue=m,Qy(fe.bind(null,l,m,t),[t]),l.flags|=2048,Jo(9,{destroy:void 0},J.bind(null,l,m,i,a),null),i},useId:function(){var t=gn(),a=bt.identifierPrefix;if(Xe){var i=ra,l=aa;i=(l&~(1<<32-hn(l)-1)).toString(32)+i,a="_"+a+"R_"+i,i=Zo++,0<\/script>",m=m.removeChild(m.firstChild);break;case"select":m=typeof l.is=="string"?T.createElement("select",{is:l.is}):T.createElement("select"),l.multiple?m.multiple=!0:l.size&&(m.size=l.size);break;default:m=typeof l.is=="string"?T.createElement(f,{is:l.is}):T.createElement(f)}}m[Wt]=a,m[pn]=l;e:for(T=a.child;T!==null;){if(T.tag===5||T.tag===6)m.appendChild(T.stateNode);else if(T.tag!==4&&T.tag!==27&&T.child!==null){T.child.return=T,T=T.child;continue}if(T===a)break e;for(;T.sibling===null;){if(T.return===null||T.return===a)break e;T=T.return}T.sibling.return=T.return,T=T.sibling}a.stateNode=m;e:switch(yn(m,f,l),f){case"button":case"input":case"select":case"textarea":l=!!l.autoFocus;break e;case"img":l=!0;break e;default:l=!1}l&&ns(a)}}return Tt(a),em(a,a.type,t===null?null:t.memoizedProps,a.pendingProps,i),null;case 6:if(t&&a.stateNode!=null)t.memoizedProps!==l&&ns(a);else{if(typeof l!="string"&&a.stateNode===null)throw Error(s(166));if(t=Oe.current,Hr(a)){if(t=a.stateNode,i=a.memoizedProps,l=null,f=Jt,f!==null)switch(f.tag){case 27:case 5:l=f.memoizedProps}t[Wt]=a,t=!!(t.nodeValue===i||l!==null&&l.suppressHydrationWarning===!0||z0(t.nodeValue,i)),t||Ca(a,!0)}else t=gf(t).createTextNode(l),t[Wt]=a,a.stateNode=t}return Tt(a),null;case 31:if(i=a.memoizedState,t===null||t.memoizedState!==null){if(l=Hr(a),i!==null){if(t===null){if(!l)throw Error(s(318));if(t=a.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(s(557));t[Wt]=a}else vr(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tt(a),t=!1}else i=Uo(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=i),t=!0;if(!t)return a.flags&256?(In(a),a):(In(a),null);if((a.flags&128)!==0)throw Error(s(558))}return Tt(a),null;case 13:if(l=a.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(f=Hr(a),l!==null&&l.dehydrated!==null){if(t===null){if(!f)throw Error(s(318));if(f=a.memoizedState,f=f!==null?f.dehydrated:null,!f)throw Error(s(317));f[Wt]=a}else vr(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tt(a),f=!1}else f=Uo(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=f),f=!0;if(!f)return a.flags&256?(In(a),a):(In(a),null)}return In(a),(a.flags&128)!==0?(a.lanes=i,a):(i=l!==null,t=t!==null&&t.memoizedState!==null,i&&(l=a.child,f=null,l.alternate!==null&&l.alternate.memoizedState!==null&&l.alternate.memoizedState.cachePool!==null&&(f=l.alternate.memoizedState.cachePool.pool),m=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(m=l.memoizedState.cachePool.pool),m!==f&&(l.flags|=2048)),i!==t&&i&&(a.child.flags|=8192),tf(a,a.updateQueue),Tt(a),null);case 4:return Qe(),t===null&&Mm(a.stateNode.containerInfo),Tt(a),null;case 10:return Rn(a.type),Tt(a),null;case 19:if(H(Ft),l=a.memoizedState,l===null)return Tt(a),null;if(f=(a.flags&128)!==0,m=l.rendering,m===null)if(f)eu(l,!1);else{if(jt!==0||t!==null&&(t.flags&128)!==0)for(t=a.child;t!==null;){if(m=Qo(t),m!==null){for(a.flags|=128,eu(l,!1),t=m.updateQueue,a.updateQueue=t,tf(a,t),a.subtreeFlags=0,t=i,i=a.child;i!==null;)Bd(i,t),i=i.sibling;return ue(Ft,Ft.current&1|2),Xe&&Ea(a,l.treeForkCount),a.child}t=t.sibling}l.tail!==null&&Mn()>of&&(a.flags|=128,f=!0,eu(l,!1),a.lanes=4194304)}else{if(!f)if(t=Qo(m),t!==null){if(a.flags|=128,f=!0,t=t.updateQueue,a.updateQueue=t,tf(a,t),eu(l,!0),l.tail===null&&l.tailMode==="hidden"&&!m.alternate&&!Xe)return Tt(a),null}else 2*Mn()-l.renderingStartTime>of&&i!==536870912&&(a.flags|=128,f=!0,eu(l,!1),a.lanes=4194304);l.isBackwards?(m.sibling=a.child,a.child=m):(t=l.last,t!==null?t.sibling=m:a.child=m,l.last=m)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=Mn(),t.sibling=null,i=Ft.current,ue(Ft,f?i&1|2:i&1),Xe&&Ea(a,l.treeForkCount),t):(Tt(a),null);case 22:case 23:return In(a),qc(),l=a.memoizedState!==null,t!==null?t.memoizedState!==null!==l&&(a.flags|=8192):l&&(a.flags|=8192),l?(i&536870912)!==0&&(a.flags&128)===0&&(Tt(a),a.subtreeFlags&6&&(a.flags|=8192)):Tt(a),i=a.updateQueue,i!==null&&tf(a,i.retryQueue),i=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(i=t.memoizedState.cachePool.pool),l=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(l=a.memoizedState.cachePool.pool),l!==i&&(a.flags|=2048),t!==null&&H(br),null;case 24:return i=null,t!==null&&(i=t.memoizedState.cache),a.memoizedState.cache!==i&&(a.flags|=2048),Rn(Dt),Tt(a),null;case 25:return null;case 30:return null}throw Error(s(156,a.tag))}function fS(t,a){switch(Po(a),a.tag){case 1:return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 3:return Rn(Dt),Qe(),t=a.flags,(t&65536)!==0&&(t&128)===0?(a.flags=t&-65537|128,a):null;case 26:case 27:case 5:return Ct(a),null;case 31:if(a.memoizedState!==null){if(In(a),a.alternate===null)throw Error(s(340));vr()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 13:if(In(a),t=a.memoizedState,t!==null&&t.dehydrated!==null){if(a.alternate===null)throw Error(s(340));vr()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 19:return H(Ft),null;case 4:return Qe(),null;case 10:return Rn(a.type),null;case 22:case 23:return In(a),qc(),t!==null&&H(br),t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 24:return Rn(Dt),null;case 25:return null;default:return null}}function Bw(t,a){switch(Po(a),a.tag){case 3:Rn(Dt),Qe();break;case 26:case 27:case 5:Ct(a);break;case 4:Qe();break;case 31:a.memoizedState!==null&&In(a);break;case 13:In(a);break;case 19:H(Ft);break;case 10:Rn(a.type);break;case 22:case 23:In(a),qc(),t!==null&&H(br);break;case 24:Rn(Dt)}}function tu(t,a){try{var i=a.updateQueue,l=i!==null?i.lastEffect:null;if(l!==null){var f=l.next;i=f;do{if((i.tag&t)===t){l=void 0;var m=i.create,T=i.inst;l=m(),T.destroy=l}i=i.next}while(i!==f)}}catch(A){_t(a,a.return,A)}}function Us(t,a,i){try{var l=a.updateQueue,f=l!==null?l.lastEffect:null;if(f!==null){var m=f.next;l=m;do{if((l.tag&t)===t){var T=l.inst,A=T.destroy;if(A!==void 0){T.destroy=void 0,f=a;var B=i,Q=A;try{Q()}catch(re){_t(f,B,re)}}}l=l.next}while(l!==m)}}catch(re){_t(a,a.return,re)}}function Pw(t){var a=t.updateQueue;if(a!==null){var i=t.stateNode;try{Vd(a,i)}catch(l){_t(t,t.return,l)}}}function Rw(t,a,i){i.props=Bi(t.type,t.memoizedProps),i.state=t.memoizedState;try{i.componentWillUnmount()}catch(l){_t(t,a,l)}}function nu(t,a){try{var i=t.ref;if(i!==null){switch(t.tag){case 26:case 27:case 5:var l=t.stateNode;break;case 30:l=t.stateNode;break;default:l=t.stateNode}typeof i=="function"?t.refCleanup=i(l):i.current=l}}catch(f){_t(t,a,f)}}function Ar(t,a){var i=t.ref,l=t.refCleanup;if(i!==null)if(typeof l=="function")try{l()}catch(f){_t(t,a,f)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(f){_t(t,a,f)}else i.current=null}function Uw(t){var a=t.type,i=t.memoizedProps,l=t.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":i.autoFocus&&l.focus();break e;case"img":i.src?l.src=i.src:i.srcSet&&(l.srcset=i.srcSet)}}catch(f){_t(t,t.return,f)}}function tm(t,a,i){try{var l=t.stateNode;DS(l,t.type,i,a),l[pn]=a}catch(f){_t(t,t.return,f)}}function Iw(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&Hs(t.type)||t.tag===4}function nm(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Iw(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&Hs(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function am(t,a,i){var l=t.tag;if(l===5||l===6)t=t.stateNode,a?(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i).insertBefore(t,a):(a=i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,a.appendChild(t),i=i._reactRootContainer,i!=null||a.onclick!==null||(a.onclick=Ga));else if(l!==4&&(l===27&&Hs(t.type)&&(i=t.stateNode,a=null),t=t.child,t!==null))for(am(t,a,i),t=t.sibling;t!==null;)am(t,a,i),t=t.sibling}function nf(t,a,i){var l=t.tag;if(l===5||l===6)t=t.stateNode,a?i.insertBefore(t,a):i.appendChild(t);else if(l!==4&&(l===27&&Hs(t.type)&&(i=t.stateNode),t=t.child,t!==null))for(nf(t,a,i),t=t.sibling;t!==null;)nf(t,a,i),t=t.sibling}function Gw(t){var a=t.stateNode,i=t.memoizedProps;try{for(var l=t.type,f=a.attributes;f.length;)a.removeAttributeNode(f[0]);yn(a,l,i),a[Wt]=t,a[pn]=i}catch(m){_t(t,t.return,m)}}var as=!1,tn=!1,rm=!1,jw=typeof WeakSet=="function"?WeakSet:Set,cn=null;function hS(t,a){if(t=t.containerInfo,Sm=Tf,t=Od(t),pc(t)){if("selectionStart"in t)var i={start:t.selectionStart,end:t.selectionEnd};else e:{i=(i=t.ownerDocument)&&i.defaultView||window;var l=i.getSelection&&i.getSelection();if(l&&l.rangeCount!==0){i=l.anchorNode;var f=l.anchorOffset,m=l.focusNode;l=l.focusOffset;try{i.nodeType,m.nodeType}catch{i=null;break e}var T=0,A=-1,B=-1,Q=0,re=0,le=t,Z=null;t:for(;;){for(var ae;le!==i||f!==0&&le.nodeType!==3||(A=T+f),le!==m||l!==0&&le.nodeType!==3||(B=T+l),le.nodeType===3&&(T+=le.nodeValue.length),(ae=le.firstChild)!==null;)Z=le,le=ae;for(;;){if(le===t)break t;if(Z===i&&++Q===f&&(A=T),Z===m&&++re===l&&(B=T),(ae=le.nextSibling)!==null)break;le=Z,Z=le.parentNode}le=ae}i=A===-1||B===-1?null:{start:A,end:B}}else i=null}i=i||{start:0,end:0}}else i=null;for(Em={focusedElem:t,selectionRange:i},Tf=!1,cn=a;cn!==null;)if(a=cn,t=a.child,(a.subtreeFlags&1028)!==0&&t!==null)t.return=a,cn=t;else for(;cn!==null;){switch(a=cn,m=a.alternate,t=a.flags,a.tag){case 0:if((t&4)!==0&&(t=a.updateQueue,t=t!==null?t.events:null,t!==null))for(i=0;i title"))),yn(m,l,i),m[Wt]=t,Yt(m),l=m;break e;case"link":var T=X0("link","href",f).get(l+(i.href||""));if(T){for(var A=0;Awt&&(T=wt,wt=Le,Le=T);var $=Cd(A,Le),U=Cd(A,wt);if($&&U&&(ae.rangeCount!==1||ae.anchorNode!==$.node||ae.anchorOffset!==$.offset||ae.focusNode!==U.node||ae.focusOffset!==U.offset)){var X=le.createRange();X.setStart($.node,$.offset),ae.removeAllRanges(),Le>wt?(ae.addRange(X),ae.extend(U.node,U.offset)):(X.setEnd(U.node,U.offset),ae.addRange(X))}}}}for(le=[],ae=A;ae=ae.parentNode;)ae.nodeType===1&&le.push({element:ae,left:ae.scrollLeft,top:ae.scrollTop});for(typeof A.focus=="function"&&A.focus(),A=0;Ai?32:i,V.T=null,i=dm,dm=null;var m=Vs,T=ls;if(nn=0,rl=Vs=null,ls=0,(ct&6)!==0)throw Error(s(331));var A=ct;if(ct|=4,Jw(m.current),Ww(m,m.current,T,i),ct=A,lu(0,!1),xn&&typeof xn.onPostCommitFiberRoot=="function")try{xn.onPostCommitFiberRoot(vs,m)}catch{}return!0}finally{W.p=f,V.T=l,g0(t,a)}}function y0(t,a,i){a=Fn(i,a),a=qp(t.stateNode,a,2),t=Qa(t,a,2),t!==null&&(ga(t,2),Cr(t))}function _t(t,a,i){if(t.tag===3)y0(t,t,i);else for(;a!==null;){if(a.tag===3){y0(a,t,i);break}else if(a.tag===1){var l=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof l.componentDidCatch=="function"&&(js===null||!js.has(l))){t=Fn(i,t),i=ww(2),l=Qa(a,i,2),l!==null&&(bw(i,l,a,t),ga(l,2),Cr(l));break}}a=a.return}}function mm(t,a,i){var l=t.pingCache;if(l===null){l=t.pingCache=new _S;var f=new Set;l.set(a,f)}else f=l.get(a),f===void 0&&(f=new Set,l.set(a,f));f.has(i)||(om=!0,f.add(i),t=bS.bind(null,t,a,i),a.then(t,t))}function bS(t,a,i){var l=t.pingCache;l!==null&&l.delete(a),t.pingedLanes|=t.suspendedLanes&i,t.warmLanes&=~i,bt===t&&(Je&i)===i&&(jt===4||jt===3&&(Je&62914560)===Je&&300>Mn()-sf?(ct&2)===0&&sl(t,0):lm|=i,al===Je&&(al=0)),Cr(t)}function w0(t,a){a===0&&(a=Vl()),t=Vr(t,a),t!==null&&(ga(t,a),Cr(t))}function MS(t){var a=t.memoizedState,i=0;a!==null&&(i=a.retryLane),w0(t,i)}function xS(t,a){var i=0;switch(t.tag){case 31:case 13:var l=t.stateNode,f=t.memoizedState;f!==null&&(i=f.retryLane);break;case 19:l=t.stateNode;break;case 22:l=t.stateNode._retryCache;break;default:throw Error(s(314))}l!==null&&l.delete(a),w0(t,i)}function TS(t,a){return Ra(t,a)}var hf=null,ol=null,_m=!1,pf=!1,gm=!1,$s=0;function Cr(t){t!==ol&&t.next===null&&(ol===null?hf=ol=t:ol=ol.next=t),pf=!0,_m||(_m=!0,ES())}function lu(t,a){if(!gm&&pf){gm=!0;do for(var i=!1,l=hf;l!==null;){if(t!==0){var f=l.pendingLanes;if(f===0)var m=0;else{var T=l.suspendedLanes,A=l.pingedLanes;m=(1<<31-hn(42|t)+1)-1,m&=f&~(T&~A),m=m&201326741?m&201326741|1:m?m|2:0}m!==0&&(i=!0,T0(l,m))}else m=Je,m=fi(l,l===bt?m:0,l.cancelPendingCommit!==null||l.timeoutHandle!==-1),(m&3)===0||hi(l,m)||(i=!0,T0(l,m));l=l.next}while(i);gm=!1}}function SS(){b0()}function b0(){pf=_m=!1;var t=0;$s!==0&&BS()&&(t=$s);for(var a=Mn(),i=null,l=hf;l!==null;){var f=l.next,m=M0(l,a);m===0?(l.next=null,i===null?hf=f:i.next=f,f===null&&(ol=i)):(i=l,(t!==0||(m&3)!==0)&&(pf=!0)),l=f}nn!==0&&nn!==5||lu(t),$s!==0&&($s=0)}function M0(t,a){for(var i=t.suspendedLanes,l=t.pingedLanes,f=t.expirationTimes,m=t.pendingLanes&-62914561;0A)break;var re=B.transferSize,le=B.initiatorType;re&&L0(le)&&(B=B.responseEnd,T+=re*(B"u"?null:document;function q0(t,a,i){var l=ll;if(l&&typeof a=="string"&&a){var f=jn(a);f='link[rel="'+t+'"][href="'+f+'"]',typeof i=="string"&&(f+='[crossorigin="'+i+'"]'),V0.has(f)||(V0.add(f),t={rel:t,crossOrigin:i,href:a},l.querySelector(f)===null&&(a=l.createElement("link"),yn(a,"link",t),Yt(a),l.head.appendChild(a)))}}function $S(t){cs.D(t),q0("dns-prefetch",t,null)}function HS(t,a){cs.C(t,a),q0("preconnect",t,a)}function YS(t,a,i){cs.L(t,a,i);var l=ll;if(l&&t&&a){var f='link[rel="preload"][as="'+jn(a)+'"]';a==="image"&&i&&i.imageSrcSet?(f+='[imagesrcset="'+jn(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(f+='[imagesizes="'+jn(i.imageSizes)+'"]')):f+='[href="'+jn(t)+'"]';var m=f;switch(a){case"style":m=cl(t);break;case"script":m=ul(t)}Oa.has(m)||(t=y({rel:"preload",href:a==="image"&&i&&i.imageSrcSet?void 0:t,as:a},i),Oa.set(m,t),l.querySelector(f)!==null||a==="style"&&l.querySelector(fu(m))||a==="script"&&l.querySelector(hu(m))||(a=l.createElement("link"),yn(a,"link",t),Yt(a),l.head.appendChild(a)))}}function XS(t,a){cs.m(t,a);var i=ll;if(i&&t){var l=a&&typeof a.as=="string"?a.as:"script",f='link[rel="modulepreload"][as="'+jn(l)+'"][href="'+jn(t)+'"]',m=f;switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":m=ul(t)}if(!Oa.has(m)&&(t=y({rel:"modulepreload",href:t},a),Oa.set(m,t),i.querySelector(f)===null)){switch(l){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(hu(m)))return}l=i.createElement("link"),yn(l,"link",t),Yt(l),i.head.appendChild(l)}}}function QS(t,a,i){cs.S(t,a,i);var l=ll;if(l&&t){var f=ys(l).hoistableStyles,m=cl(t);a=a||"default";var T=f.get(m);if(!T){var A={loading:0,preload:null};if(T=l.querySelector(fu(m)))A.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":a},i),(i=Oa.get(m))&&Nm(t,i);var B=T=l.createElement("link");Yt(B),yn(B,"link",t),B._p=new Promise(function(Q,re){B.onload=Q,B.onerror=re}),B.addEventListener("load",function(){A.loading|=1}),B.addEventListener("error",function(){A.loading|=2}),A.loading|=4,yf(T,a,l)}T={type:"stylesheet",instance:T,count:1,state:A},f.set(m,T)}}}function WS(t,a){cs.X(t,a);var i=ll;if(i&&t){var l=ys(i).hoistableScripts,f=ul(t),m=l.get(f);m||(m=i.querySelector(hu(f)),m||(t=y({src:t,async:!0},a),(a=Oa.get(f))&&Dm(t,a),m=i.createElement("script"),Yt(m),yn(m,"link",t),i.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},l.set(f,m))}}function ZS(t,a){cs.M(t,a);var i=ll;if(i&&t){var l=ys(i).hoistableScripts,f=ul(t),m=l.get(f);m||(m=i.querySelector(hu(f)),m||(t=y({src:t,async:!0,type:"module"},a),(a=Oa.get(f))&&Dm(t,a),m=i.createElement("script"),Yt(m),yn(m,"link",t),i.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},l.set(f,m))}}function $0(t,a,i,l){var f=(f=Oe.current)?vf(f):null;if(!f)throw Error(s(446));switch(t){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(a=cl(i.href),i=ys(f).hoistableStyles,l=i.get(a),l||(l={type:"style",instance:null,count:0,state:null},i.set(a,l)),l):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){t=cl(i.href);var m=ys(f).hoistableStyles,T=m.get(t);if(T||(f=f.ownerDocument||f,T={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},m.set(t,T),(m=f.querySelector(fu(t)))&&!m._p&&(T.instance=m,T.state.loading=5),Oa.has(t)||(i={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},Oa.set(t,i),m||KS(f,t,i,T.state))),a&&l===null)throw Error(s(528,""));return T}if(a&&l!==null)throw Error(s(529,""));return null;case"script":return a=i.async,i=i.src,typeof i=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=ul(i),i=ys(f).hoistableScripts,l=i.get(a),l||(l={type:"script",instance:null,count:0,state:null},i.set(a,l)),l):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,t))}}function cl(t){return'href="'+jn(t)+'"'}function fu(t){return'link[rel="stylesheet"]['+t+"]"}function H0(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function KS(t,a,i,l){t.querySelector('link[rel="preload"][as="style"]['+a+"]")?l.loading=1:(a=t.createElement("link"),l.preload=a,a.addEventListener("load",function(){return l.loading|=1}),a.addEventListener("error",function(){return l.loading|=2}),yn(a,"link",i),Yt(a),t.head.appendChild(a))}function ul(t){return'[src="'+jn(t)+'"]'}function hu(t){return"script[async]"+t}function Y0(t,a,i){if(a.count++,a.instance===null)switch(a.type){case"style":var l=t.querySelector('style[data-href~="'+jn(i.href)+'"]');if(l)return a.instance=l,Yt(l),l;var f=y({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return l=(t.ownerDocument||t).createElement("style"),Yt(l),yn(l,"style",f),yf(l,i.precedence,t),a.instance=l;case"stylesheet":f=cl(i.href);var m=t.querySelector(fu(f));if(m)return a.state.loading|=4,a.instance=m,Yt(m),m;l=H0(i),(f=Oa.get(f))&&Nm(l,f),m=(t.ownerDocument||t).createElement("link"),Yt(m);var T=m;return T._p=new Promise(function(A,B){T.onload=A,T.onerror=B}),yn(m,"link",l),a.state.loading|=4,yf(m,i.precedence,t),a.instance=m;case"script":return m=ul(i.src),(f=t.querySelector(hu(m)))?(a.instance=f,Yt(f),f):(l=i,(f=Oa.get(m))&&(l=y({},i),Dm(l,f)),t=t.ownerDocument||t,f=t.createElement("script"),Yt(f),yn(f,"link",l),t.head.appendChild(f),a.instance=f);case"void":return null;default:throw Error(s(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(l=a.instance,a.state.loading|=4,yf(l,i.precedence,t));return a.instance}function yf(t,a,i){for(var l=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=l.length?l[l.length-1]:null,m=f,T=0;T title"):null)}function JS(t,a,i){if(i===1||a.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return t=a.disabled,typeof a.precedence=="string"&&t==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function W0(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function eE(t,a,i,l){if(i.type==="stylesheet"&&(typeof l.media!="string"||matchMedia(l.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var f=cl(l.href),m=a.querySelector(fu(f));if(m){a=m._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(t.count++,t=bf.bind(t),a.then(t,t)),i.state.loading|=4,i.instance=m,Yt(m);return}m=a.ownerDocument||a,l=H0(l),(f=Oa.get(f))&&Nm(l,f),m=m.createElement("link"),Yt(m);var T=m;T._p=new Promise(function(A,B){T.onload=A,T.onerror=B}),yn(m,"link",l),i.instance=m}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(i,a),(a=i.state.preload)&&(i.state.loading&3)===0&&(t.count++,i=bf.bind(t),a.addEventListener("load",i),a.addEventListener("error",i))}}var Fm=0;function tE(t,a){return t.stylesheets&&t.count===0&&xf(t,t.stylesheets),0Fm?50:800)+a);return t.unsuspend=i,function(){t.unsuspend=null,clearTimeout(l),clearTimeout(f)}}:null}function bf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)xf(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Mf=null;function xf(t,a){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Mf=new Map,a.forEach(nE,t),Mf=null,bf.call(t))}function nE(t,a){if(!(a.state.loading&4)){var i=Mf.get(t);if(i)var l=i.get(null);else{i=new Map,Mf.set(t,i);for(var f=t.querySelectorAll("link[data-precedence],style[data-precedence]"),m=0;m"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(n){console.error(n)}}return e(),qm.exports=wE(),qm.exports}var ME=bE();/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Z1=(...e)=>e.filter((n,r,s)=>!!n&&n.trim()!==""&&s.indexOf(n)===r).join(" ").trim();/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xE=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const TE=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,r,s)=>s?s.toUpperCase():r.toLowerCase());/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const wb=e=>{const n=TE(e);return n.charAt(0).toUpperCase()+n.slice(1)};/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var SE={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const EE=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1};/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const AE=Mt.forwardRef(({color:e="currentColor",size:n=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:o="",children:c,iconNode:u,...d},h)=>Mt.createElement("svg",{ref:h,...SE,width:n,height:n,stroke:e,strokeWidth:s?Number(r)*24/Number(n):r,className:Z1("lucide",o),...!c&&!EE(d)&&{"aria-hidden":"true"},...d},[...u.map(([p,g])=>Mt.createElement(p,g)),...Array.isArray(c)?c:[c]]));/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ki=(e,n)=>{const r=Mt.forwardRef(({className:s,...o},c)=>Mt.createElement(AE,{ref:c,iconNode:n,className:Z1(`lucide-${xE(wb(e))}`,`lucide-${e}`,s),...o}));return r.displayName=wb(e),r};/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const CE=[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]],bb=Ki("arrow-left-right",CE);/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const kE=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Mb=Ki("check",kE);/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const OE=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zE=Ki("chevron-down",OE);/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const LE=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],NE=Ki("copy",LE);/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const DE=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],FE=Ki("loader-circle",DE);/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const BE=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],PE=Ki("share-2",BE);/** + * @license lucide-react v0.564.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const RE=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],UE=Ki("trash",RE),Sh=(...e)=>e.map(n=>typeof n=="string"?n:Object.entries(n||{}).filter(([,r])=>r).map(([r])=>r).join(" ")).filter(n=>n!=="").join(" ");function rg({variant:e="primary",icon:n,iconPosition:r="left",children:s,className:o="",...c}){const u="inline-flex items-center justify-center font-medium text-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2",d={primary:"bg-primary text-primary-foreground hover:bg-primary-600 active:bg-primary-700 rounded-md shadow-sm hover:shadow focus:ring-primary/50",outlined:"bg-transparent text-primary hover:bg-muted active:bg-primary-50 border border-border rounded-[48px] focus:ring-primary/30",pill:"bg-transparent text-primary hover:bg-primary-50 active:bg-muted border border-border rounded-[48px] focus:ring-primary/30","pill-selected":"bg-primary-100 text-primary-800 hover:bg-primary-200 active:bg-primary-200 border border-primary-100 rounded-[48px] shadow-sm focus:ring-primary-800/30",text:"bg-transparent text-primary hover:bg-muted active:bg-primary-50 rounded-md focus:ring-primary/30",ghost:"bg-transparent text-muted-foreground hover:bg-muted hover:text-primary active:bg-primary-50 rounded-md focus:ring-primary/30"},h={primary:"[padding:0.625em_1.5em] [gap:0.5em]",outlined:"[padding:0.5em_0.75em] [gap:0.5em]",pill:"[padding:0.5em_0.75em] [gap:0.5em]","pill-selected":"[padding:0.5em_0.75em] [gap:0.5em]",text:"[padding:0.375em_0.5em] [gap:0.5em]",ghost:"[padding:0.5em_0.75em] [gap:0.5em]"};return _e.jsxs("button",{className:Sh("cursor-pointer",u,d[e],h[e],"disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-current disabled:hover:shadow-none",o),...c,children:[n&&r==="left"&&_e.jsx(n,{className:"[width:1.25em] [height:1.25em]"}),s,n&&r==="right"&&_e.jsx(n,{className:"[width:1.25em] [height:1.25em]"})]})}function xb({variant:e="default",error:n=!1,className:r="",value:s,...o}){const c="w-full font-sans transition-all duration-200 resize-none focus:outline-none",u={default:"px-4 py-3 border border-border rounded-md bg-white hover:border-primary-300 focus:border-primary focus:ring-2 focus:ring-primary/20",minimal:"px-4 py-3 border-0 bg-transparent hover:bg-muted/30 focus:bg-white focus:shadow-sm rounded-md"},d=n?"border-destructive focus:border-destructive focus:ring-destructive/20":"",h="disabled:cursor-default",p=Mt.useMemo(()=>{const g=typeof s=="string"?s.length:0;return console.log(g),g===0||g<50?"text-2xl":g<200?"text-xl":g<300?"text-lg":"text-base"},[s]);return _e.jsx("textarea",{className:Sh(c,u[e],d,h,p,r),value:s,...o})}function IE({size:e=20,className:n=""}){return _e.jsx(FE,{className:`animate-spin text-primary ${n}`,style:{width:e,height:e}})}const Mg=[{code:"ar_EG",name:"Arabic (Egypt)"},{code:"ar_SA",name:"Arabic (Saudi Arabia)"},{code:"bg_BG",name:"Bulgarian"},{code:"bn_IN",name:"Bengali"},{code:"ca_ES",name:"Catalan"},{code:"cs_CZ",name:"Czech"},{code:"da_DK",name:"Danish"},{code:"de_DE",name:"German"},{code:"el_GR",name:"Greek"},{code:"en",name:"English"},{code:"es_XX",name:"Spanish"},{code:"et_EE",name:"Estonian"},{code:"fa_IR",name:"Persian"},{code:"fi_FI",name:"Finnish"},{code:"fil_PH",name:"Filipino"},{code:"fr_CA",name:"French (Canada)"},{code:"fr_FR",name:"French"},{code:"gu_IN",name:"Gujarati"},{code:"he_IL",name:"Hebrew"},{code:"hi_IN",name:"Hindi"},{code:"hr_HR",name:"Croatian"},{code:"hu_HU",name:"Hungarian"},{code:"id_ID",name:"Indonesian"},{code:"is_IS",name:"Icelandic"},{code:"it_IT",name:"Italian"},{code:"ja_JP",name:"Japanese"},{code:"kn_IN",name:"Kannada"},{code:"ko_KR",name:"Korean"},{code:"lt_LT",name:"Lithuanian"},{code:"lv_LV",name:"Latvian"},{code:"ml_IN",name:"Malayalam"},{code:"mr_IN",name:"Marathi"},{code:"nl_NL",name:"Dutch"},{code:"no_NO",name:"Norwegian"},{code:"pa_IN",name:"Punjabi"},{code:"pl_PL",name:"Polish"},{code:"pt_BR",name:"Portuguese (Brazil)"},{code:"pt_PT",name:"Portuguese (Portugal)"},{code:"ro_RO",name:"Romanian"},{code:"ru_RU",name:"Russian"},{code:"sk_SK",name:"Slovak"},{code:"sl_SI",name:"Slovenian"},{code:"sr_RS",name:"Serbian"},{code:"sv_SE",name:"Swedish"},{code:"sw_KE",name:"Swahili"},{code:"sw_TZ",name:"Swahili (Tanzania)"},{code:"ta_IN",name:"Tamil"},{code:"te_IN",name:"Telugu"},{code:"th_TH",name:"Thai"},{code:"tr_TR",name:"Turkish"},{code:"uk_UA",name:"Ukrainian"},{code:"ur_PK",name:"Urdu"},{code:"vi_VN",name:"Vietnamese"},{code:"zh_CN",name:"Chinese (Simplified)"},{code:"zh_TW",name:"Chinese (Traditional)"},{code:"zu_ZA",name:"Zulu"}],GE=[{code:"auto",name:"Auto"},...Mg];function Tb({value:e,onChange:n,includeAuto:r=!1}){const[s,o]=Mt.useState(!1),[c,u]=Mt.useState(""),d=Mt.useRef(null),h=Mt.useRef(null),p=r?GE:Mg,g=S=>{var E;return((E=p.find(O=>O.code===S))==null?void 0:E.name)||S},w=c?(S=>{const E=S.toLowerCase();return p.filter(O=>O.name.toLowerCase().includes(E)||O.code.toLowerCase().includes(E))})(c):p,b=S=>{n(S),o(!1),u("")};return Mt.useEffect(()=>{const S=E=>{d.current&&!d.current.contains(E.target)&&(o(!1),u(""))};return s&&(document.addEventListener("mousedown",S),setTimeout(()=>{var E;return(E=h.current)==null?void 0:E.focus()},0)),()=>{document.removeEventListener("mousedown",S)}},[s]),_e.jsxs("div",{className:"relative",ref:d,children:[_e.jsxs("button",{onClick:()=>o(!s),className:"inline-flex items-center gap-2 px-3 py-2 text-sm font-medium text-primary hover:bg-muted rounded-md transition-colors",children:[_e.jsx("span",{children:g(e)}),_e.jsx(zE,{className:`w-4 h-4 transition-transform ${s?"rotate-180":""}`})]}),s&&_e.jsxs("div",{className:"absolute top-full left-0 mt-2 w-64 bg-white border border-border rounded-md shadow-lg z-50",children:[_e.jsx("div",{className:"p-2 border-b border-border",children:_e.jsx("input",{ref:h,type:"text",placeholder:"Search languages...",value:c,onChange:S=>u(S.target.value),className:"w-full px-3 py-2 text-sm border border-border rounded-md focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"})}),_e.jsxs("div",{className:"max-h-60 overflow-auto",children:[w.map(S=>_e.jsx("button",{onClick:()=>b(S.code),className:`w-full px-3 py-2 text-left text-sm hover:bg-muted transition-colors ${e===S.code?"bg-primary-50 text-primary-800":""}`,children:S.name},S.code)),w.length===0&&_e.jsx("div",{className:"px-3 py-4 text-sm text-muted-foreground text-center",children:"No languages found"})]})]})]})}function jE(e,n=1){const s=["Bytes","KB","MB","GB","TB","PB"],o=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/Math.pow(1024,o)).toFixed(n))}${s[o]}`}function VE(e){if(e<1e3)return`${Math.round(e)}ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)}s`;const r=Math.floor(n/60),s=Math.round(n%60);return`${r}m ${s}s`}function Xm(e){return new Intl.NumberFormat("en-US").format(e)}function qE(e){return!e||e.trim().length===0?0:e.trim().split(/\s+/).filter(r=>r.length>0).length}const Sb=1e3;function $E({className:e="",translator:n}){const s=(()=>{const me=window.location.hash.slice(1),pe=new URLSearchParams(me),ne=pe.get("sl"),ee=pe.get("tl"),Me=pe.get("text"),V=W=>W?Mg.some(I=>I.code===W):!1;return{sourceLanguage:V(ne)?ne:"en",targetLanguage:V(ee)?ee:"de_DE",sourceText:Me?decodeURIComponent(Me):""}})(),[o,c]=Mt.useState(s.sourceText),[u,d]=Mt.useState(""),[h,p]=Mt.useState(s.sourceLanguage),[g,y]=Mt.useState(s.targetLanguage),[w,b]=Mt.useState(!1),[S,E]=Mt.useState(!1),[O,z]=Mt.useState(!1),D=Mt.useRef(null),[P,j]=Mt.useState(0),[G,K]=Mt.useState(0),k=()=>{p(g),y(h),c(u),d(o)},ce=async()=>{if(u)try{await navigator.clipboard.writeText(u),E(!0),setTimeout(()=>E(!1),2e3)}catch(me){console.error("Failed to copy:",me)}},oe=async()=>{try{const me=window.location.href;await navigator.clipboard.writeText(me),z(!0),setTimeout(()=>z(!1),2e3)}catch(me){console.error("Failed to share:",me)}},he=async(me,pe,ne)=>{if(!me.trim()){d(""),j(0),K(0);return}const ee=performance.now();D.current&&D.current.abort(),D.current=new AbortController;const Me=D.current;b(!0);try{const V=await n.translate(me,pe,ne);Me.signal.aborted||(d(V),j(Math.round(performance.now()-ee)),K(qE(me)))}catch(V){Me.signal.aborted||console.error("Translation error:",V)}finally{Me.signal.aborted||b(!1)}};return Mt.useEffect(()=>{const me=new URLSearchParams;me.set("sl",h),me.set("tl",g),o&&me.set("text",encodeURIComponent(o));const pe=`#${me.toString()}`;window.history.replaceState({},"",pe)},[h,g,o]),Mt.useEffect(()=>{const me=setTimeout(()=>{he(o,h,g)},500);return()=>{clearTimeout(me)}},[o,h,g]),_e.jsx("div",{className:Sh("max-w-6xl mx-auto p-2 md:p-4 relative",e),children:_e.jsxs("div",{className:"flex flex-col md:flex-row w-full gap-4 md:gap-8",children:[_e.jsxs("div",{className:"flex flex-col gap-3 w-full md:w-1/2 relative",children:[_e.jsx(Tb,{value:h,onChange:p}),_e.jsx(xb,{value:o,onChange:me=>c(me.target.value),placeholder:"Enter text to translate...",className:"h-48 md:h-70 pb-10",variant:"default",maxLength:Sb}),_e.jsxs("div",{className:"p-2 flex justify-between items-center -mt-4",children:[_e.jsxs("p",{className:"text-xs text-muted-foreground opacity-70",children:[Xm(o.length)," /"," ",Xm(Sb)]}),_e.jsxs("div",{className:"flex gap-2",children:[_e.jsx("button",{onClick:oe,className:"p-2 text-muted-foreground hover:text-primary hover:bg-muted rounded-md transition-colors","aria-label":"Share translation",children:O?_e.jsxs("span",{className:"flex text-xs gap-2",children:["link copied",_e.jsx(Mb,{className:"w-4 h-4 text-primary"})]}):_e.jsx(PE,{className:"w-4 h-4"})}),_e.jsx("button",{onClick:()=>c(""),className:"p-2 text-muted-foreground hover:text-primary hover:bg-muted rounded-md transition-colors","aria-label":"clear text",children:_e.jsx(UE,{className:"w-4 h-4"})})]})]})]}),_e.jsx("div",{className:"hidden md:block absolute left-1/2 top-5 -translate-x-1/2",children:_e.jsx(rg,{variant:"ghost",icon:bb,onClick:k,"aria-label":"Swap languages"})}),_e.jsx("div",{className:"flex md:hidden justify-center -my-2",children:_e.jsx(rg,{variant:"ghost",icon:bb,onClick:k,"aria-label":"Swap languages",className:"rotate-90"})}),_e.jsxs("div",{className:"flex flex-col gap-3 w-full md:w-1/2",children:[_e.jsxs("div",{className:"flex items-center justify-between",children:[_e.jsx(Tb,{value:g,onChange:y}),w&&_e.jsx(IE,{size:20})]}),_e.jsxs("div",{children:[_e.jsx(xb,{value:u,disabled:!0,placeholder:"Translation will appear here...",className:"h-48 md:h-70",variant:"default"}),_e.jsxs("div",{className:"p-2 flex justify-between items-center -mt-4",children:[P>0?_e.jsxs("p",{className:"text-xs text-muted-foreground opacity-70",children:["Translated ",_e.jsxs("b",{children:[Xm(G)," words"]})," in"," ",_e.jsx("b",{children:VE(P)})]}):_e.jsx("p",{}),_e.jsx("div",{children:_e.jsx("button",{onClick:ce,className:"p-2 text-muted-foreground hover:text-primary hover:bg-muted rounded-md transition-colors","aria-label":"Copy translation",children:S?_e.jsxs("span",{className:"flex text-xs gap-2",children:["translation copied",_e.jsx(Mb,{className:"w-4 h-4 text-primary"})]}):_e.jsx(NE,{className:"w-4 h-4"})})})]})]})]})]})})}/*! + * ONNX Runtime Web v1.25.0-dev.20260212-1a71a5f46e + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var xg=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,YE=Object.getOwnPropertyNames,XE=Object.prototype.hasOwnProperty,QE=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,r)=>(typeof require<"u"?require:n)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ke=(e,n)=>()=>(e&&(n=e(e=0)),n),$u=(e,n)=>{for(var r in n)xg(e,r,{get:n[r],enumerable:!0})},WE=(e,n,r,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of YE(n))!XE.call(e,o)&&o!==r&&xg(e,o,{get:()=>n[o],enumerable:!(s=HE(n,o))||s.enumerable});return e},lh=e=>WE(xg({},"__esModule",{value:!0}),e),wu,Ks,Yi,Eb,K1,J1=Ke(()=>{wu=new Map,Ks=[],Yi=(e,n,r)=>{if(n&&typeof n.init=="function"&&typeof n.createInferenceSessionHandler=="function"){let s=wu.get(e);if(s===void 0)wu.set(e,{backend:n,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==n)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let o=Ks.indexOf(e);o!==-1&&Ks.splice(o,1);for(let c=0;c{let n=wu.get(e);if(!n)return"backend not found.";if(n.initialized)return n.backend;if(n.aborted)return n.error;{let r=!!n.initPromise;try{return r||(n.initPromise=n.backend.init(e)),await n.initPromise,n.initialized=!0,n.backend}catch(s){return r||(n.error=`${s}`,n.aborted=!0),n.error}finally{delete n.initPromise}}},K1=async e=>{let n=e.executionProviders||[],r=n.map(h=>typeof h=="string"?h:h.name),s=r.length===0?Ks:r,o,c=[],u=new Set;for(let h of s){let p=await Eb(h);typeof p=="string"?c.push({name:h,err:p}):(o||(o=p),o===p&&u.add(h))}if(!o)throw new Error(`no available backend found. ERR: ${c.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:p}of c)r.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${p}`);let d=n.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,p)=>p==="executionProviders"?d:Reflect.get(h,p)})]}}),ZE=Ke(()=>{J1()}),eM,KE=Ke(()=>{eM="1.24.0-dev.20251116-b39e144322"}),Qm,un,tM=Ke(()=>{KE(),Qm="warning",un={wasm:{},webgl:{},webgpu:{},versions:{common:eM},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Qm=e}},get logLevel(){return Qm}},Object.defineProperty(un,"logLevel",{enumerable:!0})}),zt,JE=Ke(()=>{tM(),zt=un}),nM,aM,eA=Ke(()=>{nM=(e,n)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let s=r.getContext("2d");if(s!=null){let o,c;(n==null?void 0:n.tensorLayout)!==void 0&&n.tensorLayout==="NHWC"?(o=e.dims[2],c=e.dims[3]):(o=e.dims[3],c=e.dims[2]);let u=(n==null?void 0:n.format)!==void 0?n.format:"RGB",d=n==null?void 0:n.norm,h,p;d===void 0||d.mean===void 0?h=[255,255,255,255]:typeof d.mean=="number"?h=[d.mean,d.mean,d.mean,d.mean]:(h=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(h[3]=d.mean[3])),d===void 0||d.bias===void 0?p=[0,0,0,0]:typeof d.bias=="number"?p=[d.bias,d.bias,d.bias,d.bias]:(p=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(p[3]=d.bias[3]));let g=c*o,y=0,w=g,b=g*2,S=-1;u==="RGBA"?(y=0,w=g,b=g*2,S=g*3):u==="RGB"?(y=0,w=g,b=g*2):u==="RBG"&&(y=0,b=g,w=g*2);for(let E=0;E{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(r!=null){let o,c,u;(n==null?void 0:n.tensorLayout)!==void 0&&n.tensorLayout==="NHWC"?(o=e.dims[2],c=e.dims[1],u=e.dims[3]):(o=e.dims[3],c=e.dims[2],u=e.dims[1]);let d=n!==void 0&&n.format!==void 0?n.format:"RGB",h=n==null?void 0:n.norm,p,g;h===void 0||h.mean===void 0?p=[255,255,255,255]:typeof h.mean=="number"?p=[h.mean,h.mean,h.mean,h.mean]:(p=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(p[3]=h.mean[3])),h===void 0||h.bias===void 0?g=[0,0,0,0]:typeof h.bias=="number"?g=[h.bias,h.bias,h.bias,h.bias]:(g=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(g[3]=h.bias[3]));let y=c*o;if(n!==void 0&&(n.format!==void 0&&u===4&&n.format!=="RGBA"||u===3&&n.format!=="RGB"&&n.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,b=0,S=1,E=2,O=3,z=0,D=y,P=y*2,j=-1;d==="RGBA"?(z=0,D=y,P=y*2,j=y*3):d==="RGB"?(z=0,D=y,P=y*2):d==="RBG"&&(z=0,P=y,D=y*2),s=r.createImageData(o,c);for(let G=0;G{Tg(),zf=(e,n)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(n.height===void 0||n.width===void 0)throw new Error("Image height and width must be defined");if(n.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=n,o=n.norm??{mean:255,bias:0},c,u;typeof o.mean=="number"?c=[o.mean,o.mean,o.mean,o.mean]:c=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:u=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let d=n.format!==void 0?n.format:"RGBA",h=n.tensorFormat!==void 0&&n.tensorFormat!==void 0?n.tensorFormat:"RGB",p=r*s,g=h==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),y=4,w=0,b=1,S=2,E=3,O=0,z=p,D=p*2,P=-1;d==="RGB"&&(y=3,w=0,b=1,S=2,E=-1),h==="RGBA"?P=p*3:h==="RBG"?(O=0,D=p,z=p*2):h==="BGR"&&(D=0,z=p,O=p*2);for(let j=0;j{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,c=typeof e=="string",u,d=n??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=g=>typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(r){let g=h();g.width=e.width,g.height=e.height;let y=p(g);if(y!=null){let w=e.height,b=e.width;if(n!==void 0&&n.resizedHeight!==void 0&&n.resizedWidth!==void 0&&(w=n.resizedHeight,b=n.resizedWidth),n!==void 0){if(d=n,n.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=w,d.width=b}else d.tensorFormat="RGBA",d.height=w,d.width=b;y.drawImage(e,0,0),u=y.getImageData(0,0,b,w).data}else throw new Error("Can not access image data")}else if(s){let g,y;if(n!==void 0&&n.resizedWidth!==void 0&&n.resizedHeight!==void 0?(g=n.resizedHeight,y=n.resizedWidth):(g=e.height,y=e.width),n!==void 0&&(d=n),d.format="RGBA",d.height=g,d.width=y,n!==void 0){let w=h();w.width=y,w.height=g;let b=p(w);if(b!=null)b.putImageData(e,0,0),u=b.getImageData(0,0,y,g).data;else throw new Error("Can not access image data")}else u=e.data}else if(o){if(n===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=h();g.width=e.width,g.height=e.height;let y=p(g);if(y!=null){let w=e.height,b=e.width;return y.drawImage(e,0,0,b,w),u=y.getImageData(0,0,b,w).data,d.height=w,d.width=b,zf(u,d)}else throw new Error("Can not access image data")}else{if(c)return new Promise((g,y)=>{let w=h(),b=p(w);if(!e||!b)return y();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{w.width=S.width,w.height=S.height,b.drawImage(S,0,0,w.width,w.height);let E=b.getImageData(0,0,w.width,w.height);d.height=w.height,d.width=w.width,g(zf(E.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return zf(u,d);throw new Error("Input data provided is not supported - aborted tensor creation")},sM=(e,n)=>{let{width:r,height:s,download:o,dispose:c}=n,u=[1,s,r,4];return new ha({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:c})},iM=(e,n)=>{let{dataType:r,dims:s,download:o,dispose:c}=n;return new ha({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:o,dispose:c})},oM=(e,n)=>{let{dataType:r,dims:s,download:o,dispose:c}=n;return new ha({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:o,dispose:c})},lM=(e,n,r)=>new ha({location:"cpu-pinned",type:e,data:n,dims:r??[n.length]})}),$i,Fu,Wm,cM,nA=Ke(()=>{$i=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Fu=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Wm=!1,cM=()=>{if(!Wm){Wm=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,n=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&($i.set("int64",BigInt64Array),Fu.set(BigInt64Array,"int64")),n&&($i.set("uint64",BigUint64Array),Fu.set(BigUint64Array,"uint64")),s?($i.set("float16",r),Fu.set(r,"float16")):$i.set("float16",Uint16Array)}}}),uM,dM,aA=Ke(()=>{Tg(),uM=e=>{let n=1;for(let r=0;r{switch(e.location){case"cpu":return new ha(e.type,e.data,n);case"cpu-pinned":return new ha({location:"cpu-pinned",data:e.data,type:e.type,dims:n});case"texture":return new ha({location:"texture",texture:e.texture,type:e.type,dims:n});case"gpu-buffer":return new ha({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:n});case"ml-tensor":return new ha({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:n});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),ha,Tg=Ke(()=>{eA(),tA(),nA(),aA(),ha=class{constructor(e,n,r){cM();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let u=$i.get(s);if(!u)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof u))throw new TypeError(`buffer should be of type ${u.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.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=e.gpuBuffer,this.downloader=e.download,this.disposer=e.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=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let u,d;if(typeof e=="string")if(s=e,d=r,e==="string"){if(!Array.isArray(n))throw new TypeError("A string tensor's data must be a string array.");u=n}else{let h=$i.get(e);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(n)){if(e==="float16"&&h===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${h.name} as data.`);e==="uint64"||e==="int64"?u=h.from(n,BigInt):u=h.from(n)}else if(n instanceof h)u=n;else if(n instanceof Uint8ClampedArray)if(e==="uint8")u=Uint8Array.from(n);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&n instanceof Uint16Array&&h!==Uint16Array)u=new globalThis.Float16Array(n.buffer,n.byteOffset,n.length);else throw new TypeError(`A ${s} tensor's data must be type of ${h}`)}else if(d=n,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let h=typeof e[0];if(h==="string")s="string",u=e;else if(h==="boolean")s="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${h}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",u=Uint8Array.from(e);else{let h=Fu.get(e.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=h,u=e}if(d===void 0)d=[u.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");o=d,this.cpuData=u,this.dataLocation="cpu"}let c=uM(o);if(this.cpuData&&c!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(c/2)===this.cpuData.length))throw new Error(`Tensor's size(${c}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=o,this.size=c}static async fromImage(e,n){return rM(e,n)}static fromTexture(e,n){return sM(e,n)}static fromGpuBuffer(e,n){return iM(e,n)}static fromMLTensor(e,n){return oM(e,n)}static fromPinnedBuffer(e,n,r){return lM(e,n,r)}toDataURL(e){return nM(this,e)}toImageData(e){return aM(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let n=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=n,e&&this.disposer&&(this.disposer(),this.disposer=void 0),n}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return dM(this,e)}}}),tr,fM=Ke(()=>{Tg(),tr=ha}),ch,Zm,Wi,Zi,ri,si,hM=Ke(()=>{tM(),ch=(e,n)=>{(typeof un.trace>"u"?!un.wasm.trace:!un.trace)||console.timeStamp(`${e}::ORT::${n}`)},Zm=(e,n)=>{var o;let r=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let c=0;c{(typeof un.trace>"u"?!un.wasm.trace:!un.trace)||Zm("BEGIN",e)},Zi=e=>{(typeof un.trace>"u"?!un.wasm.trace:!un.trace)||Zm("END",e)},ri=e=>{(typeof un.trace>"u"?!un.wasm.trace:!un.trace)||console.time(`ORT::${e}`)},si=e=>{(typeof un.trace>"u"?!un.wasm.trace:!un.trace)||console.timeEnd(`ORT::${e}`)}}),pM,rA=Ke(()=>{J1(),fM(),hM(),pM=class mM{constructor(n){this.handler=n}async run(n,r,s){Wi(),ri("InferenceSession.run");let o={},c={};if(typeof n!="object"||n===null||n instanceof tr||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let u=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof tr)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.");u=!1;for(let p of r){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof s=="object"&&s!==null)c=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,g=Object.getOwnPropertyNames(r);for(let y of this.outputNames)if(g.indexOf(y)!==-1){let w=r[y];(w===null||w instanceof tr)&&(p=!0,u=!1,o[y]=w)}if(p){if(typeof s=="object"&&s!==null)c=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else c=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof n[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(u)for(let p of this.outputNames)o[p]=null;let d=await this.handler.run(n,o,c),h={};for(let p in d)if(Object.hasOwnProperty.call(d,p)){let g=d[p];g instanceof tr?h[p]=g:h[p]=new tr(g.type,g.data,g.dims)}return si("InferenceSession.run"),Zi(),h}async release(){return this.handler.dispose()}static async create(n,r,s,o){Wi(),ri("InferenceSession.create");let c,u={};if(typeof n=="string"){if(c=n,typeof r=="object"&&r!==null)u=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(n instanceof Uint8Array){if(c=n,typeof r=="object"&&r!==null)u=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer){let g=n,y=0,w=n.byteLength;if(typeof r=="object"&&r!==null)u=r;else if(typeof r=="number"){if(y=r,!Number.isSafeInteger(y))throw new RangeError("'byteOffset' must be an integer.");if(y<0||y>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(w=n.byteLength-y,typeof s=="number"){if(w=s,!Number.isSafeInteger(w))throw new RangeError("'byteLength' must be an integer.");if(w<=0||y+w>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-y}].`);if(typeof o=="object"&&o!==null)u=o;else if(typeof o<"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.");c=new Uint8Array(g,y,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,h]=await K1(u),p=await d.createInferenceSessionHandler(c,h);return si("InferenceSession.create"),Zi(),new mM(p)}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}}}),Sg,sA=Ke(()=>{rA(),Sg=pM}),iA=Ke(()=>{}),oA=Ke(()=>{}),lA=Ke(()=>{}),cA=Ke(()=>{}),_M={};$u(_M,{InferenceSession:()=>Sg,TRACE:()=>ch,TRACE_EVENT_BEGIN:()=>ri,TRACE_EVENT_END:()=>si,TRACE_FUNC_BEGIN:()=>Wi,TRACE_FUNC_END:()=>Zi,Tensor:()=>tr,env:()=>zt,registerBackend:()=>Yi});var Ji=Ke(()=>{ZE(),JE(),sA(),fM(),iA(),oA(),hM(),lA(),cA()}),Eg=Ke(()=>{}),gM={};$u(gM,{default:()=>vM});var Km,Jm,vM,uA=Ke(()=>{var e;NM(),eo(),Ag(),Km="ort-wasm-proxy-worker",Jm=((e=globalThis.self)==null?void 0:e.name)===Km,Jm&&(self.onmessage=n=>{let{type:r,in:s}=n.data;try{switch(r){case"init-wasm":Cg(s.wasm).then(()=>{Ng(s).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})})},o=>{postMessage({type:r,err:o})});break;case"init-ep":{let{epName:o,env:c}=s;Dg(c,o).then(()=>{postMessage({type:r})},u=>{postMessage({type:r,err:u})});break}case"copy-from":{let{buffer:o}=s,c=fh(o);postMessage({type:r,out:c});break}case"create":{let{model:o,options:c}=s;Fg(o,c).then(u=>{postMessage({type:r,out:u})},u=>{postMessage({type:r,err:u})});break}case"release":Bg(s),postMessage({type:r});break;case"run":{let{sessionId:o,inputIndices:c,inputs:u,outputIndices:d,options:h}=s;Pg(o,c,u,d,new Array(d.length).fill(null),h).then(p=>{p.some(g=>g[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:p},Ug([...u,...p]))},p=>{postMessage({type:r,err:p})});break}case"end-profiling":Rg(s),postMessage({type:r});break;default:}}catch(o){postMessage({type:r,err:o})}}),vM=Jm?null:n=>new Worker(n??da,{type:"module",name:Km})}),yM={};$u(yM,{default:()=>wM});async function Ab(e={}){var Ps,Di;var n=e,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,o=s&&((Ps=self.name)==null?void 0:Ps.startsWith("em-pthread"));n.mountExternalData=(_,v)=>{_.startsWith("./")&&(_=_.substring(2)),(n.Zc||(n.Zc=new Map)).set(_,v)},n.unmountExternalData=()=>{delete n.Zc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Me:!0}).buffer.constructor;let c=()=>{let _=v=>(...M)=>{let x=mn;return M=v(...M),mn!=x?new Promise((C,N)=>{Ur={resolve:C,reject:N}}):M};(()=>{for(let v of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[v]=_(n[v])})(),typeof jsepRunAsync<"u"&&(n._OrtRun=jsepRunAsync(n._OrtRun),n._OrtRunWithBinding=jsepRunAsync(n._OrtRunWithBinding)),c=void 0};n.asyncInit=()=>{c==null||c()};var u,d,h=(_,v)=>{throw v},p=import.meta.url,g="";if(r||s){try{g=new URL(".",p).href}catch{}s&&(d=_=>{var v=new XMLHttpRequest;return v.open("GET",_,!1),v.responseType="arraybuffer",v.send(null),new Uint8Array(v.response)}),u=async _=>{if(K(_))return new Promise((M,x)=>{var C=new XMLHttpRequest;C.open("GET",_,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?M(C.response):x(C.status)},C.onerror=x,C.send(null)});var v=await fetch(_,{credentials:"same-origin"});if(v.ok)return v.arrayBuffer();throw Error(v.status+" : "+v.url)}}var y,w,b,S,E,O,z=console.log.bind(console),D=console.error.bind(console),P=z,j=D,G=!1,K=_=>_.startsWith("file://");function k(){cr.buffer!=oe.buffer&&F()}if(o){let _=function(v){try{var M=v.data,x=M.Uc;if(x==="load"){let C=[];self.onmessage=N=>C.push(N),O=()=>{postMessage({Uc:"loaded"});for(let N of C)_(N);self.onmessage=_};for(let N of M.ne)n[N]&&!n[N].proxy||(n[N]=(...q)=>{postMessage({Uc:"callHandler",me:N,args:q})},N=="print"&&(P=n[N]),N=="printErr"&&(j=n[N]));cr=M.we,F(),w=M.xe,be(),es()}else if(x==="run"){(function(C){var N=(k(),ee)[C+52>>>2>>>0];C=(k(),ee)[C+56>>>2>>>0],Go(N,N-C),Ce(N)})(M.Sc),Ro(M.Sc,0,0,1,0,0),ad(),Kl(M.Sc),ce||(Fn(),ce=!0);try{sd(M.te,M.ad)}catch(C){if(C!="unwind")throw C}}else M.target!=="setimmediate"&&(x==="checkMailbox"?ce&&_i():x&&(j(`worker: received unknown command ${x}`),j(M)))}catch(C){throw Hr(),C}};var ce=!1;self.onunhandledrejection=v=>{throw v.reason||v},self.onmessage=_}var oe,he,me,pe,ne,ee,Me,V,W,I,R,te=!1;function F(){var _=cr.buffer;n.HEAP8=oe=new Int8Array(_),me=new Int16Array(_),n.HEAPU8=he=new Uint8Array(_),pe=new Uint16Array(_),n.HEAP32=ne=new Int32Array(_),n.HEAPU32=ee=new Uint32Array(_),Me=new Float32Array(_),V=new Float64Array(_),W=new BigInt64Array(_),I=new BigUint64Array(_)}function H(){te=!0,o?O():ia.dc()}function ue(_){throw j(_="Aborted("+_+")"),G=!0,_=new WebAssembly.RuntimeError(_+". Build with -sASSERTIONS for more info."),E==null||E(_),_}function de(){return{a:{sa:Li,g:id,K:Qh,f:Wh,n:Zh,h:Kh,wa:oo,b:lo,ea:co,Ja:fi,o:hi,fa:ld,Za:ql,$b:$l,bc:Hl,_a:fo,Xa:ho,Qa:Yl,Wa:Xl,qa:Ua,ac:Wt,Zb:pn,Ya:Br,_b:po,db:Jh,Fa:pi,Ub:ys,Sb:ud,Ea:go,P:vo,J:Ia,Tb:tp,ma:Zl,Vb:ws,Ta:hd,Xb:pd,Ka:ap,Pb:rp,Ha:bo,Sa:Kl,ab:Ga,W:To,r:Co,c:_o,tb:vi,y:sp,N:nc,D:ac,m:yi,s:wi,ub:_d,I:ip,V:op,j:lp,u:rc,q:cp,k:up,Na:dp,Oa:fp,Pa:hp,La:yd,Ma:wd,Rb:bd,fb:mp,cb:_p,$:gp,sb:vp,na:yp,bb:Md,Y:wp,$a:bp,Yb:Mp,G:pp,ib:oc,_:bi,ra:xi,Wb:Ss,hb:Td,gb:xp,pb:Ap,F:Cp,va:Ti,ua:Ad,rb:Cd,Z:kd,w:Od,ob:pc,nb:kp,mb:Es,qb:mc,lb:Si,kb:_c,jb:zd,Ua:gc,Va:_r,Ia:Rt,ga:vc,pa:yc,Ra:wc,oa:Ld,Eb:gn,za:Yc,Fb:Wc,Aa:Hc,H:It,e:Xo,t:Vd,x:jd,B:In,Ib:Bs,L:Wa,v:Vc,Ba:Np,ca:Hd,ja:Ni,Gb:Qc,Hb:Xc,Da:Wo,Ca:Zo,Kb:Fs,O:Ie,da:kt,d:qd,A:qc,l:Ds,Db:Bt,p:qn,z:Er,C:Un,E:Sr,M:Ft,Lb:ft,U:Yd,ka:Qo,ba:Dp,Mb:$d,Nb:$c,R:Jr,i:zp,a:cr,eb:Ye,Jb:Nd,la:Dd,Q:bc,ta:na,Ob:zo,S:Vn,Ab:As,Bb:Mc,xa:Lo,ha:No,T:xc,Ga:Vr,ya:Fd,aa:Do,yb:Cs,cc:Lp,X:Dn,Cb:Tc,vb:Va,wb:Fo,xb:qr,ia:Sc,zb:Pd,Qb:Ec}}}async function be(){function _(x,C){var N=ia=x.exports;x={};for(let[q,J]of Object.entries(N))typeof J=="function"?(N=Jl(J),x[q]=N):x[q]=J;return ia=x,ia=(function(){var q=ia,J=ve=>Fe=>ve(Fe)>>>0,fe=ve=>()=>ve()>>>0;return(q=Object.assign({},q)).ec=J(q.ec),q.Hc=fe(q.Hc),q.Jc=J(q.Jc),q.vd=(ve=>(Fe,ge)=>ve(Fe,ge)>>>0)(q.vd),q.Ad=J(q.Ad),q.Bd=fe(q.Bd),q.Fd=J(q.Fd),q})(),so.push(ia.md),Ac=(x=ia).ec,Fn=x.fc,n._OrtInit=x.gc,n._OrtGetLastError=x.hc,n._OrtCreateSessionOptions=x.ic,n._OrtAppendExecutionProvider=x.jc,n._OrtAddFreeDimensionOverride=x.kc,n._OrtAddSessionConfigEntry=x.lc,n._OrtReleaseSessionOptions=x.mc,n._OrtCreateSession=x.nc,n._OrtReleaseSession=x.oc,n._OrtGetInputOutputCount=x.pc,n._OrtGetInputOutputMetadata=x.qc,n._OrtFree=x.rc,n._OrtCreateTensor=x.sc,n._OrtGetTensorData=x.tc,n._OrtReleaseTensor=x.uc,n._OrtCreateRunOptions=x.vc,n._OrtAddRunConfigEntry=x.wc,n._OrtReleaseRunOptions=x.xc,n._OrtCreateBinding=x.yc,n._OrtBindInput=x.zc,n._OrtBindOutput=x.Ac,n._OrtClearBoundOutputs=x.Bc,n._OrtReleaseBinding=x.Cc,n._OrtRunWithBinding=x.Dc,n._OrtRun=x.Ec,n._OrtEndProfiling=x.Fc,gr=n._OrtGetWebGpuDevice=x.Gc,qa=x.Hc,_n=n._free=x.Ic,Sa=n._malloc=x.Jc,Bn=n._wgpuBufferRelease=x.Kc,Pn=n._wgpuCreateInstance=x.Lc,$a=x.Mc,aa=x.Nc,ra=x.Oc,Ea=x.Pc,Cc=x.Qc,Bo=x.Tc,Po=x.bd,kc=x.cd,Jt=x.dd,pt=x.fd,Xe=x.gd,Aa=x.hd,En=x.id,$r=x.jd,Ca=x.kd,Oc=x.ld,Ro=x.od,Hr=x.pd,vr=x.qd,Uo=x.rd,Yr=x.sd,Io=x.td,yr=x.ud,sa=x.vd,De=x.wd,Rn=x.xd,Go=x.yd,Ce=x.zd,Ha=x.Ad,Ae=x.Bd,wr=x.Cd,Xt=x.Dd,Ei=x.Ed,zc=x.Fd,Rd=x.Gd,Lc=x.Hd,Ud=x.Id,Dt=x.Jd,jo=x.Kd,ks=x.Ld,Os=x.Md,Vo=x.Nd,Xr=x.Od,Qr=x.Pd,Id=x.Qd,Nc=x.Rd,Gd=x.Sd,Dc=x.Td,br=x.Ud,qo=x.Vd,Ai=x.Wd,Fc=x.Yd,Wr=x.Zd,$o=x._d,Ci=x.$d,ki=x.be,Bc=x.ce,Pc=x.de,Mr=x.ee,xr=x.fe,Rc=x.ge,Uc=x.qe,Zr=x.ve,zs=x.ye,Oi=x.ze,Ls=x.Ae,zi=x.Be,Ic=x.Ce,Tr=x.De,Gc=x.Ee,Ya=x.Fe,Ho=x.Ge,Yo=x.ef,Xa=x.ff,Qa=x.gf,Ns=x.hf,w=C,ia}var v,M=de();return n.instantiateWasm?new Promise(x=>{n.instantiateWasm(M,(C,N)=>{x(_(C,N))})}):o?_(new WebAssembly.Instance(w,de()),w):(R??(R=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.asyncify.wasm",g):g+"ort-wasm-simd-threaded.asyncify.wasm":new URL("/assets/ort-wasm-simd-threaded.asyncify-BC9nQecM.wasm",import.meta.url).href),v=await(async function(x){var C=R;if(!y&&!K(C))try{var N=fetch(C,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(N,x)}catch(q){j(`wasm streaming compile failed: ${q}`),j("falling back to ArrayBuffer instantiation")}return(async function(q,J){try{var fe=await(async function(ve){if(!y)try{var Fe=await u(ve);return new Uint8Array(Fe)}catch{}if(ve==R&&y)ve=new Uint8Array(y);else{if(!d)throw"both async and sync fetching of the wasm failed";ve=d(ve)}return ve})(q);return await WebAssembly.instantiate(fe,J)}catch(ve){j(`failed to asynchronously prepare wasm: ${ve}`),ue(ve)}})(C,x)})(M),_(v.instance,v.module))}class Oe{constructor(v){L(this,"name","ExitStatus");this.message=`Program terminated with exit(${v})`,this.status=v}}var Ne=_=>{_.terminate(),_.onmessage=()=>{}},at=[],Qe=0,ht=null,Ct=_=>{xt.length==0&&(Mn(),rd(xt[0]));var v=xt.pop();if(!v)return 6;_s.push(v),Ra[_.Sc]=v,v.Sc=_.Sc;var M={Uc:"run",te:_.se,ad:_.ad,Sc:_.Sc};return v.postMessage(M,_.he),0},Ue=0,ze=(_,v,...M)=>{var x,C=16*M.length,N=Ae(),q=Ha(C),J=q>>>3;for(x of M)typeof x=="bigint"?((k(),W)[J++>>>0]=1n,(k(),W)[J++>>>0]=x):((k(),W)[J++>>>0]=0n,(k(),V)[J++>>>0]=x);return _=vr(_,0,C,q,v),Ce(N),_};function Ye(_){if(o)return ze(0,1,_);if(b=_,!(0{if(b=_,o)throw Ht(_),"unwind";Ye(_)},xt=[],_s=[],so=[],Ra={},io=_=>{var v=_.Sc;delete Ra[v],xt.push(_),_s.splice(_s.indexOf(_),1),_.Sc=0,Uo(v)};function ad(){so.forEach(_=>_())}var rd=_=>new Promise(v=>{_.onmessage=C=>{var N=C.data;if(C=N.Uc,N.$c&&N.$c!=qa()){var q=Ra[N.$c];q?q.postMessage(N,N.he):j(`Internal error! Worker sent a message "${C}" to target pthread ${N.$c}, but that thread no longer exists!`)}else C==="checkMailbox"?_i():C==="spawnThread"?Ct(N):C==="cleanupThread"?mi(()=>{io(Ra[N.ue])}):C==="loaded"?(_.loaded=!0,v(_)):N.target==="setimmediate"?_.postMessage(N):C==="uncaughtException"?_.onerror(N.error):C==="callHandler"?n[N.me](...N.args):C&&j(`worker sent an unknown command ${C}`)},_.onerror=C=>{throw j(`worker sent an error! ${C.filename}:${C.lineno}: ${C.message}`),C};var M,x=[];for(M of[])n.propertyIsEnumerable(M)&&x.push(M);_.postMessage({Uc:"load",ne:x,we:cr,xe:w})});function Mn(){var _=new Worker((()=>{let v=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new v("ort.webgpu.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});xt.push(_)}var cr,sd=(_,v)=>{Ue=0,_=Lc(_,v),0-9007199254740992>_||9007199254740992<_?NaN:Number(_);function id(_){var v=new _a(_>>>=0);return(k(),oe)[v.Vc+12>>>0]==0&&(vs(v,!0),Fr--),xn(v,!1),di.push(v),zc(_)}var gs=0,Qh=()=>{De(0,0);var _=di.pop();wr(_.nd),gs=0};function vs(_,v){v=v?1:0,(k(),oe)[_.Vc+12>>>0]=v}function xn(_,v){v=v?1:0,(k(),oe)[_.Vc+13>>>0]=v}class _a{constructor(v){this.nd=v,this.Vc=v-24}}var hn=_=>{var v=gs;if(!v)return Rn(0),0;var M=new _a(v);(k(),ee)[M.Vc+16>>>2>>>0]=v;var x=(k(),ee)[M.Vc+4>>>2>>>0];if(!x)return Rn(0),v;for(var C of _){if(C===0||C===x)break;if(Ei(C,x,M.Vc+16))return Rn(C),v}return Rn(x),v};function Wh(){return hn([])}function Zh(_){return hn([_>>>0])}function Kh(_,v,M,x){return hn([_>>>0,v>>>0,M>>>0,x>>>0])}var oo=()=>{var _=di.pop();_||ue("no exception to throw");var v=_.nd;throw(k(),oe)[_.Vc+13>>>0]==0&&(di.push(_),xn(_,!0),vs(_,!1),Fr++),Xt(v),gs=v};function lo(_,v,M){var x=new _a(_>>>=0);throw v>>>=0,M>>>=0,(k(),ee)[x.Vc+16>>>2>>>0]=0,(k(),ee)[x.Vc+4>>>2>>>0]=v,(k(),ee)[x.Vc+8>>>2>>>0]=M,Xt(_),Fr++,gs=_}var co=()=>Fr;function ur(_,v,M,x){return o?ze(2,1,_,v,M,x):fi(_,v,M,x)}function fi(_,v,M,x){if(_>>>=0,v>>>=0,M>>>=0,x>>>=0,!globalThis.SharedArrayBuffer)return 6;var C=[];return o&&C.length===0?ur(_,v,M,x):(_={se:M,Sc:_,ad:x,he:C},o?(_.Uc="spawnThread",postMessage(_,C),0):Ct(_))}function hi(_){throw gs||(gs=_>>>0),gs}var od=globalThis.TextDecoder&&new TextDecoder,Vl=(_,v,M,x)=>{if(M=v+M,x)return M;for(;_[v]&&!(v>=M);)++v;return v},uo=(_,v=0,M,x)=>{if(16<(M=Vl(_,v>>>=0,M,x))-v&&_.buffer&&od)return od.decode(_.buffer instanceof ArrayBuffer?_.subarray(v,M):_.slice(v,M));for(x="";v(C=(240&C)==224?(15&C)<<12|N<<6|q:(7&C)<<18|N<<12|q<<6|63&_[v++])?x+=String.fromCharCode(C):(C-=65536,x+=String.fromCharCode(55296|C>>10,56320|1023&C))}}else x+=String.fromCharCode(C)}return x},ga=(_,v,M)=>(_>>>=0)?uo((k(),he),_,v,M):"";function ld(_,v,M){return o?ze(3,1,_,v,M):0}function ql(_,v){if(o)return ze(4,1,_,v)}function $l(_,v){if(o)return ze(5,1,_,v)}function Hl(_,v,M){if(o)return ze(6,1,_,v,M)}function fo(_,v,M){return o?ze(7,1,_,v,M):0}function ho(_,v){if(o)return ze(8,1,_,v)}function Yl(_,v,M){if(o)return ze(9,1,_,v,M)}function Xl(_,v,M,x){if(o)return ze(10,1,_,v,M,x)}function Ua(_,v,M,x){if(o)return ze(11,1,_,v,M,x)}function Wt(_,v,M,x){if(o)return ze(12,1,_,v,M,x)}function pn(_){if(o)return ze(13,1,_)}function Br(_,v){if(o)return ze(14,1,_,v)}function po(_,v,M){if(o)return ze(15,1,_,v,M)}var Jh=()=>ue(""),va=_=>{_>>>=0;for(var v="";;){var M=(k(),he)[_++>>>0];if(!M)return v;v+=String.fromCharCode(M)}},mo={},Pr={},dr=class extends Error{constructor(_){super(_),this.name="BindingError"}};function Tn(_,v,M={}){return(function(x,C,N={}){var q=C.name;if(!x)throw new dr(`type "${q}" must have a positive integer typeid pointer`);if(Pr.hasOwnProperty(x)){if(N.oe)return;throw new dr(`Cannot register type '${q}' twice`)}Pr[x]=C,mo.hasOwnProperty(x)&&(C=mo[x],delete mo[x],C.forEach(J=>J()))})(_,v,M)}var Rr=(_,v,M)=>{switch(v){case 1:return M?x=>(k(),oe)[x>>>0]:x=>(k(),he)[x>>>0];case 2:return M?x=>(k(),me)[x>>>1>>>0]:x=>(k(),pe)[x>>>1>>>0];case 4:return M?x=>(k(),ne)[x>>>2>>>0]:x=>(k(),ee)[x>>>2>>>0];case 8:return M?x=>(k(),W)[x>>>3>>>0]:x=>(k(),I)[x>>>3>>>0];default:throw new TypeError(`invalid integer width (${v}): ${_}`)}};function pi(_,v,M,x,C){_>>>=0,M>>>=0,v=va(v>>>0);let N=q=>q;if(x=x===0n){let q=8*M;N=J=>BigInt.asUintN(q,J),C=N(C)}Tn(_,{name:v,Rc:N,Xc:(q,J)=>(typeof J=="number"&&(J=BigInt(J)),J),Wc:Rr(v,M,!x),Yc:null})}function ys(_,v,M,x){Tn(_>>>=0,{name:v=va(v>>>0),Rc:function(C){return!!C},Xc:function(C,N){return N?M:x},Wc:function(C){return this.Rc((k(),he)[C>>>0])},Yc:null})}var Yt=[],fr=[0,1,,1,null,1,!0,1,!1,1];function _o(_){9<(_>>>=0)&&--fr[_+1]==0&&(fr[_]=void 0,Yt.push(_))}var Zt=_=>{if(!_)throw new dr(`Cannot use deleted val. handle = ${_}`);return fr[_]},on=_=>{switch(_){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let v=Yt.pop()||fr.length;return fr[v]=_,fr[v+1]=1,v}};function Ql(_){return this.Rc((k(),ee)[_>>>2>>>0])}var cd={name:"emscripten::val",Rc:_=>{var v=Zt(_);return _o(_),v},Xc:(_,v)=>on(v),Wc:Ql,Yc:null};function ud(_){return Tn(_>>>0,cd)}var ep=(_,v)=>{switch(v){case 4:return function(M){return this.Rc((k(),Me)[M>>>2>>>0])};case 8:return function(M){return this.Rc((k(),V)[M>>>3>>>0])};default:throw new TypeError(`invalid float width (${v}): ${_}`)}};function go(_,v,M){M>>>=0,Tn(_>>>=0,{name:v=va(v>>>0),Rc:x=>x,Xc:(x,C)=>C,Wc:ep(v,M),Yc:null})}function vo(_,v,M,x,C){_>>>=0,M>>>=0,v=va(v>>>0);let N=J=>J;if(x===0){var q=32-8*M;N=J=>J<>>q,C=N(C)}Tn(_,{name:v,Rc:N,Xc:(J,fe)=>fe,Wc:Rr(v,M,x!==0),Yc:null})}function Ia(_,v,M){function x(N){var q=(k(),ee)[N>>>2>>>0];return N=(k(),ee)[N+4>>>2>>>0],new C((k(),oe).buffer,N,q)}var C=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][v];Tn(_>>>=0,{name:M=va(M>>>0),Rc:x,Wc:x},{oe:!0})}var Ut=(_,v,M)=>{var x=(k(),he);if(v>>>=0,0=q){if(v>=M)break;x[v++>>>0]=q}else if(2047>=q){if(v+1>=M)break;x[v++>>>0]=192|q>>6,x[v++>>>0]=128|63&q}else if(65535>=q){if(v+2>=M)break;x[v++>>>0]=224|q>>12,x[v++>>>0]=128|q>>6&63,x[v++>>>0]=128|63&q}else{if(v+3>=M)break;x[v++>>>0]=240|q>>18,x[v++>>>0]=128|q>>12&63,x[v++>>>0]=128|q>>6&63,x[v++>>>0]=128|63&q,N++}}x[v>>>0]=0,_=v-C}else _=0;return _},ya=_=>{for(var v=0,M=0;M<_.length;++M){var x=_.charCodeAt(M);127>=x?v++:2047>=x?v+=2:55296<=x&&57343>=x?(v+=4,++M):v+=3}return v};function tp(_,v){Tn(_>>>=0,{name:v=va(v>>>0),Rc(M){var x=(k(),ee)[M>>>2>>>0];return x=ga(M+4,x,!0),_n(M),x},Xc(M,x){x instanceof ArrayBuffer&&(x=new Uint8Array(x));var C=typeof x=="string";if(!(C||ArrayBuffer.isView(x)&&x.BYTES_PER_ELEMENT==1))throw new dr("Cannot pass non-string to std::string");var N=C?ya(x):x.length,q=Sa(4+N+1),J=q+4;return(k(),ee)[q>>>2>>>0]=N,C?Ut(x,J,N+1):(k(),he).set(x,J>>>0),M!==null&&M.push(_n,q),q},Wc:Ql,Yc(M){_n(M)}})}var yo=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,dd=(_,v,M)=>{if(_>>>=1,16<(v=Vl((k(),pe),_,v/2,M))-_&&yo)return yo.decode((k(),pe).slice(_,v));for(M="";_>>0];M+=String.fromCharCode(x)}return M},wo=(_,v,M)=>{if(M??(M=2147483647),2>M)return 0;var x=v;M=(M-=2)<2*_.length?M/2:_.length;for(var C=0;C>>1>>>0]=N,v+=2}return(k(),me)[v>>>1>>>0]=0,v-x},np=_=>2*_.length,jn=(_,v,M)=>{var x="";_>>>=2;for(var C=0;!(C>=v/4);C++){var N=(k(),ee)[_+C>>>0];if(!N&&!M)break;x+=String.fromCodePoint(N)}return x},Wl=(_,v,M)=>{if(v>>>=0,M??(M=2147483647),4>M)return 0;var x=v;M=x+M-4;for(var C=0;C<_.length;++C){var N=_.codePointAt(C);if(65535>>2>>>0]=N,(v+=4)+4>M)break}return(k(),ne)[v>>>2>>>0]=0,v-x},fd=_=>{for(var v=0,M=0;M<_.length;++M)65535<_.codePointAt(M)&&M++,v+=4;return v};function Zl(_,v,M){if(_>>>=0,v>>>=0,M=va(M>>>=0),v===2)var x=dd,C=wo,N=np;else x=jn,C=Wl,N=fd;Tn(_,{name:M,Rc:q=>{var J=(k(),ee)[q>>>2>>>0];return J=x(q+4,J*v,!0),_n(q),J},Xc:(q,J)=>{if(typeof J!="string")throw new dr(`Cannot pass non-string to C++ string type ${M}`);var fe=N(J),ve=Sa(4+fe+v);return(k(),ee)[ve>>>2>>>0]=fe/v,C(J,ve+4,fe+v),q!==null&&q.push(_n,ve),ve},Wc:Ql,Yc(q){_n(q)}})}function ws(_,v){Tn(_>>>=0,{pe:!0,name:v=va(v>>>0),Rc:()=>{},Xc:()=>{}})}function hd(_){Ro(_>>>0,!s,1,!r,131072,!1),ad()}var mi=_=>{if(!G)try{if(_(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Kl(_){_>>>=0,bs||(Atomics.waitAsync((k(),ne),_>>>2,_).value.then(_i),_+=128,Atomics.store((k(),ne),_>>>2,1))}var _i=()=>mi(()=>{var _=qa();_&&(Kl(_),yr())});function pd(_,v){(_>>>=0)==v>>>0?setTimeout(_i):o?postMessage({$c:_,Uc:"checkMailbox"}):(_=Ra[_])&&_.postMessage({Uc:"checkMailbox"})}var gi=[];function ap(_,v,M,x,C){for(v>>>=0,C>>>=0,gi.length=0,M=C>>>3,x=C+x>>>3;M>>0]?(k(),W)[M++>>>0]:(k(),V)[M++>>>0],gi.push(N)}return(v?Kr[v]:jc[_])(...gi)}var rp=()=>{Ue=0};function bo(_){_>>>=0,o?postMessage({Uc:"cleanupThread",ue:_}):io(Ra[_])}function Ga(_){}var Ms=_=>{try{_()}catch(v){ue(v)}};function Jl(_){var v=(...M)=>{xs.push(_);try{return _(...M)}finally{G||(xs.pop(),mn&&Nn===1&&xs.length===0&&(Nn=0,Ue+=1,Ms(Xa),typeof Fibers<"u"&&Fibers.Oe()))}};return wa.set(_,v),v}var Nn=0,mn=null,ec=0,xs=[],Mo=new Map,Ts=new Map,wa=new Map,tc=0,Ur=null,hr=[],xo=_=>(function(v){if(!G){if(Nn===0){var M=!1,x=!1;v((C=0)=>{if(!G&&(ec=C,M=!0,x)){Nn=2,Ms(()=>Qa(mn)),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.resume(),C=!1;try{var N=(function(){var fe=(k(),ne)[mn+8>>>2>>>0];return fe=Ts.get(fe),fe=wa.get(fe),--Ue,fe()})()}catch(fe){N=fe,C=!0}var q=!1;if(!mn){var J=Ur;J&&(Ur=null,(C?J.reject:J.resolve)(N),q=!0)}if(C&&!q)throw N}}),x=!0,M||(Nn=1,mn=(function(){var C=Sa(65548),N=C+12;if((k(),ee)[C>>>2>>>0]=N,(k(),ee)[C+4>>>2>>>0]=N+65536,N=xs[0],!Mo.has(N)){var q=tc++;Mo.set(N,q),Ts.set(q,N)}return N=Mo.get(N),(k(),ne)[C+8>>>2>>>0]=N,C})(),typeof MainLoop<"u"&&MainLoop.le&&MainLoop.pause(),Ms(()=>Yo(mn)))}else Nn===2?(Nn=0,Ms(Ns),_n(mn),mn=null,hr.forEach(mi)):ue(`invalid state: ${Nn}`);return ec}})(v=>{_().then(v)});function To(_){return _>>>=0,xo(async()=>{var v=await Zt(_);return on(v)})}var So=[],Eo=_=>{var v=So.length;return So.push(_),v},Ao=(_,v)=>{for(var M=Array(_),x=0;x<_;++x){var C=x,N=(k(),ee)[v+4*x>>>2>>>0],q=Pr[N];if(q===void 0)throw _=`parameter ${x}`,N=Ac(N),v=va(N),_n(N),new dr(`${_} has unknown type ${v}`);M[C]=q}return M},md=(_,v,M)=>{var x=[];return _=_(x,M),x.length&&((k(),ee)[v>>>2>>>0]=on(x)),_},Sn={},ba=_=>{var v=Sn[_];return v===void 0?va(_):v};function Co(_,v,M){var[x,...C]=Ao(_,v>>>0);v=x.Xc.bind(x);var N=C.map(fe=>fe.Wc.bind(fe));_--;var q={toValue:Zt};switch(_=N.map((fe,ve)=>{var Fe=`argFromPtr${ve}`;return q[Fe]=fe,`${Fe}(args${ve?"+"+8*ve:""})`}),M){case 0:var J="toValue(handle)";break;case 2:J="new (toValue(handle))";break;case 3:J="";break;case 1:q.getStringOrSymbol=ba,J="toValue(handle)[getStringOrSymbol(methodName)]"}return J+=`(${_})`,x.pe||(q.toReturnWire=v,q.emval_returnValue=md,J=`return emval_returnValue(toReturnWire, destructorsRef, ${J})`),J=`return function (handle, methodName, destructorsRef, args) { + ${J} + }`,M=new Function(Object.keys(q),J)(...Object.values(q)),J=`methodCaller<(${C.map(fe=>fe.name)}) => ${x.name}>`,Eo(Object.defineProperty(M,"name",{value:J}))}function vi(_,v){return v>>>=0,(_=Zt(_>>>0))==Zt(v)}function sp(_){return(_>>>=0)?(_=ba(_),on(globalThis[_])):on(globalThis)}function nc(_){return _=ba(_>>>0),on(n[_])}function ac(_,v){return v>>>=0,_=Zt(_>>>0),v=Zt(v),on(_[v])}function yi(_){9<(_>>>=0)&&(fr[_+1]+=1)}function wi(_,v,M,x,C){return So[_>>>0](v>>>0,M>>>0,x>>>0,C>>>0)}function _d(_,v,M,x,C){return wi(_>>>0,v>>>0,M>>>0,x>>>0,C>>>0)}function ip(){return on([])}function op(_){_=Zt(_>>>0);for(var v=Array(_.length),M=0;M<_.length;M++)v[M]=_[M];return on(v)}function lp(_){return on(ba(_>>>0))}function rc(){return on({})}function cp(_){for(var v=Zt(_>>>=0);v.length;){var M=v.pop();v.pop()(M)}_o(_)}function up(_,v,M){v>>>=0,M>>>=0,_=Zt(_>>>0),v=Zt(v),M=Zt(M),_[v]=M}function dp(_,v){_=fn(_),v>>>=0,_=new Date(1e3*_),(k(),ne)[v>>>2>>>0]=_.getUTCSeconds(),(k(),ne)[v+4>>>2>>>0]=_.getUTCMinutes(),(k(),ne)[v+8>>>2>>>0]=_.getUTCHours(),(k(),ne)[v+12>>>2>>>0]=_.getUTCDate(),(k(),ne)[v+16>>>2>>>0]=_.getUTCMonth(),(k(),ne)[v+20>>>2>>>0]=_.getUTCFullYear()-1900,(k(),ne)[v+24>>>2>>>0]=_.getUTCDay(),_=(_.getTime()-Date.UTC(_.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(k(),ne)[v+28>>>2>>>0]=_}var gd=_=>_%4==0&&(_%100!=0||_%400==0),vd=[0,31,60,91,121,152,182,213,244,274,305,335],sc=[0,31,59,90,120,151,181,212,243,273,304,334];function fp(_,v){_=fn(_),v>>>=0,_=new Date(1e3*_),(k(),ne)[v>>>2>>>0]=_.getSeconds(),(k(),ne)[v+4>>>2>>>0]=_.getMinutes(),(k(),ne)[v+8>>>2>>>0]=_.getHours(),(k(),ne)[v+12>>>2>>>0]=_.getDate(),(k(),ne)[v+16>>>2>>>0]=_.getMonth(),(k(),ne)[v+20>>>2>>>0]=_.getFullYear()-1900,(k(),ne)[v+24>>>2>>>0]=_.getDay();var M=(gd(_.getFullYear())?vd:sc)[_.getMonth()]+_.getDate()-1|0;(k(),ne)[v+28>>>2>>>0]=M,(k(),ne)[v+36>>>2>>>0]=-60*_.getTimezoneOffset(),M=new Date(_.getFullYear(),6,1).getTimezoneOffset();var x=new Date(_.getFullYear(),0,1).getTimezoneOffset();_=0|(M!=x&&_.getTimezoneOffset()==Math.min(x,M)),(k(),ne)[v+32>>>2>>>0]=_}function hp(_){_>>>=0;var v=new Date((k(),ne)[_+20>>>2>>>0]+1900,(k(),ne)[_+16>>>2>>>0],(k(),ne)[_+12>>>2>>>0],(k(),ne)[_+8>>>2>>>0],(k(),ne)[_+4>>>2>>>0],(k(),ne)[_>>>2>>>0],0),M=(k(),ne)[_+32>>>2>>>0],x=v.getTimezoneOffset(),C=new Date(v.getFullYear(),6,1).getTimezoneOffset(),N=new Date(v.getFullYear(),0,1).getTimezoneOffset(),q=Math.min(N,C);return 0>M?(k(),ne)[_+32>>>2>>>0]=+(C!=N&&q==x):0>>2>>>0]=v.getDay(),M=(gd(v.getFullYear())?vd:sc)[v.getMonth()]+v.getDate()-1|0,(k(),ne)[_+28>>>2>>>0]=M,(k(),ne)[_>>>2>>>0]=v.getSeconds(),(k(),ne)[_+4>>>2>>>0]=v.getMinutes(),(k(),ne)[_+8>>>2>>>0]=v.getHours(),(k(),ne)[_+12>>>2>>>0]=v.getDate(),(k(),ne)[_+16>>>2>>>0]=v.getMonth(),(k(),ne)[_+20>>>2>>>0]=v.getYear(),_=v.getTime(),BigInt(isNaN(_)?-1:_/1e3)}function yd(_,v,M,x,C,N,q){return o?ze(16,1,_,v,M,x,C,N,q):-52}function wd(_,v,M,x,C,N){if(o)return ze(17,1,_,v,M,x,C,N)}var Ir={},pp=()=>performance.timeOrigin+performance.now();function bd(_,v){if(o)return ze(18,1,_,v);if(Ir[_]&&(clearTimeout(Ir[_].id),delete Ir[_]),!v)return 0;var M=setTimeout(()=>{delete Ir[_],mi(()=>Io(_,performance.timeOrigin+performance.now()))},v);return Ir[_]={id:M,Ne:v},0}function mp(_,v,M,x){_>>>=0,v>>>=0,M>>>=0,x>>>=0;var C=new Date().getFullYear(),N=new Date(C,0,1).getTimezoneOffset();C=new Date(C,6,1).getTimezoneOffset();var q=Math.max(N,C);(k(),ee)[_>>>2>>>0]=60*q,(k(),ne)[v>>>2>>>0]=+(N!=C),_=(v=J=>{var fe=Math.abs(J);return`UTC${0<=J?"-":"+"}${String(Math.floor(fe/60)).padStart(2,"0")}${String(fe%60).padStart(2,"0")}`})(N),v=v(C),CDate.now();function _p(_,v,M){return M>>>=0,0<=_&&3>=_?(_===0?_=Date.now():_=performance.timeOrigin+performance.now(),_=Math.round(1e6*_),(k(),W)[M>>>3>>>0]=BigInt(_),0):28}var ic=[],xd=(_,v)=>{ic.length=0;for(var M;M=(k(),he)[_++>>>0];){var x=M!=105;v+=(x&=M!=112)&&v%8?4:0,ic.push(M==112?(k(),ee)[v>>>2>>>0]:M==106?(k(),W)[v>>>3>>>0]:M==105?(k(),ne)[v>>>2>>>0]:(k(),V)[v>>>3>>>0]),v+=x?8:4}return ic};function gp(_,v,M){return _>>>=0,v=xd(v>>>0,M>>>0),Kr[_](...v)}function vp(_,v,M){return _>>>=0,v=xd(v>>>0,M>>>0),Kr[_](...v)}var yp=()=>{};function wp(_,v){return j(ga(_>>>0,v>>>0))}var bp=()=>{throw Ue+=1,"unwind"};function Mp(){return 4294901760}var oc=()=>1,bi=()=>navigator.hardwareConcurrency,Gr={},lc=_=>{var v=ya(_)+1,M=Sa(v);return M&&Ut(_,M,v),M},Mi=_=>{var v;return(v=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(_))?+v[1]:(v=/:(\d+):\d+(?:\)|$)/.exec(_))?2147483648|+v[1]:0},cc=_=>{for(var v of _)(_=Mi(v))&&(Gr[_]=v)};function Td(){var _=Error().stack.toString().split(` +`);return _[0]=="Error"&&_.shift(),cc(_),Gr.Xd=Mi(_[3]),Gr.re=_,Gr.Xd}function xi(_){if(!(_=Gr[_>>>0]))return 0;var v;if(v=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(_))_=v[1];else if(v=/^\s+at (.*) \(.*\)$/.exec(_))_=v[1];else{if(!(v=/^(.+?)@/.exec(_)))return 0;_=v[1]}return _n(xi.ae??0),xi.ae=lc(_),xi.ae}function Ss(_){_>>>=0;var v=(k(),he).length;if(_<=v||4294901760<_)return!1;for(var M=1;4>=M;M*=2){var x=v*(1+.2/M);x=Math.min(x,_+100663296);e:{x=(Math.min(4294901760,65536*Math.ceil(Math.max(_,x)/65536))-cr.buffer.byteLength+65535)/65536|0;try{cr.grow(x),F();var C=1;break e}catch{}C=void 0}if(C)return!0}return!1}function xp(_,v,M){if(_>>>=0,v>>>=0,Gr.Xd==_)var x=Gr.re;else(x=Error().stack.toString().split(` +`))[0]=="Error"&&x.shift(),cc(x);for(var C=3;x[C]&&Mi(x[C])!=_;)++C;for(_=0;_>>2>>>0]=Mi(x[_+C]);return _}var Ma=_=>{var v=ya(_)+1,M=Ha(v);return Ut(_,M,v),M},uc=[],ln=(_,v)=>{uc[_>>>=0]=v},ta=[],pr=[],xa=(_,v)=>{pr[_]=new Promise(M=>v.finally(()=>M(_)))},Ee=_=>{if(_)return uc[_>>>0]},jr=(_,v,M)=>{(k(),ee)[_>>>2>>>0]=v,(k(),ee)[_+4>>>2>>>0]=M},dc=_=>{var v=(k(),ee)[_>>>2>>>0];return _=(k(),ee)[_+4>>>2>>>0],ga(v,_)},Ta=_=>{var v=(k(),ee)[_>>>2>>>0];return _=(k(),ee)[_+4>>>2>>>0],v?ga(v,_):_===0?"":void 0},fc=_=>{var v=Ta(_+4),M=(M=(k(),ee)[_+12>>>2>>>0])?Ee(M):"auto";if(_+=16){var x=Ee((k(),ee)[_+4>>>2>>>0]),C=(k(),ee)[_+16>>>2>>>0],N=(k(),ee)[_+20>>>2>>>0];if(C){for(var q={},J=0;J>>3>>>0]}C=q}else C=void 0;_={module:x,constants:C,entryPoint:Ta(_+8)}}else _=void 0;return{label:v,layout:M,compute:_}},ko=(_,v)=>{function M(C,N){C=_[C],(k(),ne)[v+N>>>2>>>0]=C}function x(C,N){C=_[C],(k(),W)[v+N>>>3>>>0]=BigInt(C)}M("maxTextureDimension1D",4),M("maxTextureDimension2D",8),M("maxTextureDimension3D",12),M("maxTextureArrayLayers",16),M("maxBindGroups",20),M("maxBindGroupsPlusVertexBuffers",24),M("maxBindingsPerBindGroup",28),M("maxDynamicUniformBuffersPerPipelineLayout",32),M("maxDynamicStorageBuffersPerPipelineLayout",36),M("maxSampledTexturesPerShaderStage",40),M("maxSamplersPerShaderStage",44),M("maxStorageBuffersPerShaderStage",48),M("maxStorageTexturesPerShaderStage",52),M("maxUniformBuffersPerShaderStage",56),M("minUniformBufferOffsetAlignment",80),M("minStorageBufferOffsetAlignment",84),x("maxUniformBufferBindingSize",64),x("maxStorageBufferBindingSize",72),M("maxVertexBuffers",88),x("maxBufferSize",96),M("maxVertexAttributes",104),M("maxVertexBufferArrayStride",108),M("maxInterStageShaderVariables",112),M("maxColorAttachments",116),M("maxColorAttachmentBytesPerSample",120),M("maxComputeWorkgroupStorageSize",124),M("maxComputeInvocationsPerWorkgroup",128),M("maxComputeWorkgroupSizeX",132),M("maxComputeWorkgroupSizeY",136),M("maxComputeWorkgroupSizeZ",140),M("maxComputeWorkgroupsPerDimension",144),_.Le!==void 0&&M("maxImmediateSize",148)},Sd=[,"validation","out-of-memory","internal"],Ed=[,"compatibility","core"],hc={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"},Tp=[,"low-power","high-performance"],Sp=[,"occlusion","timestamp"],Ep={undefined:1,unknown:1,destroyed:2};function Ap(_,v,M,x,C,N){v=fn(v),M=fn(M),x>>>=0,C>>>=0,N>>>=0;var q=Ee(_>>>0);if(_={},N){var J=(k(),ee)[N+12>>>2>>>0];if(J){var fe=(k(),ee)[N+16>>>2>>>0];_.requiredFeatures=Array.from((k(),ee).subarray(fe>>>2>>>0,fe+4*J>>>2>>>0),ge=>hc[ge])}var ve=(k(),ee)[N+20>>>2>>>0];if(ve){let ge=function(lt,Gt,Rs=!1){Gt=ve+Gt,(Gt=(k(),ee)[Gt>>>2>>>0])==4294967295||Rs&&Gt==0||(Fe[lt]=Gt)},Ge=function(lt,Gt){Gt=ve+Gt;var Rs=(k(),ee)[Gt>>>2>>>0],Ko=(k(),ee)[Gt+4>>>2>>>0];Rs==4294967295&&Ko==4294967295||(Fe[lt]=4294967296*(k(),ee)[Gt+4>>>2>>>0]+(k(),ee)[Gt>>>2>>>0])};var Fe={};ge("maxTextureDimension1D",4),ge("maxTextureDimension2D",8),ge("maxTextureDimension3D",12),ge("maxTextureArrayLayers",16),ge("maxBindGroups",20),ge("maxBindGroupsPlusVertexBuffers",24),ge("maxDynamicUniformBuffersPerPipelineLayout",32),ge("maxDynamicStorageBuffersPerPipelineLayout",36),ge("maxSampledTexturesPerShaderStage",40),ge("maxSamplersPerShaderStage",44),ge("maxStorageBuffersPerShaderStage",48),ge("maxStorageTexturesPerShaderStage",52),ge("maxUniformBuffersPerShaderStage",56),ge("minUniformBufferOffsetAlignment",80),ge("minStorageBufferOffsetAlignment",84),Ge("maxUniformBufferBindingSize",64),Ge("maxStorageBufferBindingSize",72),ge("maxVertexBuffers",88),Ge("maxBufferSize",96),ge("maxVertexAttributes",104),ge("maxVertexBufferArrayStride",108),ge("maxInterStageShaderVariables",112),ge("maxColorAttachments",116),ge("maxColorAttachmentBytesPerSample",120),ge("maxComputeWorkgroupStorageSize",124),ge("maxComputeInvocationsPerWorkgroup",128),ge("maxComputeWorkgroupSizeX",132),ge("maxComputeWorkgroupSizeY",136),ge("maxComputeWorkgroupSizeZ",140),ge("maxComputeWorkgroupsPerDimension",144),ge("maxImmediateSize",148,!0),_.requiredLimits=Fe}(J=(k(),ee)[N+24>>>2>>>0])&&(J={label:Ta(J+4)},_.defaultQueue=J),_.label=Ta(N+4)}Ue+=1,xa(v,q.requestDevice(_).then(ge=>{--Ue,ln(C,ge.queue),ln(x,ge),M&&(Ue+=1,xa(M,ge.lost.then(Ge=>{--Ue,ge.onuncapturederror=()=>{};var lt=Ae(),Gt=Ma(Ge.message);Xe(M,Ep[Ge.reason],Gt),Ce(lt)}))),ge.onuncapturederror=Ge=>{var lt=5;Ge.error instanceof GPUValidationError?lt=2:Ge.error instanceof GPUOutOfMemoryError?lt=3:Ge.error instanceof GPUInternalError&&(lt=4);var Gt=Ae();Ge=Ma(Ge.error.message),Oc(x,lt,Ge),Ce(Gt)},"adapterInfo"in ge||(ge.adapterInfo=q.info),Ca(v,1,x,0)},ge=>{--Ue;var Ge=Ae();ge=Ma(ge.message),Ca(v,3,x,ge),M&&Xe(M,4,ge),Ce(Ge)}))}function Cp(_){var v=Ee(_>>>=0),M=ta[_];if(M){for(var x=0;x{var _="getMappedRange size=0 no longer means WGPU_WHOLE_MAP_SIZE";Kt.ed||(Kt.ed={}),Kt.ed[_]||(Kt.ed[_]=1,j(_))};function Ti(_,v,M){v>>>=0,M>>>=0;var x=Ee(_>>>=0);M===0&&Kt(),M==4294967295&&(M=void 0);try{var C=x.getMappedRange(v,M)}catch{return 0}var N=sa(16,C.byteLength);return(k(),he).set(new Uint8Array(C),N>>>0),ta[_].push(()=>_n(N)),N}function Ad(_,v,M){v>>>=0,M>>>=0;var x=Ee(_>>>=0);M===0&&Kt(),M==4294967295&&(M=void 0);try{var C=x.getMappedRange(v,M)}catch{return 0}var N=sa(16,C.byteLength);return(k(),he).fill(0,N,C.byteLength),ta[_].push(()=>{new Uint8Array(C).set((k(),he).subarray(N>>>0,N+C.byteLength>>>0)),_n(N)}),N}function Cd(_,v,M,x,C){_>>>=0,v=fn(v),M=fn(M),C>>>=0;var N=Ee(_);ta[_]=[],C==4294967295&&(C=void 0),Ue+=1,xa(v,N.mapAsync(M,x>>>0,C).then(()=>{--Ue,Aa(v,1,0)},q=>{--Ue,Ae();var J=Ma(q.message);Aa(v,q.name==="AbortError"?4:q.name==="OperationError"?3:0,J),delete ta[_]}))}function kd(_){var v=Ee(_>>>=0),M=ta[_];if(M){for(var x=0;x>>0]}function pc(_,v,M){_>>>=0,v>>>=0,M>>>=0;var x=!!(k(),ee)[v+32>>>2>>>0];v={label:Ta(v+4),usage:(k(),ee)[v+16>>>2>>>0],size:4294967296*(k(),ee)[v+28>>>2>>>0]+(k(),ee)[v+24>>>2>>>0],mappedAtCreation:x},_=Ee(_);try{var C=_.createBuffer(v)}catch{return!1}return ln(M,C),x&&(ta[M]=[]),!0}function kp(_,v,M,x){_>>>=0,v=fn(v),x>>>=0,M=fc(M>>>0),_=Ee(_),Ue+=1,xa(v,_.createComputePipelineAsync(M).then(C=>{--Ue,ln(x,C),pt(v,1,x,0)},C=>{--Ue;var N=Ae(),q=Ma(C.message);pt(v,C.reason==="validation"?3:C.reason==="internal"?4:0,x,q),Ce(N)}))}function Es(_,v,M){_>>>=0,v>>>=0,M>>>=0;var x=(k(),ee)[v>>>2>>>0],C=(k(),ee)[x+4>>>2>>>0];v={label:Ta(v+4),code:""},C===2&&(v.code=dc(x+8)),ln(M,Ee(_).createShaderModule(v))}var mc=_=>{(_=Ee(_)).onuncapturederror=null,_.destroy()};function Si(_,v){v=fn(v),_=Ee(_>>>0),Ue+=1,xa(v,_.popErrorScope().then(M=>{--Ue;var x=5;M?M instanceof GPUValidationError?x=2:M instanceof GPUOutOfMemoryError?x=3:M instanceof GPUInternalError&&(x=4):x=1;var C=Ae();M=M?Ma(M.message):0,En(v,1,x,M),Ce(C)},M=>{--Ue;var x=Ae();M=Ma(M.message),En(v,1,5,M),Ce(x)}))}function _c(_,v,M,x){if(v=fn(v),x>>>=0,M>>>=0){var C=(k(),ee)[M+4>>>2>>>0];C={featureLevel:Ed[C],powerPreference:Tp[(k(),ee)[M+8>>>2>>>0]],forceFallbackAdapter:!!(k(),ee)[M+12>>>2>>>0]},(M=(k(),ee)[M>>>2>>>0])!==0&&(k(),C.Qe=!!(k(),ee)[M+8>>>2>>>0])}"gpu"in navigator?(Ue+=1,xa(v,navigator.gpu.requestAdapter(C).then(N=>{if(--Ue,N)ln(x,N),$r(v,1,x,0);else{N=Ae();var q=Ma("WebGPU not available on this browser (requestAdapter returned null)");$r(v,3,x,q),Ce(N)}},N=>{--Ue;var q=Ae();N=Ma(N.message),$r(v,4,x,N),Ce(q)}))):(M=Ae(),C=Ma("WebGPU not available on this browser (navigator.gpu is not available)"),$r(v,3,x,C),Ce(M))}function zd(_,v,M){return _>>>=0,v>>>=0,M>>>=0,xo(async()=>{var x=[];if(M){var C=(k(),ne)[M>>>2>>>0];x.length=v+1,x[v]=new Promise(J=>setTimeout(J,C,0))}else x.length=v;for(var N=0;N>>2>>>0]+(k(),ee)[_+8*N>>>2>>>0];if(!(q in pr))return q;x[N]=pr[q]}return x=await Promise.race(x),delete pr[x],x})}var ja,mr={},Oo=()=>{var x;if(!ja){var _,v={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(((x=globalThis.navigator)==null?void 0:x.language)??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(_ in mr)mr[_]===void 0?delete v[_]:v[_]=mr[_];var M=[];for(_ in v)M.push(`${_}=${v[_]}`);ja=M}return ja};function gc(_,v){if(o)return ze(19,1,_,v);_>>>=0,v>>>=0;var M,x=0,C=0;for(M of Oo()){var N=v+x;(k(),ee)[_+C>>>2>>>0]=N,x+=Ut(M,N,1/0)+1,C+=4}return 0}function _r(_,v){if(o)return ze(20,1,_,v);_>>>=0,v>>>=0;var M=Oo();for(var x of((k(),ee)[_>>>2>>>0]=M.length,_=0,M))_+=ya(x)+1;return(k(),ee)[v>>>2>>>0]=_,0}function vc(_){return o?ze(21,1,_):52}function yc(_,v,M,x){return o?ze(22,1,_,v,M,x):52}function wc(_,v,M,x){return o?ze(23,1,_,v,M,x):70}var Op=[null,[],[]];function Ld(_,v,M,x){if(o)return ze(24,1,_,v,M,x);v>>>=0,M>>>=0,x>>>=0;for(var C=0,N=0;N>>2>>>0],J=(k(),ee)[v+4>>>2>>>0];v+=8;for(var fe=0;fe>>0],ge=Op[ve];Fe===0||Fe===10?((ve===1?P:j)(uo(ge)),ge.length=0):ge.push(Fe)}C+=J}return(k(),ee)[x>>>2>>>0]=C,0}function zp(_){return _>>>0}function Nd(_,v){return ko(Ee(_>>>0).limits,v>>>0),1}function Dd(_,v){return Ee(_>>>0).features.has(hc[v])}function bc(_){return BigInt(Ee(_>>>0).size)}function na(_){return BigInt(Ee(_>>>0).usage)}function zo(_,v){if(_>>>=0,v>>>=0){var M=Ta(v+4);M={label:M,timestampWrites:v=(v=(k(),ee)[v+12>>>2>>>0])!==0?{querySet:Ee((k(),ee)[v+4>>>2>>>0]),beginningOfPassWriteIndex:(k(),ee)[v+8>>>2>>>0],endOfPassWriteIndex:(k(),ee)[v+12>>>2>>>0]}:void 0}}return _=Ee(_),v=Cc(0),ln(v,_.beginComputePass(M)),v}function Vn(_,v,M,x,C,N){M=fn(M),C=fn(C),N=fn(N),Ee(_>>>0).copyBufferToBuffer(Ee(v>>>0),M,Ee(x>>>0),C,N)}function As(_){_=Ee(_>>>0);var v=ra(0);return ln(v,_.finish()),v}function Mc(_,v,M,x,C,N){N=fn(N),Ee(_>>>0).resolveQuerySet(Ee(v>>>0),M,x,Ee(C>>>0),N)}function Lo(_,v,M,x){Ee(_>>>0).dispatchWorkgroups(v,M,x)}function No(_,v,M){M=fn(M),Ee(_>>>0).dispatchWorkgroupsIndirect(Ee(v>>>0),M)}function xc(_){Ee(_>>>0).end()}function Vr(_,v,M,x,C){x>>>=0,C>>>=0,_=Ee(_>>>0),M=Ee(M>>>0),x==0?_.setBindGroup(v,M):_.setBindGroup(v,M,(k(),ee),C>>>2,x)}function Fd(_,v){Ee(_>>>0).setPipeline(Ee(v>>>0))}function Do(_,v,M){Ee(_>>>0).Pe(Ee(v>>>0),M)}function Cs(_,v){_=Ee(_>>>0);var M=aa(0);return ln(M,_.getBindGroupLayout(v)),M}function Lp(_,v){_>>>=0;var M=Ta(4+(v>>>=0)),x=Ee((k(),ee)[v+12>>>2>>>0]),C=(k(),ee)[v+16>>>2>>>0];v=(k(),ee)[v+20>>>2>>>0];for(var N=[],q=0;q>>2>>>0],ge=(k(),ee)[ve+32>>>2>>>0],Ge=(k(),ee)[ve+36>>>2>>>0],lt=(k(),ee)[ve+4>>>2>>>0];Fe?(ge=ve+24,(ge=(k(),ee)[ge>>>2>>>0]+4294967296*(k(),ne)[ge+4>>>2>>>0])==-1&&(ge=void 0),ve={binding:lt,resource:{buffer:Ee(Fe),offset:4294967296*(k(),ee)[ve+4+16>>>2>>>0]+(k(),ee)[ve+16>>>2>>>0],size:ge}}):ve=ge?{binding:lt,resource:Ee(ge)}:{binding:lt,resource:Ee(Ge)},fe.call(J,ve)}return M={label:M,layout:x,entries:N},_=Ee(_),x=$a(0),ln(x,_.createBindGroup(M)),x}function Dn(_,v){var M;return _>>>=0,(v>>>=0)&&(M={label:Ta(v+4)}),_=Ee(_),v=Ea(0),ln(v,_.createCommandEncoder(M)),v}function Tc(_,v){_>>>=0,v>>>=0,v={type:Sp[(k(),ee)[v+12>>>2>>>0]],count:(k(),ee)[v+16>>>2>>>0]},_=Ee(_);var M=Bo(0);return ln(M,_.createQuerySet(v)),M}function Va(_,v){_=Ee(_>>>0).adapterInfo,v>>>=0,(k(),ne)[v+52>>>2>>>0]=_.subgroupMinSize,(k(),ne)[v+56>>>2>>>0]=_.subgroupMaxSize;var M=lc(_.vendor+_.architecture+_.device+_.description),x=ya(_.vendor);return jr(v+4,M,x),M+=x,x=ya(_.architecture),jr(v+12,M,x),M+=x,x=ya(_.device),jr(v+20,M,x),jr(v+28,M+x,ya(_.description)),(k(),ne)[v+36>>>2>>>0]=2,_=_.isFallbackAdapter?3:4,(k(),ne)[v+40>>>2>>>0]=_,(k(),ne)[v+44>>>2>>>0]=0,(k(),ne)[v+48>>>2>>>0]=0,1}var Bd={"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 Fo(_,v){v>>>=0,_=Ee(_>>>0);var M=Sa(4*_.features.size),x=0,C=0;_.features.forEach(N=>{0<=(N=Bd[N])&&((k(),ne)[M+x>>>2>>>0]=N,x+=4,C++)}),(k(),ee)[v+4>>>2>>>0]=M,(k(),ee)[v>>>2>>>0]=C}function qr(_,v){return ko(Ee(_>>>0).limits,v>>>0),1}function Sc(_,v){Ee(_>>>0).pushErrorScope(Sd[v])}function Pd(_,v,M){v>>>=0,M>>>=0,_=Ee(_>>>0),v=Array.from((k(),ne).subarray(M>>>2>>>0,M+4*v>>>2>>>0),x=>Ee(x)),_.submit(v)}function Ec(_,v,M,x,C){M=fn(M),x>>>=0,C>>>=0,_=Ee(_>>>0),v=Ee(v>>>0),x=(k(),he).subarray(x>>>0,x+C>>>0),_.writeBuffer(v,M,x,0,C)}o||(function(){for(var _=n.numThreads-1;_--;)Mn();at.push(async()=>{var v=(async function(){if(!o)return Promise.all(xt.map(rd))})();Qe++,await v,--Qe==0&&ht&&(v=ht,ht=null,v())})})(),o||(cr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),F()),n.wasmBinary&&(y=n.wasmBinary),n.stackSave=()=>Ae(),n.stackRestore=_=>Ce(_),n.stackAlloc=_=>Ha(_),n.setValue=function(_,v,M="i8"){switch(M.endsWith("*")&&(M="*"),M){case"i1":case"i8":(k(),oe)[_>>>0]=v;break;case"i16":(k(),me)[_>>>1>>>0]=v;break;case"i32":(k(),ne)[_>>>2>>>0]=v;break;case"i64":(k(),W)[_>>>3>>>0]=BigInt(v);break;case"float":(k(),Me)[_>>>2>>>0]=v;break;case"double":(k(),V)[_>>>3>>>0]=v;break;case"*":(k(),ee)[_>>>2>>>0]=v;break;default:ue(`invalid type for setValue: ${M}`)}},n.getValue=function(_,v="i8"){switch(v.endsWith("*")&&(v="*"),v){case"i1":case"i8":return(k(),oe)[_>>>0];case"i16":return(k(),me)[_>>>1>>>0];case"i32":return(k(),ne)[_>>>2>>>0];case"i64":return(k(),W)[_>>>3>>>0];case"float":return(k(),Me)[_>>>2>>>0];case"double":return(k(),V)[_>>>3>>>0];case"*":return(k(),ee)[_>>>2>>>0];default:ue(`invalid type for getValue: ${v}`)}},n.UTF8ToString=ga,n.stringToUTF8=Ut,n.lengthBytesUTF8=ya;var Ac,Fn,gr,qa,_n,Sa,Bn,Pn,$a,aa,ra,Ea,Cc,Bo,Po,kc,Jt,pt,Xe,Aa,En,$r,Ca,Oc,Ro,Hr,vr,Uo,Yr,Io,yr,sa,De,Rn,Go,Ce,Ha,Ae,wr,Xt,Ei,zc,Rd,Lc,Ud,Dt,jo,ks,Os,Vo,Xr,Qr,Id,Nc,Gd,Dc,br,qo,Ai,Fc,Wr,$o,Ci,ki,Bc,Pc,Mr,xr,Rc,Uc,Zr,zs,Oi,Ls,zi,Ic,Tr,Gc,Ya,Ho,Yo,Xa,Qa,Ns,ia,jc=[Ye,Ht,ur,ld,ql,$l,Hl,fo,ho,Yl,Xl,Ua,Wt,pn,Br,po,yd,wd,bd,gc,_r,vc,yc,wc,Ld],Kr={1117404:(_,v,M,x,C)=>{if(n===void 0||!n.Zc)return 1;if((_=ga(Number(_>>>0))).startsWith("./")&&(_=_.substring(2)),!(_=n.Zc.get(_)))return 2;if(v=Number(v>>>0),M=Number(M>>>0),x=Number(x>>>0),v+M>_.byteLength)return 3;try{let N=_.subarray(v,v+M);switch(C){case 0:(k(),he).set(N,x>>>0);break;case 1:n.ie?n.ie(x,N):n.Ke(x,N);break;default:return 4}return 0}catch{return 4}},1118228:(_,v,M)=>{n.ke(_,(k(),he).subarray(v>>>0,v+M>>>0))},1118292:()=>n.Ie(),1118334:_=>{n.je(_)},1118371:()=>typeof wasmOffsetConverter<"u"};function Li(){return typeof wasmOffsetConverter<"u"}function jd(_,v,M,x){var C=Ae();try{return Qr(_,v,M,x)}catch(N){if(Ce(C),N!==N+0)throw N;De(1,0)}}function Vd(_,v,M){var x=Ae();try{return Os(_,v,M)}catch(C){if(Ce(x),C!==C+0)throw C;De(1,0)}}function Ds(_,v,M){var x=Ae();try{Rd(_,v,M)}catch(C){if(Ce(x),C!==C+0)throw C;De(1,0)}}function Xo(_,v){var M=Ae();try{return Lc(_,v)}catch(x){if(Ce(M),x!==x+0)throw x;De(1,0)}}function qd(_){var v=Ae();try{Ud(_)}catch(M){if(Ce(v),M!==M+0)throw M;De(1,0)}}function Vc(_,v,M,x,C,N,q){var J=Ae();try{return ks(_,v,M,x,C,N,q)}catch(fe){if(Ce(J),fe!==fe+0)throw fe;De(1,0)}}function qc(_,v){var M=Ae();try{Id(_,v)}catch(x){if(Ce(M),x!==x+0)throw x;De(1,0)}}function Un(_,v,M,x,C,N){var q=Ae();try{Dt(_,v,M,x,C,N)}catch(J){if(Ce(q),J!==J+0)throw J;De(1,0)}}function qn(_,v,M,x){var C=Ae();try{Xr(_,v,M,x)}catch(N){if(Ce(C),N!==N+0)throw N;De(1,0)}}function Sr(_,v,M,x,C,N,q){var J=Ae();try{Gd(_,v,M,x,C,N,q)}catch(fe){if(Ce(J),fe!==fe+0)throw fe;De(1,0)}}function $c(_,v,M,x,C,N,q){var J=Ae();try{Dc(_,v,M,x,C,N,q)}catch(fe){if(Ce(J),fe!==fe+0)throw fe;De(1,0)}}function $d(_,v,M,x,C,N,q,J){var fe=Ae();try{Pc(_,v,M,x,C,N,q,J)}catch(ve){if(Ce(fe),ve!==ve+0)throw ve;De(1,0)}}function Er(_,v,M,x,C){var N=Ae();try{jo(_,v,M,x,C)}catch(q){if(Ce(N),q!==q+0)throw q;De(1,0)}}function In(_,v,M,x,C){var N=Ae();try{return Nc(_,v,M,x,C)}catch(q){if(Ce(N),q!==q+0)throw q;De(1,0)}}function Ft(_,v,M,x,C,N,q,J){var fe=Ae();try{Mr(_,v,M,x,C,N,q,J)}catch(ve){if(Ce(fe),ve!==ve+0)throw ve;De(1,0)}}function Qo(_,v,M,x,C,N,q,J,fe,ve,Fe,ge){var Ge=Ae();try{br(_,v,M,x,C,N,q,J,fe,ve,Fe,ge)}catch(lt){if(Ce(Ge),lt!==lt+0)throw lt;De(1,0)}}function Wa(_,v,M,x,C,N){var q=Ae();try{return ki(_,v,M,x,C,N)}catch(J){if(Ce(q),J!==J+0)throw J;De(1,0)}}function Ie(_,v,M){var x=Ae();try{return Wr(_,v,M)}catch(C){if(Ce(x),C!==C+0)throw C;return De(1,0),0n}}function ft(_,v,M,x,C,N,q,J,fe){var ve=Ae();try{Vo(_,v,M,x,C,N,q,J,fe)}catch(Fe){if(Ce(ve),Fe!==Fe+0)throw Fe;De(1,0)}}function It(_){var v=Ae();try{return Ai(_)}catch(M){if(Ce(v),M!==M+0)throw M;De(1,0)}}function Wo(_,v,M){var x=Ae();try{return xr(_,v,M)}catch(C){if(Ce(x),C!==C+0)throw C;De(1,0)}}function Fs(_,v){var M=Ae();try{return Ho(_,v)}catch(x){if(Ce(M),x!==x+0)throw x;return De(1,0),0n}}function Jr(_,v,M,x,C){var N=Ae();try{Rc(_,v,M,x,C)}catch(q){if(Ce(N),q!==q+0)throw q;De(1,0)}}function Zo(_){var v=Ae();try{return qo(_)}catch(M){if(Ce(v),M!==M+0)throw M;return De(1,0),0n}}function Ni(_,v,M,x,C,N){var q=Ae();try{return zs(_,v,M,x,C,N)}catch(J){if(Ce(q),J!==J+0)throw J;De(1,0)}}function Bs(_,v,M,x,C,N){var q=Ae();try{return Oi(_,v,M,x,C,N)}catch(J){if(Ce(q),J!==J+0)throw J;De(1,0)}}function Np(_,v,M,x,C,N,q,J){var fe=Ae();try{return Bc(_,v,M,x,C,N,q,J)}catch(ve){if(Ce(fe),ve!==ve+0)throw ve;De(1,0)}}function kt(_,v,M,x,C){var N=Ae();try{return Ls(_,v,M,x,C)}catch(q){if(Ce(N),q!==q+0)throw q;return De(1,0),0n}}function Hc(_,v,M,x){var C=Ae();try{return zi(_,v,M,x)}catch(N){if(Ce(C),N!==N+0)throw N;De(1,0)}}function Yc(_,v,M,x){var C=Ae();try{return Ic(_,v,M,x)}catch(N){if(Ce(C),N!==N+0)throw N;De(1,0)}}function Hd(_,v,M,x,C,N,q,J,fe,ve,Fe,ge){var Ge=Ae();try{return Tr(_,v,M,x,C,N,q,J,fe,ve,Fe,ge)}catch(lt){if(Ce(Ge),lt!==lt+0)throw lt;De(1,0)}}function Yd(_,v,M,x,C,N,q,J,fe,ve,Fe){var ge=Ae();try{Uc(_,v,M,x,C,N,q,J,fe,ve,Fe)}catch(Ge){if(Ce(ge),Ge!==Ge+0)throw Ge;De(1,0)}}function Dp(_,v,M,x,C,N,q,J,fe,ve,Fe,ge,Ge,lt,Gt,Rs){var Ko=Ae();try{Zr(_,v,M,x,C,N,q,J,fe,ve,Fe,ge,Ge,lt,Gt,Rs)}catch(Fi){if(Ce(Ko),Fi!==Fi+0)throw Fi;De(1,0)}}function Xc(_,v,M,x){var C=Ae();try{return Gc(_,v,M,x)}catch(N){if(Ce(C),N!==N+0)throw N;De(1,0)}}function Qc(_,v,M,x,C){var N=Ae();try{return Ya(_,v,M,x,C)}catch(q){if(Ce(N),q!==q+0)throw q;De(1,0)}}function Wc(_,v,M){var x=Ae();try{return Fc(_,v,M)}catch(C){if(Ce(x),C!==C+0)throw C;De(1,0)}}function gn(_,v,M){var x=Ae();try{return $o(_,v,M)}catch(C){if(Ce(x),C!==C+0)throw C;De(1,0)}}function Bt(_,v,M,x){var C=Ae();try{Ci(_,v,M,x)}catch(N){if(Ce(C),N!==N+0)throw N;De(1,0)}}function es(){if(0{let v=new WeakMap,M,x,C=1;n.webgpuRegisterDevice=J=>{if(x!==void 0)throw Error("another WebGPU EP inference session is being created.");if(J){var fe=v.get(J);if(!fe){let ve=((Fe,ge=0)=>{var Ge=Jt(ge);return ge=kc(ge,Ge),ln(Ge,Fe.queue),ln(ge,Fe),ge})(J,fe=Pn(0));fe=[C++,fe,ve],v.set(J,fe)}return M=J,x=fe[0],fe}M=void 0,x=0};let N=new Map;n.webgpuOnCreateSession=J=>{if(x!==void 0){var fe=x;if(x=void 0,J){let ve=gr(fe);N.set(J,ve),fe===0&&_(M??Ee(ve))}M=void 0}},n.webgpuOnReleaseSession=J=>{N.delete(J)};let q=Symbol("gpuBufferMetadata");n.webgpuRegisterBuffer=(J,fe,ve)=>{if(ve)return J[q]=[ve,NaN],ve;if(ve=J[q])return ve[1]++,ve[0];if((fe=N.get(fe))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return fe=((Fe,ge=0)=>(Fe.mapState!="pending"||ue(),ge=Po(ge,Fe.mapState=="mapped"?3:1),ln(ge,Fe),Fe.mapState=="mapped"&&(ta[ge]=[]),ge))(J,fe),J[q]=[fe,1],fe},n.webgpuUnregisterBuffer=J=>{let fe=J[q];if(!fe)throw Error("Buffer is not registered");fe[1]--,fe[1]===0&&(Bn(fe[0]),delete J[q])},n.webgpuGetBuffer=J=>Ee(J),n.webgpuCreateDownloader=(J,fe,ve)=>{if((ve=N.get(ve))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let Fe=Ee(ve),ge=16*Math.ceil(Number(fe)/16);return async()=>{let Ge=Fe.createBuffer({size:ge,usage:9});try{let lt=Fe.createCommandEncoder();return lt.copyBufferToBuffer(J,0,Ge,0,ge),Fe.queue.submit([lt.finish()]),await Ge.mapAsync(GPUMapMode.READ),Ge.getMappedRange().slice(0,fe)}finally{Ge.destroy()}}},n.ie=(J,fe)=>{var ve=fe.buffer;let Fe=fe.byteOffset,ge=fe.byteLength;if(fe=16*Math.ceil(Number(ge)/16),J=Ee(J),!M){var Ge=gr(x);M=Ee(Ge)}let lt=(Ge=M.createBuffer({mappedAtCreation:!0,size:fe,usage:6})).getMappedRange();new Uint8Array(lt).set(new Uint8Array(ve,Fe,ge)),Ge.unmap(),(ve=M.createCommandEncoder()).copyBufferToBuffer(Ge,0,J,0,fe),M.queue.submit([ve.finish()]),Ge.destroy()}},n.webnnInit=_=>{let v=_[0];[n.Ie,n.je,n.webnnEnsureTensor,n.ke,n.webnnDownloadTensor,n.He,n.webnnEnableTraceEvent]=_.slice(1),n.webnnReleaseTensorId=n.je,n.webnnUploadTensor=n.ke,n.webnnRegisterMLContext=n.He,n.webnnOnRunStart=M=>v.onRunStart(M),n.webnnOnRunEnd=v.onRunEnd.bind(v),n.webnnOnReleaseSession=M=>{v.onReleaseSession(M)},n.webnnCreateMLTensorDownloader=(M,x)=>v.createMLTensorDownloader(M,x),n.webnnRegisterMLTensor=(M,x,C,N)=>v.registerMLTensor(M,x,C,N),n.webnnCreateMLContext=M=>v.createMLContext(M),n.webnnRegisterMLConstant=(M,x,C,N,q,J)=>v.registerMLConstant(M,x,C,N,q,n.Zc,J),n.webnnRegisterGraphInput=v.registerGraphInput.bind(v),n.webnnIsGraphInput=v.isGraphInput.bind(v),n.webnnRegisterGraphOutput=v.registerGraphOutput.bind(v),n.webnnIsGraphOutput=v.isGraphOutput.bind(v),n.webnnCreateTemporaryTensor=v.createTemporaryTensor.bind(v),n.webnnIsGraphInputOutputTypeSupported=v.isGraphInputOutputTypeSupported.bind(v)},te?n:new Promise((_,v)=>{S=_,E=v})}var wM,Cb,dA=Ke(()=>{var e,n;wM=Ab,Cb=(n=(e=globalThis.self)==null?void 0:e.name)==null?void 0:n.startsWith("em-pthread"),Cb&&Ab()}),e_,sg,kb,da,bM,Lf,Ob,zb,t_,Lb,n_,MM,a_,xM,Ag=Ke(()=>{Eg(),e_=typeof location>"u"?void 0:location.origin,sg=import.meta.url>"file:"&&import.meta.url<"file;",kb=()=>{{if(sg){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,e_).href}return import.meta.url}},da=kb(),bM=()=>{if(da&&!da.startsWith("blob:"))return da.substring(0,da.lastIndexOf("/")+1)},Lf=(e,n)=>{try{let r=n??da;return(r?new URL(e,r):new URL(e)).origin===e_}catch{return!1}},Ob=(e,n)=>{let r=n??da;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},zb=(e,n)=>`${n??"./"}${e}`,t_=async e=>{let n=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},Lb=async e=>(await import(e)).default,n_=(uA(),lh(gM)).default,MM=async()=>{if(!da)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Lf(da))return[void 0,n_()];let e=await t_(da);return[e,n_(e)]},a_=(dA(),lh(yM)).default,xM=async(e,n,r,s)=>{let o=a_&&!(e||n);if(o)if(da)o=Lf(da);else if(s&&!r)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,a_];{let c="ort-wasm-simd-threaded.asyncify.mjs",u=e??Ob(c,n),d=r&&u&&!Lf(u,n),h=d?await t_(u):u??zb(c,n);return[d?h:void 0,await Lb(h)]}}}),r_,Nf,bu,s_,Nb,Db,Fb,Cg,gt,eo=Ke(()=>{Ag(),Nf=!1,bu=!1,s_=!1,Nb=()=>{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}},Db=()=>{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}},Fb=()=>{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}},Cg=async e=>{if(Nf)return Promise.resolve();if(bu)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(s_)throw new Error("previous call to 'initializeWebAssembly()' failed.");bu=!0;let n=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Fb())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Db())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Nb();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."),e.numThreads=r=1);let o=e.wasmPaths,c=typeof o=="string"?o:void 0,u=o==null?void 0:o.mjs,d=(u==null?void 0:u.href)??u,h=o==null?void 0:o.wasm,p=(h==null?void 0:h.href)??h,g=e.wasmBinary,[y,w]=await xM(d,c,r>1,!!g||!!p),b=!1,S=[];if(n>0&&S.push(new Promise(E=>{setTimeout(()=>{b=!0,E()},n)})),S.push(new Promise((E,O)=>{let z={numThreads:r};if(g)z.wasmBinary=g;else if(p||c)z.locateFile=D=>p??c+D;else if(d&&d.indexOf("blob:")!==0)z.locateFile=D=>new URL(D,d).href;else if(y){let D=bM();D&&(z.locateFile=P=>D+P)}w(z).then(D=>{bu=!1,Nf=!0,r_=D,E(),y&&URL.revokeObjectURL(y)},D=>{bu=!1,s_=!0,O(D)})})),await Promise.race(S),b)throw new Error(`WebAssembly backend initializing failed due to timeout: ${n}ms`)},gt=()=>{if(Nf&&r_)return r_;throw new Error("WebAssembly is not initialized yet.")}}),fa,uh,ot,kg=Ke(()=>{eo(),fa=(e,n)=>{let r=gt(),s=r.lengthBytesUTF8(e)+1,o=r._malloc(s);return r.stringToUTF8(e,o,s),n.push(o),o},uh=(e,n,r,s)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([o,c])=>{let u=n?n+o:o;if(typeof c=="object")uh(c,u+".",r,s);else if(typeof c=="string"||typeof c=="number")s(u,c.toString());else if(typeof c=="boolean")s(u,c?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof c}`)})},ot=e=>{let n=gt(),r=n.stackSave();try{let s=n.PTR_SIZE,o=n.stackAlloc(2*s);n._OrtGetLastError(o,o+s);let c=Number(n.getValue(o,s===4?"i32":"i64")),u=n.getValue(o+s,"*"),d=u?n.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${c}, ERROR_MESSAGE: ${d}`)}finally{n.stackRestore(r)}}}),TM,fA=Ke(()=>{eo(),kg(),TM=e=>{let n=gt(),r=0,s=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(o.terminate=!1);let c=0;return(e==null?void 0:e.tag)!==void 0&&(c=fa(e.tag,s)),r=n._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,c),r===0&&ot("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&uh(e.extra,"",new WeakSet,(u,d)=>{let h=fa(u,s),p=fa(d,s);n._OrtAddRunConfigEntry(r,h,p)!==0&&ot(`Can't set a run config entry: ${u} - ${d}.`)}),[r,s]}catch(c){throw r!==0&&n._OrtReleaseRunOptions(r),s.forEach(u=>n._free(u)),c}}}),Bb,Pb,Rb,Df,Js,Ub,SM,hA=Ke(()=>{eo(),kg(),Bb=e=>{switch(e){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: ${e}`)}},Pb=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Rb=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let n=e.extra.session;n.use_ort_model_bytes_directly||(n.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},Df=(e,n,r,s)=>{let o=fa(n,s),c=fa(r,s);gt()._OrtAddSessionConfigEntry(e,o,c)!==0&&ot(`Can't set a session config entry: ${n} - ${r}.`)},Js=(e,n,r,s)=>{let o=fa(n,s),c=fa(r,s);e.push([o,c])},Ub=async(e,n,r)=>{let s=n.executionProviders;for(let o of s){let c=typeof o=="string"?o:o.name,u=[];switch(c){case"webnn":if(c="WEBNN",typeof o!="string"){let y=o==null?void 0:o.deviceType;y&&Df(e,"deviceType",y,r)}break;case"webgpu":{c="WebGPU";let y;if(typeof o!="string"){let b=o;if(b.device)if(typeof GPUDevice<"u"&&b.device instanceof GPUDevice)y=b.device;else throw new Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:S}=n;if(typeof S=="boolean"&&S&&Js(u,"enableGraphCapture","1",r),typeof b.preferredLayout=="string"&&Js(u,"preferredLayout",b.preferredLayout,r),b.forceCpuNodeNames){let E=Array.isArray(b.forceCpuNodeNames)?b.forceCpuNodeNames:[b.forceCpuNodeNames];Js(u,"forceCpuNodeNames",E.join(` +`),r)}b.validationMode&&Js(u,"validationMode",b.validationMode,r)}let w=gt().webgpuRegisterDevice(y);if(w){let[b,S,E]=w;Js(u,"deviceId",b.toString(),r),Js(u,"webgpuInstance",S.toString(),r),Js(u,"webgpuDevice",E.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${c}`)}let d=fa(c,r),h=u.length,p=0,g=0;if(h>0){p=gt()._malloc(h*gt().PTR_SIZE),r.push(p),g=gt()._malloc(h*gt().PTR_SIZE),r.push(g);for(let y=0;y{let n=gt(),r=0,s=[],o=e||{};Rb(o);try{let c=Bb(o.graphOptimizationLevel??"all"),u=Pb(o.executionMode??"sequential"),d=typeof o.logId=="string"?fa(o.logId,s):0,h=o.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log severity level is not valid: ${h}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let g=typeof o.optimizedModelFilePath=="string"?fa(o.optimizedModelFilePath,s):0;if(r=n._OrtCreateSessionOptions(c,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,d,h,p,g),r===0&&ot("Can't create session options."),o.executionProviders&&await Ub(r,o,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Df(r,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[y,w]of Object.entries(o.freeDimensionOverrides)){if(typeof y!="string")throw new Error(`free dimension override name must be a string: ${y}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let b=fa(y,s);n._OrtAddFreeDimensionOverride(r,b,w)!==0&&ot(`Can't set a free dimension override: ${y} - ${w}.`)}return o.extra!==void 0&&uh(o.extra,"",new WeakSet,(y,w)=>{Df(r,y,w,s)}),[r,s]}catch(c){throw r!==0&&n._OrtReleaseSessionOptions(r)!==0&&ot("Can't release session options."),s.forEach(u=>n._free(u)),c}}}),Hi,rh,gl,Vu,dh,Og,zg,ig,Tl=Ke(()=>{Hi=e=>{switch(e){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: ${e}`)}},rh=e=>{switch(e){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: ${e}`)}},gl=(e,n)=>{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][e],s=typeof n=="number"?n:n.reduce((o,c)=>o*c,1);return r>0?Math.ceil(s*r):void 0},Vu=e=>{switch(e){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: ${e}`)}},dh=e=>{switch(e){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: ${e}`)}},Og=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",zg=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ig=e=>{switch(e){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: ${e}`)}}}),Lg,EM=Ke(()=>{Eg(),Lg=async e=>{if(typeof e=="string"){let n=await fetch(e);if(!n.ok)throw new Error(`failed to load external data file: ${e}`);let r=n.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await n.arrayBuffer());{if(!n.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=n.body.getReader(),c;try{c=new ArrayBuffer(s)}catch(d){if(d instanceof RangeError){let h=Math.ceil(s/65536);c=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw d}let u=0;for(;;){let{done:d,value:h}=await o.read();if(d)break;let p=h.byteLength;new Uint8Array(c,u,p).set(h),u+=p}return new Uint8Array(c,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),AM,pA=Ke(()=>{Tl(),AM=(e,n)=>new(Vu(n))(e)}),Ib,Gb,jb,Vb,CM,qb,kn,kM=Ke(()=>{Tl(),Ib=["V","I","W","E","F"],Gb=(e,n)=>{console.log(`[${Ib[e]},${new Date().toISOString()}]${n}`)},CM=(e,n)=>{jb=e,Vb=n},qb=(e,n)=>{let r=dh(e),s=dh(jb);r>=s&&Gb(r,typeof n=="function"?n():n)},kn=(...e)=>{Vb&&qb(...e)}}),i_,og,o_,$b,l_,Hb,c_,u_,d_,Yb,OM,mA=Ke(()=>{Tl(),kM(),i_=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),og=(e,n)=>{if(n==="int32")return e;let r=i_.get(n);if(!r)throw new Error(`WebNN backend does not support data type: ${n}`);let s=r/8;if(e.byteLength%s!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${s}.`);let o=e.byteLength/s,c=new(Vu(n))(e.buffer,e.byteOffset,o);switch(n){case"int64":case"uint64":{let u=new Int32Array(o);for(let d=0;d2147483647n||h<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[d]=Number(h)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(n==="uint32"&&c.some(d=>d>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let u=Int32Array.from(c,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from ${n} to 'int32'`)}},o_=(e,n)=>{if(n==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let r=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,r);switch(n){case"int64":{let o=BigInt64Array.from(s,BigInt);return new Uint8Array(o.buffer)}case"uint64":{if(s.some(c=>c<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let o=BigUint64Array.from(s,BigInt);return new Uint8Array(o.buffer)}case"int8":{if(s.some(c=>c<-128||c>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let o=Int8Array.from(s,Number);return new Uint8Array(o.buffer)}case"uint8":{if(s.some(o=>o<0||o>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(c=>c<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let o=Uint32Array.from(s,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${n}`)}},$b=1,l_=()=>$b++,Hb=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),c_=(e,n)=>{let r=i_.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return n.length>0?Math.ceil(n.reduce((s,o)=>s*o)*r/8):0},u_=class{constructor(e){this.isDataConverted=!1;let{sessionId:n,context:r,tensor:s,dataType:o,shape:c,fallbackDataType:u}=e;this.sessionId=n,this.mlContext=r,this.mlTensor=s,this.dataType=o,this.tensorShape=c,this.fallbackDataType=u}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return c_(this.dataType,this.tensorShape)}destroy(){kn("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let n=await this.mlContext.readTensor(this.mlTensor),r=o_(new Uint8Array(n),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(r);return}else return r.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,n,r){return this.mlContext===e&&this.dataType===n&&this.tensorShape.length===r.length&&this.tensorShape.every((s,o)=>s===r[o])}setIsDataConverted(e){this.isDataConverted=e}},d_=class{constructor(e,n){this.tensorManager=e,this.wrapper=n}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,n,r,s){let o=this.tensorManager.getMLContext(e),c=this.tensorManager.getMLOpSupportLimits(e),u;if(!(c!=null&&c.input.dataTypes.includes(n))){if(u=Hb.get(n),!u||(c==null?void 0:c.input.dataTypes.includes(u)))throw new Error(`WebNN backend does not support data type: ${n}`);kn("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${n} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,n,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==c_(n,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 d=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,n,r,d,!0,!0,u),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let n=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")n=og(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(n);return}else kn("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(n):this.activeUpload=new Uint8Array(n)}async download(e){var n,r;if(this.activeUpload){let s=(n=this.wrapper)!=null&&n.isDataConverted?o_(this.activeUpload,(r=this.wrapper)==null?void 0:r.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(s):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(s);return}else return s.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Yb=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let n=this.backend.getMLContext(e);if(!n)throw new Error("MLContext not found for session.");return n}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=l_();return this.tensorTrackersById.set(e,new d_(this)),e}releaseTensorId(e){let n=this.tensorTrackersById.get(e);n&&(this.tensorTrackersById.delete(e),n.tensorWrapper&&this.releaseTensor(n.tensorWrapper))}async ensureTensor(e,n,r,s,o){kn("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${n}, dataType: ${r}, shape: ${s}, copyOld: ${o}}`);let c=this.tensorTrackersById.get(n);if(!c)throw new Error("Tensor not found.");return c.ensureTensor(e,r,s,o)}upload(e,n){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(n)}async download(e,n){kn("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${n==null?void 0:n.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(n)}releaseTensorsForSession(e){for(let n of this.freeTensors)n.sessionId===e&&n.destroy();this.freeTensors=this.freeTensors.filter(n=>n.sessionId!==e)}registerTensor(e,n,r,s){let o=this.getMLContext(e),c=l_(),u=new u_({sessionId:e,context:o,tensor:n,dataType:r,shape:s});return this.tensorTrackersById.set(c,new d_(this,u)),this.externalTensors.add(u),c}async getCachedTensor(e,n,r,s,o,c,u){let d=this.getMLContext(e);for(let[p,g]of this.freeTensors.entries())if(g.canReuseTensor(d,n,r)){kn("verbose",()=>`[WebNN] Reusing tensor {dataType: ${n}, ${u?`fallbackDataType: ${u},`:""} shape: ${r}`);let y=this.freeTensors.splice(p,1)[0];return y.sessionId=e,y}kn("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${n}, ${u?`fallbackDataType: ${u},`:""} shape: ${r}}`);let h=await d.createTensor({dataType:u??n,shape:r,dimensions:r,usage:s,writable:o,readable:c});return new u_({sessionId:e,context:d,tensor:h,dataType:n,shape:r,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},OM=(...e)=>new Yb(...e)}),zM={};$u(zM,{WebNNBackend:()=>LM});var Mu,Xb,LM,_A=Ke(()=>{Tl(),eo(),pA(),mA(),kM(),Mu=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Xb=(e,n)=>{if(e===n)return!0;if(e===void 0||n===void 0)return!1;let r=Object.keys(e).sort(),s=Object.keys(n).sort();return r.length===s.length&&r.every((o,c)=>o===s[c]&&e[o]===n[o])},LM=class{constructor(e){this.tensorManager=OM(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,CM(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){kn("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){kn("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let n=this.temporarySessionTensorIds.get(e);if(n){for(let r of n)kn("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${r}}`),this.tensorManager.releaseTensorId(r);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let r=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(r!==-1)return this.mlContextCache[r].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===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 n=this.mlContextCache.findIndex(r=>Xb(r.options,e));if(n!==-1)return this.mlContextCache[n].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,n){this.mlContextBySessionId.set(e,n);let r=this.sessionIdsByMLContext.get(n);r||(r=new Set,this.sessionIdsByMLContext.set(n,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,n.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let n=this.mlContextBySessionId.get(e);if(!n)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(n);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(n);let s=this.mlContextCache.findIndex(o=>o.mlContext===n);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){kn("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,n,r,s,o){let c=Mu.get(r);if(!c)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,n,c,s,o)}async createTemporaryTensor(e,n,r){kn("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${n}, shape: ${r}}`);let s=Mu.get(n);if(!s)throw new Error(`Unsupported ONNX data type: ${n}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,r,!1);let c=this.temporarySessionTensorIds.get(e);return c?c.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,n){if(!gt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");kn("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${n.byteLength}}`),this.tensorManager.upload(e,n)}async downloadTensor(e,n){return this.tensorManager.download(e,n)}createMLTensorDownloader(e,n){return async()=>{let r=await this.tensorManager.download(e);return AM(r,n)}}registerMLTensor(e,n,r,s){let o=Mu.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let c=this.tensorManager.registerTensor(e,n,o,s);return kn("verbose",()=>`[WebNN] registerMLTensor {tensor: ${n}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${c}}`),c}registerMLConstant(e,n,r,s,o,c,u=!1){if(!c)throw new Error("External mounted files are not available.");let d=e;e.startsWith("./")&&(d=e.substring(2));let h=c.get(d);if(!h)throw new Error(`File with name ${d} not found in preloaded files.`);if(n+r>h.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=h.slice(n,n+r).buffer,g;switch(o.dataType){case"float32":g=new Float32Array(p);break;case"float16":g=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(p):new Uint16Array(p);break;case"int32":g=new Int32Array(p);break;case"uint32":g=new Uint32Array(p);break;case"int64":if(u){let y=og(new Uint8Array(p),"int64");g=new Int32Array(y.buffer),o.dataType="int32"}else g=new BigInt64Array(p);break;case"uint64":g=new BigUint64Array(p);break;case"int8":g=new Int8Array(p);break;case"int4":case"uint4":case"uint8":g=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return kn("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${u?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,g)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,n){let r=this.sessionGraphInputs.get(e);return r?r.includes(n):!1}isGraphOutput(e,n){let r=this.sessionGraphOutputs.get(e);return r?r.includes(n):!1}isGraphInputOutputTypeSupported(e,n,r=!0){let s=Mu.get(Hi(n)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof s>"u"?!1:r?!!(o!=null&&o.input.dataTypes.includes(s)):!!(o!=null&&o.output.dataTypes.includes(s))}flush(){}}}),Qb,Ng,Dg,ei,Wb,f_,fh,Fg,Bg,h_,Pg,Rg,Ug,NM=Ke(()=>{Ji(),fA(),hA(),Tl(),eo(),kg(),EM(),Qb=(e,n)=>{gt()._OrtInit(e,n)!==0&&ot("Can't initialize onnxruntime.")},Ng=async e=>{Qb(e.wasm.numThreads,dh(e.logLevel))},Dg=async(e,n)=>{var s,o;(o=(s=gt()).asyncInit)==null||o.call(s);let r=e.webgpu.adapter;if(n==="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 c=e.webgpu.powerPreference;if(c!==void 0&&c!=="low-power"&&c!=="high-performance")throw new Error(`Invalid powerPreference setting: "${c}"`);let u=e.webgpu.forceFallbackAdapter;if(u!==void 0&&typeof u!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${u}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:c,forceFallbackAdapter:u}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(n==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(n==="webgpu"&>().webgpuInit(c=>{e.webgpu.device=c}),n==="webnn"){let c=new(_A(),lh(zM)).WebNNBackend(e);gt().webnnInit([c,()=>c.reserveTensorId(),u=>c.releaseTensorId(u),async(u,d,h,p,g)=>c.ensureTensor(u,d,h,p,g),(u,d)=>{c.uploadTensor(u,d)},async(u,d)=>c.downloadTensor(u,d),(u,d)=>c.registerMLContext(u,d),!!e.trace])}},ei=new Map,Wb=e=>{let n=gt(),r=n.stackSave();try{let s=n.PTR_SIZE,o=n.stackAlloc(2*s);n._OrtGetInputOutputCount(e,o,o+s)!==0&&ot("Can't get session input/output count.");let c=s===4?"i32":"i64";return[Number(n.getValue(o,c)),Number(n.getValue(o+s,c))]}finally{n.stackRestore(r)}},f_=(e,n)=>{let r=gt(),s=r.stackSave(),o=0;try{let c=r.PTR_SIZE,u=r.stackAlloc(2*c);r._OrtGetInputOutputMetadata(e,n,u,u+c)!==0&&ot("Can't get session input/output metadata.");let d=Number(r.getValue(u,"*"));o=Number(r.getValue(u+c,"*"));let h=r.HEAP32[o/4];if(h===0)return[d,0];let p=r.HEAPU32[o/4+1],g=[];for(let y=0;y{let n=gt(),r=n._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return n.HEAPU8.set(e,r),[r,e.byteLength]},Fg=async(e,n)=>{var y,w,b,S;let r,s,o=gt();Array.isArray(e)?[r,s]=e:e.buffer===o.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=fh(e);let c=0,u=0,d=0,h=[],p=[],g=[];try{if([u,h]=await SM(n),(n==null?void 0:n.externalData)&&o.mountExternalData){let ce=[];for(let oe of n.externalData){let he=typeof oe=="string"?oe:oe.path;ce.push(Lg(typeof oe=="string"?oe:oe.data).then(me=>{o.mountExternalData(he,me)}))}await Promise.all(ce)}for(let ce of(n==null?void 0:n.executionProviders)??[])if((typeof ce=="string"?ce:ce.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof ce!="string"){let oe=ce,he=oe==null?void 0:oe.context,me=oe==null?void 0:oe.gpuDevice,pe=oe==null?void 0:oe.deviceType,ne=oe==null?void 0:oe.powerPreference;he?o.currentContext=he:me?o.currentContext=await o.webnnCreateMLContext(me):o.currentContext=await o.webnnCreateMLContext({deviceType:pe,powerPreference:ne})}else o.currentContext=await o.webnnCreateMLContext();break}c=await o._OrtCreateSession(r,s,u),(y=o.webgpuOnCreateSession)==null||y.call(o,c),c===0&&ot("Can't create a session."),(w=o.jsepOnCreateSession)==null||w.call(o),o.currentContext&&(o.webnnRegisterMLContext(c,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[E,O]=Wb(c),z=!!(n!=null&&n.enableGraphCapture),D=[],P=[],j=[],G=[],K=[];for(let ce=0;cece==="gpu-buffer"||ce==="ml-tensor"||ce==="ml-tensor-cpu-output")&&(d=o._OrtCreateBinding(c),d===0&&ot("Can't create IO binding."),k={handle:d,outputPreferredLocations:K,outputPreferredLocationsEncoded:K.map(ce=>ce==="ml-tensor-cpu-output"?"ml-tensor":ce).map(ce=>ig(ce))}),ei.set(c,[c,p,g,k,z,!1]),[c,D,P,j,G]}catch(E){throw p.forEach(O=>o._OrtFree(O)),g.forEach(O=>o._OrtFree(O)),d!==0&&o._OrtReleaseBinding(d)!==0&&ot("Can't release IO binding."),c!==0&&o._OrtReleaseSession(c)!==0&&ot("Can't release session."),E}finally{o._free(r),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&ot("Can't release session options."),h.forEach(E=>o._free(E)),(S=o.unmountExternalData)==null||S.call(o)}},Bg=e=>{var h,p,g;let n=gt(),r=ei.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,c,u,d]=r;u&&(d&&n._OrtClearBoundOutputs(u.handle)!==0&&ot("Can't clear bound outputs."),n._OrtReleaseBinding(u.handle)!==0&&ot("Can't release IO binding.")),(h=n.jsepOnReleaseSession)==null||h.call(n,e),(p=n.webnnOnReleaseSession)==null||p.call(n,e),(g=n.webgpuOnReleaseSession)==null||g.call(n,e),o.forEach(y=>n._OrtFree(y)),c.forEach(y=>n._OrtFree(y)),n._OrtReleaseSession(s)!==0&&ot("Can't release session."),ei.delete(e)},h_=async(e,n,r,s,o,c,u=!1)=>{if(!e){n.push(0);return}let d=gt(),h=d.PTR_SIZE,p=e[0],g=e[1],y=e[3],w=y,b,S;if(p==="string"&&(y==="gpu-buffer"||y==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(u&&y!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${c} when enableGraphCapture is true.`);if(y==="gpu-buffer"){let z=e[2].gpuBuffer;S=gl(Hi(p),g);{let D=d.webgpuRegisterBuffer;if(!D)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');b=D(z,s)}}else if(y==="ml-tensor"){let z=e[2].mlTensor;S=gl(Hi(p),g);let D=d.webnnRegisterMLTensor;if(!D)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');b=D(s,z,Hi(p),g)}else{let z=e[2];if(Array.isArray(z)){S=h*z.length,b=d._malloc(S),r.push(b);for(let D=0;Dd.setValue(O+P*h,D,h===4?"i32":"i64"));let z=d._OrtCreateTensor(Hi(p),b,S,O,g.length,ig(w));z===0&&ot(`Can't create tensor for input/output. session=${s}, index=${c}.`),n.push(z)}finally{d.stackRestore(E)}},Pg=async(e,n,r,s,o,c)=>{var pe,ne,ee,Me;let u=gt(),d=u.PTR_SIZE,h=ei.get(e);if(!h)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=h[0],g=h[1],y=h[2],w=h[3],b=h[4],S=h[5],E=n.length,O=s.length,z=0,D=[],P=[],j=[],G=[],K=[],k=u.stackSave(),ce=u.stackAlloc(E*d),oe=u.stackAlloc(E*d),he=u.stackAlloc(O*d),me=u.stackAlloc(O*d);try{[z,D]=TM(c),ri("wasm prepareInputOutputTensor");for(let R=0;Rze*Ye,1);de=rh(Ne);let Ue=w==null?void 0:w.outputPreferredLocations[s[R]];if(de==="string"){if(Ue==="gpu-buffer"||Ue==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ze=[];for(let Ye=0;Ye0){let ze=u.webgpuGetBuffer;if(!ze)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ye=ze(be),Ht=gl(Ne,Ct);if(Ht===void 0||!Og(de))throw new Error(`Unsupported data type: ${de}`);ue=!0;{u.webgpuRegisterBuffer(Ye,e,be);let Rt=u.webgpuCreateDownloader(Ye,Ht,e);W.push([de,ht,{gpuBuffer:Ye,download:async()=>{let xt=await Rt();return new(Vu(de))(xt)},dispose:()=>{u._OrtReleaseTensor(te)!==0&&ot("Can't release tensor.")}},"gpu-buffer"])}}else if(Ue==="ml-tensor"&&Ct>0){let ze=u.webnnEnsureTensor,Ye=u.webnnIsGraphInputOutputTypeSupported;if(!ze||!Ye)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(gl(Ne,Ct)===void 0||!zg(de))throw new Error(`Unsupported data type: ${de}`);if(!Ye(e,de,!1))throw new Error(`preferredLocation "ml-tensor" for ${de} output is not supported by current WebNN Context.`);let Ht=await ze(e,be,Ne,ht,!1);ue=!0,W.push([de,ht,{mlTensor:Ht,download:u.webnnCreateMLTensorDownloader(be,de),dispose:()=>{u.webnnReleaseTensorId(be),u._OrtReleaseTensor(te)}},"ml-tensor"])}else if(Ue==="ml-tensor-cpu-output"&&Ct>0){let ze=u.webnnCreateMLTensorDownloader(be,de)(),Ye=W.length;ue=!0,I.push((async()=>{let Ht=[Ye,await ze];return u.webnnReleaseTensorId(be),u._OrtReleaseTensor(te),Ht})()),W.push([de,ht,[],"cpu"])}else{let ze=Vu(de),Ye=new ze(Ct);new Uint8Array(Ye.buffer,Ye.byteOffset,Ye.byteLength).set(u.HEAPU8.subarray(be,be+Ye.byteLength)),W.push([de,ht,Ye,"cpu"])}}finally{u.stackRestore(F),de==="string"&&be&&u._free(be),ue||u._OrtReleaseTensor(te)}}w&&!b&&(u._OrtClearBoundOutputs(w.handle)!==0&&ot("Can't clear bound outputs."),ei.set(e,[p,g,y,w,b,!1]));for(let[R,te]of await Promise.all(I))W[R][2]=te;return si("wasm ProcessOutputTensor"),W}finally{(Me=u.webnnOnRunEnd)==null||Me.call(u,p),u.stackRestore(k),r.forEach(V=>{V&&V[3]==="gpu-buffer"&&u.webgpuUnregisterBuffer(V[2].gpuBuffer)}),o.forEach(V=>{V&&V[3]==="gpu-buffer"&&u.webgpuUnregisterBuffer(V[2].gpuBuffer)}),P.forEach(V=>u._OrtReleaseTensor(V)),j.forEach(V=>u._OrtReleaseTensor(V)),G.forEach(V=>u._free(V)),z!==0&&u._OrtReleaseRunOptions(z),D.forEach(V=>u._free(V))}},Rg=e=>{let n=gt(),r=ei.get(e);if(!r)throw new Error("invalid session id");let s=r[0],o=n._OrtEndProfiling(s);o===0&&ot("Can't get an profile file name."),n._OrtFree(o)},Ug=e=>{let n=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&n.push(s.buffer)}return n}}),ti,Wn,fl,xu,Tu,Ff,p_,Bf,Ui,Ii,Zb,DM,FM,BM,PM,RM,UM,IM,GM=Ke(()=>{Ji(),NM(),eo(),Ag(),ti=()=>!!zt.wasm.proxy&&typeof document<"u",fl=!1,xu=!1,Tu=!1,Bf=new Map,Ui=(e,n)=>{let r=Bf.get(e);r?r.push(n):Bf.set(e,[n])},Ii=()=>{if(fl||!xu||Tu||!Wn)throw new Error("worker not ready")},Zb=e=>{switch(e.data.type){case"init-wasm":fl=!1,e.data.err?(Tu=!0,p_[1](e.data.err)):(xu=!0,p_[0]()),Ff&&(URL.revokeObjectURL(Ff),Ff=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let n=Bf.get(e.data.type);e.data.err?n.shift()[1](e.data.err):n.shift()[0](e.data.out);break}}},DM=async()=>{if(!xu){if(fl)throw new Error("multiple calls to 'initWasm()' detected.");if(Tu)throw new Error("previous call to 'initWasm()' failed.");if(fl=!0,ti())return new Promise((e,n)=>{Wn==null||Wn.terminate(),MM().then(([r,s])=>{try{Wn=s,Wn.onerror=c=>n(c),Wn.onmessage=Zb,p_=[e,n];let o={type:"init-wasm",in:zt};!o.in.wasm.wasmPaths&&(r||sg)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.asyncify-BC9nQecM.wasm",import.meta.url).href}),Wn.postMessage(o),Ff=r}catch(o){n(o)}},n)});try{await Cg(zt.wasm),await Ng(zt),xu=!0}catch(e){throw Tu=!0,e}finally{fl=!1}}},FM=async e=>{if(ti())return Ii(),new Promise((n,r)=>{Ui("init-ep",[n,r]);let s={type:"init-ep",in:{epName:e,env:zt}};Wn.postMessage(s)});await Dg(zt,e)},BM=async e=>ti()?(Ii(),new Promise((n,r)=>{Ui("copy-from",[n,r]);let s={type:"copy-from",in:{buffer:e}};Wn.postMessage(s,[e.buffer])})):fh(e),PM=async(e,n)=>{if(ti()){if(n!=null&&n.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ii(),new Promise((r,s)=>{Ui("create",[r,s]);let o={type:"create",in:{model:e,options:{...n}}},c=[];e instanceof Uint8Array&&c.push(e.buffer),Wn.postMessage(o,c)})}else return Fg(e,n)},RM=async e=>{if(ti())return Ii(),new Promise((n,r)=>{Ui("release",[n,r]);let s={type:"release",in:e};Wn.postMessage(s)});Bg(e)},UM=async(e,n,r,s,o,c)=>{if(ti()){if(r.some(u=>u[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(u=>u))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ii(),new Promise((u,d)=>{Ui("run",[u,d]);let h=r,p={type:"run",in:{sessionId:e,inputIndices:n,inputs:h,outputIndices:s,options:c}};Wn.postMessage(p,Ug(h))})}else return Pg(e,n,r,s,o,c)},IM=async e=>{if(ti())return Ii(),new Promise((n,r)=>{Ui("end-profiling",[n,r]);let s={type:"end-profiling",in:e};Wn.postMessage(s)});Rg(e)}}),m_,Kb,jM,gA=Ke(()=>{Ji(),GM(),Tl(),Eg(),EM(),m_=(e,n)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${n()}`)}},Kb=e=>{switch(e[3]){case"cpu":return new tr(e[0],e[2],e[1]);case"gpu-buffer":{let n=e[0];if(!Og(n))throw new Error(`not supported data type: ${n} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:o}=e[2];return tr.fromGpuBuffer(r,{dataType:n,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let n=e[0];if(!zg(n))throw new Error(`not supported data type: ${n} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:o}=e[2];return tr.fromMLTensor(r,{dataType:n,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},jM=class{async fetchModelAndCopyToWasmMemory(e){return BM(await Lg(e))}async loadModel(e,n){Wi();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await PM(r,n),Zi()}async dispose(){return RM(this.sessionId)}async run(e,n,r){Wi();let s=[],o=[];Object.entries(e).forEach(y=>{let w=y[0],b=y[1],S=this.inputNames.indexOf(w);if(S===-1)throw new Error(`invalid input '${w}'`);s.push(b),o.push(S)});let c=[],u=[];Object.entries(n).forEach(y=>{let w=y[0],b=y[1],S=this.outputNames.indexOf(w);if(S===-1)throw new Error(`invalid output '${w}'`);c.push(b),u.push(S)});let d=s.map((y,w)=>m_(y,()=>`input "${this.inputNames[o[w]]}"`)),h=c.map((y,w)=>y?m_(y,()=>`output "${this.outputNames[u[w]]}"`):null),p=await UM(this.sessionId,o,d,u,h,r),g={};for(let y=0;ycg,initializeFlags:()=>lg,wasmBackend:()=>qM});var lg,cg,qM,vA=Ke(()=>{Ji(),GM(),gA(),lg=()=>{(typeof zt.wasm.initTimeout!="number"||zt.wasm.initTimeout<0)&&(zt.wasm.initTimeout=0);let e=zt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),zt.wasm.simd=!1),typeof zt.wasm.proxy!="boolean"&&(zt.wasm.proxy=!1),typeof zt.wasm.trace!="boolean"&&(zt.wasm.trace=!1),typeof zt.wasm.numThreads!="number"||!Number.isInteger(zt.wasm.numThreads)||zt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)zt.wasm.numThreads=1;else{let n=typeof navigator>"u"?QE("node:os").cpus().length:navigator.hardwareConcurrency;zt.wasm.numThreads=Math.min(4,Math.ceil((n||1)/2))}},cg=class{async init(e){lg(),await DM(),await FM(e)}async createInferenceSessionHandler(e,n){let r=new jM;return await r.loadModel(e,n),r}},qM=new cg});Ji();Ji();Ji();var yA="1.25.0-dev.20260212-1a71a5f46e",wA=_M;{let e=(vA(),lh(VM)).wasmBackend;Yi("webgpu",e,5),Yi("webnn",e,5),Yi("cpu",e,10),Yi("wasm",e,10)}Object.defineProperty(zt.versions,"web",{value:yA,enumerable:!0});const bA=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return Sg},get TRACE(){return ch},get TRACE_EVENT_BEGIN(){return ri},get TRACE_EVENT_END(){return si},get TRACE_FUNC_BEGIN(){return Wi},get TRACE_FUNC_END(){return Zi},get Tensor(){return tr},default:wA,get env(){return zt},get registerBackend(){return Yi}},Symbol.toStringTag,{value:"Module"})),MA=(e,n)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];const s=r.getContext("2d");if(s!=null){let o,c;(n==null?void 0:n.tensorLayout)!==void 0&&n.tensorLayout==="NHWC"?(o=e.dims[2],c=e.dims[3]):(o=e.dims[3],c=e.dims[2]);const u=(n==null?void 0:n.format)!==void 0?n.format:"RGB",d=n==null?void 0:n.norm;let h,p;d===void 0||d.mean===void 0?h=[255,255,255,255]:typeof d.mean=="number"?h=[d.mean,d.mean,d.mean,d.mean]:(h=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(h[3]=d.mean[3])),d===void 0||d.bias===void 0?p=[0,0,0,0]:typeof d.bias=="number"?p=[d.bias,d.bias,d.bias,d.bias]:(p=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(p[3]=d.bias[3]));const g=c*o;let y=0,w=g,b=g*2,S=-1;u==="RGBA"?(y=0,w=g,b=g*2,S=g*3):u==="RGB"?(y=0,w=g,b=g*2):u==="RBG"&&(y=0,b=g,w=g*2);for(let E=0;E{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(r!=null){let o,c,u;(n==null?void 0:n.tensorLayout)!==void 0&&n.tensorLayout==="NHWC"?(o=e.dims[2],c=e.dims[1],u=e.dims[3]):(o=e.dims[3],c=e.dims[2],u=e.dims[1]);const d=n!==void 0&&n.format!==void 0?n.format:"RGB",h=n==null?void 0:n.norm;let p,g;h===void 0||h.mean===void 0?p=[255,255,255,255]:typeof h.mean=="number"?p=[h.mean,h.mean,h.mean,h.mean]:(p=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(p[3]=h.mean[3])),h===void 0||h.bias===void 0?g=[0,0,0,0]:typeof h.bias=="number"?g=[h.bias,h.bias,h.bias,h.bias]:(g=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(g[3]=h.bias[3]));const y=c*o;if(n!==void 0&&(n.format!==void 0&&u===4&&n.format!=="RGBA"||u===3&&n.format!=="RGB"&&n.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const w=4;let b=0,S=1,E=2,O=3,z=0,D=y,P=y*2,j=-1;d==="RGBA"?(z=0,D=y,P=y*2,j=y*3):d==="RGB"?(z=0,D=y,P=y*2):d==="RBG"&&(z=0,P=y,D=y*2),s=r.createImageData(o,c);for(let G=0;G{if(e===void 0)throw new Error("Image buffer must be defined");if(n.height===void 0||n.width===void 0)throw new Error("Image height and width must be defined");if(n.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:s}=n,o=n.norm??{mean:255,bias:0};let c,u;typeof o.mean=="number"?c=[o.mean,o.mean,o.mean,o.mean]:c=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:u=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const d=n.format!==void 0?n.format:"RGBA",h=n.tensorFormat!==void 0&&n.tensorFormat!==void 0?n.tensorFormat:"RGB",p=r*s,g=h==="RGBA"?new Float32Array(p*4):new Float32Array(p*3);let y=4,w=0,b=1,S=2,E=3,O=0,z=p,D=p*2,P=-1;d==="RGB"&&(y=3,w=0,b=1,S=2,E=-1),h==="RGBA"?P=p*3:h==="RBG"?(O=0,D=p,z=p*2):h==="BGR"&&(D=0,z=p,O=p*2);for(let G=0;G{const r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,c=typeof e=="string";let u,d=n??{};const h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=g=>typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(r){const g=h();g.width=e.width,g.height=e.height;const y=p(g);if(y!=null){let w=e.height,b=e.width;if(n!==void 0&&n.resizedHeight!==void 0&&n.resizedWidth!==void 0&&(w=n.resizedHeight,b=n.resizedWidth),n!==void 0){if(d=n,n.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=w,d.width=b}else d.tensorFormat="RGBA",d.height=w,d.width=b;y.drawImage(e,0,0),u=y.getImageData(0,0,b,w).data}else throw new Error("Can not access image data")}else if(s){let g,y;if(n!==void 0&&n.resizedWidth!==void 0&&n.resizedHeight!==void 0?(g=n.resizedHeight,y=n.resizedWidth):(g=e.height,y=e.width),n!==void 0&&(d=n),d.format="RGBA",d.height=g,d.width=y,n!==void 0){const w=h();w.width=y,w.height=g;const b=p(w);if(b!=null)b.putImageData(e,0,0),u=b.getImageData(0,0,y,g).data;else throw new Error("Can not access image data")}else u=e.data}else if(o){if(n===void 0)throw new Error("Please provide image config with format for Imagebitmap");const g=h();g.width=e.width,g.height=e.height;const y=p(g);if(y!=null){const w=e.height,b=e.width;return y.drawImage(e,0,0,b,w),u=y.getImageData(0,0,b,w).data,d.height=w,d.width=b,__(u,d)}else throw new Error("Can not access image data")}else{if(c)return new Promise((g,y)=>{const w=h(),b=p(w);if(!e||!b)return y();const S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{w.width=S.width,w.height=S.height,b.drawImage(S,0,0,w.width,w.height);const E=b.getImageData(0,0,w.width,w.height);d.height=w.height,d.width=w.width,g(__(E.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return __(u,d);throw new Error("Input data provided is not supported - aborted tensor creation")},SA=(e,n)=>{const{width:r,height:s,download:o,dispose:c}=n,u=[1,s,r,4];return new Da({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:c})},EA=(e,n)=>{const{dataType:r,dims:s,download:o,dispose:c}=n;return new Da({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:o,dispose:c})},AA=(e,n)=>{const{dataType:r,dims:s,download:o,dispose:c}=n;return new Da({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:o,dispose:c})},CA=(e,n,r)=>new Da({location:"cpu-pinned",type:e,data:n,dims:r??[n.length]}),yl=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),sh=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Jb=!1;const kA=()=>{if(!Jb){Jb=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,n=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(yl.set("int64",BigInt64Array),sh.set(BigInt64Array,"int64")),n&&(yl.set("uint64",BigUint64Array),sh.set(BigUint64Array,"uint64")),s?(yl.set("float16",r),sh.set(r,"float16")):yl.set("float16",Uint16Array)}},OA=e=>{let n=1;for(let r=0;r{switch(e.location){case"cpu":return new Da(e.type,e.data,n);case"cpu-pinned":return new Da({location:"cpu-pinned",data:e.data,type:e.type,dims:n});case"texture":return new Da({location:"texture",texture:e.texture,type:e.type,dims:n});case"gpu-buffer":return new Da({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:n});case"ml-tensor":return new Da({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:n});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Da=class{constructor(n,r,s){kA();let o,c;if(typeof n=="object"&&"location"in n)switch(this.dataLocation=n.location,o=n.type,c=n.dims,n.location){case"cpu-pinned":{const d=yl.get(o);if(!d)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(n.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=n.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=n.texture,this.downloader=n.download,this.disposer=n.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=n.gpuBuffer,this.downloader=n.download,this.disposer=n.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=n.mlTensor,this.downloader=n.download,this.disposer=n.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,h;if(typeof n=="string")if(o=n,h=s,n==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");d=r}else{const p=yl.get(n);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(r)){if(n==="float16"&&p===Uint16Array||n==="uint4"||n==="int4")throw new TypeError(`Creating a ${n} tensor from number array is not supported. Please use ${p.name} as data.`);n==="uint64"||n==="int64"?d=p.from(r,BigInt):d=p.from(r)}else if(r instanceof p)d=r;else if(r instanceof Uint8ClampedArray)if(n==="uint8")d=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(n==="float16"&&r instanceof Uint16Array&&p!==Uint16Array)d=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${o} tensor's data must be type of ${p}`)}else if(h=r,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const p=typeof n[0];if(p==="string")o="string",d=n;else if(p==="boolean")o="bool",d=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(n instanceof Uint8ClampedArray)o="uint8",d=Uint8Array.from(n);else{const p=sh.get(n.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);o=p,d=n}if(h===void 0)h=[d.length];else if(!Array.isArray(h))throw new TypeError("A tensor's dims must be a number array");c=h,this.cpuData=d,this.dataLocation="cpu"}const u=OA(c);if(this.cpuData&&u!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(u/2)===this.cpuData.length))throw new Error(`Tensor's size(${u}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=c,this.size=u}static async fromImage(n,r){return TA(n,r)}static fromTexture(n,r){return SA(n,r)}static fromGpuBuffer(n,r){return EA(n,r)}static fromMLTensor(n,r){return AA(n,r)}static fromPinnedBuffer(n,r,s){return CA(n,r,s)}toDataURL(n){return MA(this,n)}toImageData(n){return xA(this,n)}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(n){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;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,n&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(n){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return zA(this,n)}};const LA=Da;var us={},NA=Object.defineProperty,Sl=(e,n)=>{for(var r in n)NA(e,r,{get:n[r],enumerable:!0})},DA={},er=DA,FA={},fs=FA,BA={},PA=BA,RA="4.0.0-next.3",$M=typeof process<"u",X1,HM=$M&&((X1=process==null?void 0:process.release)==null?void 0:X1.name)==="node",Iu=!WM(er),YM=!WM(fs),UA=typeof globalThis.Deno<"u",XM=typeof window<"u"&&typeof window.document<"u",Q1,QM=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes((Q1=self.constructor)==null?void 0:Q1.name),ug=typeof self<"u"&&"caches"in self,IA=HM||typeof navigator<"u"&&"gpu"in navigator,GA=typeof navigator<"u"&&"ml"in navigator,jA=()=>{if(typeof navigator>"u")return!1;const e=navigator.userAgent,r=(navigator.vendor||"").indexOf("Apple")>-1,s=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes("Chrome")&&!e.includes("Android");return r&&s},VA=jA(),Nt=Object.freeze({IS_BROWSER_ENV:XM,IS_WEBWORKER_ENV:QM,IS_WEB_CACHE_AVAILABLE:ug,IS_WEBGPU_AVAILABLE:IA,IS_WEBNN_AVAILABLE:GA,IS_SAFARI:VA,IS_PROCESS_AVAILABLE:$M,IS_NODE_ENV:HM,IS_FS_AVAILABLE:Iu,IS_PATH_AVAILABLE:YM}),Ig=Iu&&YM,hh="./";if(Ig){const e=Object(import.meta).url;e?hh=fs.dirname(fs.dirname(PA.fileURLToPath(e))):typeof __dirname<"u"&&(hh=fs.dirname(__dirname))}var qA=Ig?fs.join(hh,"/.cache/"):null,e1="/models/",$A=Ig?fs.join(hh,e1):e1,pa={version:RA,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(XM||QM),localModelPath:$A,useFS:Iu,useBrowserCache:ug&&!UA,useFSCache:Iu,cacheDir:qA,useCustomCache:!1,customCache:null,useWasmCache:ug||Iu,cacheKey:"transformers-cache"};function WM(e){return Object.keys(e).length===0}var HA=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const n=Object.create(null);for(const r of e){let s=n;for(let o=0;os&&n.push(e.slice(s,o)),n.push(u),o+=u.length,s=o):++o}return s{const e=[...Array.from({length:94},(o,c)=>c+33),...Array.from({length:12},(o,c)=>c+161),...Array.from({length:82},(o,c)=>c+174)],n=e.slice();let r=0;for(let o=0;o<256;++o)e.includes(o)||(e.push(o),n.push(256+r),r+=1);const s=n.map(o=>String.fromCharCode(o));return Object.fromEntries(e.map((o,c)=>[o,s[c]]))})(),QA=e=>Object.fromEntries(Object.entries(e).map(([n,r])=>[r,n])),WA=QA(ZM),n1=".,!?…。,、।۔،",ZA=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|[${n1}])]+`,` ?[^\\s${n1}]+`]]),ph="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Gg=e=>e.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),Eh=(e,n=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");for(const[s,o]of ZA)r=r.replaceAll(s,o);try{return new RegExp(r,"gu")}catch(s){if(!(s instanceof SyntaxError)||!s.message.toLowerCase().includes("invalid property name"))throw s;let o=!1;const c=r.replace(/(\\[pP])\{([^}=]+)\}/g,(u,d,h)=>{try{return new RegExp(`\\p{${h}}`,"u"),`${d}{${h}}`}catch{return o=!0,`${d}{Script=${h}}`}});if(!o)throw s;try{return new RegExp(c,"gu")}catch{throw s}}}else if(e.String!==void 0){const r=KA(e.String);return new RegExp(n?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},KA=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),JA=(e,n,r)=>{const s=[];let o=0;for(;oe>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,tC=e=>Number.isInteger(e)||typeof e=="bigint",nC=e=>{let n=0;for(const r of e)++n;return n},aC=e=>KM(e.toLowerCase()),nr=(...e)=>Array.prototype.concat.apply([],e),jg=e=>new Map(Object.entries(e)),rC=(e,n)=>{const r=[];let s=0;for(const o of e.matchAll(n)){const c=o[0];s0&&r.push(c),s=o.index+c.length}return se.replace(new RegExp("\\p{M}","gu"),""),a1=(e,n,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${n} must be a valid object`;for(const s of r)if(!(s in e))return`${n} must contain a "${s}" property`;return null},sC=e=>e.match(/\S+/g)||[],iC=class{constructor(){const e=function(...n){return e._call(...n)};return Object.setPrototypeOf(e,new.target.prototype)}},Hu=iC,oC=class extends Hu{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},ps=oC,lC=class extends ps{tokenize_chinese_chars(e){const n=[];for(let r=0;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},dC=uC,fC=class extends ps{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(n=>JM(n))}normalize(e){return this.normalizers.reduce((n,r)=>r?r.normalize(n):n,e)}},hC=fC,pC=class extends ps{normalize(e){const n=Eh(this.config.pattern??{});return n===null?e:e.replaceAll(n,this.config.content??"")}},mC=pC,_C=class extends ps{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},Ah=_C,gC=class extends Ah{constructor(){super(...arguments),this.form="NFC"}},vC=gC,yC=class extends Ah{constructor(){super(...arguments),this.form="NFD"}},wC=yC,bC=class extends Ah{constructor(){super(...arguments),this.form="NFKC"}},MC=bC,xC=class extends Ah{constructor(){super(...arguments),this.form="NFKD"}},TC=xC,SC=class extends ps{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},EC=SC,AC=class extends ps{normalize(e){return KM(e)}},CC=AC,kC=class extends ps{normalize(e){return e.toLowerCase()}},OC=kC,zC=class extends ps{normalize(e){return e=this.config.prepend+e,e}},LC=zC;function NC(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new cC(e);case"Precompiled":return new dC(e);case"Sequence":return new hC(e);case"Replace":return new mC(e);case"NFC":return new vC(e);case"NFD":return new wC(e);case"NFKC":return new MC(e);case"NFKD":return new TC(e);case"Strip":return new EC(e);case"StripAccents":return new CC(e);case"Lowercase":return new OC(e);case"Prepend":return new LC(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var JM=NC,DC=class extends Hu{pre_tokenize(e,n){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,n)):this.pre_tokenize_text(e,n)).flat()}_call(e,n){return this.pre_tokenize(e,n)}},sr=DC,FC=class extends sr{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=ZM,this.text_encoder=new TextEncoder}pre_tokenize_text(e,n){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(s=>Array.from(this.text_encoder.encode(s),o=>this.byte_encoder[o]).join(""))}},BC=FC,PC=class extends sr{pre_tokenize_text(e,n){return e.match(/\w+|[^\w\s]+/g)||[]}},RC=PC,UC=class extends sr{constructor(e){super(),this.replacement=e.replacement??"▁",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,n){const{section_index:r=void 0}=n??{};let s=e.replaceAll(" ",this.str_rep);return!s.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&r===0)&&(s=this.str_rep+s),[s]}},IC=UC,GC=class extends sr{constructor(e){super(),this.config=e,this.pattern=Eh(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){var n;return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:((n=this.config.behavior)==null?void 0:n.toLowerCase())==="removed"?e.split(this.pattern).filter(r=>r):rC(e,this.pattern)}},jC=GC,VC=class extends sr{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${ph}]+|[${ph}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},qC=VC,$C=class extends sr{constructor(e){super(),this.config=e;const n=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(n,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},HC=$C,YC=class extends sr{constructor(){super(),this.pattern=new RegExp(`[^\\s${ph}]+|[${ph}]`,"gu")}pre_tokenize_text(e,n){return e.trim().match(this.pattern)||[]}},XC=YC,QC=class extends sr{constructor(e){super(),this.config=e,this.pattern=Eh(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},WC=QC,ZC=class extends sr{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(n=>ex(n))}pre_tokenize_text(e,n){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,n):r,[e])}},KC=ZC,JC=class extends sr{pre_tokenize_text(e){return sC(e)}},ek=JC,tk=class extends sr{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const n=[];for(let r=0;rthis.max_input_chars_per_word){n.push(this.unk_token);continue}let o=!1,c=0;const u=[];for(;c0&&(p=this.config.continuing_subword_prefix+p),this.tokens_to_ids.has(p)){h=p;break}--d}if(h===null){o=!0;break}u.push(h),c=d}o?n.push(this.unk_token):n.push(...u)}return n}},r1=sk,s1=class tx{constructor(n,r){this.is_leaf=n,this.children=r}static default(){return new tx(!1,new Map)}},ik=class{constructor(){this.root=s1.default()}extend(e){for(const n of e)this.push(n)}push(e){let n=this.root;for(const r of e){let s=n.children.get(r);s===void 0&&(s=s1.default(),n.children.set(r,s)),n=s}n.is_leaf=!0}*common_prefix_search(e){let n=this.root;if(n===void 0)return;let r="";for(const s of e){if(r+=s,n=n.children.get(s),n===void 0)return;n.is_leaf&&(yield r)}}},ok=ik,g_=class nx{constructor(n,r,s,o,c){this.token_id=n,this.node_id=r,this.pos=s,this.length=o,this.score=c,this.prev=null,this.backtrace_score=0}clone(){const n=new nx(this.token_id,this.node_id,this.pos,this.length,this.score);return n.prev=this.prev,n.backtrace_score=this.backtrace_score,n}},lk=class{constructor(e,n,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=n,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},()=>[]);const s=new g_(this.bos_token_id??0,0,0,0,0),o=new g_(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(s.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(s)}insert(e,n,r,s){const o=this.nodes.length,c=new g_(s,o,e,n,r);this.begin_nodes[e].push(c),this.end_nodes[e+n].push(c),this.nodes.push(c)}viterbi(){const e=this.len;let n=0;for(;n<=e;){if(this.begin_nodes[n].length==0)return[];for(let u of this.begin_nodes[n]){u.prev=null;let d=0,h=null;for(let p of this.end_nodes[n]){const g=p.backtrace_score+u.score;(h===null||g>d)&&(h=p.clone(),d=g)}if(h!==null)u.prev=h,u.backtrace_score=d;else return[]}++n}const r=[],o=this.begin_nodes[e][0].prev;if(o===null)return[];let c=o.clone();for(;c.prev!==null;)r.push(c.clone()),c=c.clone().prev.clone();return r.reverse(),r}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join("")}tokens(){return this.viterbi().map(n=>this.piece(n))}token_ids(){return this.viterbi().map(n=>n.token_id)}},ck=lk;function uk(e){if(e.length===0)throw new Error("Array must not be empty");let n=e[0],r=0;for(let s=1;s[s,o])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=n,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=uk(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new ok,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const n=e.chars,r=1;let s=0;for(;sr>s,n=1/0){this._heap=[],this._comparator=e,this._max_size=n}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(const n of e)if(this.size0&&this._swap(0,n),this._heap.pop(),this._sift_down(),e}replace(e){const n=this.peek();return this._heap[0]=e,this._sift_down(),n}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,n){return this._comparator(this._heap[e],this._heap[n])}_swap(e,n){const r=this._heap[e];this._heap[e]=this._heap[n],this._heap[n]=r}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},mk=pk,_k=class extends Ch{constructor(e){super(e),this.tokens_to_ids=jg(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[r,s]of this.tokens_to_ids)this.vocab[s]=r;const n=Array.isArray(e.merges[0]);this.merges=n?e.merges:e.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=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new mk(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];const n=this.cache.get(e);if(n!==void 0)return n;const r=Array.from(e);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let s=[];if(r.length>1){const o=new hk((d,h)=>d.score`<0x${u.toString(16).toUpperCase().padStart(2,"0")}>`);c.every(u=>this.tokens_to_ids.has(u))?n.push(...c):n.push(this.unk_token)}else n.push(this.unk_token)}return n}},o1=_k,gk=class extends Ch{constructor(e,n){super(e);const r=e.vocab;this.tokens_to_ids=jg(n.target_lang?r[n.target_lang]:r),this.bos_token=n.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=n.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=n.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=n.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[s,o]of this.tokens_to_ids)this.vocab[o]=s}encode(e){return e}},vk=gk;function yk(e,n){switch(e.type){case"WordPiece":return new r1(e);case"Unigram":return new i1(e,n.eos_token);case"BPE":return new o1(e);default:if(e.vocab)return Array.isArray(e.vocab)?new i1(e,n.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new o1(e):new r1(e):new vk(e,{target_lang:n.target_lang,bos_token:n.bos_token,eos_token:n.eos_token,pad_token:n.pad_token,unk_token:n.unk_token});throw new Error(`Unknown TokenizerModel type: ${e==null?void 0:e.type}`)}}var wk=yk,bk=class extends Hu{constructor(e){super(),this.config=e}_call(e,...n){return this.post_process(e,...n)}},Yu=bk,Mk=class extends Yu{post_process(e,n=null,r=!0){const s=n===null?this.config.single:this.config.pair;let o=[],c=[];for(const u of s)"SpecialToken"in u?r&&(o.push(u.SpecialToken.id),c.push(u.SpecialToken.type_id)):"Sequence"in u&&(u.Sequence.id==="A"?(o=nr(o,e),c=nr(c,new Array(e.length).fill(u.Sequence.type_id))):u.Sequence.id==="B"&&(o=nr(o,n),c=nr(c,new Array(n.length).fill(u.Sequence.type_id))));return{tokens:o,token_type_ids:c}}},xk=Mk,Tk=class extends Yu{post_process(e,n=null){return{tokens:e,tokens_pair:n}}},Sk=Tk,Ek=class extends Yu{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,n=null,r=!0){r&&(e=nr([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(n){const o=[],c=r?[this.sep[0]]:[];e=nr(e,o,n,c),s=nr(s,new Array(n.length+o.length+c.length).fill(1))}return{tokens:e,token_type_ids:s}}},Ak=Ek,Ck=class extends Yu{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,n,r=!0){r&&(e=nr([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(n){const o=r?[this.sep[0]]:[],c=r?[this.sep[0]]:[];e=nr(e,o,n,c),s=nr(s,new Array(n.length+o.length+c.length).fill(1))}return{tokens:e,token_type_ids:s}}},kk=Ck,Ok=class extends Yu{constructor(e){super(e),this.processors=(e.processors??[]).map(n=>ax(n))}post_process(e,n=null,r=!0){let s={tokens:e,tokens_pair:n};for(const o of this.processors)s=o.post_process(s.tokens,s.tokens_pair,r);return s}},zk=Ok;function Lk(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new xk(e);case"ByteLevel":return new Sk(e);case"BertProcessing":return new Ak(e);case"RobertaProcessing":return new kk(e);case"Sequence":return new zk(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var ax=Lk,Nk=class extends Hu{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join("")}},ir=Nk,Dk=class extends ir{constructor(e){super(e),this.byte_decoder=WA,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const n=e.join(""),r=new Uint8Array([...n].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(e){const n=[];let r=[];for(const s of e)this.added_tokens.find(o=>o.content===s)!==void 0?(r.length>0&&(n.push(this.convert_tokens_to_string(r)),r=[]),n.push(s)):r.push(s);return r.length>0&&n.push(this.convert_tokens_to_string(r)),n}},Fk=Dk,Bk=class extends ir{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((n,r)=>{if(r!==0){const s=this.config.prefix;s&&n.startsWith(s)?n=n.replace(s,""):n=" "+n}return this.cleanup&&(n=Gg(n)),n})}},Pk=Bk,Rk=class extends ir{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const n=[];for(let r=0;rn.replaceAll(this.suffix,r===e.length-1?"":" "))}},Gk=Ik,jk=class extends ir{constructor(e){super(e),this.pad_token=e.pad_token??"",this.word_delimiter_token=e.word_delimiter_token??"",this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return"";const n=[e[0]];for(let o=1;oo!==this.pad_token).join("");return this.cleanup&&(s=Gg(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}},Vk=jk,qk=class extends ir{constructor(e){super(e),this.decoders=(e.decoders??[]).map(n=>rx(n))}decode_chain(e){return this.decoders.reduce((n,r)=>r.decode_chain(n),e)}},$k=qk,Hk=class extends ir{decode_chain(e){const n=Eh(this.config.pattern),r=this.config.content??"";return n===null?e:e.map(s=>s.replaceAll(n,r))}},Yk=Hk,Xk=class extends ir{decode_chain(e){return[e.join("")]}},Qk=Xk,Wk=class extends ir{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(n=>{let r=0;for(let o=0;o")){const c=parseInt(s.slice(3,5),16);isNaN(c)||(o=c)}if(o!==null)r.push(o);else{if(r.length>0){const c=this.text_decoder.decode(Uint8Array.from(r));n.push(c),r=[]}n.push(s)}}if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));n.push(s),r=[]}return n}},Jk=Kk;function eO(e){if(e===null)return null;switch(e.type){case"ByteLevel":return new Fk(e);case"WordPiece":return new Pk(e);case"Metaspace":return new Uk(e);case"BPEDecoder":return new Gk(e);case"CTC":return new Vk(e);case"Sequence":return new $k(e);case"Replace":return new Yk(e);case"Fuse":return new Qk(e);case"Strip":return new Zk(e);case"ByteFallback":return new Jk(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var rx=eO,tO=class{constructor(e,n){const r=a1(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const s=a1(n,"Config");if(s)throw new Error(s);this.tokenizer=e,this.config=n,this.normalizer=JM(this.tokenizer.normalizer),this.pre_tokenizer=ex(this.tokenizer.pre_tokenizer),this.model=wk(this.tokenizer.model,this.config),this.post_processor=ax(this.tokenizer.post_processor),this.decoder=rx(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const o=[],c=[];this.added_tokens_map=new Map;for(const u of this.tokenizer.added_tokens){const d=new XA(u);if(this.added_tokens.push(d),this.model.tokens_to_ids.set(d.content,d.id),this.model.vocab[d.id]=d.content,d.special&&(this.special_tokens.push(d.content),this.all_special_ids.push(d.id)),this.added_tokens_map.set(d.content,d),d.normalized&&this.normalizer!==null){const h=this.normalizer(d.content);c.push(h),this.added_tokens_map.set(h,d)}else o.push(d.content)}(this.config.additional_special_tokens??[]).forEach(u=>{this.special_tokens.includes(u)||this.special_tokens.push(u)}),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 t1(o),this.splitter_normalized=new t1(c),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:n=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){const{tokens:o,token_type_ids:c}=this.tokenize_helper(e,{text_pair:n,add_special_tokens:r}),u=o.map(h=>{var p;return((p=this.added_tokens_map.get(h))==null?void 0:p.id)??this.model.tokens_to_ids.get(h)??this.model.unk_token_id}),d={ids:u,tokens:o,attention_mask:new Array(u.length).fill(1)};return s&&c&&(d.token_type_ids=c),d}decode(e,n={}){if(!Array.isArray(e)||e.length===0||!tC(e[0]))throw Error("token_ids must be a non-empty array of integers.");let r=e.map(o=>this.model.vocab[Number(o)]??this.model.unk_token);n.skip_special_tokens&&(r=r.filter(o=>!this.special_tokens.includes(o)));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," "),n.skip_special_tokens&&(s=s.trim())),(n.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=Gg(s)),s}tokenize(e,{text_pair:n=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:n,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;const n=this.splitter_unnormalized.split(e);return n.forEach((r,s)=>{const o=this.added_tokens_map.get(r);o&&(o.lstrip&&s>0&&(n[s-1]=n[s-1].trimEnd()),o.rstrip&&s{if(r.length===0)return[];if(this.added_tokens_map.has(r))return[r];if(this.remove_space===!0&&(r=r.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(r=aC(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const o=this.splitter_normalized.split(r);return o.forEach((c,u)=>{const d=this.added_tokens_map.get(c);d&&(d.lstrip&&u>0&&(o[u-1]=o[u-1].trimEnd()),d.rstrip&&u{if(c.length===0)return[];if(this.added_tokens_map.has(c))return[c];const u=this.pre_tokenizer!==null?this.pre_tokenizer(c,{section_index:s}):[c];return this.model(u)})})}tokenize_helper(e,{text_pair:n=null,add_special_tokens:r=!0}){const s=this.encode_text(e),o=this.encode_text(n||null);return this.post_processor?this.post_processor(s,o,r):{tokens:nr(s??[],o??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){const e=new Map;for(const n of this.added_tokens)e.set(n.id,n);return e}get_vocab(e=!0){const n=new Map;for(let r=0;r=",se.ComparisonBinaryOperator],["==",se.ComparisonBinaryOperator],["!=",se.ComparisonBinaryOperator],["<",se.ComparisonBinaryOperator],[">",se.ComparisonBinaryOperator],["+",se.AdditiveBinaryOperator],["-",se.AdditiveBinaryOperator],["~",se.AdditiveBinaryOperator],["*",se.MultiplicativeBinaryOperator],["/",se.MultiplicativeBinaryOperator],["%",se.MultiplicativeBinaryOperator],["=",se.Equals]],rO=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function sO(e,n={}){return e.endsWith(` +`)&&(e=e.slice(0,-1)),n.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),n.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function iO(e,n={}){var p,g;const r=[],s=sO(e,n);let o=0,c=0;const u=y=>{let w="";for(;y(s[o]);){if(s[o]==="\\"){if(++o,o>=s.length)throw new SyntaxError("Unexpected end of input");const b=s[o++],S=rO.get(b);if(S===void 0)throw new SyntaxError(`Unexpected escaped character: ${b}`);w+=S;continue}if(w+=s[o++],o>=s.length)throw new SyntaxError("Unexpected end of input")}return w},d=()=>{const y=r.at(-1);y&&y.type===se.Text&&(y.value=y.value.trimEnd(),y.value===""&&r.pop())},h=()=>{for(;o0){r.push(new za(b,se.Text));continue}}if(s[o]==="{"&&s[o+1]==="#"){o+=2;const b=s[o]==="-";b&&++o;let S="";for(;s[o]!=="#"||s[o+1]!=="}";){if(o+2>=s.length)throw new SyntaxError("Missing end of comment tag");S+=s[o++]}const E=S.endsWith("-");E&&(S=S.slice(0,-1)),b&&d(),r.push(new za(S,se.Comment)),o+=2,E&&h();continue}if(s.slice(o,o+3)==="{%-"){d(),r.push(new za("{%",se.OpenStatement)),o+=3;continue}if(s.slice(o,o+3)==="{{-"){d(),r.push(new za("{{",se.OpenExpression)),c=0,o+=3;continue}if(u(c1),s.slice(o,o+3)==="-%}"){r.push(new za("%}",se.CloseStatement)),o+=3,h();continue}if(s.slice(o,o+3)==="-}}"){r.push(new za("}}",se.CloseExpression)),o+=3,h();continue}const w=s[o];if(w==="-"||w==="+"){const b=(g=r.at(-1))==null?void 0:g.type;if(b===se.Text||b===void 0)throw new SyntaxError(`Unexpected character: ${w}`);switch(b){case se.Identifier:case se.NumericLiteral:case se.StringLiteral:case se.CloseParen:case se.CloseSquareBracket:break;default:{++o;const S=u(Su);r.push(new za(`${w}${S}`,S.length>0?se.NumericLiteral:se.UnaryOperator));continue}}}for(const[b,S]of aO){if(b==="}}"&&c>0)continue;if(s.slice(o,o+b.length)===b){r.push(new za(b,S)),S===se.OpenExpression?c=0:S===se.OpenCurlyBracket?++c:S===se.CloseCurlyBracket&&--c,o+=b.length;continue e}}if(w==="'"||w==='"'){++o;const b=u(S=>S!==w);r.push(new za(b,se.StringLiteral)),++o;continue}if(Su(w)){let b=u(Su);if(s[o]==="."&&Su(s[o+1])){++o;const S=u(Su);b=`${b}.${S}`}r.push(new za(b,se.NumericLiteral));continue}if(l1(w)){const b=u(l1);r.push(new za(b,se.Identifier));continue}throw new SyntaxError(`Unexpected character: ${w}`)}return r}var or=class{constructor(){L(this,"type","Statement")}},oO=class extends or{constructor(n){super();L(this,"type","Program");this.body=n}},lO=class extends or{constructor(n,r,s){super();L(this,"type","If");this.test=n,this.body=r,this.alternate=s}},cO=class extends or{constructor(n,r,s,o){super();L(this,"type","For");this.loopvar=n,this.iterable=r,this.body=s,this.defaultBlock=o}},uO=class extends or{constructor(){super(...arguments);L(this,"type","Break")}},dO=class extends or{constructor(){super(...arguments);L(this,"type","Continue")}},fO=class extends or{constructor(n,r,s){super();L(this,"type","Set");this.assignee=n,this.value=r,this.body=s}},hO=class extends or{constructor(n,r,s){super();L(this,"type","Macro");this.name=n,this.args=r,this.body=s}},pO=class extends or{constructor(n){super();L(this,"type","Comment");this.value=n}},ma=class extends or{constructor(){super(...arguments);L(this,"type","Expression")}},mO=class extends ma{constructor(n,r,s){super();L(this,"type","MemberExpression");this.object=n,this.property=r,this.computed=s}},u1=class extends ma{constructor(n,r){super();L(this,"type","CallExpression");this.callee=n,this.args=r}},hl=class extends ma{constructor(n){super();L(this,"type","Identifier");this.value=n}},El=class extends ma{constructor(n){super();L(this,"type","Literal");this.value=n}},_O=class extends El{constructor(){super(...arguments);L(this,"type","IntegerLiteral")}},gO=class extends El{constructor(){super(...arguments);L(this,"type","FloatLiteral")}},d1=class extends El{constructor(){super(...arguments);L(this,"type","StringLiteral")}},vO=class extends El{constructor(){super(...arguments);L(this,"type","ArrayLiteral")}},f1=class extends El{constructor(){super(...arguments);L(this,"type","TupleLiteral")}},yO=class extends El{constructor(){super(...arguments);L(this,"type","ObjectLiteral")}},Eu=class extends ma{constructor(n,r,s){super();L(this,"type","BinaryExpression");this.operator=n,this.left=r,this.right=s}},wO=class extends ma{constructor(n,r){super();L(this,"type","FilterExpression");this.operand=n,this.filter=r}},bO=class extends or{constructor(n,r){super();L(this,"type","FilterStatement");this.filter=n,this.body=r}},MO=class extends ma{constructor(n,r){super();L(this,"type","SelectExpression");this.lhs=n,this.test=r}},xO=class extends ma{constructor(n,r,s){super();L(this,"type","TestExpression");this.operand=n,this.negate=r,this.test=s}},TO=class extends ma{constructor(n,r){super();L(this,"type","UnaryExpression");this.operator=n,this.argument=r}},SO=class extends ma{constructor(n=void 0,r=void 0,s=void 0){super();L(this,"type","SliceExpression");this.start=n,this.stop=r,this.step=s}},EO=class extends ma{constructor(n,r){super();L(this,"type","KeywordArgumentExpression");this.key=n,this.value=r}},AO=class extends ma{constructor(n){super();L(this,"type","SpreadExpression");this.argument=n}},CO=class extends or{constructor(n,r,s){super();L(this,"type","CallStatement");this.call=n,this.callerArgs=r,this.body=s}},kO=class extends ma{constructor(n,r,s){super();L(this,"type","Ternary");this.condition=n,this.trueExpr=r,this.falseExpr=s}};function OO(e){const n=new oO([]);let r=0;function s(I,R){const te=e[r++];if(!te||te.type!==I)throw new Error(`Parser Error: ${R}. ${te.type} !== ${I}.`);return te}function o(I){if(!h(I))throw new SyntaxError(`Expected ${I}`);++r}function c(){switch(e[r].type){case se.Comment:return new pO(e[r++].value);case se.Text:return p();case se.OpenStatement:return g();case se.OpenExpression:return y();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function u(...I){return r+I.length<=e.length&&I.every((R,te)=>R===e[r+te].type)}function d(...I){var R,te,F;return((R=e[r])==null?void 0:R.type)===se.OpenStatement&&((te=e[r+1])==null?void 0:te.type)===se.Identifier&&I.includes((F=e[r+1])==null?void 0:F.value)}function h(...I){return r+I.length<=e.length&&I.every((R,te)=>e[r+te].type==="Identifier"&&R===e[r+te].value)}function p(){return new d1(s(se.Text,"Expected text token").value)}function g(){if(s(se.OpenStatement,"Expected opening statement token"),e[r].type!==se.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const I=e[r].value;let R;switch(I){case"set":++r,R=w();break;case"if":++r,R=b(),s(se.OpenStatement,"Expected {% token"),o("endif"),s(se.CloseStatement,"Expected %} token");break;case"macro":++r,R=S(),s(se.OpenStatement,"Expected {% token"),o("endmacro"),s(se.CloseStatement,"Expected %} token");break;case"for":++r,R=O(),s(se.OpenStatement,"Expected {% token"),o("endfor"),s(se.CloseStatement,"Expected %} token");break;case"call":{++r;let te=null;u(se.OpenParen)&&(te=he());const F=W();if(F.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const H=he();s(se.CloseStatement,"Expected closing statement token");const ue=[];for(;!d("endcall");)ue.push(c());s(se.OpenStatement,"Expected '{%'"),o("endcall"),s(se.CloseStatement,"Expected closing statement token");const de=new u1(F,H);R=new CO(de,te,ue);break}case"break":++r,s(se.CloseStatement,"Expected closing statement token"),R=new uO;break;case"continue":++r,s(se.CloseStatement,"Expected closing statement token"),R=new dO;break;case"filter":{++r;let te=W();te instanceof hl&&u(se.OpenParen)&&(te=oe(te)),s(se.CloseStatement,"Expected closing statement token");const F=[];for(;!d("endfilter");)F.push(c());s(se.OpenStatement,"Expected '{%'"),o("endfilter"),s(se.CloseStatement,"Expected '%}'"),R=new bO(te,F);break}default:throw new SyntaxError(`Unknown statement type: ${I}`)}return R}function y(){s(se.OpenExpression,"Expected opening expression token");const I=z();return s(se.CloseExpression,"Expected closing expression token"),I}function w(){const I=E();let R=null;const te=[];if(u(se.Equals))++r,R=E();else{for(s(se.CloseStatement,"Expected %} token");!d("endset");)te.push(c());s(se.OpenStatement,"Expected {% token"),o("endset")}return s(se.CloseStatement,"Expected closing statement token"),new fO(I,R,te)}function b(){const I=z();s(se.CloseStatement,"Expected closing statement token");const R=[],te=[];for(;!d("elif","else","endif");)R.push(c());if(d("elif")){++r,++r;const F=b();te.push(F)}else if(d("else"))for(++r,++r,s(se.CloseStatement,"Expected closing statement token");!d("endif");)te.push(c());return new lO(I,R,te)}function S(){const I=W();if(I.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const R=he();s(se.CloseStatement,"Expected closing statement token");const te=[];for(;!d("endmacro");)te.push(c());return new hO(I,R,te)}function E(I=!1){const R=I?W:z,te=[R()],F=u(se.Comma);for(;F&&(++r,te.push(R()),!!u(se.Comma)););return F?new f1(te):te[0]}function O(){const I=E(!0);if(!(I instanceof hl||I instanceof f1))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${I.type} instead`);if(!h("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const R=z();s(se.CloseStatement,"Expected closing statement token");const te=[];for(;!d("endfor","else");)te.push(c());const F=[];if(d("else"))for(++r,++r,s(se.CloseStatement,"Expected closing statement token");!d("endfor");)F.push(c());return new cO(I,R,te,F)}function z(){return D()}function D(){const I=P();if(h("if")){++r;const R=P();if(h("else")){++r;const te=D();return new kO(R,I,te)}else return new MO(I,R)}return I}function P(){let I=j();for(;h("or");){const R=e[r];++r;const te=j();I=new Eu(R,I,te)}return I}function j(){let I=G();for(;h("and");){const R=e[r];++r;const te=G();I=new Eu(R,I,te)}return I}function G(){let I;for(;h("not");){const R=e[r];++r;const te=G();I=new TO(R,te)}return I??K()}function K(){let I=k();for(;;){let R;if(h("not","in"))R=new za("not in",se.Identifier),r+=2;else if(h("in"))R=e[r++];else if(u(se.ComparisonBinaryOperator))R=e[r++];else break;const te=k();I=new Eu(R,I,te)}return I}function k(){let I=ee();for(;u(se.AdditiveBinaryOperator);){const R=e[r];++r;const te=ee();I=new Eu(R,I,te)}return I}function ce(){const I=ne(W());return u(se.OpenParen)?oe(I):I}function oe(I){let R=new u1(I,he());return R=ne(R),u(se.OpenParen)&&(R=oe(R)),R}function he(){s(se.OpenParen,"Expected opening parenthesis for arguments list");const I=me();return s(se.CloseParen,"Expected closing parenthesis for arguments list"),I}function me(){const I=[];for(;!u(se.CloseParen);){let R;if(e[r].type===se.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const te=z();R=new AO(te)}else if(R=z(),u(se.Equals)){if(++r,!(R instanceof hl))throw new SyntaxError("Expected identifier for keyword argument");const te=z();R=new EO(R,te)}I.push(R),u(se.Comma)&&++r}return I}function pe(){const I=[];let R=!1;for(;!u(se.CloseSquareBracket);)u(se.Colon)?(I.push(void 0),++r,R=!0):(I.push(z()),u(se.Colon)&&(++r,R=!0));if(I.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(R){if(I.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new SO(...I)}return I[0]}function ne(I){for(;u(se.Dot)||u(se.OpenSquareBracket);){const R=e[r];++r;let te;const F=R.type===se.OpenSquareBracket;if(F)te=pe(),s(se.CloseSquareBracket,"Expected closing square bracket");else if(te=W(),te.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");I=new mO(I,te,F)}return I}function ee(){let I=Me();for(;u(se.MultiplicativeBinaryOperator);){const R=e[r++],te=Me();I=new Eu(R,I,te)}return I}function Me(){let I=V();for(;h("is");){++r;const R=h("not");R&&++r;const te=W();if(!(te instanceof hl))throw new SyntaxError("Expected identifier for the test");I=new xO(I,R,te)}return I}function V(){let I=ce();for(;u(se.Pipe);){++r;let R=W();if(!(R instanceof hl))throw new SyntaxError("Expected identifier for the filter");u(se.OpenParen)&&(R=oe(R)),I=new wO(I,R)}return I}function W(){const I=e[r++];switch(I.type){case se.NumericLiteral:{const R=I.value;return R.includes(".")?new gO(Number(R)):new _O(Number(R))}case se.StringLiteral:{let R=I.value;for(;u(se.StringLiteral);)R+=e[r++].value;return new d1(R)}case se.Identifier:return new hl(I.value);case se.OpenParen:{const R=E();return s(se.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),R}case se.OpenSquareBracket:{const R=[];for(;!u(se.CloseSquareBracket);)R.push(z()),u(se.Comma)&&++r;return++r,new vO(R)}case se.OpenCurlyBracket:{const R=new Map;for(;!u(se.CloseCurlyBracket);){const te=z();s(se.Colon,"Expected colon between key and value in object literal");const F=z();R.set(te,F),u(se.Comma)&&++r}return++r,new yO(R)}default:throw new SyntaxError(`Unexpected token: ${I.type}`)}}for(;r0)for(let o=e;on;o+=r)s.push(o);return s}function h1(e,n,r,s=1){const o=Math.sign(s);o>=0?(n=(n??(n=0))<0?Math.max(e.length+n,0):Math.min(n,e.length),r=(r??(r=e.length))<0?Math.max(e.length+r,0):Math.min(r,e.length)):(n=(n??(n=e.length-1))<0?Math.max(e.length+n,-1):Math.min(n,e.length-1),r=(r??(r=-1))<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const c=[];for(let u=n;o*un.toUpperCase())}function NO(e){return DO(new Date,e)}function DO(e,n){const r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),o=c=>c<10?"0"+c:c.toString();return n.replace(/%[YmdbBHM%]/g,c=>{switch(c){case"%Y":return e.getFullYear().toString();case"%m":return o(e.getMonth()+1);case"%d":return o(e.getDate());case"%b":return s.format(e);case"%B":return r.format(e);case"%H":return o(e.getHours());case"%M":return o(e.getMinutes());case"%%":return"%";default:return c}})}function FO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function BO(e,n,r,s){if(s===0)return e;let o=s==null||s<0?1/0:s;const c=n.length===0?new RegExp("(?=)","gu"):new RegExp(FO(n),"gu");return e.replaceAll(c,u=>o>0?(--o,r):u)}var p1=class extends Error{},m1=class extends Error{},Nr=class{constructor(e=void 0){L(this,"type","RuntimeValue");L(this,"value");L(this,"builtins",new Map);this.value=e}__bool__(){return new Be(!!this.value)}toString(){return String(this.value)}},Ve=class extends Nr{constructor(){super(...arguments);L(this,"type","IntegerValue")}},qt=class extends Nr{constructor(){super(...arguments);L(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Te=class extends Nr{constructor(){super(...arguments);L(this,"type","StringValue");L(this,"builtins",new Map([["upper",new Et(()=>new Te(this.value.toUpperCase()))],["lower",new Et(()=>new Te(this.value.toLowerCase()))],["strip",new Et(()=>new Te(this.value.trim()))],["title",new Et(()=>new Te(LO(this.value)))],["capitalize",new Et(()=>new Te(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new Ve(this.value.length)],["rstrip",new Et(()=>new Te(this.value.trimEnd()))],["lstrip",new Et(()=>new Te(this.value.trimStart()))],["startswith",new Et(n=>{if(n.length===0)throw new Error("startswith() requires at least one argument");const r=n[0];if(r instanceof Te)return new Be(this.value.startsWith(r.value));if(r instanceof tt){for(const s of r.value){if(!(s instanceof Te))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(s.value))return new Be(!0)}return new Be(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Et(n=>{if(n.length===0)throw new Error("endswith() requires at least one argument");const r=n[0];if(r instanceof Te)return new Be(this.value.endsWith(r.value));if(r instanceof tt){for(const s of r.value){if(!(s instanceof Te))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(s.value))return new Be(!0)}return new Be(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Et(n=>{const r=n[0]??new Lt;if(!(r instanceof Te||r instanceof Lt))throw new Error("sep argument must be a string or null");const s=n[1]??new Ve(-1);if(!(s instanceof Ve))throw new Error("maxsplit argument must be a number");let o=[];if(r instanceof Lt){const c=this.value.trimStart();for(const{0:u,index:d}of c.matchAll(/\S+/g)){if(s.value!==-1&&o.length>=s.value&&d!==void 0){o.push(u+c.slice(d+u.length));break}o.push(u)}}else{if(r.value==="")throw new Error("empty separator");o=this.value.split(r.value),s.value!==-1&&o.length>s.value&&o.push(o.splice(s.value).join(r.value))}return new tt(o.map(c=>new Te(c)))})],["replace",new Et(n=>{if(n.length<2)throw new Error("replace() requires at least two arguments");const r=n[0],s=n[1];if(!(r instanceof Te&&s instanceof Te))throw new Error("replace() arguments must be strings");let o;if(n.length>2?n[2].type==="KeywordArgumentsValue"?o=n[2].value.get("count")??new Lt:o=n[2]:o=new Lt,!(o instanceof Ve||o instanceof Lt))throw new Error("replace() count argument must be a number or null");return new Te(BO(this.value,r.value,s.value,o.value))})]]))}},Be=class extends Nr{constructor(){super(...arguments);L(this,"type","BooleanValue")}},PO=/[\x7f-\uffff]/g;function _1(e){return e.replace(PO,n=>"\\u"+n.charCodeAt(0).toString(16).padStart(4,"0"))}function Qi(e,n={},r=0,s=!0){const{indent:o=null,ensureAscii:c=!1,separators:u=null,sortKeys:d=!1}=n;let h,p;switch(u?[h,p]=u:o?(h=",",p=": "):(h=", ",p=": "),e.type){case"NullValue":return"null";case"UndefinedValue":return s?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(e.value);case"StringValue":{let g=JSON.stringify(e.value);return c&&(g=_1(g)),g}case"ArrayValue":case"ObjectValue":{const g=o?" ".repeat(o):"",y=` +`+g.repeat(r),w=y+g;if(e.type==="ArrayValue"){const b=e.value.map(S=>Qi(S,n,r+1,s));return o?`[${w}${b.join(`${h}${w}`)}${y}]`:`[${b.join(h)}]`}else{let b=Array.from(e.value.entries());d&&(b=b.sort(([E],[O])=>E.localeCompare(O)));const S=b.map(([E,O])=>{let z=JSON.stringify(E);c&&(z=_1(z));const D=`${z}${p}${Qi(O,n,r+1,s)}`;return o?`${w}${D}`:D});return o?`{${S.join(h)}${y}}`:`{${S.join(h)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var Cn=class extends Nr{constructor(){super(...arguments);L(this,"type","ObjectValue");L(this,"builtins",new Map([["get",new Et(([n,r])=>{if(!(n instanceof Te))throw new Error(`Object key must be a string: got ${n.type}`);return this.value.get(n.value)??r??new Lt})],["items",new Et(()=>this.items())],["keys",new Et(()=>this.keys())],["values",new Et(()=>this.values())],["dictsort",new Et(n=>{let r=new Map;const s=n.filter(h=>h instanceof Bu?(r=h.value,!1):!0),o=s.at(0)??r.get("case_sensitive")??new Be(!1);if(!(o instanceof Be))throw new Error("case_sensitive must be a boolean");const c=s.at(1)??r.get("by")??new Te("key");if(!(c instanceof Te))throw new Error("by must be a string");if(!["key","value"].includes(c.value))throw new Error("by must be either 'key' or 'value'");const u=s.at(2)??r.get("reverse")??new Be(!1);if(!(u instanceof Be))throw new Error("reverse must be a boolean");const d=Array.from(this.value.entries()).map(([h,p])=>new tt([new Te(h),p])).sort((h,p)=>{const g=c.value==="key"?0:1,y=h.value[g],w=p.value[g],b=dg(y,w,o.value);return u.value?-b:b});return new tt(d)})]]))}__bool__(){return new Be(this.value.size>0)}items(){return new tt(Array.from(this.value.entries()).map(([n,r])=>new tt([new Te(n),r])))}keys(){return new tt(Array.from(this.value.keys()).map(n=>new Te(n)))}values(){return new tt(Array.from(this.value.values()))}toString(){return Qi(this,{},0,!1)}},Bu=class extends Cn{constructor(){super(...arguments);L(this,"type","KeywordArgumentsValue")}},tt=class extends Nr{constructor(){super(...arguments);L(this,"type","ArrayValue");L(this,"builtins",new Map([["length",new Ve(this.value.length)]]))}__bool__(){return new Be(this.value.length>0)}toString(){return Qi(this,{},0,!1)}},g1=class extends tt{constructor(){super(...arguments);L(this,"type","TupleValue")}},Et=class extends Nr{constructor(){super(...arguments);L(this,"type","FunctionValue")}},Lt=class extends Nr{constructor(){super(...arguments);L(this,"type","NullValue")}},St=class extends Nr{constructor(){super(...arguments);L(this,"type","UndefinedValue")}},Vi=class{constructor(e){L(this,"variables",new Map([["namespace",new Et(e=>{if(e.length===0)return new Cn(new Map);if(e.length!==1||!(e[0]instanceof Cn))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]));L(this,"tests",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Et],["odd",e=>{if(!(e instanceof Ve))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof Ve))throw new Error(`cannot even on ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["none",e=>e.type==="NullValue"],["string",e=>e.type==="StringValue"],["number",e=>e instanceof Ve||e instanceof qt],["integer",e=>e instanceof Ve],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e.type==="ObjectValue"],["lower",e=>{const n=e.value;return e.type==="StringValue"&&n===n.toLowerCase()}],["upper",e=>{const n=e.value;return e.type==="StringValue"&&n===n.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,n)=>e.value===n.value],["eq",(e,n)=>e.value===n.value]]));this.parent=e}set(e,n){return this.declareVariable(e,ih(n))}declareVariable(e,n){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,n),n}setVariable(e,n){return this.variables.set(e,n),n}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new St}catch{return new St}}};function RO(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",n=>{throw new Error(n)}),e.set("range",zO),e.set("strftime_now",NO),e.set("True",!0),e.set("False",!1),e.set("None",null)}function v1(e,n){const r=n.split(".");let s=e;for(const o of r)if(s instanceof Cn)s=s.value.get(o)??new St;else if(s instanceof tt){const c=parseInt(o,10);if(!isNaN(c)&&c>=0&&cc instanceof Ve||c instanceof qt||c instanceof Be,o=c=>c instanceof Be?c.value?1:0:c.value;if(s(e)&&s(n)){const c=o(e),u=o(n);return cu?1:0}if(e.type!==n.type)throw new Error(`Cannot compare different types: ${e.type} and ${n.type}`);switch(e.type){case"StringValue":{let c=e.value,u=n.value;return r||(c=c.toLowerCase(),u=u.toLowerCase()),cu?1:0}default:throw new Error(`Cannot compare type: ${e.type}`)}}var UO=class{constructor(e){L(this,"global");this.global=e??new Vi}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,n){const r=this.evaluate(e.left,n);switch(e.operator.value){case"and":return r.__bool__().value?this.evaluate(e.right,n):r;case"or":return r.__bool__().value?r:this.evaluate(e.right,n)}const s=this.evaluate(e.right,n);switch(e.operator.value){case"==":return new Be(r.value==s.value);case"!=":return new Be(r.value!=s.value)}if(r instanceof St||s instanceof St){if(s instanceof St&&["in","not in"].includes(e.operator.value))return new Be(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof Lt||s instanceof Lt)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new Te(r.value.toString()+s.value.toString());if((r instanceof Ve||r instanceof qt)&&(s instanceof Ve||s instanceof qt)){const o=r.value,c=s.value;switch(e.operator.value){case"+":case"-":case"*":{const u=e.operator.value==="+"?o+c:e.operator.value==="-"?o-c:o*c;return r instanceof qt||s instanceof qt?new qt(u):new Ve(u)}case"/":return new qt(o/c);case"%":{const u=o%c;return r instanceof qt||s instanceof qt?new qt(u):new Ve(u)}case"<":return new Be(o":return new Be(o>c);case">=":return new Be(o>=c);case"<=":return new Be(o<=c)}}else if(r instanceof tt&&s instanceof tt)switch(e.operator.value){case"+":return new tt(r.value.concat(s.value))}else if(s instanceof tt){const o=s.value.find(c=>c.value===r.value)!==void 0;switch(e.operator.value){case"in":return new Be(o);case"not in":return new Be(!o)}}}if(r instanceof Te||s instanceof Te)switch(e.operator.value){case"+":return new Te(r.value.toString()+s.value.toString())}if(r instanceof Te&&s instanceof Te)switch(e.operator.value){case"in":return new Be(s.value.includes(r.value));case"not in":return new Be(!s.value.includes(r.value))}if(r instanceof Te&&s instanceof Cn)switch(e.operator.value){case"in":return new Be(s.value.has(r.value));case"not in":return new Be(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(e,n){const r=[],s=new Map;for(const o of e)if(o.type==="SpreadExpression"){const c=o,u=this.evaluate(c.argument,n);if(!(u instanceof tt))throw new Error(`Cannot unpack non-iterable type: ${u.type}`);for(const d of u.value)r.push(d)}else if(o.type==="KeywordArgumentExpression"){const c=o;s.set(c.key.value,this.evaluate(c.value,n))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(o,n))}return[r,s]}applyFilter(e,n,r){if(n.type==="Identifier"){const s=n;if(s.value==="tojson")return new Te(Qi(e,{}));if(e instanceof tt)switch(s.value){case"list":return e;case"first":return e.value[0];case"last":return e.value[e.value.length-1];case"length":return new Ve(e.value.length);case"reverse":return new tt(e.value.slice().reverse());case"sort":return new tt(e.value.slice().sort((o,c)=>dg(o,c,!1)));case"join":return new Te(e.value.map(o=>o.value).join(""));case"string":return new Te(Qi(e,{},0,!1));case"unique":{const o=new Set,c=[];for(const u of e.value)o.has(u.value)||(o.add(u.value),c.push(u));return new tt(c)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(e instanceof Te)switch(s.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const o=e.builtins.get(s.value);if(o instanceof Et)return o.value([],r);if(o instanceof Ve)return o;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new Te(e.value.trim());case"indent":return new Te(e.value.split(` +`).map((o,c)=>c===0||o.length===0?o:" "+o).join(` +`));case"join":case"string":return e;case"int":{const o=parseInt(e.value,10);return new Ve(isNaN(o)?0:o)}case"float":{const o=parseFloat(e.value);return new qt(isNaN(o)?0:o)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(e instanceof Ve||e instanceof qt)switch(s.value){case"abs":return e instanceof Ve?new Ve(Math.abs(e.value)):new qt(Math.abs(e.value));case"int":return new Ve(Math.floor(e.value));case"float":return new qt(e.value);default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(e instanceof Cn)switch(s.value){case"items":return new tt(Array.from(e.value.entries()).map(([o,c])=>new tt([new Te(o),c])));case"length":return new Ve(e.value.size);default:{const o=e.builtins.get(s.value);if(o)return o instanceof Et?o.value([],r):o;throw new Error(`Unknown ObjectValue filter: ${s.value}`)}}else if(e instanceof Be)switch(s.value){case"bool":return new Be(e.value);case"int":return new Ve(e.value?1:0);case"float":return new qt(e.value?1:0);case"string":return new Te(e.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${s.value}`)}throw new Error(`Cannot apply filter "${s.value}" to type: ${e.type}`)}else if(n.type==="CallExpression"){const s=n;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);const o=s.callee.value;if(o==="tojson"){const[,c]=this.evaluateArguments(s.args,r),u=c.get("indent")??new Lt;if(!(u instanceof Ve||u instanceof Lt))throw new Error("If set, indent must be a number");const d=c.get("ensure_ascii")??new Be(!1);if(!(d instanceof Be))throw new Error("If set, ensure_ascii must be a boolean");const h=c.get("sort_keys")??new Be(!1);if(!(h instanceof Be))throw new Error("If set, sort_keys must be a boolean");const p=c.get("separators")??new Lt;let g=null;if(p instanceof tt||p instanceof g1){if(p.value.length!==2)throw new Error("separators must be a tuple of two strings");const[y,w]=p.value;if(!(y instanceof Te)||!(w instanceof Te))throw new Error("separators must be a tuple of two strings");g=[y.value,w.value]}else if(!(p instanceof Lt))throw new Error("If set, separators must be a tuple of two strings");return new Te(Qi(e,{indent:u.value,ensureAscii:d.value,sortKeys:h.value,separators:g}))}else if(o==="join"){let c;if(e instanceof Te)c=Array.from(e.value);else if(e instanceof tt)c=e.value.map(p=>p.value);else throw new Error(`Cannot apply filter "${o}" to type: ${e.type}`);const[u,d]=this.evaluateArguments(s.args,r),h=u.at(0)??d.get("separator")??new Te("");if(!(h instanceof Te))throw new Error("separator must be a string");return new Te(c.join(h.value))}else if(o==="int"||o==="float"){const[c,u]=this.evaluateArguments(s.args,r),d=c.at(0)??u.get("default")??(o==="int"?new Ve(0):new qt(0));if(e instanceof Te){const h=o==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(h)?d:o==="int"?new Ve(h):new qt(h)}else{if(e instanceof Ve||e instanceof qt)return e;if(e instanceof Be)return o==="int"?new Ve(e.value?1:0):new qt(e.value?1:0);throw new Error(`Cannot apply filter "${o}" to type: ${e.type}`)}}else if(o==="default"){const[c,u]=this.evaluateArguments(s.args,r),d=c[0]??new Te(""),h=c[1]??u.get("boolean")??new Be(!1);if(!(h instanceof Be))throw new Error("`default` filter flag must be a boolean");return e instanceof St||h.value&&!e.__bool__().value?d:e}if(e instanceof tt){switch(o){case"sort":{const[c,u]=this.evaluateArguments(s.args,r),d=c.at(0)??u.get("reverse")??new Be(!1);if(!(d instanceof Be))throw new Error("reverse must be a boolean");const h=c.at(1)??u.get("case_sensitive")??new Be(!1);if(!(h instanceof Be))throw new Error("case_sensitive must be a boolean");const p=c.at(2)??u.get("attribute")??new Lt;if(!(p instanceof Te||p instanceof Ve||p instanceof Lt))throw new Error("attribute must be a string, integer, or null");const g=y=>{if(p instanceof Lt)return y;const w=p instanceof Ve?String(p.value):p.value;return v1(y,w)};return new tt(e.value.slice().sort((y,w)=>{const b=g(y),S=g(w),E=dg(b,S,h.value);return d.value?-E:E}))}case"selectattr":case"rejectattr":{const c=o==="selectattr";if(e.value.some(y=>!(y instanceof Cn)))throw new Error(`\`${o}\` can only be applied to array of objects`);if(s.args.some(y=>y.type!=="StringLiteral"))throw new Error(`arguments of \`${o}\` must be strings`);const[u,d,h]=s.args.map(y=>this.evaluate(y,r));let p;if(d){const y=r.tests.get(d.value);if(!y)throw new Error(`Unknown test: ${d.value}`);p=y}else p=(...y)=>y[0].__bool__().value;const g=e.value.filter(y=>{const w=y.value.get(u.value),b=w?p(w,h):!1;return c?b:!b});return new tt(g)}case"map":{const[,c]=this.evaluateArguments(s.args,r);if(c.has("attribute")){const u=c.get("attribute");if(!(u instanceof Te))throw new Error("attribute must be a string");const d=c.get("default"),h=e.value.map(p=>{if(!(p instanceof Cn))throw new Error("items in map must be an object");const g=v1(p,u.value);return g instanceof St?d??new St:g});return new tt(h)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${o}`)}else if(e instanceof Te){switch(o){case"indent":{const[c,u]=this.evaluateArguments(s.args,r),d=c.at(0)??u.get("width")??new Ve(4);if(!(d instanceof Ve))throw new Error("width must be a number");const h=c.at(1)??u.get("first")??new Be(!1),p=c.at(2)??u.get("blank")??new Be(!1),g=e.value.split(` +`),y=" ".repeat(d.value),w=g.map((b,S)=>!h.value&&S===0||!p.value&&b.length===0?b:y+b);return new Te(w.join(` +`))}case"replace":{const c=e.builtins.get("replace");if(!(c instanceof Et))throw new Error("replace filter not available");const[u,d]=this.evaluateArguments(s.args,r);return c.value([...u,new Bu(d)],r)}}throw new Error(`Unknown StringValue filter: ${o}`)}else if(e instanceof Cn){const c=e.builtins.get(o);if(c&&c instanceof Et){const[u,d]=this.evaluateArguments(s.args,r);return d.size>0&&u.push(new Bu(d)),c.value(u,r)}throw new Error(`Unknown ObjectValue filter: ${o}`)}else throw new Error(`Cannot apply filter "${o}" to type: ${e.type}`)}throw new Error(`Unknown filter: ${n.type}`)}evaluateFilterExpression(e,n){const r=this.evaluate(e.operand,n);return this.applyFilter(r,e.filter,n)}evaluateTestExpression(e,n){const r=this.evaluate(e.operand,n),s=n.tests.get(e.test.value);if(!s)throw new Error(`Unknown test: ${e.test.value}`);const o=s(r);return new Be(e.negate?!o:o)}evaluateSelectExpression(e,n){return this.evaluate(e.test,n).__bool__().value?this.evaluate(e.lhs,n):new St}evaluateUnaryExpression(e,n){const r=this.evaluate(e.argument,n);switch(e.operator.value){case"not":return new Be(!r.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,n){return this.evaluate(e.condition,n).__bool__().value?this.evaluate(e.trueExpr,n):this.evaluate(e.falseExpr,n)}evalProgram(e,n){return this.evaluateBlock(e.body,n)}evaluateBlock(e,n){let r="";for(const s of e){const o=this.evaluate(s,n);o.type!=="NullValue"&&o.type!=="UndefinedValue"&&(r+=o.toString())}return new Te(r)}evaluateIdentifier(e,n){return n.lookupVariable(e.value)}evaluateCallExpression(e,n){const[r,s]=this.evaluateArguments(e.args,n);s.size>0&&r.push(new Bu(s));const o=this.evaluate(e.callee,n);if(o.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${o.type}`);return o.value(r,n)}evaluateSliceExpression(e,n,r){if(!(e instanceof tt||e instanceof Te))throw new Error("Slice object must be an array or string");const s=this.evaluate(n.start,r),o=this.evaluate(n.stop,r),c=this.evaluate(n.step,r);if(!(s instanceof Ve||s instanceof St))throw new Error("Slice start must be numeric or undefined");if(!(o instanceof Ve||o instanceof St))throw new Error("Slice stop must be numeric or undefined");if(!(c instanceof Ve||c instanceof St))throw new Error("Slice step must be numeric or undefined");return e instanceof tt?new tt(h1(e.value,s.value,o.value,c.value)):new Te(h1(Array.from(e.value),s.value,o.value,c.value).join(""))}evaluateMemberExpression(e,n){const r=this.evaluate(e.object,n);let s;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,n);s=this.evaluate(e.property,n)}else s=new Te(e.property.value);let o;if(r instanceof Cn){if(!(s instanceof Te))throw new Error(`Cannot access property with non-string: got ${s.type}`);o=r.value.get(s.value)??r.builtins.get(s.value)}else if(r instanceof tt||r instanceof Te)if(s instanceof Ve)o=r.value.at(s.value),r instanceof Te&&(o=new Te(r.value.at(s.value)));else if(s instanceof Te)o=r.builtins.get(s.value);else throw new Error(`Cannot access property with non-string/non-number: got ${s.type}`);else{if(!(s instanceof Te))throw new Error(`Cannot access property with non-string: got ${s.type}`);o=r.builtins.get(s.value)}return o instanceof Nr?o:new St}evaluateSet(e,n){const r=e.value?this.evaluate(e.value,n):this.evaluateBlock(e.body,n);if(e.assignee.type==="Identifier"){const s=e.assignee.value;n.setVariable(s,r)}else if(e.assignee.type==="TupleLiteral"){const s=e.assignee;if(!(r instanceof tt))throw new Error(`Cannot unpack non-iterable type in set: ${r.type}`);const o=r.value;if(o.length!==s.value.length)throw new Error(`Too ${s.value.length>o.length?"few":"many"} items to unpack in set`);for(let c=0;cb.setVariable(e.loopvar.value,y);else if(e.loopvar.type==="TupleLiteral"){const b=e.loopvar;if(y.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${y.type}`);const S=y;if(b.value.length!==S.value.length)throw new Error(`Too ${b.value.length>S.value.length?"few":"many"} items to unpack`);w=E=>{for(let O=0;O0?c[p-1]:new St],["nextitem",p{var u;const o=new Vi(s);r=r.slice();let c;((u=r.at(-1))==null?void 0:u.type)==="KeywordArgumentsValue"&&(c=r.pop());for(let d=0;d{const p=new Vi(h);if(e.callerArgs)for(let g=0;gthis.evaluate(r,n)));case"TupleLiteral":return new g1(e.value.map(r=>this.evaluate(r,n)));case"ObjectLiteral":{const r=new Map;for(const[s,o]of e.value){const c=this.evaluate(s,n);if(!(c instanceof Te))throw new Error(`Object keys must be strings: got ${c.type}`);r.set(c.value,this.evaluate(o,n))}return new Cn(r)}case"Identifier":return this.evaluateIdentifier(e,n);case"CallExpression":return this.evaluateCallExpression(e,n);case"MemberExpression":return this.evaluateMemberExpression(e,n);case"UnaryExpression":return this.evaluateUnaryExpression(e,n);case"BinaryExpression":return this.evaluateBinaryExpression(e,n);case"FilterExpression":return this.evaluateFilterExpression(e,n);case"FilterStatement":return this.evaluateFilterStatement(e,n);case"TestExpression":return this.evaluateTestExpression(e,n);case"SelectExpression":return this.evaluateSelectExpression(e,n);case"Ternary":return this.evaluateTernaryExpression(e,n);case"Comment":return new Lt;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function ih(e){switch(typeof e){case"number":return Number.isInteger(e)?new Ve(e):new qt(e);case"string":return new Te(e);case"boolean":return new Be(e);case"undefined":return new St;case"object":return e===null?new Lt:Array.isArray(e)?new tt(e.map(ih)):new Cn(new Map(Object.entries(e).map(([n,r])=>[n,ih(r)])));case"function":return new Et((n,r)=>{const s=e(...n.map(o=>o.value))??null;return ih(s)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var an=` +`,IO="{%- ",GO=" -%}";function jO(e){switch(e.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return e.operator.value==="and"?1:e.operator.value==="in"||e.operator.value==="not in"?2:0}return 0}function VO(e,n=" "){const r=typeof n=="number"?" ".repeat(n):n;return ar(e.body,0,r).replace(/\n$/,"")}function wn(...e){return IO+e.join(" ")+GO}function ar(e,n,r){return e.map(s=>qO(s,n,r)).join(an)}function qO(e,n,r){const s=r.repeat(n);switch(e.type){case"Program":return ar(e.body,n,r);case"If":return $O(e,n,r);case"For":return HO(e,n,r);case"Set":return YO(e,n,r);case"Macro":return XO(e,n,r);case"Break":return s+wn("break");case"Continue":return s+wn("continue");case"CallStatement":return QO(e,n,r);case"FilterStatement":return WO(e,n,r);case"Comment":return s+"{# "+e.value+" #}";default:return s+"{{- "+nt(e)+" -}}"}}function $O(e,n,r){const s=r.repeat(n),o=[];let c=e;for(;c&&(o.push({test:c.test,body:c.body}),c.alternate.length===1&&c.alternate[0].type==="If");)c=c.alternate[0];let u=s+wn("if",nt(o[0].test))+an+ar(o[0].body,n+1,r);for(let d=1;d0&&(u+=an+s+wn("else")+an+ar(c.alternate,n+1,r)),u+=an+s+wn("endif"),u}function HO(e,n,r){const s=r.repeat(n);let o="";if(e.iterable.type==="SelectExpression"){const u=e.iterable;o=`${nt(u.lhs)} if ${nt(u.test)}`}else o=nt(e.iterable);let c=s+wn("for",nt(e.loopvar),"in",o)+an+ar(e.body,n+1,r);return e.defaultBlock.length>0&&(c+=an+s+wn("else")+an+ar(e.defaultBlock,n+1,r)),c+=an+s+wn("endfor"),c}function YO(e,n,r){const s=r.repeat(n),o=nt(e.assignee),c=e.value?nt(e.value):"",u=s+wn("set",`${o}${e.value?" = "+c:""}`);return e.body.length===0?u:u+an+ar(e.body,n+1,r)+an+s+wn("endset")}function XO(e,n,r){const s=r.repeat(n),o=e.args.map(nt).join(", ");return s+wn("macro",`${e.name.value}(${o})`)+an+ar(e.body,n+1,r)+an+s+wn("endmacro")}function QO(e,n,r){const s=r.repeat(n),o=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(nt).join(", ")})`:"",c=nt(e.call);let u=s+wn(`call${o}`,c)+an;return u+=ar(e.body,n+1,r)+an,u+=s+wn("endcall"),u}function WO(e,n,r){const s=r.repeat(n),o=e.filter.type==="Identifier"?e.filter.value:nt(e.filter);let c=s+wn("filter",o)+an;return c+=ar(e.body,n+1,r)+an,c+=s+wn("endfilter"),c}function nt(e,n=-1){switch(e.type){case"SpreadExpression":return`*${nt(e.argument)}`;case"Identifier":return e.value;case"IntegerLiteral":return`${e.value}`;case"FloatLiteral":return`${e.value}`;case"StringLiteral":return JSON.stringify(e.value);case"BinaryExpression":{const r=e,s=jO(r),o=nt(r.left,s),c=nt(r.right,s+1),u=`${o} ${r.operator.value} ${c}`;return s`${nt(s)}: ${nt(o)}`).join(", ")}}`;case"SliceExpression":{const r=e,s=r.start?nt(r.start):"",o=r.stop?nt(r.stop):"",c=r.step?`:${nt(r.step)}`:"";return`${s}:${o}${c}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${nt(r.value)}`}case"Ternary":{const r=e,s=`${nt(r.trueExpr)} if ${nt(r.condition,0)} else ${nt(r.falseExpr)}`;return n>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${e.type}`)}}var ZO=class{constructor(e){L(this,"parsed");const n=iO(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=OO(n)}render(e){const n=new Vi;if(RO(n),e)for(const[o,c]of Object.entries(e))n.set(o,c);return new UO(n).run(this.parsed).value}format(e){return VO(this.parsed,(e==null?void 0:e.indent)||" ")}},Ba=class{constructor(){let e=function(...n){return e._call(...n)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function Xi(e,n){e&&e(n)}function KO(e){return Number.isInteger(e)||typeof e=="bigint"}function y1(e){return e==null||e===-1}function w1(e){const n=[];let r=e;for(;Array.isArray(r);)n.push(r.length),r=r[0];return n}function zr(...e){return Array.prototype.concat.apply([],e)}function JO(...e){return e.reduce((n,r)=>n.flatMap(s=>r.map(o=>[s,o])))}function mh(e,n){return Math.abs((e+n)%(2*n)-n)}function Kn(e,n){return Object.assign({},...n.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function e3(e,n){let r=0;for(const s of e)s===n&&++r;return r}var t3={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"},_h=class sx{constructor(n){if(this.filePath=n,this.headers=new Headers,this.exists=er.existsSync(n),this.exists){this.status=200,this.statusText="OK";let r=er.statSync(n);this.headers.set("content-length",r.size.toString()),this.updateContentType();const s=er.createReadStream(n);this.body=new ReadableStream({start(o){s.on("data",c=>o.enqueue(c)),s.on("end",()=>o.close()),s.on("error",c=>o.error(c))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const n=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",t3[n]??"application/octet-stream")}clone(){let n=new sx(this.filePath);return n.exists=this.exists,n.status=this.status,n.statusText=this.statusText,n.headers=new Headers(this.headers),n}async arrayBuffer(){return(await er.promises.readFile(this.filePath)).buffer}async blob(){const n=await er.promises.readFile(this.filePath);return new Blob([n],{type:this.headers.get("content-type")})}async text(){return await er.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},ix=class{constructor(e){this.path=e}async match(e){let n=fs.join(this.path,e),r=new _h(n);if(r.exists)return r}async put(e,n,r=void 0){let s=fs.join(this.path,e);try{const o=n.headers.get("Content-Length"),c=parseInt(o??"0");let u=0;await er.promises.mkdir(fs.dirname(s),{recursive:!0});const d=er.createWriteStream(s),h=n.body.getReader();for(;;){const{done:p,value:g}=await h.read();if(p)break;await new Promise((w,b)=>{d.write(g,S=>{if(S){b(S);return}w()})}),u+=g.length;const y=c?u/c*100:0;r==null||r({progress:y,loaded:u,total:c})}d.close()}catch(o){try{await er.promises.unlink(s)}catch{}throw o}}},n3={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"},b1=100,a3=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function Pf(...e){return e=e.map((n,r)=>(r&&(n=n.replace(new RegExp("^/"),"")),r!==e.length-1&&(n=n.replace(new RegExp("/$"),"")),n)),e.join("/")}function gh(e,n=null,r=null){let s;try{s=new URL(e)}catch{return!1}return!(n&&!n.includes(s.protocol)||r&&!r.includes(s.hostname))}function r3(e){return!(!a3.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function s3(e,n,r){if(!r)return null;const s=n3[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${s}: "${n}".`)}async function i3(e,n){const r=e.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"),o=new Uint8Array(s),c=0;const u=e.body.getReader();async function d(){const{done:h,value:p}=await u.read();if(h)return;const g=c+p.length;if(g>s){s=g;const w=new Uint8Array(s);w.set(o),o=w}o.set(p,c),c=g;const y=c/s*100;return n({progress:y,loaded:c,total:s}),d()}return await d(),o}async function ox(e=null){let n=null;if(!n&&pa.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{n=await caches.open(pa.cacheKey)}catch(r){console.warn("An error occurred while opening the browser cache:",r)}}if(!n&&pa.useFSCache){if(!Nt.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");n=new ix(e??pa.cacheDir)}return n}async function o3(e,...n){for(let r of n)try{let s=await e.match(r);if(s)return s}catch{continue}}async function vh(e){var n;if(pa.useFS&&!gh(e,["http:","https:","blob:"]))return new _h(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e);if(typeof process<"u"&&((n=process==null?void 0:process.release)==null?void 0:n.name)==="node"){const r=!!(us!=null&&us.TESTING_REMOTELY),s=pa.version,o=new Headers;if(o.set("User-Agent",`transformers.js/${s}; is_ci/${r};`),gh(e,["http:","https:"],["huggingface.co","hf.co"])){const u=(us==null?void 0:us.HF_TOKEN)??(us==null?void 0:us.HF_ACCESS_TOKEN);u&&o.set("Authorization",`Bearer ${u}`)}return fetch(e,{headers:o})}else return fetch(e)}function l3(e,n,r={},s=null){const o=r.revision??"main",c=Pf(e,n),u=r3(e),d=u?Pf(pa.localModelPath,c):c,h=Pf(pa.remoteHost,pa.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(o)),n),p=s instanceof ix?o==="main"?c:Pf(e,o,n):h;return{requestURL:c,localPath:d,remoteURL:h,proposedCacheKey:p,validModelId:u}}async function c3(e,n,r){if(e)return await o3(e,n,r)}async function u3(e,n,r,s,o,c,u={}){if(await r.match(s)===void 0)if(c)typeof o!="string"&&await r.put(s,new Response(c,{headers:o.headers})).catch(d=>{console.warn(`Unable to add response to browser cache: ${d}.`)});else{const d=u.progress_callback?h=>Xi(u.progress_callback,{status:"progress",name:e,file:n,...h}):void 0;await r.put(s,o,d)}}async function d3(e,n,r=!0,s={},o=!1,c=null){const{requestURL:u,localPath:d,remoteURL:h,proposedCacheKey:p,validModelId:g}=l3(e,n,s,c);let y,w=!1,b;b=await c3(c,d,p);const S=b!==void 0;if(!S){if(pa.allowLocalModels)if(gh(u,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${u}.`)}else try{b=await vh(d),y=d}catch(D){console.warn(`Unable to load from local path "${d}": "${D}"`)}if(b===void 0||typeof b!="string"&&b.status===404){if(s.local_files_only){if(r)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${d}".`);return null}if(!g)throw Error(`Local file missing at "${d}" and download aborted due to invalid model ID "${e}".`);if(b=await vh(h),b.status!==200)return s3(b.status,h,r);y=p}w=c&&typeof Response<"u"&&b instanceof Response&&b.status===200}Xi(s.progress_callback,{status:"download",name:e,file:n});let E;if(!(Nt.IS_NODE_ENV&&o)){let z;typeof b!="string"&&(s.progress_callback?S&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(z=new Uint8Array(await b.arrayBuffer()),Xi(s.progress_callback,{status:"progress",name:e,file:n,progress:100,loaded:z.length,total:z.length})):z=await i3(b,D=>{Xi(s.progress_callback,{status:"progress",name:e,file:n,...D})}):z=new Uint8Array(await b.arrayBuffer())),E=z}if(w&&y&&typeof b!="string"&&await u3(e,n,c,y,b,E,s),Xi(s.progress_callback,{status:"done",name:e,file:n}),E){if(!Nt.IS_NODE_ENV&&o)throw new Error("Cannot return path in a browser environment.");return E}if(b instanceof _h)return b.filePath;const O=await(c==null?void 0:c.match(y));if(O instanceof _h)return O.filePath;if(O instanceof Response)return new Uint8Array(await O.arrayBuffer());if(typeof O=="string")return O;throw new Error("Unable to get model file path or buffer.")}async function yh(e,n,r=!0,s={},o=!1){if(!pa.allowLocalModels&&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`).");Xi(s.progress_callback,{status:"initiate",name:e,file:n});const c=await ox(s==null?void 0:s.cache_dir);return await d3(e,n,r,s,o,c)}async function lx(e,n,r=!0,s={}){const o=await yh(e,n,r,s,!1);return o===null?null:new TextDecoder("utf-8").decode(o)}async function Lr(e,n,r=!0,s={}){const o=await lx(e,n,r,s);return o===null?{}:JSON.parse(o)}function f3(e,[n,r,s],[o,c],u="bilinear",d=!1){const h=c/s,p=o/r,g=new e.constructor(o*c*n),y=r*s,w=o*c;for(let b=0;b=0;--d)o[d]=h,s[d]=n[r[d]],h*=s[d];const c=r.map((d,h)=>o[r.indexOf(h)]),u=new e.constructor(e.length);for(let d=0;d=0;--p)h+=g%n[p]*c[p],g=Math.floor(g/n[p]);u[h]=e[d]}return[u,s]}function bn(e){const n=Qt(e)[0],r=e.map(c=>Math.exp(c-n)),s=r.reduce((c,u)=>c+u,0);return r.map(c=>c/s)}function p3(e){const n=Qt(e)[0];let r=0;for(let c=0;cc-n-s)}function fg(e){if(e.length===0)throw Error("Array must not be empty");let n=e[0],r=0;for(let s=1;sn&&(n=e[s],r=s);return[n,r]}function cx(e){return e>0&&(e&e-1)===0}var ux=class{constructor(e){if(this.size=e|0,this.size<=1||!cx(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 r=0;rr;r<<=1)++n;this._width=n%2===0?n-1:n,this._bitrev=new Int32Array(1<>>s&3)<>>1);for(let s=0;s>>1]=e[s];return r}toComplexArray(e,n){const r=n||this.createComplexArray();for(let s=0;s>>1],r[s+1]=0;return r}transform(e,n){if(e===n)throw new Error("Input and output buffers must be different");this._transform4(e,n,1)}realTransform(e,n){if(e===n)throw new Error("Input and output buffers must be different");this._realTransform4(e,n,1)}inverseTransform(e,n){if(e===n)throw new Error("Input and output buffers must be different");this._transform4(e,n,-1);for(let r=0;r>=2;c>=2;c>>=2){u=s/c<<1;const y=u>>>2;for(d=0;d>>1,c>>>1)}else for(d=0,h=0;d>>1,c>>>1,r)}const g=this.table;for(c>>=2;c>=2;c>>=2){u=s/c<<1;const w=u>>>1,b=w>>>1,S=b>>>1;for(d=0;d>>1;for(let w=2;w>1;++p){const g=(p+1-e)**2/2,y=Math.sqrt(d**2+h**2)**g,w=g*Math.atan2(h,d),b=2*p;o[b]=y*Math.cos(w),o[b+1]=y*Math.sin(w),c[b]=o[b],c[b+1]=-o[b+1]}this._slicedChirpBuffer=o.subarray(n,r),this._f=new ux(s>>1),this._f.transform(this._chirpBuffer,c)}_transform(e,n,r){const s=this._buffer1,o=this._buffer2,c=this._outBuffer1,u=this._outBuffer2,d=this._chirpBuffer,h=this._slicedChirpBuffer,p=this._a;if(r)for(let g=0;g>1,b=n[w];s[g]=b*h[g],s[y]=b*h[y]}else for(let g=0;g=e.length&&(h=2*(e.length-1)-h),s[u++]=e[h]}s.sort(),r[c]=s[o]}return r}function Pu(e,n){const r=Math.pow(10,n);return Math.round(e*r)/r}function v3(e){const n=Math.round(e);return Math.abs(e)%1===.5?n%2===0?n:n-1:n}function y3(e){const n=e.length,r=e[0].length,s=[n+1,r+1],o=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));o[0][0]=0;const c=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let g=1;g0||d>0;)switch(h.push(u-1),p.push(d-1),c[u][d]){case 0:--u,--d;break;case 1:--u;break;case 2:--d;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${u}, ${d}]. Please file a bug report.`)}return h.reverse(),p.reverse(),[h,p]}var w3=(function(){let e=null;return function(n){if(!e){e=new Float32Array(65536);const c=new ArrayBuffer(4),u=new Uint32Array(c),d=new Float32Array(c);for(let h=0;h>10;let w=h&1023;if(y===31)p=g|2139095040|w<<13;else if(y===0)if(w===0)p=g;else{let b=113;for(;(w&1024)===0;)w<<=1,--b;w&=-1025,p=g|b<<23|w<<13}else p=g|y+112<<23|w<<13;u[0]=p,e[h]=d[0]}}const r=n.length,s=e,o=new Float32Array(r);for(let c=0;cx3,createReadStream:()=>E3,createWriteStream:()=>S3,default:()=>M3,pipeline:()=>T3});var kh=()=>{},b3={},M3=b3,x3={fromWeb:kh},T3=kh,S3=kh,E3=kh;async function fx(e){const n=e.split("/").pop();let r;try{if(r=await ox(),r){const o=await r.match(e);if(o)return o}}catch(o){console.warn(`Failed to load ${n} from cache:`,o)}const s=await fetch(e);if(!s.ok)throw new Error(`Failed to fetch ${n}: ${s.status} ${s.statusText}`);if(r)try{await r.put(e,s.clone())}catch(o){console.warn(`Failed to cache ${n}:`,o)}return s}async function A3(e){const n=await fx(e);if(!n||typeof n=="string")return null;try{return await n.arrayBuffer()}catch(r){return console.warn("Failed to read WASM binary:",r),null}}async function C3(e){const n=await fx(e);if(!n||typeof n=="string")return null;try{let r=await n.text();const s=e.split("/").slice(0,-1).join("/");r=r.replace(/import\.meta\.url/g,`"${s}"`);const o=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(o)}catch(r){return console.warn("Failed to read WASM binary:",r),null}}function M1(e){return gh(e,["blob:"])}function x1(e){let n;if(typeof location<"u"&&location.href)n=location.href;else if(typeof import.meta<"u"&&import.meta.url)n=import.meta.url;else return e;return new URL(e,n).href}var k3=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"}}),O3=["verbose","info","warning","error","fatal"],hx=4,Na=[],hg,ii,T1=Symbol.for("onnxruntime");if(T1 in globalThis)ii=globalThis[T1];else if(Nt.IS_NODE_ENV){switch(ii=dx,process.platform){case"win32":Na.push("dml");break;case"linux":process.arch==="x64"&&Na.push("cuda");break;case"darwin":Na.push("coreml");break}Na.push("webgpu"),Na.push("cpu"),hg=["cpu"]}else ii=bA,Nt.IS_WEBNN_AVAILABLE&&Na.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),Nt.IS_WEBGPU_AVAILABLE&&Na.push("webgpu"),Na.push("wasm"),hg=["wasm"];var z3=ii.InferenceSession;function L3(e=null){if(!e)return hg;switch(e){case"auto":return Na;case"gpu":return Na.filter(n=>["webgpu","cuda","dml","webnn-gpu"].includes(n))}if(Na.includes(e))return[k3[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${Na.join(", ")}.`)}var px=Nt.IS_BROWSER_ENV||Nt.IS_WEBWORKER_ENV,S1=Promise.resolve(),pl=null;async function N3(){var n,r,s,o,c;return pl||(pa.useWasmCache&&typeof((n=vt==null?void 0:vt.wasm)==null?void 0:n.wasmPaths)=="object"&&((s=(r=vt==null?void 0:vt.wasm)==null?void 0:r.wasmPaths)==null?void 0:s.wasm)&&((c=(o=vt==null?void 0:vt.wasm)==null?void 0:o.wasmPaths)==null?void 0:c.mjs)?(pl=(async()=>{const u=vt.wasm.wasmPaths;await Promise.all([u.wasm&&!M1(u.wasm)?(async()=>{try{const d=await A3(x1(u.wasm));d&&(vt.wasm.wasmBinary=d)}catch(d){console.warn("Failed to pre-load WASM binary:",d)}})():Promise.resolve(),u.mjs&&!M1(u.mjs)?(async()=>{try{const d=await C3(x1(u.mjs));d&&(vt.wasm.wasmPaths.mjs=d)}catch(d){console.warn("Failed to pre-load WASM factory:",d)}})():Promise.resolve()])})(),pl):(pl=Promise.resolve(),pl))}async function mx(e,n,r){await N3();const s=()=>z3.create(e,{logSeverityLevel:hx,...n}),o=await(px?S1=S1.then(s):s());return o.config=r,o}var E1=Promise.resolve();async function _x(e,n){const r=()=>e.run(n);return await(px?E1=E1.then(r):r())}function gx(e){return e instanceof ii.Tensor}var vt=ii==null?void 0:ii.env;vt.logLevel=O3[hx];var W1;if(vt!=null&&vt.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&((W1=vt.versions)!=null&&W1.web)&&!vt.wasm.wasmPaths){const e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${vt.versions.web}/dist/`;vt.wasm.wasmPaths=Nt.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}vt.wasm.proxy=!1}vt!=null&&vt.webgpu&&(vt.webgpu.powerPreference="high-performance");function Vg(){var e;return(e=vt==null?void 0:vt.wasm)==null?void 0:e.proxy}pa.backends.onnx=vt;var ni=async(e,n,r)=>{const s=await mx(new Uint8Array(e),n);return(async o=>{const c=Vg(),u=Object.fromEntries(Object.entries(o).map(([h,p])=>[h,(c?p.clone():p).ort_tensor])),d=await _x(s,u);return Array.isArray(r)?r.map(h=>new we(d[h])):new we(d[r])})},S_,bl=(S_=class{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=ni([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=ni([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=ni([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=ni([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=ni([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=ni([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=ni([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=ni([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}},L(S_,"session_options",{}),S_),D3=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"}),F3=(function(){let e;return async function(){if(e===void 0)if(!Nt.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),On=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),A1=Object.freeze({[D3.wasm]:On.q8}),C1=Object.freeze({[On.fp32]:"",[On.fp16]:"_fp16",[On.int8]:"_int8",[On.uint8]:"_uint8",[On.q8]:"_quantized",[On.q4]:"_q4",[On.q4f16]:"_q4f16",[On.bnb4]:"_bnb4"}),wh=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}),we=class Vt{constructor(...n){L(this,"ort_tensor");return gx(n[0])?this.ort_tensor=n[0]:this.ort_tensor=new LA(n[0],n[1],n[2]),new Proxy(this,{get:(r,s)=>{if(typeof s=="string"){let o=Number(s);if(Number.isInteger(o))return r._getitem(o)}return r[s]},set:(r,s,o)=>r[s]=o})}get dims(){return this.ort_tensor.dims}set dims(n){this.ort_tensor.dims=n}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}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[n,...r]=this.dims;if(r.length>0){const s=r.reduce((o,c)=>o*c);for(let o=0;o0){const o=s.reduce((c,u)=>c*u);return this._subarray(n,o,s)}else return new Vt(this.type,[this.data[n]],s)}indexOf(n){const r=this.data;for(let s=0;sb)throw new Error(`Invalid slice: ${y}`);const S=[Math.max(w,0),Math.min(b,this.dims[g])];s.push(S),r.push(S[1]-S[0])}else throw new Error(`Invalid slice: ${y}`)}const o=s.map(([g,y])=>y-g),c=o.reduce((g,y)=>g*y),u=this.data,d=new u.constructor(c),h=this.stride();let p=!0;for(let g=1;g=0;--w){const S=o[w];y+=(b%S+s[w][0])*h[w],b=Math.floor(b/S)}d[g]=u[y]}return new Vt(this.type,d,r)}permute(...n){return P3(this,n)}transpose(...n){return this.permute(...n)}sum(n=null,r=!1){return this.norm(1,n,r)}norm(n="fro",r=null,s=!1){if(n==="fro")n=2;else if(typeof n=="string")throw Error(`Unsupported norm: ${n}`);const o=this.data,c=(p,g)=>p+g**n;if(r===null){const p=o.reduce(c,0)**(1/n);return new Vt(this.type,[p],[])}const[u,d,h]=Gu(c,this,r,s);if(n!==1)for(let p=0;p=0;--h){const y=this.dims[h];if(h!==r){const w=p%y;d+=w*g,g*=this.dims[h]}p=Math.floor(p/y)}o[u]/=c[d]}return this}normalize(n=2,r=1){return this.clone().normalize_(n,r)}stride(){return v_(this.dims)}squeeze(n=null){return new Vt(this.type,this.data,k1(this.dims,n))}squeeze_(n=null){return this.dims=k1(this.dims,n),this}unsqueeze(n){return new Vt(this.type,this.data,O1(this.dims,n))}unsqueeze_(n){return this.dims=O1(this.dims,n),this}flatten_(n=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,n),o=this.dims.slice(n,r+1),c=this.dims.slice(r+1);return this.dims=[...s,o.reduce((u,d)=>u*d,1),...c],this}flatten(n=0,r=-1){return this.clone().flatten_(n,r)}view(...n){let r=-1;for(let o=0;od!==r?c*u:c,1);n[r]=s.length/o}return new Vt(this.type,s,n)}neg_(){const n=this.data;for(let r=0;rn?1:0;return new Vt("bool",r,this.dims)}lt(n){const r=new Uint8Array(this.data.length),s=this.data;for(let o=0;oMath.min(u,d),this,n,r,1/0);return new Vt(s,o,c)}max(n=null,r=!1){if(n===null){const u=Qt(this.data)[0];return new Vt(this.type,[u],[])}const[s,o,c]=Gu((u,d)=>Math.max(u,d),this,n,r,-1/0);return new Vt(s,o,c)}argmin(n=null,r=!1){if(n!==null)throw new Error("`dim !== null` not yet implemented.");const s=fg(this.data)[1];return new Vt("int64",[BigInt(s)],[])}argmax(n=null,r=!1){if(n!==null)throw new Error("`dim !== null` not yet implemented.");const s=Qt(this.data)[1];return new Vt("int64",[BigInt(s)],[])}repeat(...n){if(n.lengthg===1)){if(n.length===this.dims.length)return this.clone();const g=n.length-this.dims.length,y=Array(g).fill(1).concat(this.dims);return new Vt(this.type,this.data.slice(),y)}const r=n.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),o=s.map((g,y)=>g*n[y]),c=o.reduce((g,y)=>g*y,1),u=this.data,d=new u.constructor(c),h=v_(s),p=v_(o);for(let g=0;gBigInt(Math.floor(c)):r=BigInt;else if(this.type==="float16"&&n=="float32"&&this.data instanceof Uint16Array)return new Vt(n,w3(this.data),this.dims);return new Vt(n,wh[n].from(this.data,r),this.dims)}};function B3(e,n){const r=e.length,s=n.reduce((c,u)=>c*u);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${n})`);let o=e;for(let c=n.length-1;c>=0;c--)o=o.reduce((u,d)=>{let h=u[u.length-1];return h.lengthnew we("int64",e,[e.length]);async function yx(e,n,r,s,o){return await(await bl.slice)({x:e,s:Rf(n),e:Rf(r),a:Rf(s),t:Rf(new Array(s.length).fill(1))})}function U3(e,n){const r=e.data,s=n.data,o=[e.dims[0],e.dims[2]],c=new r.constructor(o[0]*o[1]),[u,d,h]=e.dims;let p=0;for(let g=0;gr!==1):typeof n=="number"?e[n]===1&&e.splice(n,1):Array.isArray(n)&&(e=e.filter((r,s)=>r!==1||!n.includes(s))),e}function O1(e,n){return n=Or(n,e.length+1),e=e.slice(),e.splice(n,0,1),e}function Or(e,n,r=null,s=!0){if(e<-n||e>=n){if(s)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${n}`);return e<-n?0:n}return e<0&&(e=(e%n+n)%n),e}function Pt(e,n=0){n=Or(n,e[0].dims.length);const r=e[0].dims.slice();r[n]=e.reduce((u,d)=>u+d.dims[n],0);const s=r.reduce((u,d)=>u*d,1),o=new e[0].data.constructor(s),c=e[0].type;if(n===0){let u=0;for(const d of e){const h=d.data;o.set(h,u),u+=h.length}}else{let u=0;for(let d=0;d=0;--w){const E=p[w];let O=b%E;w===n&&(O+=u),y+=O*S,S*=r[w],b=Math.floor(b/E)}o[y]=h[g]}u+=p[n]}}return new we(c,o,r)}function Cl(e,n=0){return Pt(e.map(r=>r.unsqueeze(n)),n)}function Gu(e,n,r,s=!1,o=null){const c=n.data,u=n.dims;r=Or(r,u.length);const d=u.slice();d[r]=1;const h=new c.constructor(c.length/u[r]);o!==null&&h.fill(o);for(let p=0;p=0;--y){const S=u[y];if(y!==r){const E=w%S;g+=E*b,b*=d[y]}w=Math.floor(w/S)}h[g]=e(h[g],c[p],p,g)}return s||d.splice(r,1),[n.type,h,d]}function I3(e,n=null,r=1,s=!1){const o=e.data,c=e.dims;if(n===null){const b=o.reduce((z,D)=>z+D,0)/o.length,S=Math.sqrt(o.reduce((z,D)=>z+(D-b)**2,0)/(o.length-r)),E=new we(e.type,[b],[]);return[new we(e.type,[S],[]),E]}n=Or(n,c.length);const u=qg(e,n,s),d=u.data,[h,p,g]=Gu((w,b,S,E)=>w+(b-d[E])**2,e,n,s);for(let w=0;wp+g,0);return new we(e.type,[h/o.length],[])}n=Or(n,s.length);const[c,u,d]=Gu((h,p)=>h+p,e,n,r);if(s[n]!==1)for(let h=0;h=0;--r)n[r]=s,s*=e[r];return n}function $g(e,n,r,s){const o=e.reduce((c,u)=>c*u,1);return new we(r,new s(o).fill(n),e)}function zn(e,n){let r,s;if(typeof n=="number")r="float32",s=Float32Array;else if(typeof n=="bigint")r="int64",s=BigInt64Array;else if(typeof n=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof n}`);return $g(e,n,r,s)}function pg(e,n){return zn(e.dims,n)}function Fa(e){return $g(e,1n,"int64",BigInt64Array)}function wx(e){return Fa(e.dims)}function bx(e){return $g(e,0n,"int64",BigInt64Array)}function Mx(e){return bx(e.dims)}function G3(e){const n=e.reduce((s,o)=>s*o,1),r=new Float32Array(n);for(let s=0;s0?1:0,p=Math.floor(d/8),g=d%8;u[p]|=h<<7-g,r&&g===0&&(u[p]-=128)}return new we(s,u,[e.dims[0],e.dims[1]/8])}async function xx(e,n){return await Promise.all([Lr(e,"tokenizer.json",!0,n),Lr(e,"tokenizer_config.json",!0,n)])}function Tx(e){const n=e.dims;switch(n.length){case 1:return e.tolist();case 2:if(n[0]!==1)throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw new Error(`Expected tensor to have 1-2 dimensions, got ${n.length}.`)}}var V3=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function q3(e,n,r,s){for(const o of Object.keys(e)){const c=n-e[o].length,u=r(o),d=new Array(c).fill(u);e[o]=s==="right"?zr(e[o],d):zr(d,e[o])}}function $3(e,n){for(const r of Object.keys(e))e[r].length=n}function Gi(e,...n){for(const r of n){if(!Object.hasOwn(e,r))continue;const s=e[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 H3(e){const n=[];for(const r of e.get_added_tokens_decoder().values())r.special&&n.push(r);return n}var Re=class extends Ba{constructor(n,r){super();L(this,"return_token_type_ids",!1);L(this,"padding_side","right");if(this._tokenizerJSON=n,this._tokenizerConfig=r,this._tokenizer=new nO(n,r),this.config=r,this.padding_side=r.padding_side??this.padding_side,this.mask_token=Gi(r,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Gi(r,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Gi(r,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Gi(r,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Gi(r,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Gi(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)){const o=Object.create(null);for(const{name:c,template:u}of this.chat_template){if(typeof c!="string"||typeof u!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');o[c]=u}this.chat_template=o}this._compiled_template_cache=new Map;const s=H3(this._tokenizer);this.all_special_ids=s.map(o=>o.id),this.all_special_tokens=s.map(o=>o.content)}static async from_pretrained(n,{progress_callback:r=null,config:s=null,cache_dir:o=null,local_files_only:c=!1,revision:u="main"}={}){const d=await xx(n,{progress_callback:r,cache_dir:o,local_files_only:c,revision:u});return new this(...d)}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(n){return typeof n=="string"?this._tokenizer.token_to_id(n):n.map(r=>this._tokenizer.token_to_id(r))}_call(n,{text_pair:r=null,add_special_tokens:s=!0,padding:o=!1,truncation:c=null,max_length:u=null,return_tensor:d=!0,return_token_type_ids:h=null}={}){const p=Array.isArray(n);let g;if(p){if(n.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(n.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");g=n.map((w,b)=>this._encode_plus(w,{text_pair:r[b],add_special_tokens:s,return_token_type_ids:h}))}else g=n.map(w=>this._encode_plus(w,{add_special_tokens:s,return_token_type_ids:h}))}else{if(n==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).");g=[this._encode_plus(n,{text_pair:r,add_special_tokens:s,return_token_type_ids:h})]}if(u===null?u=this.model_max_length:c===null&&(o===!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'`."),u=this.model_max_length):o===!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."),c=!0)),o===!0&&(u=Math.min(Qt(g.map(w=>w.input_ids.length))[0],u??1/0)),u=Math.min(u,this.model_max_length??1/0),o||c)for(let w=0;wu?c&&$3(g[w],u):o&&q3(g[w],u,b=>b==="input_ids"?this.pad_token_id:0,this.padding_side));const y={};if(d){if(!(o&&c)&&g.some(b=>{var S;for(const E of Object.keys(b))if(b[E].length!==((S=g[0][E])==null?void 0:S.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.");const w=[g.length,g[0].input_ids.length];for(const b of Object.keys(g[0]))y[b]=new we("int64",BigInt64Array.from(g.flatMap(S=>S[b]).map(BigInt)),w)}else{for(const w of Object.keys(g[0]))y[w]=g.map(b=>b[w]);if(!p)for(const w of Object.keys(y))y[w]=y[w][0]}return y}_encode_text(n){return n===null?null:this._tokenizer.encode(n).tokens}_encode_plus(n,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:o=null}={}){const{ids:c,attention_mask:u,token_type_ids:d}=this._tokenizer.encode(n,{text_pair:r,add_special_tokens:s,return_token_type_ids:o??this.return_token_type_ids});return{input_ids:c,attention_mask:u,...d?{token_type_ids:d}:{}}}tokenize(n,{pair:r=null,add_special_tokens:s=!1}={}){return this._tokenizer.tokenize(n,{text_pair:r,add_special_tokens:s})}encode(n,{text_pair:r=null,add_special_tokens:s=!0,return_token_type_ids:o=null}={}){return this._tokenizer.encode(n,{text_pair:r,add_special_tokens:s,return_token_type_ids:o}).ids}batch_decode(n,r={}){return n instanceof we&&(n=n.tolist()),n.map(s=>this.decode(s,r))}decode(n,r={}){if(n instanceof we&&(n=Tx(n)),!Array.isArray(n)||n.length===0||!KO(n[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(n,r)}decode_single(n,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:s=null}){return this._tokenizer.decode(n,{skip_special_tokens:r,clean_up_tokenization_spaces:s})}get_chat_template({chat_template:n=null,tools:r=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const s=this.chat_template;if(n!==null&&Object.hasOwn(s,n))n=s[n];else if(n===null)if(r!==null&&"tool_use"in s)n=s.tool_use;else if("default"in s)n=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(n===null)if(this.chat_template)n=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 n}apply_chat_template(n,{tools:r=null,documents:s=null,chat_template:o=null,add_generation_prompt:c=!1,tokenize:u=!0,padding:d=!1,truncation:h=!1,max_length:p=null,return_tensor:g=!0,return_dict:y=!0,tokenizer_kwargs:w={},...b}={}){if(o=this.get_chat_template({chat_template:o,tools:r}),typeof o!="string")throw Error(`chat_template must be a string, but got ${typeof o}`);let S=this._compiled_template_cache.get(o);S===void 0&&(S=new ZO(o),this._compiled_template_cache.set(o,S));const E=Object.create(null);for(const z of V3){const D=Gi(this.config,z);D&&(E[z]=D)}const O=S.render({messages:n,add_generation_prompt:c,tools:r,documents:s,...E,...b});if(u){const z=this._call(O,{add_special_tokens:!1,padding:d,truncation:h,max_length:p,return_tensor:g,...w});return y?z:z.input_ids}return O}};function Hg(e,n,r,s){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const o=s.src_lang,c=s.tgt_lang;if(!e.language_codes.includes(c))throw new Error(`Target language code "${c}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(o!==void 0){if(!e.language_codes.includes(o))throw new Error(`Source language code "${o}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const u of e._tokenizer.post_processor.config.single)if("SpecialToken"in u&&e.languageRegex.test(u.SpecialToken.id)){u.SpecialToken.id=e.lang_to_token(o);break}}return s.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(c)),e._call(n,r)}var Sx={};Sl(Sx,{AlbertTokenizer:()=>Y3,AutoTokenizer:()=>$e,BartTokenizer:()=>X3,BertTokenizer:()=>Q3,BlenderbotSmallTokenizer:()=>W3,BlenderbotTokenizer:()=>Z3,BloomTokenizer:()=>K3,CLIPTokenizer:()=>ez,CamembertTokenizer:()=>J3,CodeGenTokenizer:()=>nz,CodeLlamaTokenizer:()=>tz,CohereTokenizer:()=>az,ConvBertTokenizer:()=>rz,DebertaTokenizer:()=>iz,DebertaV2Tokenizer:()=>sz,DistilBertTokenizer:()=>oz,ElectraTokenizer:()=>lz,EsmTokenizer:()=>cz,FalconTokenizer:()=>uz,GPT2Tokenizer:()=>hz,GPTNeoXTokenizer:()=>fz,GemmaTokenizer:()=>dz,HerbertTokenizer:()=>pz,LlamaTokenizer:()=>mz,M2M100Tokenizer:()=>_z,MBart50Tokenizer:()=>vz,MBartTokenizer:()=>Ex,MPNetTokenizer:()=>bz,MarianTokenizer:()=>gz,MgpstrTokenizer:()=>yz,MobileBertTokenizer:()=>wz,NllbTokenizer:()=>Mz,NougatTokenizer:()=>xz,PreTrainedTokenizer:()=>Re,Qwen2Tokenizer:()=>Tz,RoFormerTokenizer:()=>Ez,RobertaTokenizer:()=>Sz,SiglipTokenizer:()=>Az,SpeechT5Tokenizer:()=>Cz,SqueezeBertTokenizer:()=>kz,T5Tokenizer:()=>Oz,TokenizersBackend:()=>Re,VitsTokenizer:()=>Lz,Wav2Vec2CTCTokenizer:()=>Nz,WhisperTokenizer:()=>Pz,XLMRobertaTokenizer:()=>Rz,XLMTokenizer:()=>Uz});var Y3=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},X3=class extends Re{},Q3=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},W3=class extends Re{},Z3=class extends Re{},K3=class extends Re{},J3=class extends Re{},ez=class extends Re{},tz=class extends Re{},nz=class extends Re{},az=class extends Re{},rz=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},sz=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},iz=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},oz=class extends Re{},lz=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},cz=class extends Re{},uz=class extends Re{},dz=class extends Re{},fz=class extends Re{},hz=class extends Re{},pz=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},mz=class extends Re{constructor(){super(...arguments);L(this,"padding_side","left")}},_z=class extends Re{constructor(e,n){super(e,n),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(e,n,r){return Hg(this,e,n,r)}},gz=class extends Re{constructor(e,n){super(e,n),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),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;const[n,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(n);if(r.length===2){const[s,o]=r;return this.supported_language_codes.includes(s)||console.warn(`Unsupported language code "${s}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),zr([s],super._encode_text(o))}}},Ex=class extends Re{constructor(e,n){super(e,n),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r),this.lang_to_token=r=>r}_build_translation_inputs(e,n,r){return Hg(this,e,n,r)}},vz=class extends Ex{},yz=class extends Re{},wz=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},bz=class extends Re{},Mz=class extends Re{constructor(e,n){super(e,n),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(e,n,r){return Hg(this,e,n,r)}},xz=class extends Re{},Tz=class extends Re{},Sz=class extends Re{},Ez=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},Az=class extends Re{},Cz=class extends Re{},kz=class extends Re{constructor(){super(...arguments);L(this,"return_token_type_ids",!0)}},Oz=class extends Re{},zz=class extends ir{decode_chain(e){let n="";for(let r=1;r[n,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Fz(e){e=e.toLowerCase();let n=Dz.get(e);if(n===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),oh.has(e))n=e;else{const o=e.length===2?oh.keys():oh.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(o))}`)}}return n}var Bz="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",z1=new RegExp(`^[${Bz}]+$`,"gu"),Pz=class extends Re{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:n=!1,return_language:r=!1,time_precision:s=null,force_full_sequences:o=!0}={}){if(s===null)throw Error("Must specify time_precision");let c=null;const u=n==="word";function d(){return{language:c,timestamp:[null,null],text:""}}const h=[];let p=d(),g=0;const y=this.timestamp_begin,b=y+1500;let S=[],E=[],O=!1,z=null;const D=new Set(this.all_special_ids);for(const G of e){const K=G.tokens,k=u?G.token_timestamps:null;let ce=null,oe=y;if("stride"in G){const[pe,ne,ee]=G.stride;if(g-=ne,z=pe-ee,ne&&(oe=ne/s+y),ee)for(let Me=K.length-1;Me>=0;--Me){const V=Number(K[Me]);if(V>=y){if(ce!==null&&(V-y)*s=y&&ne<=b){const ee=(ne-y)*s+g,Me=Pu(ee,2);if(ce!==null&&ne>=ce)O=!0;else if(O||S.length>0&&ne0?(S.push(he),u&&E.push(me)):S.every(pe=>pe.length===0)&&(p=d(),S=[],he=[],E=[],me=[])}if(S.length>0){if(o&&n)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.");const[G,K]=this.findLongestCommonSequence(S,E),k=this.decode(G);p.text=k,u&&(p.words=this.collateWordTimestamps(G,K,c)),h.push(p)}let P=Object.create(null);const j=h.map(G=>G.text).join("");if(n||r){for(let G=0;G0;let u=c?[]:null,d=c?n[0]:null;for(let h=1;hne===oe[ee]&&d[j+ee]<=n[h][k+ee]).length:he=K.filter((ne,ee)=>ne===oe[ee]).length;const me=P/1e4,pe=he/P+me;he>1&&pe>g&&(g=pe,y=[j,G,k,ce])}const[b,S,E,O]=y,z=Math.floor((S+b)/2),D=Math.floor((O+E)/2);o.push(...r.slice(0,z)),r=p.slice(D),s=r.length,c&&(u.push(...d.slice(0,z)),d=n[h].slice(D))}return o.push(...r),c?(u.push(...d),[o,u]):[o,[]]}collateWordTimestamps(e,n,r){const[s,o,c]=this.combineTokensIntoWords(e,r),u=[];for(let d=0;d=s){const u=((c-s)*r).toFixed(2);o.push(`<|${u}|>`),o.push([])}else o[o.length-1].push(c);return o=o.map(c=>typeof c=="string"?c:super.decode(c,n)),o.join("")}splitTokensOnUnicode(e){const n=this.decode(e,{decode_with_timestamps:!0}),r="�",s=[],o=[],c=[];let u=[],d=[],h=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),w=h.startsWith(" "),b=h.trim(),S=z1.test(b);if(y||w||S||o.length===0)o.push(h),c.push(p),u.push(g);else{const E=o.length-1;o[E]+=h,c[E].push(...p),u[E].push(...g)}}return[o,c,u]}mergePunctuations(e,n,r,s,o){const c=structuredClone(e),u=structuredClone(n),d=structuredClone(r);let h=c.length-2,p=c.length-1;for(;h>=0;)c[h].startsWith(" ")&&s.includes(c[h].trim())?(c[p]=c[h]+c[p],u[p]=zr(u[h],u[p]),d[p]=zr(d[h],d[p]),c[h]="",u[h]=[],d[h]=[]):p=h,--h;for(h=0,p=1;pg),u.filter(g=>g.length>0),d.filter(g=>g.length>0)]}},Rz=class extends Re{},Uz=class extends Re{constructor(n,r){super(n,r);L(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},$e=class{static async from_pretrained(e,{progress_callback:n=null,config:r=null,cache_dir:s=null,local_files_only:o=!1,revision:c="main"}={}){var g;const[u,d]=await xx(e,{progress_callback:n,cache_dir:s,local_files_only:o,revision:c}),h=((g=d.tokenizer_class)==null?void 0:g.replace(/Fast$/,""))??"PreTrainedTokenizer";let p=Sx[h];return p||(console.warn(`Unknown tokenizer class "${h}", attempting to construct from base class.`),p=Re),new p(u,d)}},Yg="https://github.com/huggingface/transformers.js/issues/new/choose",Xg="preprocessor_config.json",Qg=Xg,Iz="processor_config.json",Gz="chat_template.jinja",Au,At=(Au=class extends Ba{constructor(e,n,r){super(),this.config=e,this.components=n,this.chat_template=r}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,n={}){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,...n})}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,...n){for(const r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...n);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,n={}){const[r,s,o]=await Promise.all([this.uses_processor_config?Lr(e,Iz,!0,n):{},Promise.all(this.classes.filter(c=>c in this).map(async c=>{const u=await this[c].from_pretrained(e,n);return[c.replace(/_class$/,""),u]})).then(Object.fromEntries),this.uses_chat_template_file?lx(e,Gz,!0,n):null]);return new this(r,s,o)}},L(Au,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),L(Au,"uses_processor_config",!1),L(Au,"uses_chat_template_file",!1),Au),mg={};Sl(mg,{ChatterboxProcessor:()=>pL,Florence2Processor:()=>l4,Gemma3nProcessor:()=>c4,GroundingDinoProcessor:()=>d4,Idefics3Processor:()=>B1,JinaCLIPProcessor:()=>_4,LlavaProcessor:()=>g4,MgpstrProcessor:()=>v4,MoonshineProcessor:()=>y4,OwlViTProcessor:()=>w4,PaliGemmaProcessor:()=>M4,Phi3VProcessor:()=>T4,PixtralProcessor:()=>S4,Processor:()=>At,PyAnnoteProcessor:()=>E4,Qwen2VLProcessor:()=>A4,Sam2Processor:()=>e2,Sam2VideoProcessor:()=>C4,SamProcessor:()=>Jx,SmolVLMProcessor:()=>B1,SpeechT5Processor:()=>k4,UltravoxProcessor:()=>O4,VLChatProcessor:()=>m4,VoxtralProcessor:()=>D4,Wav2Vec2Processor:()=>F4,Wav2Vec2ProcessorWithLM:()=>B4,WhisperProcessor:()=>P4});var Jn=class extends Ba{constructor(e){super(),this.config=e}static async from_pretrained(e,n={}){const r=await Lr(e,Xg,!0,n);return new this(r)}};function Pa(e,n){var r;if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${n} expects input to be a Float32Array or a Float64Array, but got ${((r=e==null?void 0:e.constructor)==null?void 0:r.name)??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var Wg={};Sl(Wg,{ASTFeatureExtractor:()=>tL,ChatterboxFeatureExtractor:()=>nL,ClapFeatureExtractor:()=>aL,DacFeatureExtractor:()=>Lx,EncodecFeatureExtractor:()=>zx,FeatureExtractor:()=>Jn,Gemma3nAudioFeatureExtractor:()=>rL,MoonshineFeatureExtractor:()=>sL,ParakeetFeatureExtractor:()=>oL,PyAnnoteFeatureExtractor:()=>Nx,SeamlessM4TFeatureExtractor:()=>lL,SnacFeatureExtractor:()=>cL,SpeechT5FeatureExtractor:()=>uL,Wav2Vec2FeatureExtractor:()=>dL,WeSpeakerFeatureExtractor:()=>fL,WhisperFeatureExtractor:()=>hL});var jz=()=>{},Vz=jz;async function Cx(e,n){if(Nt.IS_BROWSER_ENV){if(Nt.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=e,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(Nt.IS_FS_AVAILABLE)n.stream(),er.createWriteStream(e),await Vz();else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function qz(e,n){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.");const r=await(await vh(e)).arrayBuffer(),s=new AudioContext({sampleRate:n});typeof n>"u"&&console.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);const o=await s.decodeAudioData(r);let c;if(o.numberOfChannels===2){const u=Math.sqrt(2),d=o.getChannelData(0),h=o.getChannelData(1);c=new Float32Array(d.length);for(let p=0;p2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,n=1e3,r=15,s=27/Math.log(6.4))=>e>=n?r+Math.log(e/n)*s:3*e/200};function y_(e,n="htk"){const r=Hz[n];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(s=>r(s))}var Yz={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,n=1e3,r=15,s=Math.log(6.4)/27)=>e>=r?n*Math.exp(s*(e-r)):200*e/3};function Xz(e,n="htk"){const r=Yz[n];if(!r)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof e=="number"?r(e):e.map(s=>r(s))}function Qz(e,n){const r=Float64Array.from({length:n.length-1},(u,d)=>n[d+1]-n[d]),s=Array.from({length:e.length},()=>new Array(n.length));for(let u=0;unew Array(e.length));for(let u=0;ue+s*c)}function li(e,n,r,s,o,c=null,u="htk",d=!1){if(c!==null&&c!=="slaney")throw new Error('norm must be one of null or "slaney"');if(e<2)throw new Error(`Require num_frequency_bins: ${e} >= 2`);if(r>s)throw new Error(`Require min_frequency: ${r} <= max_frequency: ${s}`);const h=y_(r,u),p=y_(s,u),g=N1(h,p,n+2);let y=Xz(g,u),w;if(d){const S=o/((e-1)*2);w=y_(Float64Array.from({length:e},(E,O)=>O*S),u),y=g}else w=N1(0,Math.floor(o/2),e);const b=Qz(w,y);if(c!==null&&c==="slaney")for(let S=0;So)throw Error(`frame_length (${r}) may not be larger than fft_length (${o})`);if(k!==r)throw new Error(`Length of the window (${k}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(c===null&&y!==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(!g)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(u)switch(d){case"reflect":{const R=Math.floor((o-1)/2)+1;e=Wz(e,R,R);break}case"constant":{const R=Math.floor(o/2),te=new e.constructor(e.length+2*R);te.set(e,R),e=te;break}default:throw new Error(`pad_mode="${d}" not implemented yet.`)}let ce=Math.floor(1+Math.floor((e.length-r)/s));D!==null&&cece?j&&(me=P):me=he=P);const pe=new _3(o),ne=new Float64Array(o),ee=new Float64Array(pe.outputBufferSize),Me=new Float32Array(oe*me);for(let R=0;R=1;--H)ne[H]-=p*ne[H-1];ne[0]*=1-p}for(let H=0;HMath.pow(d,.85));break;default:throw new Error(`Unknown window type ${n}.`)}if(r&&(u=u.subarray(0,e)),s===null)return u;if(e>s)throw new Error(`Length of the window (${e}) may not be larger than frame_length (${s})`);return u}function Jz(e,n){const r=e.reduce((c,u)=>c+u.length,0),s=new ArrayBuffer(44),o=new DataView(s);return Uf(o,0,"RIFF"),o.setUint32(4,36+r*4,!0),Uf(o,8,"WAVE"),Uf(o,12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,3,!0),o.setUint16(22,1,!0),o.setUint32(24,n,!0),o.setUint32(28,n*4,!0),o.setUint16(32,4,!0),o.setUint16(34,32,!0),Uf(o,36,"data"),o.setUint32(40,r*4,!0),new Blob([s,...e.map(c=>c.buffer)],{type:"audio/wav"})}function Uf(e,n,r){for(let s=0;ss+o.length,0),n=new Float32Array(e);let r=0;for(const s of this.audio)n.set(s,r),r+=s.length;return n}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),Jz(e,this.sampling_rate)}async save(e){return Cx(e,this.toBlob())}},tL=class extends Jn{constructor(e){super(e);const n=this.config.sampling_rate,r=li(257,this.config.num_mel_bins,20,Math.floor(n/2),n,null,"kaldi",!0);this.mel_filters=r,this.window=no(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,n){return to(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:n,transpose:!0})}async _call(e){Pa(e,"ASTFeatureExtractor");const n=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,s=n.data;for(let o=0;o0)if(r==="rand_trunc"){const u=Math.floor(Math.random()*(c+1));e=e.subarray(u,u+n),o=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${r}" not implemented`);else{if(c<0){let u=new Float64Array(n);if(u.set(e),s==="repeat")for(let d=e.length;dn&&(e=e.slice(0,n)),s&&e.length%o!==0){const d=o-e.length%o,h=new Float64Array(e.length+d);h.set(e),this.config.padding_value!==0&&h.fill(this.config.padding_value,e.length),e=h}const c=await this._extract_fbank_features(e,this.config.max_length),u=zn([1,c.dims[0]],!0);return{input_features:c.unsqueeze_(0),input_features_mask:u}}},sL=class extends Jn{async _call(e){Pa(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const n=[1,e.length];return{input_values:new we("float32",e,n)}}},iL=1e-5,oL=class extends Jn{constructor(e){var s;super(e),(s=this.config).mel_filters??(s.mel_filters=li(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney"));const n=no(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const r=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(n,r)}async _extract_fbank_features(e){const n=this.config.preemphasis;e=new Float64Array(e);for(let s=e.length-1;s>=1;--s)e[s]-=n*e[s-1];return await to(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){Pa(e,"ParakeetFeatureExtractor");const n=await this._extract_fbank_features(e),r=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),s=n.data;s.fill(0,r*n.dims[1]);const[o,c]=n.dims,u=new Float64Array(c),d=new Float64Array(c);for(let g=0;g1?r-1:1;for(let g=0;g({id:d,start:h*r,end:p*r,confidence:g/(p-h)})))}return s}},lL=class extends Jn{constructor(e){super(e);const n=this.config.sampling_rate,r=li(257,this.config.num_mel_bins,20,Math.floor(n/2),n,null,"kaldi",!0);this.mel_filters=r,this.window=no(400,"povey",{periodic:!1})}async _extract_fbank_features(e,n){return e=e.map(r=>r*32768),to(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:n,transpose:!0})}async _call(e,{padding:n=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:s=!0,return_attention_mask:o=!0}={}){Pa(e,"SeamlessM4TFeatureExtractor");let c=await this._extract_fbank_features(e,this.config.max_length);if(s){const[b,S]=c.dims,E=c.data;for(let O=0;O0){const z=new Float32Array(S*(b+O));z.set(E),z.fill(this.config.padding_value,E.length);const D=b+O;c=new we(c.type,z,[D,S]),o&&(u=new we("int64",new BigInt64Array(D),[1,D]),u.data.fill(1n,0,b))}}const[d,h]=c.dims,p=this.config.stride;if(d%p!==0)throw new Error(`The number of frames (${d}) must be a multiple of the stride (${p}).`);const y=c.view(1,Math.floor(d/p),h*p),w={input_features:y};if(o){const b=y.dims[1],S=new BigInt64Array(b);if(u){const E=u.data;for(let O=1,z=0;Oo+c,0)/e.length,s=e.reduce((o,c)=>o+(c-r)**2,0)/e.length;return e.map(o=>(o-r)/Math.sqrt(s+1e-7))}async _call(e){Pa(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let n=e;this.config.do_normalize&&(n=this._zero_mean_unit_var_norm(n));const r=[1,n.length];return{input_values:new we("float32",n,r),attention_mask:new we("int64",new BigInt64Array(n.length).fill(1n),r)}}},fL=class extends Jn{constructor(e){super(e);const n=this.config.sampling_rate,r=li(257,this.config.num_mel_bins,20,Math.floor(n/2),n,null,"kaldi",!0);this.mel_filters=r,this.window=no(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(n=>n*32768),to(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){Pa(e,"WeSpeakerFeatureExtractor");const n=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const r=n.mean(1).data,s=n.data,[o,c,u]=n.dims;for(let d=0;ds?(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`."),r=e.slice(0,s)):(r=new Float32Array(s),r.set(e)),{input_features:(await this._extract_fbank_features(r)).unsqueeze_(0)}}},ms=class{static async from_pretrained(e,n={}){const r=await Lr(e,Xg,!0,n),s=r.feature_extractor_type,o=Wg[s];if(!o)throw new Error(`Unknown feature_extractor_type: '${s}'. Please report this at ${Yg}.`);return new o(r)}},Vf,pL=(Vf=class extends At{async _call(e,n=null){const r=this.tokenizer(e),s=n?await this.feature_extractor(n):{};return{...r,...s}}},L(Vf,"tokenizer_class",$e),L(Vf,"feature_extractor_class",ms),Vf),mL={},_g=mL,qi,Dx,ai,Ja=Nt.IS_BROWSER_ENV||Nt.IS_WEBWORKER_ENV;if(Ja)qi=(e,n)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(e,n)},ai=self.createImageBitmap,Dx=self.ImageData;else if(_g)ai=async e=>{const r=(await e.metadata()).channels,{data:s,info:o}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),c=new rr(new Uint8ClampedArray(s),o.width,o.height,o.channels);return r!==void 0&&r!==o.channels&&c.convert(r),c};else throw new Error("Unable to load image processing library.");var _L={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},gL=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),rr=class kr{constructor(n,r,s,o){this.data=n,this.width=r,this.height=s,this.channels=o}get size(){return[this.width,this.height]}static async read(n){if(n instanceof kr)return n;if(typeof n=="string"||n instanceof URL)return await this.fromURL(n);if(n instanceof Blob)return await this.fromBlob(n);if(typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&n instanceof OffscreenCanvas)return this.fromCanvas(n);throw new Error(`Unsupported input type: ${typeof n}`)}static fromCanvas(n){if(!Ja)throw new Error("fromCanvas() is only supported in browser environments.");const s=n.getContext("2d").getImageData(0,0,n.width,n.height).data;return new kr(s,n.width,n.height,4)}static async fromURL(n){const r=await vh(n);if(r.status!==200)throw new Error(`Unable to read image from "${n}" (${r.status} ${r.statusText})`);const s=await r.blob();return this.fromBlob(s)}static async fromBlob(n){if(Ja){const r=await ai(n),s=qi(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{const r=_g(await n.arrayBuffer());return await ai(r)}}static fromTensor(n,r="CHW"){if(n.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${n.dims.length} dimensions.`);if(r==="CHW")n=n.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(n.data instanceof Uint8ClampedArray||n.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${n.type}`);switch(n.dims[2]){case 1:case 2:case 3:case 4:return new kr(n.data,n.dims[1],n.dims[0],n.dims[2]);default:throw new Error(`Unsupported number of channels: ${n.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const n=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?h=s:g=-s,o>=0?p=o:y=-o,d.drawImage(u,h,p,n,r,g,y,n,r),new kr(d.getImageData(0,0,n,r).data,n,r,4).convert(c)}else{let c=this.toSharp();if(s>=0&&o>=0)c=c.extract({left:Math.floor(s),top:Math.floor(o),width:n,height:r});else if(s<=0&&o<=0){const u=Math.floor(-o),d=Math.floor(-s);c=c.extend({top:u,left:d,right:n-this.width-d,bottom:r-this.height-u})}else{let u=[0,0],d=0;o<0?(u[0]=Math.floor(-o),u[1]=r-this.height-u[0]):d=Math.floor(o);let h=[0,0],p=0;s<0?(h[0]=Math.floor(-s),h[1]=n-this.width-h[0]):p=Math.floor(s),c=c.extend({top:u[0],bottom:u[1],left:h[0],right:h[1]}).extract({left:p,top:d,width:n,height:r})}return await ai(c)}}async toBlob(n="image/png",r=1){if(!Ja)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:n,quality:r})}toTensor(n="CHW"){let r=new we("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(n!=="HWC")if(n==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${n}`);return r}toCanvas(){if(!Ja)throw new Error("toCanvas() is only supported in browser environments.");const n=this.clone().rgba(),r=qi(n.width,n.height),s=new Dx(n.data,n.width,n.height);return r.getContext("2d").putImageData(s,0,0),r}split(){const{data:n,width:r,height:s,channels:o}=this,c=n.constructor,u=n.length/o,d=Array.from({length:o},()=>new c(u));for(let h=0;hnew kr(h,r,s,1))}_update(n,r,s,o=null){return this.data=n,this.width=r,this.height=s,o!==null&&(this.channels=o),this}clone(){return new kr(this.data.slice(),this.width,this.height,this.channels)}convert(n){if(this.channels===n)return this;switch(n){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(n){if(Ja){if(Nt.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=n.split(".").pop().toLowerCase(),s=gL.get(r)??"image/png",o=await this.toBlob(s);return Cx(n,o)}else if(Nt.IS_FS_AVAILABLE)await this.toSharp().toFile(n);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(Ja)throw new Error("toSharp() is only supported in server-side environments.");return _g(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};rr.read.bind(rr);function D1(e,n,r=0,s=null){const o=e/n;let c=v3(o)*n;return s!==null&&c>s&&(c=Math.floor(o)*n),cn&&z.push(P)}else{let P=Qt(O.data)[1];if(P===h-1||(D=bn(O.data),D[P]G*y[(K+1)%2])),w.boxes.push(j),w.classes.push(P),w.scores.push(D[P])}}p.push(w)}return p}function Bx(e,n=null){const r=e.logits,s=r.dims[0];if(n!==null&&n.length!==s)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const o=[];for(let c=0;cy[z]&&(y[z]=O[z],w[z]=E)}const b=new Array(d.dims[0]);for(let E=0;EE!==void 0);o.push({segmentation:g,labels:S})}return o}function vL(e,n,r,s){const o=[],c=[],u=[];for(let d=0;dr&&(o.push(p),c.push(w),u.push(g))}return[o,c,u]}function yL(e,n,r,s=.5,o=.8){const c=[];let u=0,d=0;const h=n[r].data;for(let g=0;g=s&&++d;let p=u>0&&d>0;return p&&(p=u/d>o),[p,c]}function wL(e,n,r,s,o,c=null,u=null){const[d,h]=u??e[0].dims,p=new we("int32",new Int32Array(d*h),[d,h]),g=[];if(u!==null)for(let E=0;Ew[D]&&(y[D]=E,w[D]=z[D])}let b=0;const S=p.data;for(let E=0;E200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,n)/Math.min(e,n)}`);let c=Math.round(e/r)*r,u=Math.round(n/r)*r;if(c*u>o){const d=Math.sqrt(e*n/o);c=Math.floor(e/d/r)*r,u=Math.floor(n/d/r)*r}else if(c*uo?h=Math.floor(o*d/s):o>s&&(d=Math.floor(s*h/o)),await e.resize(h,d,{resample:r}))}async crop_margin(e,n=200){const r=e.clone().grayscale(),s=fg(r.data)[0],c=Qt(r.data)[0]-s;if(c===0)return e;const u=n/255;let d=r.width,h=r.height,p=0,g=0;const y=r.data;for(let w=0;wthis.preprocess(o)));return{pixel_values:Cl(r.map(o=>o.pixel_values),0),original_sizes:r.map(o=>o.original_size),reshaped_input_sizes:r.map(o=>o.reshaped_input_size)}}static async from_pretrained(e,n={}){const r=await Lr(e,Qg,!0,n);return new this(r)}},bh={};Sl(bh,{BeitFeatureExtractor:()=>ML,BitImageProcessor:()=>xL,CLIPFeatureExtractor:()=>SL,CLIPImageProcessor:()=>Ux,ChineseCLIPFeatureExtractor:()=>TL,ConvNextFeatureExtractor:()=>EL,ConvNextImageProcessor:()=>Ix,DINOv3ViTImageProcessor:()=>kL,DPTFeatureExtractor:()=>zL,DPTImageProcessor:()=>Vx,DeiTFeatureExtractor:()=>AL,DeiTImageProcessor:()=>Gx,DetrFeatureExtractor:()=>CL,DetrImageProcessor:()=>jx,DonutFeatureExtractor:()=>OL,DonutImageProcessor:()=>Zg,EfficientNetImageProcessor:()=>LL,GLPNFeatureExtractor:()=>NL,GroundingDinoImageProcessor:()=>DL,Idefics3ImageProcessor:()=>F1,ImageFeatureExtractor:()=>He,ImageProcessor:()=>He,JinaCLIPImageProcessor:()=>BL,LlavaOnevisionImageProcessor:()=>PL,Mask2FormerImageProcessor:()=>UL,MaskFormerFeatureExtractor:()=>RL,MaskFormerImageProcessor:()=>Kg,MobileNetV1FeatureExtractor:()=>IL,MobileNetV1ImageProcessor:()=>qx,MobileNetV2FeatureExtractor:()=>GL,MobileNetV2ImageProcessor:()=>$x,MobileNetV3FeatureExtractor:()=>jL,MobileNetV3ImageProcessor:()=>Hx,MobileNetV4FeatureExtractor:()=>VL,MobileNetV4ImageProcessor:()=>Yx,MobileViTFeatureExtractor:()=>qL,MobileViTImageProcessor:()=>Xx,NougatImageProcessor:()=>$L,OwlViTFeatureExtractor:()=>HL,OwlViTImageProcessor:()=>Jg,Owlv2ImageProcessor:()=>YL,Phi3VImageProcessor:()=>QL,PixtralImageProcessor:()=>WL,PvtImageProcessor:()=>ZL,Qwen2VLImageProcessor:()=>KL,RTDetrImageProcessor:()=>JL,Sam2ImageProcessor:()=>x_,Sam3ImageProcessor:()=>x_,SamImageProcessor:()=>x_,SapiensFeatureExtractor:()=>e4,SapiensImageProcessor:()=>Qx,SegformerFeatureExtractor:()=>t4,SegformerImageProcessor:()=>Wx,SiglipImageProcessor:()=>n4,SmolVLMImageProcessor:()=>F1,Swin2SRImageProcessor:()=>a4,VLMImageProcessor:()=>FL,ViTFeatureExtractor:()=>r4,ViTImageProcessor:()=>Zx,VitMatteImageProcessor:()=>s4,VitPoseImageProcessor:()=>i4,YolosFeatureExtractor:()=>o4,YolosImageProcessor:()=>Kx});var ML=class extends He{},xL=class extends He{},TL=class extends He{},Ux=class extends He{},SL=class extends Ux{},Ix=class extends He{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){var r;const n=(r=this.size)==null?void 0:r.shortest_edge;if(n===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(n<384){const s=Math.floor(n/this.crop_pct),[o,c]=this.get_resize_output_image_size(e,{shortest_edge:s});e=await e.resize(o,c,{resample:this.resample}),e=await e.center_crop(n,n)}else e=await e.resize(n,n,{resample:this.resample});return e}},EL=class extends Ix{},Gx=class extends He{},AL=class extends Gx{},jx=class extends He{async _call(e){const n=await super._call(e),r=[n.pixel_values.dims[0],64,64],s=zn(r,1n);return{...n,pixel_mask:s}}post_process_object_detection(...e){return Oh(...e)}post_process_panoptic_segmentation(...e){return Px(...e)}post_process_instance_segmentation(...e){return Rx(...e)}},CL=class extends jx{},kL=class extends He{},Zg=class extends He{pad_image(e,n,r,s={}){const[o,c,u]=n;let d=this.image_mean;Array.isArray(this.image_mean)||(d=new Array(u).fill(d));let h=this.image_std;Array.isArray(h)||(h=new Array(u).fill(d));const p=d.map((g,y)=>-g/h[y]);return super.pad_image(e,n,r,{center:!0,constant_values:p,...s})}},OL=class extends Zg{},Vx=class extends He{},zL=class extends Vx{},LL=class extends He{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(n=>n*n))}},NL=class extends He{},DL=class extends He{async _call(e){const n=await super._call(e),r=n.pixel_values.dims,s=Fa([r[0],r[2],r[3]]);return{...n,pixel_mask:s}}},F1=class extends He{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,n){let[r,s]=e.dims.slice(-2);const o=s/r;return s>=r?(s=Math.ceil(s/n)*n,r=Math.floor(s/o),r=Math.ceil(r/n)*n):(r=Math.ceil(r/n)*n,s=Math.floor(r*o),s=Math.ceil(s/n)*n),{height:r,width:s}}async _call(e,{do_image_splitting:n=null,return_row_col_info:r=!1}={}){let s;if(!Array.isArray(e))s=[[e]];else{if(e.length===0||!e[0])throw new Error("No images provided.");Array.isArray(e[0])?s=e:s=[e]}let o=[],c=[],u=[];const d=[],h=[];for(const O of s){let z=await Promise.all(O.map(j=>this.preprocess(j)));d.push(...z.map(j=>j.original_size)),h.push(...z.map(j=>j.reshaped_input_size)),z.forEach(j=>j.pixel_values.unsqueeze_(0));const{longest_edge:D}=this.max_image_size;let P;if(n??this.do_image_splitting){let j=new Array(z.length),G=new Array(z.length);P=await Promise.all(z.map(async(K,k)=>{const ce=this.get_resize_for_vision_encoder(K.pixel_values,D),oe=await oi(K.pixel_values,{size:[ce.height,ce.width]}),{frames:he,num_splits_h:me,num_splits_w:pe}=await this.split_image(oe,this.max_image_size);return j[k]=me,G[k]=pe,Pt(he,0)})),c.push(j),u.push(G)}else{const j=[D,D];P=await Promise.all(z.map(G=>oi(G.pixel_values,{size:j}))),c.push(new Array(z.length).fill(0)),u.push(new Array(z.length).fill(0))}o.push(Pt(P,0))}const p=o.length,[g,y,w,b]=o[0].dims;let S,E;if(p===1)S=o[0].unsqueeze_(0),E=zn([p,g,w,b],!0);else{const O=Math.max(...o.map(P=>P.dims.at(0)));E=zn([p,O,w,b],!0);const z=E.data,D=O*w*b;for(let P=0;Pr||u>s){d=Math.ceil(c/r),h=Math.ceil(u/s);const p=Math.ceil(c/d),g=Math.ceil(u/h);for(let b=0;bn*this.rescale_factor)}pad_image(e,n,r,s){return super.pad_image(e,n,r,{constant_values:this.constant_values,center:!0,...s})}},BL=class extends He{constructor(e){const{resize_mode:n,fill_color:r,interpolation:s,size:o,...c}=e,u=n==="squash"?{width:o,height:o}:n==="shortest"?{shortest_edge:o}:{longest_edge:o},d=s==="bicubic"?3:2;super({...c,size:u,resample:d,do_center_crop:!0,crop_size:o,do_normalize:!0})}},PL=class extends He{},Kg=class extends He{post_process_panoptic_segmentation(...e){return Px(...e)}post_process_instance_segmentation(...e){return Rx(...e)}},RL=class extends Kg{},UL=class extends Kg{},qx=class extends He{},IL=class extends qx{},$x=class extends He{},GL=class extends $x{},Hx=class extends He{},jL=class extends Hx{},Yx=class extends He{},VL=class extends Yx{},Xx=class extends He{},qL=class extends Xx{},$L=class extends Zg{},Jg=class extends He{post_process_object_detection(...e){return Oh(...e)}},HL=class extends Jg{},YL=class extends Jg{},ua=336,XL=[2,3],{ceil:b_,floor:ml,sqrt:M_}=Math,QL=class extends He{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,n){const{num_img_tokens:r}=this.config;return ml((ml(n/ua)*ml(e/ua)+1)*r+1+(ml(n/ua)+1)*M_(r))}get_resize_output_image_size(e,n){const r=this._num_crops,[s,o]=e.size;let c=s/o,u=1;for(;u*Math.ceil(u/c)<=r;)u+=1;u-=1;const d=Math.floor(u*336),h=Math.floor(d/c);return[d,h]}pad_image(e,n,r,s={}){const[o,c]=n,u=ua*b_(o/ua),d=ua*b_(c/ua),h=[1,1,1].map((p,g)=>(p-this.image_mean[g])/this.image_std[g]);return super.pad_image(e,n,{width:d,height:u},{center:!0,constant_values:h,...s})}async _call(e,{num_crops:n=null}={}){if(this._num_crops=n??(n=this.config.num_crops),n<4||M_(n)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(e)||(e=[e]);const r=e.length,s=await Promise.all(e.map(y=>this.preprocess(y))),o=s.map(y=>y.original_size),c=s.map(y=>y.reshaped_input_size),u=[];for(const{pixel_values:y}of s){y.unsqueeze_(0);const[w,b]=y.dims.slice(-2),S=await oi(y,{size:[ua,ua],mode:"bicubic"});if(n>0){const E=[],O=M_(n),z=ml(b/O),D=ml(w/O);for(let j=0;jy.map(w=>ua*b_(w/ua))),p=new we("int64",h.flat(),[r,2]),g=h.map(([y,w])=>this.calc_num_image_tokens_from_image_size(w,y));return{pixel_values:d,original_sizes:o,reshaped_input_sizes:c,image_sizes:p,num_img_tokens:g}}},WL=class extends He{get_resize_output_image_size(e,n){const{longest_edge:r}=n;if(r===void 0)throw new Error("size must contain 'longest_edge'");const[s,o]=e.size,c=Math.max(s,o)/r;let u=s,d=o;c>1&&(u=Math.floor(s/c),d=Math.floor(o/c));const{patch_size:h,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");const g=h*p,y=Math.floor((u-1)/g)+1,w=Math.floor((d-1)/g)+1;return[y*g,w*g]}},ZL=class extends He{},KL=class extends He{async _call(e,...n){const{pixel_values:r,original_sizes:s,reshaped_input_sizes:o}=await super._call(e,...n);let c=r;const{temporal_patch_size:u,merge_size:d,patch_size:h}=this.config;c.dims[0]===1&&(c=Pt(Array.from({length:u},()=>c),0));const p=c.dims[0]/u,g=c.dims[1],y=Math.floor(c.dims[2]/h),w=Math.floor(c.dims[3]/h),b=c.view(p,u,g,Math.floor(y/d),d,h,Math.floor(w/d),d,h).permute(0,3,6,4,7,2,1,5,8).view(p*y*w,g*u*h*h),S=new we("int64",[p,y,w],[1,3]);return{pixel_values:b,image_grid_thw:S,original_sizes:s,reshaped_input_sizes:o}}},JL=class extends He{post_process_object_detection(...e){return Oh(...e)}},x_=class extends He{reshape_input_points(e,n,r,s=!1){e=structuredClone(e);let o=w1(e);if(o.length===3)s||(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 c=0;cs!==n.dims[o]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new we("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:n=null,input_labels:r=null,input_boxes:s=null}={}){const o=await super._call(e);if(n&&(o.input_points=this.reshape_input_points(n,o.original_sizes,o.reshaped_input_sizes)),r){if(!o.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");o.input_labels=this.add_input_labels(r,o.input_points)}return s&&(o.input_boxes=this.reshape_input_points(s,o.original_sizes,o.reshaped_input_sizes,!0)),o}async post_process_masks(e,n,r,{mask_threshold:s=0,binarize:o=!0,pad_size:c=null}={}){const u=[];c=c??this.pad_size??this.size;const d=[c.height,c.width];for(let h=0;hs&&(b[S]=1);y=new we("bool",b,y.dims)}u.push(y)}return u}generate_crop_boxes(e,n,{crop_n_layers:r=0,overlap_ratio:s=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:c=1}={}){}},Qx=class extends He{post_process_semantic_segmentation(...e){return Bx(...e)}},e4=class extends Qx{},Wx=class extends He{post_process_semantic_segmentation(...e){return Bx(...e)}},t4=class extends Wx{},n4=class extends He{},a4=class extends He{pad_image(e,n,r,s={}){const[o,c,u]=n;return super.pad_image(e,n,{width:c+(r-c%r)%r,height:o+(r-o%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...s})}},Zx=class extends He{},r4=class extends Zx{},s4=class extends He{async _call(e,n){Array.isArray(e)||(e=[e]),Array.isArray(n)||(n=[n]);const r=await Promise.all(e.map(c=>this.preprocess(c))),s=await Promise.all(n.map(c=>this.preprocess(c,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Cl(r.map((c,u)=>Pt([c.pixel_values,s[u].pixel_values],0)),0),original_sizes:r.map(c=>c.original_size),reshaped_input_sizes:r.map(c=>c.reshaped_input_size)}}},i4=class extends He{post_process_pose_estimation(e,n,{threshold:r=null}={}){const s=e.tolist(),[o,c,u,d]=e.dims,h=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);const n=[];for(const r of e)if(this.task_prompts_without_inputs.has(r))n.push(this.task_prompts_without_inputs.get(r));else{for(const[s,o]of this.task_prompts_with_input)if(r.includes(s)){n.push(o.replaceAll("{input}",r).replaceAll(s,""));break}n.length!==e.length&&n.push(r)}return n}post_process_generation(e,n,r){const s=this.tasks_answer_post_processing_type.get(n)??"pure_text";e=e.replaceAll("","").replaceAll("","");let o;switch(s){case"pure_text":o=e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const c=s==="ocr"?"quad_boxes":"bboxes",u=e.matchAll(this.regexes[c]),d=[],h=[];for(const[p,g,...y]of u)d.push(g?g.trim():d.at(-1)??""),h.push(y.map((w,b)=>(Number(w)+.5)/this.size_per_bin*r[b%2]));o={labels:d,[c]:h};break;default:throw new Error(`Task "${n}" (of type "${s}") not yet implemented.`)}return{[n]:o}}async _call(e,n=null,r={}){if(!e&&!n)throw new Error("Either text or images must be provided");const s=await this.image_processor(e,r),o=n?this.tokenizer(this.construct_prompts(n),r):{};return{...s,...o}}},L(qf,"tokenizer_class",$e),L(qf,"image_processor_class",ea),qf),ji,c4=(ji=class extends At{constructor(e,n,r){super(e,n,r),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:s,boa_token:o,audio_token:c,eoa_token:u,image_token_id:d,boi_token:h,image_token:p,eoi_token:g}=this.tokenizer.config;this.audio_token_id=s,this.boa_token=o,this.audio_token=c;const y=c.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${o}${y}${u} + +`,this.image_token_id=d,this.boi_token=h,this.image_token=p;const w=p.repeat(this.image_seq_length);this.full_image_sequence=` + +${h}${w}${g} + +`}async _call(e,n=null,r=null,s={}){typeof e=="string"&&(e=[e]);let o;r&&(o=await this.feature_extractor(r,s),e=e.map(d=>d.replaceAll(this.audio_token,this.full_audio_sequence)));let c;return n&&(c=await this.image_processor(n,s),e=e.map(d=>d.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,s),...c,...o}}},L(ji,"image_processor_class",ea),L(ji,"feature_extractor_class",ms),L(ji,"tokenizer_class",$e),L(ji,"uses_processor_config",!0),L(ji,"uses_chat_template_file",!0),ji);function u4(e,n){const s=e.dims.at(-1)-1,o=e.tolist();o.fill(!1,0,1),o.fill(!1,s);const c=n.tolist();return o.map((u,d)=>u?d:null).filter(u=>u!==null).map(u=>c[u])}var $f,d4=($f=class extends At{async _call(e,n,r={}){const s=e?await this.image_processor(e,r):{};return{...n?this.tokenizer(n,r):{},...s}}post_process_grounded_object_detection(e,n,{box_threshold:r=.25,text_threshold:s=.25,target_sizes:o=null}={}){const{logits:c,pred_boxes:u}=e,d=c.dims[0];if(o!==null&&o.length!==d)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const h=c.dims.at(1),p=c.sigmoid(),g=p.max(-1).tolist(),y=u.tolist().map(b=>b.map(S=>Fx(S))),w=[];for(let b=0;bP.map((j,G)=>j*S[(G+1)%2])));const E=g[b],O=[],z=[],D=[];for(let P=0;P`+o.repeat(e);u+=` +`}return u+=` +${s}${c}`+o.repeat(e)+`${s}`,u}function h4(e,n,r,s){return`${n}${s}`+r.repeat(e)+`${n}`}function p4(e,n,r,s,o,c){return e===0&&n===0?h4(r,s,o,c):f4(r,e,n,s,o,c)}var Cu,B1=(Cu=class extends At{constructor(){super(...arguments);L(this,"fake_image_token","");L(this,"image_token","");L(this,"global_img_token","")}async _call(n,r=null,s={}){s.return_row_col_info??(s.return_row_col_info=!0);let o;r&&(o=await this.image_processor(r,s)),Array.isArray(n)||(n=[n]);const c=o.rows??[new Array(n.length).fill(0)],u=o.cols??[new Array(n.length).fill(0)],d=this.config.image_seq_len,h=[],p=[];for(let y=0;yp4(D,S[P],d,this.fake_image_token,this.image_token,this.global_img_token)),O=w.split(this.image_token);if(O.length===0)throw new Error("The image token should be present in the text.");let z=O[0];for(let D=0;DE.images).flatMap(E=>E.images).map(E=>rr.read(E)));const s=this.tokenizer,o=s.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),c=E=>s.encode(E,{add_special_tokens:!1}),u=o.split(this.image_tag),d=u.length-1;if(n.length!==d)throw new Error(`Number of images provided (${n.length}) does not match number of "${this.image_tag}" image tags (${d})`);const[h,p,g]=s.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let y=c(u[0]),w=new Array(y.length).fill(!1);for(let E=1;E0){const E=await this.image_processor(n);return E.pixel_values.unsqueeze_(0),{...S,...E}}return S}},L(ku,"image_processor_class",ea),L(ku,"tokenizer_class",$e),L(ku,"uses_processor_config",!0),ku),Hf,_4=(Hf=class extends At{async _call(e=null,n=null,r={}){if(!e&&!n)throw new Error("Either text or images must be provided");const s=e?this.tokenizer(e,r):{},o=n?await this.image_processor(n,r):{};return{...s,...o}}},L(Hf,"tokenizer_class",$e),L(Hf,"image_processor_class",ea),Hf),Ou,g4=(Ou=class extends At{async _call(e,n=null,r={}){const s=await this.image_processor(e,r);if(n){const[c,u]=s.pixel_values.dims.slice(-2),{image_token:d,patch_size:h,num_additional_image_tokens:p}=this.config,g=Math.floor(c/h)*Math.floor(u/h)+p;n=structuredClone(n),Array.isArray(n)||(n=[n]);for(let y=0;y0?S.reduce((O,z)=>O*z,1):0;h.push(b),d.push(E)}return[o(h),d]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(n=>n.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(n=>n.replaceAll(" ",""))}batch_decode([e,n,r]){const[s,o]=this._decode_helper(e,"char"),[c,u]=this._decode_helper(n,"bpe"),[d,h]=this._decode_helper(r,"wp"),p=[],g=[];for(let y=0;yh.includes(_l))?c=n.map(h=>{const p=h.replaceAll(_l,_l.repeat(o)),g=p.lastIndexOf(_l),y=g===-1?0:g+_l.length;return p.slice(0,y)+s+p.slice(y)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),c=n.map(h=>b4(h,s,o,_l,e.length)));const u=this.tokenizer(c,r);return{...await this.image_processor(e,r),...u}}},L(zu,"tokenizer_class",$e),L(zu,"image_processor_class",ea),L(zu,"uses_processor_config",!1),zu),R1="<|image|>",x4=/<\|image_\d+\|>/g,Wf,T4=(Wf=class extends At{async _call(e,n=null,{padding:r=!0,truncation:s=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let c,u;if(n){u=await this.image_processor(n,{num_crops:o});const{num_img_tokens:d}=u,h=e.map((g,y)=>g.split(x4).join(R1.repeat(d[y])));c=this.tokenizer(h,{padding:r,truncation:s});const p=this.tokenizer._tokenizer.token_to_id(R1);c.input_ids.map_(g=>g==p?-g:g)}else c=this.tokenizer(e);return{...c,...u}}},L(Wf,"image_processor_class",ea),L(Wf,"tokenizer_class",$e),Wf),Lu,S4=(Lu=class extends At{async _call(e,n=null,r={}){const s=await this.image_processor(e,r);if(n){const[c,u]=s.pixel_values.dims.slice(-2),{image_token:d,image_break_token:h,image_end_token:p,patch_size:g,spatial_merge_size:y}=this.config,w=g*y,b=Math.floor(c/w),S=Math.floor(u/w);n=structuredClone(n),Array.isArray(n)||(n=[n]);for(let E=0;E{for(;p.includes("<|image_pad|>");){const g=Number(h[d++].reduce((y,w)=>y*w,1n));p=p.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(g/u)))}return p.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(e),...s}}},L(Zf,"image_processor_class",ea),L(Zf,"tokenizer_class",$e),Zf),A_,Jx=(A_=class extends At{async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}},L(A_,"image_processor_class",ea),A_),e2=class extends Jx{},C4=class extends e2{},Kf,k4=(Kf=class extends At{async _call(e){return await this.feature_extractor(e)}},L(Kf,"tokenizer_class",$e),L(Kf,"feature_extractor_class",ms),Kf),Nu,O4=(Nu=class extends At{async _call(e,n=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(n){const c=n.length,{input_features:u}=await this.feature_extractor(n,{...r,max_length:c}),d=Math.round(c/this.config.encoder_ds_factor+1e-4),h=1+Math.ceil(d/this.config.stack_factor);s.audio_token_len=[h],s.audio_values=u;const p=this.config.audio_placeholder;if(!e.includes(p))throw new Error(`The input text does not contain the image token ${p}.`);e=e.replaceAll(p,p.repeat(h))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},L(Nu,"tokenizer_class",$e),L(Nu,"feature_extractor_class",ms),L(Nu,"uses_processor_config",!0),Nu),If="[AUDIO]",z4="[BEGIN_AUDIO]",L4=375;function N4(e,n){const r=[];for(let s=0;sN4(b,d)),p=h.map(b=>b.length),g=h.flat(),y=(await Promise.all(g.map(b=>this.feature_extractor(b,r)))).map(b=>b.input_features);s.audio_values=y.length>1?Pt(y,0):y[0];let w=c[0];for(let b=0;bb1)throw new Error(`The number of external data chunks (${g}) exceeds the maximum allowed value (${b1}).`);for(let y=0;y{const O=await yh(e,b,!0,s,d);S(O instanceof Uint8Array?{path:w,data:O}:w)}))}}else c.externalData!==void 0&&(h=c.externalData.map(async p=>{if(typeof p.data=="string"){const g=await yh(e,p.data,!0,s);return{...p,data:g}}return p}));return Promise.all(h)}async function V4(e,n,r,s=!1){var G;let o=((G=r.config)==null?void 0:G["transformers.js_config"])??{},c=r.device??o.device;c&&typeof c!="string"&&(c.hasOwnProperty(n)?c=c[n]:(console.warn(`device not specified for "${n}". Using the default device.`),c=null));const u=c??(Nt.IS_NODE_ENV?"cpu":"wasm"),d=L3(u),h=o.device_config??{};h.hasOwnProperty(u)&&(o={...o,...h[u]});let p=r.dtype??o.dtype;if(typeof p!="string"&&(p&&p.hasOwnProperty(n)?p=p[n]:(p=A1[u]??On.fp32,console.warn(`dtype not specified for "${n}". Using the default dtype (${p}) for this device (${u}).`))),p===On.auto){let K=o.dtype;typeof K!="string"&&(K=K==null?void 0:K[n]),K&&K!==On.auto&&On.hasOwnProperty(K)?p=K:p=A1[u]??On.fp32}const g=p;if(C1.hasOwnProperty(g)){if(u==="webgpu"&&!Nt.IS_NODE_ENV&&g===On.fp16&&!await F3())throw new Error(`The device (${u}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${g}. Should be one of: ${Object.keys(On).join(", ")}`);const y=o.kv_cache_dtype,w=y?typeof y=="string"?y:y[g]??"float32":void 0;if(w&&!["float32","float16"].includes(w))throw new Error(`Invalid kv_cache_dtype: ${w}. Should be one of: float32, float16`);const b=C1[g],S={...r.session_options};S.executionProviders??(S.executionProviders=d);const E=o.free_dimension_overrides;E?S.freeDimensionOverrides??(S.freeDimensionOverrides=E):u.startsWith("webnn")&&!S.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${u}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const O=G4(e,n,r,b),z=r.use_external_data_format??o.use_external_data_format,D=await j4(e,n,b,r,z,S);if(D.length>0&&!Nt.IS_NODE_ENV&&(S.externalData=D),s&&u==="webgpu"&&y!==!1){const K=t2(r.config,{prefix:"present"});if(Object.keys(K).length>0&&!Vg()){const k={};for(const ce in K)k[ce]="gpu-buffer";S.preferredOutputLocation=k}}return{buffer_or_path:await O,session_options:S,session_config:{dtype:g,kv_cache_dtype:w,device:u}}}async function Zn(e,n,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(n).map(async o=>{const{buffer_or_path:c,session_options:u,session_config:d}=await V4(e,n[o],r,o===s),h=await mx(c,u,d);return[o,h]})))}function a2(e){for(let n in e)gx(e[n])?e[n]=new we(e[n]):typeof e[n]=="object"&&a2(e[n]);return e}async function rt(e,n){const r=q4(e,n);try{const s=Object.fromEntries(Object.entries(r).map(([c,u])=>{const d=u.ort_tensor;return Nt.IS_NODE_ENV&&typeof Float16Array<"u"&&d.cpuData instanceof Float16Array&&(d.cpuData=new Uint16Array(d.cpuData.buffer)),[c,d]})),o=await _x(e,s);return a2(o)}catch(s){const o=Object.fromEntries(Object.entries(r).map(([c,u])=>{const d={type:u.type,dims:u.dims,location:u.location};return d.location!=="gpu-buffer"&&(d.data=u.data),[c,d]}));throw console.error(`An error occurred during model execution: "${s}".`),console.error("Inputs given to model:",o),s}}function q4(e,n){const r=Object.create(null),s=[];for(const u of e.inputNames){const d=n[u];if(!(d instanceof we)){s.push(u);continue}r[u]=Vg()?d.clone():d}if(s.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${s.join(", ")}.`);const o=Object.keys(n).length,c=e.inputNames.length;if(o>c){let u=Object.keys(n).filter(d=>!e.inputNames.includes(d));console.warn(`WARNING: Too many inputs were provided (${o} > ${c}). The following inputs will be ignored: "${u.join(", ")}".`)}return r}var rn=class{},Pe=class extends rn{constructor({logits:e,...n}){super(),this.logits=e;const r=Object.values(n);r.length>0&&(this.attentions=r)}},sn=class extends rn{constructor({logits:e}){super(),this.logits=e}},dn=class extends rn{constructor({logits:e}){super(),this.logits=e}},Ln=class extends rn{constructor({start_logits:e,end_logits:n}){super(),this.start_logits=e,this.end_logits=n}},ao=class extends rn{constructor({logits:e}){super(),this.logits=e}},$4=class extends rn{constructor({alphas:e}){super(),this.alphas=e}},Dr=class extends Ba{_call(e,n){throw Error("`_call` should be implemented in a subclass")}},H4=class extends Ba{_call(e,n){throw Error("`_call` should be implemented in a subclass")}},vg=class extends Ba{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,n){let r=n;for(const s of this.processors)r=s(e,r);return r}[Symbol.iterator](){return this.processors.values()}},Y4=class extends Dr{constructor(e){super(),this.bos_token_id=e}_call(e,n){for(let r=0;r=1&&o[o.length-1]>=this.timestamp_begin,u=o.length<2||o[o.length-2]>=this.timestamp_begin;if(c&&(u?s.subarray(this.timestamp_begin).fill(-1/0):s.subarray(0,this.eos_token_id).fill(-1/0)),e[r].length===this.begin_index&&this.max_initial_timestamp_index!==null){const g=this.timestamp_begin+this.max_initial_timestamp_index;s.subarray(g+1).fill(-1/0)}const d=p3(s),h=Math.log(d.subarray(this.timestamp_begin).map(Math.exp).reduce((g,y)=>g+y)),p=Qt(d.subarray(0,this.timestamp_begin))[0];h>p&&s.subarray(0,this.timestamp_begin).fill(-1/0)}return n}},W4=class extends Dr{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const n=e.length,r=[];for(let o=0;o1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,n){if(n.dims[0]!==2*e.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${n.dims[0]} for the logits and ${e.length} for the input ids.`);const r=e.length,s=n.slice([0,r],null),o=n.slice([r,n.dims[0]],null);for(let c=0;cn.length>=this.max_length)}},sN=class extends ev{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,n){return e.map(r=>{const s=r.at(-1);return this.eos_token_id.some(o=>s==o)})}},zh=class extends Ba{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error("sample should be implemented in subclasses.")}getLogits(e,n){let r=e.dims.at(-1),s=e.data;if(n===-1)s=s.slice(-r);else{let o=n*r;s=s.slice(o,o+r)}return s}randomSelect(e){let n=0;for(let s=0;s1)return new lN(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new iN(e)}},iN=class extends zh{async sample(e){const n=Qt(e.data)[1];return[[BigInt(n),0]]}},oN=class extends zh{async sample(e){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const[r,s]=await Al(e,n),o=bn(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const c=this.randomSelect(o);return[s.data[c],Math.log(o[c])]})}},lN=class extends zh{async sample(e){let n=e.dims.at(-1);this.generation_config.top_k>0&&(n=Math.min(this.generation_config.top_k,n));const[r,s]=await Al(e,n),o=bn(r.data);return Array.from({length:this.generation_config.num_beams},(c,u)=>[s.data[u],Math.log(o[u])])}},Ru=null;function cN(e){Ru=e}function yg(e){if(e instanceof we)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(n=>n.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new we("int64",BigInt64Array.from(e.flat().map(n=>BigInt(n))),[e.length,e[0].length])}else return new we("int64",BigInt64Array.from(e.map(n=>BigInt(n))),[1,e.length])}function o2(e){return new we("bool",[e],[1])}var ye={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15},U1={[ye.DecoderOnly]:{can_generate:!0,forward:hs,prepare_inputs:Mh},[ye.DecoderOnlyWithoutHead]:{can_generate:!1,forward:hs,prepare_inputs:Mh},[ye.Seq2Seq]:{can_generate:!0,forward:Gf,prepare_inputs:xh},[ye.Vision2Seq]:{can_generate:!0,forward:Gf,prepare_inputs:xh},[ye.Musicgen]:{can_generate:!0,forward:Gf},[ye.EncoderDecoder]:{can_generate:!1,forward:Gf},[ye.ImageTextToText]:{can_generate:!0,forward:fN,prepare_inputs:jf},[ye.AudioTextToText]:{can_generate:!0,forward:dN,prepare_inputs:jf},[ye.Phi3V]:{can_generate:!0,prepare_inputs:jf},[ye.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:jf},[ye.MultiModality]:{can_generate:!0},[ye.AutoEncoder]:{can_generate:!1,forward:uN},[ye.Chatterbox]:{can_generate:!0,forward:ci},default:{can_generate:!1,forward:ci}},xl=new Map,tv=new Map,Ml=new Map,Y=class extends Ba{constructor(n,r,s){super();L(this,"main_input_name","input_ids");L(this,"forward_params",["input_ids","attention_mask"]);L(this,"_return_dict_in_generate_keys",null);this.config=n,this.sessions=r,this.configs=s;const o=Ml.get(this.constructor),c=xl.get(o),u=U1[c]??U1.default;this.can_generate=u.can_generate,this._forward=u.forward,this._prepare_inputs_for_generation=u.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var r;const n=[];for(const s of Object.values(this.sessions))n.push((r=s.release)==null?void 0:r.call(s));return await Promise.all(n)}static async from_pretrained(n,{progress_callback:r=null,config:s=null,cache_dir:o=null,local_files_only:c=!1,revision:u="main",model_file_name:d=null,subfolder:h="onnx",device:p=null,dtype:g=null,use_external_data_format:y=null,session_options:w={}}={}){const b={progress_callback:r,config:s,cache_dir:o,local_files_only:c,revision:u,model_file_name:d,subfolder:h,device:p,dtype:g,use_external_data_format:y,session_options:w},S=Ml.get(this),E=xl.get(S);s=b.config=await n2.from_pretrained(n,b);let O;if(E===ye.DecoderOnly)O=await Promise.all([Zn(n,{model:b.model_file_name??"model"},b,"model"),ds(n,{generation_config:"generation_config.json"},b)]);else if(E===ye.Seq2Seq||E===ye.Vision2Seq)O=await Promise.all([Zn(n,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},b,"decoder_model_merged"),ds(n,{generation_config:"generation_config.json"},b)]);else if(E===ye.MaskGeneration)O=await Promise.all([Zn(n,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},b)]);else if(E===ye.EncoderDecoder)O=await Promise.all([Zn(n,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},b,"decoder_model_merged")]);else if(E===ye.ImageTextToText){const z={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};s.is_encoder_decoder&&(z.model="encoder_model"),O=await Promise.all([Zn(n,z,b,"decoder_model_merged"),ds(n,{generation_config:"generation_config.json"},b)])}else if(E===ye.AudioTextToText){const z={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};O=await Promise.all([Zn(n,z,b,"decoder_model_merged"),ds(n,{generation_config:"generation_config.json"},b)])}else if(E===ye.ImageAudioTextToText){const z={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};O=await Promise.all([Zn(n,z,b),ds(n,{generation_config:"generation_config.json"},b)])}else if(E===ye.Musicgen)O=await Promise.all([Zn(n,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},b,"decoder_model_merged"),ds(n,{generation_config:"generation_config.json"},b)]);else if(E===ye.MultiModality)O=await Promise.all([Zn(n,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},b,"model"),ds(n,{generation_config:"generation_config.json"},b)]);else if(E===ye.Phi3V)O=await Promise.all([Zn(n,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},b,"model"),ds(n,{generation_config:"generation_config.json"},b)]);else if(E===ye.Chatterbox)O=await Promise.all([Zn(n,{embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"},b,"model"),ds(n,{generation_config:"generation_config.json"},b)]);else if(E===ye.AutoEncoder)O=await Promise.all([Zn(n,{encoder_model:"encoder_model",decoder_model:"decoder_model"},b)]);else if(E===ye.Supertonic)O=await Promise.all([Zn(n,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},b)]);else{if(E===void 0){const z=S??(s==null?void 0:s.model_type);z!=="custom"&&console.warn(`Model type for '${z}' not found, assuming encoder-only architecture. Please report this at ${Yg}.`)}O=await Promise.all([Zn(n,{model:b.model_file_name??"model"},b)])}return new this(s,...O)}async _call(n){return await this.forward(n)}async forward(n){return await this._forward(this,n)}get generation_config(){var n;return((n=this.configs)==null?void 0:n.generation_config)??null}_get_logits_processor(n,r,s=null){const o=new vg;if(n.repetition_penalty!==null&&n.repetition_penalty!==1&&o.push(new Z4(n.repetition_penalty)),n.no_repeat_ngram_size!==null&&n.no_repeat_ngram_size>0&&o.push(new W4(n.no_repeat_ngram_size)),n.bad_words_ids!==null&&o.push(new eN(n.bad_words_ids,n.eos_token_id)),n.min_length!==null&&n.eos_token_id!==null&&n.min_length>0&&o.push(new K4(n.min_length,n.eos_token_id)),n.min_new_tokens!==null&&n.eos_token_id!==null&&n.min_new_tokens>0&&o.push(new J4(r,n.min_new_tokens,n.eos_token_id)),n.forced_bos_token_id!==null&&o.push(new Y4(n.forced_bos_token_id)),n.forced_eos_token_id!==null&&o.push(new X4(n.max_length,n.forced_eos_token_id)),n.begin_suppress_tokens!==null){const c=r>1||n.forced_bos_token_id===null?r:r+1;o.push(new r2(n.begin_suppress_tokens,c))}return n.guidance_scale!==null&&n.guidance_scale>1&&o.push(new tN(n.guidance_scale)),n.temperature===0&&n.do_sample&&(console.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),n.do_sample=!1),n.do_sample&&n.temperature!==null&&n.temperature!==1&&o.push(new nN(n.temperature)),s!==null&&o.extend(s),o}_prepare_generation_config(n,r,s=s2){const o={...this.config};for(const u of["decoder","generator","text_config"])u in o&&Object.assign(o,o[u]);const c=new s(o);return Object.assign(c,this.generation_config??{}),n&&Object.assign(c,n),r&&Object.assign(c,Kn(r,Object.getOwnPropertyNames(c))),c}_get_stopping_criteria(n,r=null){const s=new aN;return n.max_length!==null&&s.push(new rN(n.max_length,this.config.max_position_embeddings??null)),n.eos_token_id!==null&&s.push(new sN(n.eos_token_id)),r&&s.extend(r),s}_validate_model_class(){if(!this.can_generate){const n=[Ru.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Ru.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Ru.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Ru.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),r=Ml.get(this.constructor),s=new Set,o=this.config.model_type;for(const u of n){const d=u==null?void 0:u.get(o);d&&s.add(d)}let c=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw s.size>0&&(c+=` Please use the following class instead: ${[...s].join(", ")}`),Error(c)}}prepare_inputs_for_generation(...n){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...n)}_update_model_kwargs_for_generation({generated_input_ids:n,outputs:r,model_inputs:s,is_encoder_decoder:o}){return s.past_key_values=this.getPastKeyValues(r,s.past_key_values),s.input_ids=new we("int64",n.flat(),[n.length,1]),o||(s.attention_mask=Pt([s.attention_mask,Fa([s.attention_mask.dims[0],1])],1)),s.position_ids=null,s}_prepare_model_inputs({inputs:n,bos_token_id:r,model_kwargs:s}){const o=Kn(s,this.forward_params),c=this.main_input_name;if(c in o){if(n)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else o[c]=n;return{inputs_tensor:o[c],model_inputs:o,model_input_name:c}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:n,model_inputs:r,model_input_name:s,generation_config:o}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!r.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:u,pixel_values:d,attention_mask:h,...p}=r,g=await this._prepare_inputs_embeds(r);r={...p,...Kn(g,["inputs_embeds","attention_mask"])}}let{last_hidden_state:c}=await ci(this,r);if(o.guidance_scale!==null&&o.guidance_scale>1)c=Pt([c,pg(c,0)],0),"attention_mask"in r&&(r.attention_mask=Pt([r.attention_mask,Mx(r.attention_mask)],0));else if(r.decoder_input_ids){const u=yg(r.decoder_input_ids).dims[0];if(u!==c.dims[0]){if(c.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${c.dims[0]}) than the decoder inputs (${u}).`);c=Pt(Array.from({length:u},()=>c),0)}}return r.encoder_outputs=c,r}_prepare_decoder_input_ids_for_generation({batch_size:n,model_input_name:r,model_kwargs:s,decoder_start_token_id:o,bos_token_id:c,generation_config:u}){let{decoder_input_ids:d,...h}=s;if(!(d instanceof we)){if(d)Array.isArray(d[0])||(d=Array.from({length:n},()=>d));else if(o??(o=c),this.config.model_type==="musicgen")d=Array.from({length:n*this.config.decoder.num_codebooks},()=>[o]);else if(Array.isArray(o)){if(o.length!==n)throw new Error(`\`decoder_start_token_id\` expcted to have length ${n} but got ${o.length}`);d=o}else d=Array.from({length:n},()=>[o]);d=yg(d)}return s.decoder_attention_mask=wx(d),{input_ids:d,model_inputs:h}}async generate({inputs:n=null,generation_config:r=null,logits_processor:s=null,stopping_criteria:o=null,streamer:c=null,...u}){this._validate_model_class(),r=this._prepare_generation_config(r,u);let{inputs_tensor:d,model_inputs:h,model_input_name:p}=this._prepare_model_inputs({inputs:n,model_kwargs:u});const g=this.config.is_encoder_decoder;g&&("encoder_outputs"in h||(h=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:d,model_inputs:h,model_input_name:p,generation_config:r})));let y;g?{input_ids:y,model_inputs:h}=this._prepare_decoder_input_ids_for_generation({batch_size:h[p].dims.at(0),model_input_name:p,model_kwargs:h,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):y=h[p];let w=y.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=w+r.max_new_tokens);const b=this._get_logits_processor(r,w,s),S=this._get_stopping_criteria(r,o),E=h[p].dims.at(0),O=zh.getSampler(r),z=new Array(E).fill(0),D=y.tolist();c&&c.put(D);let P,j={},G={};for(;;){if(h=this.prepare_inputs_for_generation(D,h,r),P=await this.forward(h),r.return_dict_in_generate)if(r.output_attentions){const pe=this.getAttentions(P);for(const ne in pe)ne in j||(j[ne]=[]),j[ne].push(pe[ne])}else this._return_dict_in_generate_keys&&Object.assign(G,Kn(P,this._return_dict_in_generate_keys));const ce=P.logits.slice(null,-1,null).to("float32"),oe=b(D,ce),he=[];for(let pe=0;pepe))break;h=this._update_model_kwargs_for_generation({generated_input_ids:he,outputs:P,model_inputs:h,is_encoder_decoder:g})}c&&c.end();const K=this.getPastKeyValues(P,h.past_key_values,!0),k=new we("int64",D.flat(),[D.length,D[0].length]);if(r.return_dict_in_generate)return{sequences:k,past_key_values:K,...j,...G};for(const ce of Object.values(P))ce.location==="gpu-buffer"&&ce.dispose();return k}getPastKeyValues(n,r,s=!1){const o=Object.create(null);for(const c in n)if(c.startsWith("present")){const u=c.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present","past_key_values"),d=c.includes("encoder");if(d&&r?o[u]=r[u]:o[u]=n[c],r&&(!d||s)){const h=r[u];h.location==="gpu-buffer"&&h.dispose()}}return o}getAttentions(n){const r={};for(const s of["cross_attentions","encoder_attentions","decoder_attentions"])for(const o in n)o.startsWith(s)&&(s in r||(r[s]=[]),r[s].push(n[o]));return r}addPastKeyValues(n,r){var s,o,c;if(r)Object.assign(n,r);else{const u=this.sessions.decoder_model_merged??this.sessions.model,d=((o=(s=n[this.main_input_name]??n.attention_mask)==null?void 0:s.dims)==null?void 0:o[0])??1,h=((c=u==null?void 0:u.config)==null?void 0:c.kv_cache_dtype)??"float32",p=h==="float16"?wh.float16:wh.float32,g=t2(this.config,{batch_size:d});for(const y in g){const w=g[y].reduce((b,S)=>b*S,1);n[y]=new we(h,new p(w),g[y])}}}async encode_image({pixel_values:n}){return(await rt(this.sessions.vision_encoder,{pixel_values:n})).image_features}async encode_text({input_ids:n}){return(await rt(this.sessions.embed_tokens,{input_ids:n})).inputs_embeds}async encode_audio({audio_values:n}){return(await rt(this.sessions.audio_encoder,{audio_values:n})).audio_features}};async function Gf(e,n){let{encoder_outputs:r,input_ids:s,decoder_input_ids:o,...c}=n;if(!r){const u=Kn(n,e.sessions.model.inputNames);r=(await ci(e,u)).last_hidden_state}return c.input_ids=o,c.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(c.encoder_attention_mask=n.attention_mask),await hs(e,c,!0)}async function ci(e,n){const r=e.sessions.model,s=Kn(n,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!n.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");s.inputs_embeds=await e.encode_text({input_ids:n.input_ids})}if(r.inputNames.includes("token_type_ids")&&!s.token_type_ids){if(!s.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");s.token_type_ids=Mx(s.input_ids)}if(r.inputNames.includes("pixel_mask")&&!s.pixel_mask){if(!s.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const o=s.pixel_values.dims;s.pixel_mask=Fa([o[0],o[2],o[3]])}return await rt(r,s)}async function uN(e,n){const r=await e.encode(n);return await e.decode(r)}async function hs(e,n,r=!1){const s=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:o,...c}=n;if(s.inputNames.includes("use_cache_branch")&&(c.use_cache_branch=o2(!!o)),s.inputNames.includes("position_ids")&&c.attention_mask&&!c.position_ids){const d=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;c.position_ids=hN(c,o,d)}e.addPastKeyValues(c,o);const u=Kn(c,s.inputNames);return await rt(s,u)}async function l2(e,{encode_function:n,merge_function:r,modality_input_name:s,modality_output_name:o,input_ids:c=null,attention_mask:u=null,position_ids:d=null,inputs_embeds:h=null,past_key_values:p=null,generation_config:g=null,logits_processor:y=null,...w}){const b=w[s];if(!h){if(h=await e.encode_text({input_ids:c,...w}),b&&c.dims[1]!==1){const E=await n({[s]:b,...w});({inputs_embeds:h,attention_mask:u}=r({[o]:E,inputs_embeds:h,input_ids:c,attention_mask:u}))}else if(p&&b&&c.dims[1]===1){const E=c.dims[1],O=Object.values(p)[0].dims.at(-2);u=Pt([Fa([c.dims[0],O]),u.slice(null,[u.dims[1]-E,u.dims[1]])],1)}}if(!d&&e.config.model_type==="qwen2_vl"){const{image_grid_thw:E,video_grid_thw:O}=w;[d]=e.get_rope_index(c,E,O,u)}return await hs(e,{inputs_embeds:h,past_key_values:p,attention_mask:u,position_ids:d,generation_config:g,logits_processor:y},!0)}async function dN(e,n){return await l2(e,{...n,modality_input_name:"audio_values",modality_output_name:"audio_features",encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function fN(e,n){return await l2(e,{...n,modality_input_name:"pixel_values",modality_output_name:"image_features",encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function c2(e,n=0){const[r,s]=e.dims,o=e.data,c=new BigInt64Array(o.length);for(let u=0;uc.dims[1]||o[o.at(-1)])),{...r,decoder_input_ids:yg(n)}}function jf(e,...n){return e.config.is_encoder_decoder?xh(e,...n):Mh(e,...n)}function u2({modality_token_id:e,inputs_embeds:n,modality_features:r,input_ids:s,attention_mask:o}){const c=s.tolist().map(p=>p.reduce((g,y,w)=>(y==e&&g.push(w),g),[])),u=c.reduce((p,g)=>p+g.length,0),d=r.dims[0];if(u!==d)throw new Error(`Number of tokens and features do not match: tokens: ${u}, features ${d}`);let h=0;for(let p=0;p{const o=await Lr(e,n[s],!1,r);return[s,o]})))}var nv={};Sl(nv,{ASTForAudioClassification:()=>xN,ASTModel:()=>MN,ASTPreTrainedModel:()=>sv,AlbertForMaskedLM:()=>gN,AlbertForQuestionAnswering:()=>_N,AlbertForSequenceClassification:()=>mN,AlbertModel:()=>pN,AlbertPreTrainedModel:()=>Qu,ApertusForCausalLM:()=>yN,ApertusModel:()=>vN,ApertusPreTrainedModel:()=>av,ArceeForCausalLM:()=>bN,ArceeModel:()=>wN,ArceePreTrainedModel:()=>rv,BartForConditionalGeneration:()=>SN,BartForSequenceClassification:()=>EN,BartModel:()=>TN,BartPretrainedModel:()=>Lh,BeitForImageClassification:()=>CN,BeitModel:()=>AN,BeitPreTrainedModel:()=>iv,BertForMaskedLM:()=>ON,BertForQuestionAnswering:()=>NN,BertForSequenceClassification:()=>zN,BertForTokenClassification:()=>LN,BertModel:()=>kN,BertPreTrainedModel:()=>kl,BlenderbotForConditionalGeneration:()=>FN,BlenderbotModel:()=>DN,BlenderbotPreTrainedModel:()=>ov,BlenderbotSmallForConditionalGeneration:()=>PN,BlenderbotSmallModel:()=>BN,BlenderbotSmallPreTrainedModel:()=>lv,BloomForCausalLM:()=>UN,BloomModel:()=>RN,BloomPreTrainedModel:()=>cv,CLIPModel:()=>XN,CLIPPreTrainedModel:()=>ro,CLIPSegForImageSegmentation:()=>JN,CLIPSegModel:()=>KN,CLIPSegPreTrainedModel:()=>uv,CLIPTextModel:()=>QN,CLIPTextModelWithProjection:()=>g2,CLIPVisionModel:()=>WN,CLIPVisionModelWithProjection:()=>ZN,CamembertForMaskedLM:()=>GN,CamembertForQuestionAnswering:()=>qN,CamembertForSequenceClassification:()=>jN,CamembertForTokenClassification:()=>VN,CamembertModel:()=>IN,CamembertPreTrainedModel:()=>Ol,ChatterboxModel:()=>h2,ChatterboxPreTrainedModel:()=>f2,ChineseCLIPModel:()=>HN,ChineseCLIPPreTrainedModel:()=>p2,ClapAudioModelWithProjection:()=>_2,ClapModel:()=>YN,ClapPreTrainedModel:()=>Nh,ClapTextModelWithProjection:()=>m2,CodeGenForCausalLM:()=>tD,CodeGenModel:()=>eD,CodeGenPreTrainedModel:()=>dv,CohereForCausalLM:()=>aD,CohereModel:()=>nD,CoherePreTrainedModel:()=>fv,ConvBertForMaskedLM:()=>sD,ConvBertForQuestionAnswering:()=>lD,ConvBertForSequenceClassification:()=>iD,ConvBertForTokenClassification:()=>oD,ConvBertModel:()=>rD,ConvBertPreTrainedModel:()=>zl,ConvNextForImageClassification:()=>uD,ConvNextModel:()=>cD,ConvNextPreTrainedModel:()=>hv,ConvNextV2ForImageClassification:()=>fD,ConvNextV2Model:()=>dD,ConvNextV2PreTrainedModel:()=>pv,DFineForObjectDetection:()=>_D,DFineModel:()=>mD,DFinePreTrainedModel:()=>_v,DINOv3ConvNextModel:()=>ID,DINOv3ConvNextPreTrainedModel:()=>E2,DINOv3ViTModel:()=>GD,DINOv3ViTPreTrainedModel:()=>A2,DPTForDepthEstimation:()=>QD,DPTModel:()=>XD,DPTPreTrainedModel:()=>bv,DacDecoderModel:()=>b2,DacDecoderOutput:()=>y2,DacEncoderModel:()=>w2,DacEncoderOutput:()=>v2,DacModel:()=>gD,DacPreTrainedModel:()=>Dh,DebertaForMaskedLM:()=>yD,DebertaForQuestionAnswering:()=>MD,DebertaForSequenceClassification:()=>wD,DebertaForTokenClassification:()=>bD,DebertaModel:()=>vD,DebertaPreTrainedModel:()=>Ll,DebertaV2ForMaskedLM:()=>TD,DebertaV2ForQuestionAnswering:()=>AD,DebertaV2ForSequenceClassification:()=>SD,DebertaV2ForTokenClassification:()=>ED,DebertaV2Model:()=>xD,DebertaV2PreTrainedModel:()=>Nl,DecisionTransformerModel:()=>CD,DecisionTransformerPreTrainedModel:()=>M2,DeiTForImageClassification:()=>OD,DeiTModel:()=>kD,DeiTPreTrainedModel:()=>gv,DepthAnythingForDepthEstimation:()=>zD,DepthAnythingPreTrainedModel:()=>x2,DepthProForDepthEstimation:()=>LD,DepthProPreTrainedModel:()=>T2,DetrForObjectDetection:()=>DD,DetrForSegmentation:()=>FD,DetrModel:()=>ND,DetrObjectDetectionOutput:()=>vv,DetrPreTrainedModel:()=>Fh,DetrSegmentationOutput:()=>S2,Dinov2ForImageClassification:()=>PD,Dinov2Model:()=>BD,Dinov2PreTrainedModel:()=>yv,Dinov2WithRegistersForImageClassification:()=>UD,Dinov2WithRegistersModel:()=>RD,Dinov2WithRegistersPreTrainedModel:()=>wv,DistilBertForMaskedLM:()=>HD,DistilBertForQuestionAnswering:()=>$D,DistilBertForSequenceClassification:()=>VD,DistilBertForTokenClassification:()=>qD,DistilBertModel:()=>jD,DistilBertPreTrainedModel:()=>Dl,DonutSwinModel:()=>YD,DonutSwinPreTrainedModel:()=>C2,EdgeTamModel:()=>LP,EfficientNetForImageClassification:()=>ZD,EfficientNetModel:()=>WD,EfficientNetPreTrainedModel:()=>Mv,ElectraForMaskedLM:()=>JD,ElectraForQuestionAnswering:()=>nF,ElectraForSequenceClassification:()=>eF,ElectraForTokenClassification:()=>tF,ElectraModel:()=>KD,ElectraPreTrainedModel:()=>Fl,Ernie4_5ForCausalLM:()=>rF,Ernie4_5Model:()=>aF,Ernie4_5PretrainedModel:()=>xv,EsmForMaskedLM:()=>iF,EsmForSequenceClassification:()=>oF,EsmForTokenClassification:()=>lF,EsmModel:()=>sF,EsmPreTrainedModel:()=>Zu,ExaoneForCausalLM:()=>uF,ExaoneModel:()=>cF,ExaonePreTrainedModel:()=>Tv,FalconForCausalLM:()=>fF,FalconH1ForCausalLM:()=>pF,FalconH1Model:()=>hF,FalconH1PreTrainedModel:()=>Ev,FalconModel:()=>dF,FalconPreTrainedModel:()=>Sv,FastViTForImageClassification:()=>_F,FastViTModel:()=>mF,FastViTPreTrainedModel:()=>Av,Florence2ForConditionalGeneration:()=>gF,Florence2PreTrainedModel:()=>k2,GLPNForDepthEstimation:()=>AF,GLPNModel:()=>EF,GLPNPreTrainedModel:()=>Lv,GPT2LMHeadModel:()=>PF,GPT2Model:()=>BF,GPT2PreTrainedModel:()=>Pv,GPTBigCodeForCausalLM:()=>kF,GPTBigCodeModel:()=>CF,GPTBigCodePreTrainedModel:()=>Nv,GPTJForCausalLM:()=>UF,GPTJModel:()=>RF,GPTJPreTrainedModel:()=>Rv,GPTNeoForCausalLM:()=>zF,GPTNeoModel:()=>OF,GPTNeoPreTrainedModel:()=>Dv,GPTNeoXForCausalLM:()=>NF,GPTNeoXModel:()=>LF,GPTNeoXPreTrainedModel:()=>Fv,Gemma2ForCausalLM:()=>bF,Gemma2Model:()=>wF,Gemma2PreTrainedModel:()=>kv,Gemma3ForCausalLM:()=>xF,Gemma3Model:()=>MF,Gemma3PreTrainedModel:()=>Ov,Gemma3nForConditionalGeneration:()=>z2,Gemma3nPreTrainedModel:()=>O2,GemmaForCausalLM:()=>yF,GemmaModel:()=>vF,GemmaPreTrainedModel:()=>Cv,GlmForCausalLM:()=>SF,GlmModel:()=>TF,GlmPreTrainedModel:()=>zv,GptOssForCausalLM:()=>FF,GptOssModel:()=>DF,GptOssPreTrainedModel:()=>Bv,GraniteForCausalLM:()=>GF,GraniteModel:()=>IF,GraniteMoeHybridForCausalLM:()=>VF,GraniteMoeHybridModel:()=>jF,GraniteMoeHybridPreTrainedModel:()=>Iv,GranitePreTrainedModel:()=>Uv,GroundingDinoForObjectDetection:()=>qF,GroundingDinoPreTrainedModel:()=>L2,GroupViTModel:()=>$F,GroupViTPreTrainedModel:()=>N2,HeliumForCausalLM:()=>YF,HeliumModel:()=>HF,HeliumPreTrainedModel:()=>Gv,HieraForImageClassification:()=>QF,HieraModel:()=>XF,HieraPreTrainedModel:()=>jv,HubertForCTC:()=>n6,HubertForSequenceClassification:()=>a6,HubertModel:()=>t6,HubertPreTrainedModel:()=>e6,HunYuanDenseV1ForCausalLM:()=>s6,HunYuanDenseV1Model:()=>r6,HunYuanDenseV1PreTrainedModel:()=>Vv,IJepaForImageClassification:()=>l6,IJepaModel:()=>o6,IJepaPreTrainedModel:()=>qv,Idefics3ForConditionalGeneration:()=>F2,Idefics3PreTrainedModel:()=>D2,JAISLMHeadModel:()=>u6,JAISModel:()=>c6,JAISPreTrainedModel:()=>$v,JinaCLIPModel:()=>d6,JinaCLIPPreTrainedModel:()=>Bh,JinaCLIPTextModel:()=>B2,JinaCLIPVisionModel:()=>f6,Lfm2ForCausalLM:()=>p6,Lfm2Model:()=>h6,Lfm2MoeForCausalLM:()=>_6,Lfm2MoeModel:()=>m6,Lfm2MoePreTrainedModel:()=>Yv,Lfm2PreTrainedModel:()=>Hv,LiteWhisperForConditionalGeneration:()=>q8,Llama4ForCausalLM:()=>y6,Llama4PreTrainedModel:()=>P2,LlamaForCausalLM:()=>v6,LlamaModel:()=>g6,LlamaPreTrainedModel:()=>Xv,LlavaForConditionalGeneration:()=>Th,LlavaOnevisionForConditionalGeneration:()=>Th,LlavaPreTrainedModel:()=>R2,LlavaQwen2ForCausalLM:()=>b6,LongT5ForConditionalGeneration:()=>x6,LongT5Model:()=>M6,LongT5PreTrainedModel:()=>Qv,M2M100ForConditionalGeneration:()=>S6,M2M100Model:()=>T6,M2M100PreTrainedModel:()=>Wv,MBartForCausalLM:()=>N6,MBartForConditionalGeneration:()=>z6,MBartForSequenceClassification:()=>L6,MBartModel:()=>O6,MBartPreTrainedModel:()=>Ku,MPNetForMaskedLM:()=>gB,MPNetForQuestionAnswering:()=>wB,MPNetForSequenceClassification:()=>vB,MPNetForTokenClassification:()=>yB,MPNetModel:()=>_B,MPNetPreTrainedModel:()=>Bl,MT5ForConditionalGeneration:()=>TB,MT5Model:()=>xB,MT5PreTrainedModel:()=>iy,MarianMTModel:()=>A6,MarianModel:()=>E6,MarianPreTrainedModel:()=>Zv,MaskFormerForInstanceSegmentation:()=>k6,MaskFormerModel:()=>C6,MaskFormerPreTrainedModel:()=>Kv,Metric3DForDepthEstimation:()=>D6,Metric3DPreTrainedModel:()=>U2,Metric3Dv2ForDepthEstimation:()=>F6,Metric3Dv2PreTrainedModel:()=>I2,MgpstrForSceneTextRecognition:()=>B6,MgpstrModelOutput:()=>G2,MgpstrPreTrainedModel:()=>j2,MimiDecoderModel:()=>H2,MimiDecoderOutput:()=>q2,MimiEncoderModel:()=>$2,MimiEncoderOutput:()=>V2,MimiModel:()=>P6,MimiPreTrainedModel:()=>Ph,MistralForCausalLM:()=>U6,MistralModel:()=>R6,MistralPreTrainedModel:()=>Jv,MobileBertForMaskedLM:()=>G6,MobileBertForQuestionAnswering:()=>V6,MobileBertForSequenceClassification:()=>j6,MobileBertModel:()=>I6,MobileBertPreTrainedModel:()=>Ju,MobileLLMForCausalLM:()=>$6,MobileLLMModel:()=>q6,MobileLLMPreTrainedModel:()=>ey,MobileNetV1ForImageClassification:()=>Y6,MobileNetV1ForSemanticSegmentation:()=>X6,MobileNetV1Model:()=>H6,MobileNetV1PreTrainedModel:()=>Rh,MobileNetV2ForImageClassification:()=>W6,MobileNetV2ForSemanticSegmentation:()=>Z6,MobileNetV2Model:()=>Q6,MobileNetV2PreTrainedModel:()=>Uh,MobileNetV3ForImageClassification:()=>J6,MobileNetV3ForSemanticSegmentation:()=>eB,MobileNetV3Model:()=>K6,MobileNetV3PreTrainedModel:()=>Ih,MobileNetV4ForImageClassification:()=>nB,MobileNetV4ForSemanticSegmentation:()=>aB,MobileNetV4Model:()=>tB,MobileNetV4PreTrainedModel:()=>Gh,MobileViTForImageClassification:()=>sB,MobileViTModel:()=>rB,MobileViTPreTrainedModel:()=>ty,MobileViTV2ForImageClassification:()=>oB,MobileViTV2Model:()=>iB,MobileViTV2PreTrainedModel:()=>ny,ModernBertDecoderForCausalLM:()=>hB,ModernBertDecoderModel:()=>fB,ModernBertDecoderPreTrainedModel:()=>ay,ModernBertForMaskedLM:()=>cB,ModernBertForSequenceClassification:()=>uB,ModernBertForTokenClassification:()=>dB,ModernBertModel:()=>lB,ModernBertPreTrainedModel:()=>ed,Moondream1ForConditionalGeneration:()=>w6,MoonshineForConditionalGeneration:()=>mB,MoonshineModel:()=>pB,MoonshinePreTrainedModel:()=>ry,MptForCausalLM:()=>MB,MptModel:()=>bB,MptPreTrainedModel:()=>sy,MultiModalityCausalLM:()=>SB,MultiModalityPreTrainedModel:()=>Y2,MusicgenForCausalLM:()=>AB,MusicgenForConditionalGeneration:()=>X2,MusicgenModel:()=>EB,MusicgenPreTrainedModel:()=>oy,NanoChatForCausalLM:()=>kB,NanoChatModel:()=>CB,NanoChatPreTrainedModel:()=>ly,NeoBertForMaskedLM:()=>zB,NeoBertForQuestionAnswering:()=>DB,NeoBertForSequenceClassification:()=>LB,NeoBertForTokenClassification:()=>NB,NeoBertModel:()=>OB,NeoBertPreTrainedModel:()=>Pl,NomicBertModel:()=>FB,NomicBertPreTrainedModel:()=>Q2,OPTForCausalLM:()=>$B,OPTModel:()=>qB,OPTPreTrainedModel:()=>hy,Olmo2ForCausalLM:()=>UB,Olmo2Model:()=>RB,Olmo2PreTrainedModel:()=>uy,Olmo3ForCausalLM:()=>GB,Olmo3Model:()=>IB,Olmo3PreTrainedModel:()=>dy,OlmoForCausalLM:()=>PB,OlmoModel:()=>BB,OlmoPreTrainedModel:()=>cy,OpenELMForCausalLM:()=>VB,OpenELMModel:()=>jB,OpenELMPreTrainedModel:()=>fy,OwlViTForObjectDetection:()=>QB,OwlViTModel:()=>XB,OwlViTPreTrainedModel:()=>my,Owlv2ForObjectDetection:()=>YB,Owlv2Model:()=>HB,Owlv2PreTrainedModel:()=>py,PaliGemmaForConditionalGeneration:()=>WB,PaliGemmaPreTrainedModel:()=>W2,ParakeetForCTC:()=>ZB,ParakeetPreTrainedModel:()=>Z2,PatchTSMixerForPrediction:()=>JB,PatchTSMixerModel:()=>KB,PatchTSMixerPreTrainedModel:()=>_y,PatchTSTForPrediction:()=>tP,PatchTSTModel:()=>eP,PatchTSTPreTrainedModel:()=>gy,Phi3ForCausalLM:()=>sP,Phi3Model:()=>rP,Phi3PreTrainedModel:()=>yy,Phi3VForCausalLM:()=>J2,Phi3VPreTrainedModel:()=>K2,PhiForCausalLM:()=>aP,PhiModel:()=>nP,PhiPreTrainedModel:()=>vy,PreTrainedModel:()=>Y,PvtForImageClassification:()=>oP,PvtModel:()=>iP,PvtPreTrainedModel:()=>wy,PyAnnoteForAudioFrameClassification:()=>cP,PyAnnoteModel:()=>lP,PyAnnotePreTrainedModel:()=>by,Qwen2ForCausalLM:()=>dP,Qwen2Model:()=>uP,Qwen2PreTrainedModel:()=>My,Qwen2VLForConditionalGeneration:()=>fP,Qwen2VLPreTrainedModel:()=>eT,Qwen3ForCausalLM:()=>pP,Qwen3Model:()=>hP,Qwen3PreTrainedModel:()=>xy,RFDetrForObjectDetection:()=>vP,RFDetrModel:()=>gP,RFDetrObjectDetectionOutput:()=>tT,RFDetrPreTrainedModel:()=>Sy,RTDetrForObjectDetection:()=>pD,RTDetrModel:()=>hD,RTDetrObjectDetectionOutput:()=>Wu,RTDetrPreTrainedModel:()=>mv,RTDetrV2ForObjectDetection:()=>OP,RTDetrV2Model:()=>kP,RTDetrV2ObjectDetectionOutput:()=>nT,RTDetrV2PreTrainedModel:()=>Ey,ResNetForImageClassification:()=>_P,ResNetModel:()=>mP,ResNetPreTrainedModel:()=>Ty,RoFormerForMaskedLM:()=>SP,RoFormerForQuestionAnswering:()=>CP,RoFormerForSequenceClassification:()=>EP,RoFormerForTokenClassification:()=>AP,RoFormerModel:()=>TP,RoFormerPreTrainedModel:()=>Ul,RobertaForMaskedLM:()=>wP,RobertaForQuestionAnswering:()=>xP,RobertaForSequenceClassification:()=>bP,RobertaForTokenClassification:()=>MP,RobertaModel:()=>yP,RobertaPreTrainedModel:()=>Rl,Sam2ImageSegmentationOutput:()=>sT,Sam2Model:()=>Ay,Sam2PreTrainedModel:()=>iT,Sam3TrackerModel:()=>NP,SamImageSegmentationOutput:()=>aT,SamModel:()=>zP,SamPreTrainedModel:()=>rT,SapiensForDepthEstimation:()=>FP,SapiensForNormalEstimation:()=>BP,SapiensForSemanticSegmentation:()=>DP,SapiensPreTrainedModel:()=>jh,SegformerForImageClassification:()=>RP,SegformerForSemanticSegmentation:()=>UP,SegformerModel:()=>PP,SegformerPreTrainedModel:()=>Vh,SiglipModel:()=>IP,SiglipPreTrainedModel:()=>Cy,SiglipTextModel:()=>oT,SiglipVisionModel:()=>GP,SmolLM3ForCausalLM:()=>VP,SmolLM3Model:()=>jP,SmolLM3PreTrainedModel:()=>ky,SmolVLMForConditionalGeneration:()=>i6,SnacDecoderModel:()=>cT,SnacEncoderModel:()=>lT,SnacModel:()=>qP,SnacPreTrainedModel:()=>qh,SpeechT5ForSpeechToText:()=>HP,SpeechT5ForTextToSpeech:()=>YP,SpeechT5HifiGan:()=>XP,SpeechT5Model:()=>$P,SpeechT5PreTrainedModel:()=>$h,SqueezeBertForMaskedLM:()=>WP,SqueezeBertForQuestionAnswering:()=>KP,SqueezeBertForSequenceClassification:()=>ZP,SqueezeBertModel:()=>QP,SqueezeBertPreTrainedModel:()=>td,StableLmForCausalLM:()=>e8,StableLmModel:()=>JP,StableLmPreTrainedModel:()=>Oy,Starcoder2ForCausalLM:()=>n8,Starcoder2Model:()=>t8,Starcoder2PreTrainedModel:()=>zy,StyleTextToSpeech2Model:()=>a8,StyleTextToSpeech2PreTrainedModel:()=>uT,SupertonicForConditionalGeneration:()=>fT,SupertonicPreTrainedModel:()=>dT,Swin2SRForImageSuperResolution:()=>l8,Swin2SRModel:()=>o8,Swin2SRPreTrainedModel:()=>Ly,SwinForImageClassification:()=>s8,SwinForSemanticSegmentation:()=>i8,SwinModel:()=>r8,SwinPreTrainedModel:()=>Hh,T5ForConditionalGeneration:()=>u8,T5Model:()=>c8,T5PreTrainedModel:()=>Ny,TableTransformerForObjectDetection:()=>f8,TableTransformerModel:()=>d8,TableTransformerObjectDetectionOutput:()=>hT,TableTransformerPreTrainedModel:()=>Dy,TrOCRForCausalLM:()=>h8,TrOCRPreTrainedModel:()=>pT,UltravoxModel:()=>_T,UltravoxPreTrainedModel:()=>mT,UniSpeechForCTC:()=>_8,UniSpeechForSequenceClassification:()=>g8,UniSpeechModel:()=>m8,UniSpeechPreTrainedModel:()=>Yh,UniSpeechSatForAudioFrameClassification:()=>b8,UniSpeechSatForCTC:()=>y8,UniSpeechSatForSequenceClassification:()=>w8,UniSpeechSatModel:()=>v8,UniSpeechSatPreTrainedModel:()=>nd,VaultGemmaForCausalLM:()=>x8,VaultGemmaModel:()=>M8,VaultGemmaPreTrainedModel:()=>Fy,ViTForImageClassification:()=>E8,ViTMAEModel:()=>A8,ViTMAEPreTrainedModel:()=>gT,ViTMSNForImageClassification:()=>k8,ViTMSNModel:()=>C8,ViTMSNPreTrainedModel:()=>Py,ViTModel:()=>S8,ViTPreTrainedModel:()=>By,VisionEncoderDecoderModel:()=>T8,VitMatteForImageMatting:()=>O8,VitMattePreTrainedModel:()=>vT,VitPoseForPoseEstimation:()=>z8,VitPosePreTrainedModel:()=>yT,VitsModel:()=>L8,VitsModelOutput:()=>wT,VitsPreTrainedModel:()=>bT,VoxtralForConditionalGeneration:()=>p8,Wav2Vec2BertForCTC:()=>D8,Wav2Vec2BertForSequenceClassification:()=>F8,Wav2Vec2BertModel:()=>N8,Wav2Vec2BertPreTrainedModel:()=>Xh,Wav2Vec2ForAudioFrameClassification:()=>JF,Wav2Vec2ForCTC:()=>ZF,Wav2Vec2ForSequenceClassification:()=>KF,Wav2Vec2Model:()=>WF,Wav2Vec2PreTrainedModel:()=>ui,WavLMForAudioFrameClassification:()=>I8,WavLMForCTC:()=>P8,WavLMForSequenceClassification:()=>R8,WavLMForXVector:()=>U8,WavLMModel:()=>B8,WavLMPreTrainedModel:()=>Il,WeSpeakerResNetModel:()=>G8,WeSpeakerResNetPreTrainedModel:()=>xT,WhisperForConditionalGeneration:()=>TT,WhisperModel:()=>V8,WhisperPreTrainedModel:()=>Ry,XLMForQuestionAnswering:()=>Q8,XLMForSequenceClassification:()=>Y8,XLMForTokenClassification:()=>X8,XLMModel:()=>$8,XLMPreTrainedModel:()=>Gl,XLMRobertaForMaskedLM:()=>Z8,XLMRobertaForQuestionAnswering:()=>eR,XLMRobertaForSequenceClassification:()=>K8,XLMRobertaForTokenClassification:()=>J8,XLMRobertaModel:()=>W8,XLMRobertaPreTrainedModel:()=>jl,XLMWithLMHeadModel:()=>H8,XVectorOutput:()=>MT,YolosForObjectDetection:()=>nR,YolosModel:()=>tR,YolosObjectDetectionOutput:()=>ST,YolosPreTrainedModel:()=>Uy,YoutuForCausalLM:()=>rR,YoutuModel:()=>aR,YoutuPreTrainedModel:()=>Iy});var Qu=class extends Y{},pN=class extends Qu{},mN=class extends Qu{async _call(e){return new Pe(await super._call(e))}},_N=class extends Qu{async _call(e){return new Ln(await super._call(e))}},gN=class extends Qu{async _call(e){return new dn(await super._call(e))}},av=class extends Y{},vN=class extends av{},yN=class extends av{},rv=class extends Y{},wN=class extends rv{},bN=class extends rv{},sv=class extends Y{},MN=class extends sv{},xN=class extends sv{},Lh=class extends Y{},TN=class extends Lh{},SN=class extends Lh{},EN=class extends Lh{async _call(e){return new Pe(await super._call(e))}},iv=class extends Y{},AN=class extends iv{},CN=class extends iv{async _call(e){return new Pe(await super._call(e))}},kl=class extends Y{},kN=class extends kl{},ON=class extends kl{async _call(e){return new dn(await super._call(e))}},zN=class extends kl{async _call(e){return new Pe(await super._call(e))}},LN=class extends kl{async _call(e){return new sn(await super._call(e))}},NN=class extends kl{async _call(e){return new Ln(await super._call(e))}},ov=class extends Y{},DN=class extends ov{},FN=class extends ov{},lv=class extends Y{},BN=class extends lv{},PN=class extends lv{},cv=class extends Y{},RN=class extends cv{},UN=class extends cv{},Ol=class extends Y{},IN=class extends Ol{},GN=class extends Ol{async _call(e){return new dn(await super._call(e))}},jN=class extends Ol{async _call(e){return new Pe(await super._call(e))}},VN=class extends Ol{async _call(e){return new sn(await super._call(e))}},qN=class extends Ol{async _call(e){return new Ln(await super._call(e))}},$N=4299n,I1=6561n,f2=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"]);L(this,"main_input_name","input_ids");L(this,"_return_dict_in_generate_keys",["audio_tokens","speaker_embeddings","speaker_features"])}},h2=class extends f2{async encode_speech(e){return rt(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:n=null,audio_values:r=null,exaggeration:s=null,position_ids:o=null,inputs_embeds:c=null,past_key_values:u=null,generation_config:d=null,logits_processor:h=null,audio_features:p=null,audio_tokens:g=null,speaker_embeddings:y=null,speaker_features:w=null,...b}){let S;if(!c){const O=this.sessions.embed_tokens.inputNames,z={input_ids:e};if(O.includes("exaggeration")){if(!(s instanceof we)){const D=e.dims[0];if(s==null)s=zn([D],.5);else if(typeof s=="number")s=zn([D],s);else if(Array.isArray(s))s=new we("float32",s,[D]);else throw new Error("Unsupported type for `exaggeration` input")}z.exaggeration=s}if(O.includes("position_ids")&&(z.position_ids=o),{inputs_embeds:c}=await rt(this.sessions.embed_tokens,z),p&&g&&y&&w&&(S={audio_features:p,audio_tokens:g,speaker_embeddings:y,speaker_features:w}),S||r)S??(S=await this.encode_speech(r)),c=Pt([S.audio_features,c],1),n=Fa([c.dims[0],c.dims[1]]);else{const D=c.dims[1];if(!u||D!==1)throw new Error("Incorrect state encountered during generation.");const P=Object.values(u)[0].dims.at(-2);n=Fa([c.dims[0],P+D])}}return{...await hs(this,{inputs_embeds:c,past_key_values:u,attention_mask:n,generation_config:d,logits_processor:h},!1),...S}}prepare_inputs_for_generation(e,n,r){if(!n.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(n.input_ids.dims[1]===1){const s=Array.from({length:e.length},(o,c)=>e[c].length-e[c].findLastIndex(u=>u==I1)-1);n.position_ids=new we("int64",s,[e.length,1])}else{const o=n.input_ids.tolist().map(c=>{let u=0;return c.map(d=>d>=I1?0:u++)});n.position_ids=new we("int64",o.flat(),n.input_ids.dims)}return n.input_ids.dims[1]===1&&(delete n.audio_values,delete n.audio_features,delete n.audio_tokens,delete n.speaker_embeddings,delete n.speaker_features),Mh(this,e,n)}async generate(e){const{sequences:n,audio_tokens:r,speaker_embeddings:s,speaker_features:o}=await super.generate({...e,return_dict_in_generate:!0}),c=n.slice(null,[e.input_ids.dims[1],-1]),u=zn([c.dims[0],3],$N),d=Pt([r,c,u],1),{waveform:h}=await rt(this.sessions.conditional_decoder,{speech_tokens:d,speaker_features:o,speaker_embeddings:s});return h}},p2=class extends Y{},HN=class extends p2{},Nh=class extends Y{},YN=class extends Nh{},m2=class extends Nh{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"text_model"})}},_2=class extends Nh{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"audio_model"})}},ro=class extends Y{},XN=class extends ro{},QN=class extends ro{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"text_model"})}},g2=class extends ro{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"text_model"})}},WN=class extends ro{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"vision_model"})}},ZN=class extends ro{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"vision_model"})}},uv=class extends Y{},KN=class extends uv{},JN=class extends uv{},dv=class extends Y{},eD=class extends dv{},tD=class extends dv{},fv=class extends Y{},nD=class extends fv{},aD=class extends fv{},zl=class extends Y{},rD=class extends zl{},sD=class extends zl{async _call(e){return new dn(await super._call(e))}},iD=class extends zl{async _call(e){return new Pe(await super._call(e))}},oD=class extends zl{async _call(e){return new sn(await super._call(e))}},lD=class extends zl{async _call(e){return new Ln(await super._call(e))}},hv=class extends Y{},cD=class extends hv{},uD=class extends hv{async _call(e){return new Pe(await super._call(e))}},pv=class extends Y{},dD=class extends pv{},fD=class extends pv{async _call(e){return new Pe(await super._call(e))}},mv=class extends Y{},hD=class extends mv{},pD=class extends mv{async _call(e){return new Wu(await super._call(e))}},Wu=class extends rn{constructor({logits:e,pred_boxes:n}){super(),this.logits=e,this.pred_boxes=n}},_v=class extends Y{},mD=class extends _v{},_D=class extends _v{async _call(e){return new Wu(await super._call(e))}},v2=class extends rn{constructor({audio_codes:e}){super(),this.audio_codes=e}},y2=class extends rn{constructor({audio_values:e}){super(),this.audio_values=e}},Dh=class extends Y{constructor(){super(...arguments);L(this,"main_input_name","input_values");L(this,"forward_params",["input_values"])}},gD=class extends Dh{async encode(e){return new v2(await rt(this.sessions.encoder_model,e))}async decode(e){return new y2(await rt(this.sessions.decoder_model,e))}},w2=class extends Dh{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"encoder_model"})}},b2=class extends Dh{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"decoder_model"})}},Ll=class extends Y{},vD=class extends Ll{},yD=class extends Ll{async _call(e){return new dn(await super._call(e))}},wD=class extends Ll{async _call(e){return new Pe(await super._call(e))}},bD=class extends Ll{async _call(e){return new sn(await super._call(e))}},MD=class extends Ll{async _call(e){return new Ln(await super._call(e))}},Nl=class extends Y{},xD=class extends Nl{},TD=class extends Nl{async _call(e){return new dn(await super._call(e))}},SD=class extends Nl{async _call(e){return new Pe(await super._call(e))}},ED=class extends Nl{async _call(e){return new sn(await super._call(e))}},AD=class extends Nl{async _call(e){return new Ln(await super._call(e))}},M2=class extends Y{},CD=class extends M2{},gv=class extends Y{},kD=class extends gv{},OD=class extends gv{async _call(e){return new Pe(await super._call(e))}},x2=class extends Y{},zD=class extends x2{},T2=class extends Y{},LD=class extends T2{},Fh=class extends Y{},ND=class extends Fh{},DD=class extends Fh{async _call(e){return new vv(await super._call(e))}},FD=class extends Fh{async _call(e){return new S2(await super._call(e))}},vv=class extends rn{constructor({logits:e,pred_boxes:n}){super(),this.logits=e,this.pred_boxes=n}},S2=class extends rn{constructor({logits:e,pred_boxes:n,pred_masks:r}){super(),this.logits=e,this.pred_boxes=n,this.pred_masks=r}},yv=class extends Y{},BD=class extends yv{},PD=class extends yv{async _call(e){return new Pe(await super._call(e))}},wv=class extends Y{},RD=class extends wv{},UD=class extends wv{async _call(e){return new Pe(await super._call(e))}},E2=class extends Y{},ID=class extends E2{},A2=class extends Y{},GD=class extends A2{},Dl=class extends Y{},jD=class extends Dl{},VD=class extends Dl{async _call(e){return new Pe(await super._call(e))}},qD=class extends Dl{async _call(e){return new sn(await super._call(e))}},$D=class extends Dl{async _call(e){return new Ln(await super._call(e))}},HD=class extends Dl{async _call(e){return new dn(await super._call(e))}},C2=class extends Y{},YD=class extends C2{},bv=class extends Y{},XD=class extends bv{},QD=class extends bv{},Mv=class extends Y{},WD=class extends Mv{},ZD=class extends Mv{async _call(e){return new Pe(await super._call(e))}},Fl=class extends Y{},KD=class extends Fl{},JD=class extends Fl{async _call(e){return new dn(await super._call(e))}},eF=class extends Fl{async _call(e){return new Pe(await super._call(e))}},tF=class extends Fl{async _call(e){return new sn(await super._call(e))}},nF=class extends Fl{async _call(e){return new Ln(await super._call(e))}},xv=class extends Y{},aF=class extends xv{},rF=class extends xv{},Zu=class extends Y{},sF=class extends Zu{},iF=class extends Zu{async _call(e){return new dn(await super._call(e))}},oF=class extends Zu{async _call(e){return new Pe(await super._call(e))}},lF=class extends Zu{async _call(e){return new sn(await super._call(e))}},Tv=class extends Y{},cF=class extends Tv{},uF=class extends Tv{},Sv=class extends Y{},dF=class extends Sv{},fF=class extends Sv{},Ev=class extends Y{},hF=class extends Ev{},pF=class extends Ev{},Av=class extends Y{},mF=class extends Av{},_F=class extends Av{async _call(e){return new Pe(await super._call(e))}},k2=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"]);L(this,"main_input_name","inputs_embeds")}},gF=class extends k2{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:n,input_ids:r,attention_mask:s}){return{inputs_embeds:Pt([n,e],1),attention_mask:Pt([Fa(n.dims.slice(0,2)),s],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:n,inputs_embeds:r,attention_mask:s}){if(!e&&!n)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,c;return e&&(o=await this.encode_text({input_ids:e})),n&&(c=await this.encode_image({pixel_values:n})),o&&c?{inputs_embeds:r,attention_mask:s}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:c,input_ids:e,attention_mask:s}):r=o||c,{inputs_embeds:r,attention_mask:s}}async forward({input_ids:e,pixel_values:n,attention_mask:r,decoder_input_ids:s,decoder_attention_mask:o,encoder_outputs:c,past_key_values:u,inputs_embeds:d,decoder_inputs_embeds:h}){if(d||({inputs_embeds:d,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:n,inputs_embeds:d,attention_mask:r})),!c){let{last_hidden_state:g}=await ci(this,{inputs_embeds:d,attention_mask:r});c=g}if(!h){if(!s)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");h=await this.encode_text({input_ids:s})}return await hs(this,{inputs_embeds:h,attention_mask:o,encoder_attention_mask:r,encoder_hidden_states:c,past_key_values:u},!0)}},Cv=class extends Y{},vF=class extends Cv{},yF=class extends Cv{},kv=class extends Y{},wF=class extends kv{},bF=class extends kv{},Ov=class extends Y{},MF=class extends Ov{},xF=class extends Ov{},O2=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"])}},z2=class extends O2{async forward({input_ids:e=null,attention_mask:n=null,pixel_values:r=null,input_features:s=null,input_features_mask:o=null,position_ids:c=null,inputs_embeds:u=null,per_layer_inputs:d=null,past_key_values:h=null,generation_config:p=null,logits_processor:g=null,...y}){if((!u||!d)&&({inputs_embeds:u,per_layer_inputs:d}=await rt(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:b}=await rt(this.sessions.vision_encoder,{pixel_values:r});({inputs_embeds:u,attention_mask:n}=this._merge_input_ids_with_image_features({image_features:b,inputs_embeds:u,input_ids:e,attention_mask:n}))}if(s){const{audio_features:b}=await rt(this.sessions.audio_encoder,{input_features:s,input_features_mask:o});({inputs_embeds:u,attention_mask:n}=this._merge_input_ids_with_audio_features({audio_features:b,inputs_embeds:u,input_ids:e,attention_mask:n}))}}return await hs(this,{inputs_embeds:u,per_layer_inputs:d,past_key_values:h,attention_mask:n,position_ids:c,generation_config:p,logits_processor:g},!0)}_merge_input_ids_with_image_features(e){const n=e.image_features.dims.at(-1),r=e.image_features.view(-1,n);return Xu({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){const n=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,n);return d2({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},zv=class extends Y{},TF=class extends zv{},SF=class extends zv{},Lv=class extends Y{},EF=class extends Lv{},AF=class extends Lv{},Nv=class extends Y{},CF=class extends Nv{},kF=class extends Nv{},Dv=class extends Y{},OF=class extends Dv{},zF=class extends Dv{},Fv=class extends Y{},LF=class extends Fv{},NF=class extends Fv{},Bv=class extends Y{},DF=class extends Bv{},FF=class extends Bv{},Pv=class extends Y{},BF=class extends Pv{},PF=class extends Pv{},Rv=class extends Y{},RF=class extends Rv{},UF=class extends Rv{},Uv=class extends Y{},IF=class extends Uv{},GF=class extends Uv{},Iv=class extends Y{},jF=class extends Iv{},VF=class extends Iv{},L2=class extends Y{},qF=class extends L2{},N2=class extends Y{},$F=class extends N2{},Gv=class extends Y{},HF=class extends Gv{},YF=class extends Gv{},jv=class extends Y{},XF=class extends jv{},QF=class extends jv{async _call(e){return new Pe(await super._call(e))}},ui=class extends Y{},WF=class extends ui{},ZF=class extends ui{async _call(e){return new ao(await super._call(e))}},KF=class extends ui{async _call(e){return new Pe(await super._call(e))}},JF=class extends ui{async _call(e){return new sn(await super._call(e))}},e6=class extends Y{},t6=class extends ui{},n6=class extends ui{async _call(e){return new ao(await super._call(e))}},a6=class extends ui{async _call(e){return new Pe(await super._call(e))}},Vv=class extends Y{},r6=class extends Vv{},s6=class extends Vv{},D2=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"])}},F2=class extends D2{async encode_image({pixel_values:e,pixel_attention_mask:n}){return(await rt(this.sessions.vision_encoder,{pixel_values:e,pixel_attention_mask:n})).image_features}_merge_input_ids_with_image_features(e){const n=e.image_features.dims.at(-1),r=e.image_features.view(-1,n);return Xu({image_token_id:this.config.image_token_id,...e,image_features:r})}},i6=class extends F2{},qv=class extends Y{},o6=class extends qv{},l6=class extends qv{async _call(e){return new Pe(await super._call(e))}},$v=class extends Y{},c6=class extends $v{},u6=class extends $v{},Bh=class extends Y{},d6=class extends Bh{async forward(e){const n=!e.input_ids,r=!e.pixel_values;if(n&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(n&&(e.input_ids=Fa([e.pixel_values.dims[0],1])),r){const{image_size:h}=this.config.vision_config;e.pixel_values=zn([0,3,h,h],0)}const{text_embeddings:s,image_embeddings:o,l2norm_text_embeddings:c,l2norm_image_embeddings:u}=await super.forward(e),d={};return n||(d.text_embeddings=s,d.l2norm_text_embeddings=c),r||(d.image_embeddings=o,d.l2norm_image_embeddings=u),d}},B2=class extends Bh{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"text_model"})}},f6=class extends Bh{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"vision_model"})}},Hv=class extends Y{},h6=class extends Hv{},p6=class extends Hv{},Yv=class extends Y{},m6=class extends Yv{},_6=class extends Yv{},Xv=class extends Y{},g6=class extends Xv{},v6=class extends Xv{},P2=class extends Y{},y6=class extends P2{},R2=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}},Th=class extends R2{_merge_input_ids_with_image_features(e){const n=e.image_features.dims.at(-1),r=e.image_features.view(-1,n);return Xu({image_token_id:this.config.image_token_index,...e,image_features:r})}},w6=class extends Th{},b6=class extends Th{},Qv=class extends Y{},M6=class extends Qv{},x6=class extends Qv{},Wv=class extends Y{},T6=class extends Wv{},S6=class extends Wv{},Zv=class extends Y{},E6=class extends Zv{},A6=class extends Zv{},Kv=class extends Y{},C6=class extends Kv{},k6=class extends Kv{},Ku=class extends Y{},O6=class extends Ku{},z6=class extends Ku{},L6=class extends Ku{async _call(e){return new Pe(await super._call(e))}},N6=class extends Ku{},U2=class extends Y{},D6=class extends U2{},I2=class extends Y{},F6=class extends I2{},G2=class extends rn{constructor({char_logits:e,bpe_logits:n,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=n,this.wp_logits=r}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},j2=class extends Y{},B6=class extends j2{async _call(e){return new G2(await super._call(e))}},V2=class extends rn{constructor({audio_codes:e}){super(),this.audio_codes=e}},q2=class extends rn{constructor({audio_values:e}){super(),this.audio_values=e}},Ph=class extends Y{constructor(){super(...arguments);L(this,"main_input_name","input_values");L(this,"forward_params",["input_values"])}},P6=class extends Ph{async encode(e){return new V2(await rt(this.sessions.encoder_model,e))}async decode(e){return new q2(await rt(this.sessions.decoder_model,e))}},$2=class extends Ph{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"encoder_model"})}},H2=class extends Ph{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"decoder_model"})}},Jv=class extends Y{},R6=class extends Jv{},U6=class extends Jv{},Ju=class extends Y{},I6=class extends Ju{},G6=class extends Ju{async _call(e){return new dn(await super._call(e))}},j6=class extends Ju{async _call(e){return new Pe(await super._call(e))}},V6=class extends Ju{async _call(e){return new Ln(await super._call(e))}},ey=class extends Y{},q6=class extends ey{},$6=class extends ey{},Rh=class extends Y{},H6=class extends Rh{},Y6=class extends Rh{async _call(e){return new Pe(await super._call(e))}},X6=class extends Rh{},Uh=class extends Y{},Q6=class extends Uh{},W6=class extends Uh{async _call(e){return new Pe(await super._call(e))}},Z6=class extends Uh{},Ih=class extends Y{},K6=class extends Ih{},J6=class extends Ih{async _call(e){return new Pe(await super._call(e))}},eB=class extends Ih{},Gh=class extends Y{},tB=class extends Gh{},nB=class extends Gh{async _call(e){return new Pe(await super._call(e))}},aB=class extends Gh{},ty=class extends Y{},rB=class extends ty{},sB=class extends ty{async _call(e){return new Pe(await super._call(e))}},ny=class extends Y{},iB=class extends ny{},oB=class extends ny{async _call(e){return new Pe(await super._call(e))}},ed=class extends Y{},lB=class extends ed{},cB=class extends ed{async _call(e){return new dn(await super._call(e))}},uB=class extends ed{async _call(e){return new Pe(await super._call(e))}},dB=class extends ed{async _call(e){return new sn(await super._call(e))}},ay=class extends Y{},fB=class extends ay{},hB=class extends ay{},ry=class extends Y{constructor(){super(...arguments);L(this,"requires_attention_mask",!1);L(this,"main_input_name","input_values");L(this,"forward_params",["input_values","decoder_input_ids","past_key_values"])}},pB=class extends ry{},mB=class extends ry{},Bl=class extends Y{},_B=class extends Bl{},gB=class extends Bl{async _call(e){return new dn(await super._call(e))}},vB=class extends Bl{async _call(e){return new Pe(await super._call(e))}},yB=class extends Bl{async _call(e){return new sn(await super._call(e))}},wB=class extends Bl{async _call(e){return new Ln(await super._call(e))}},sy=class extends Y{},bB=class extends sy{},MB=class extends sy{},iy=class extends Y{},xB=class extends iy{},TB=class extends iy{},Y2=class extends Y{},SB=class extends Y2{constructor(...n){super(...n);L(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(n){const r=this._generation_mode??"text";let s;if(r==="text"||!n.past_key_values){const h=this.sessions.prepare_inputs_embeds,p=Kn(n,h.inputNames);s=await rt(h,p)}else{const h=this.sessions.gen_img_embeds,p=Kn({image_ids:n.input_ids},h.inputNames);s=await rt(h,p)}const o={...n,...s},c=await hs(this,o),u=this.sessions[r==="text"?"lm_head":"gen_head"];if(!u)throw new Error(`Unable to find "${u}" generation head`);const d=await rt(u,Kn(c,u.inputNames));return{...s,...c,...d}}prepare_inputs_for_generation(n,r,s){const o=!!r.past_key_values;return s.guidance_scale!==null&&s.guidance_scale>1&&(o?r.input_ids=Pt([r.input_ids,r.input_ids],0):(r.input_ids=Pt([r.input_ids,pg(r.input_ids,BigInt(s.pad_token_id))],0),r.attention_mask=Pt([r.attention_mask,pg(r.attention_mask,0n)],0))),(o||!r.pixel_values)&&(r.pixel_values=zn([0,0,3,384,384],1)),o&&(r.images_seq_mask=new we("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),r.images_emb_mask=new we("bool",new Array(0).fill(!1),[1,1,0])),r}async generate(n){return this._generation_mode="text",super.generate(n)}async generate_images(n){this._generation_mode="image";const r=(n.inputs??n[this.main_input_name]).dims[1],o=(await super.generate(n)).slice(null,[r,null]),c=this.sessions.image_decode,{decoded_image:u}=await rt(c,{generated_tokens:o}),d=u.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),h=[];for(const p of d){const g=rr.fromTensor(p);h.push(g)}return h}},oy=class extends Y{},EB=class extends oy{},AB=class extends oy{},X2=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(n){const[r,s]=n.dims,o=this.config.decoder.num_codebooks,c=s-o;let u=0;for(let p=0;p0&&w<=c&&(n.data[u++]=n.data[p])}const d=Math.floor(r/o),h=u/(d*o);return new we(n.type,n.data.slice(0,u),[d,o,h])}prepare_inputs_for_generation(n,r,s){const o=BigInt(this.config.decoder.pad_token_id);let c=structuredClone(n);for(let u=0;u=d&&(c[u][d]=o);return s.guidance_scale!==null&&s.guidance_scale>1&&(c=c.concat(c)),xh(this,c,r)}async generate(n){const r=await super.generate(n),s=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:o}=await rt(this.sessions.encodec_decode,{audio_codes:s});return o}},ly=class extends Y{},CB=class extends ly{},kB=class extends ly{},Pl=class extends Y{},OB=class extends Pl{},zB=class extends Pl{async _call(e){return new dn(await super._call(e))}},LB=class extends Pl{async _call(e){return new Pe(await super._call(e))}},NB=class extends Pl{async _call(e){return new sn(await super._call(e))}},DB=class extends Pl{async _call(e){return new Ln(await super._call(e))}},Q2=class extends Y{},FB=class extends Q2{},cy=class extends Y{},BB=class extends cy{},PB=class extends cy{},uy=class extends Y{},RB=class extends uy{},UB=class extends uy{},dy=class extends Y{},IB=class extends dy{},GB=class extends dy{},fy=class extends Y{},jB=class extends fy{},VB=class extends fy{},hy=class extends Y{},qB=class extends hy{},$B=class extends hy{},py=class extends Y{},HB=class extends py{},YB=class extends py{},my=class extends Y{},XB=class extends my{},QB=class extends my{},W2=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","attention_mask","pixel_values","position_ids","past_key_values"])}},WB=class extends W2{_merge_input_ids_with_image_features(e){const n=e.image_features.dims.at(-1),r=e.image_features.view(-1,n);return Xu({image_token_id:this.config.image_token_index,...e,image_features:r})}},Z2=class extends Y{},ZB=class extends Z2{async _call(e){return new ao(await super._call(e))}},_y=class extends Y{},KB=class extends _y{},JB=class extends _y{},gy=class extends Y{},eP=class extends gy{},tP=class extends gy{},vy=class extends Y{},nP=class extends vy{},aP=class extends vy{},yy=class extends Y{},rP=class extends yy{},sP=class extends yy{},K2=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"])}},J2=class extends K2{async forward({input_ids:e=null,attention_mask:n=null,pixel_values:r=null,image_sizes:s=null,position_ids:o=null,inputs_embeds:c=null,past_key_values:u=null,generation_config:d=null,logits_processor:h=null,...p}){if(!c){let y;if(r&&e.dims[1]!==1){if(!s)throw new Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:y}=await rt(this.sessions.vision_encoder,{pixel_values:r,image_sizes:s}))}else{const w=this.config.normalized_config.hidden_size;y=new we("float32",[],[0,w])}({inputs_embeds:c}=await rt(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:y}))}return await hs(this,{inputs_embeds:c,past_key_values:u,attention_mask:n,position_ids:o,generation_config:d,logits_processor:h},!1)}},wy=class extends Y{},iP=class extends wy{},oP=class extends wy{async _call(e){return new Pe(await super._call(e))}},by=class extends Y{},lP=class extends by{},cP=class extends by{async _call(e){return new sn(await super._call(e))}},My=class extends Y{},uP=class extends My{},dP=class extends My{},eT=class extends Y{constructor(){super(...arguments);L(this,"forward_params",["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"])}},fP=class extends eT{get_rope_index(e,n,r,s){const{vision_config:o,image_token_id:c,video_token_id:u,vision_start_token_id:d}=this.config,h=o.spatial_merge_size??2,p=[];if(n||r){let g=e.tolist();s||(s=wx(e));const y=s.tolist(),w=Array.from({length:3},z=>Array.from({length:e.dims[0]},D=>Array.from({length:e.dims[1]},P=>1))),b=n?n.tolist():[],S=r?r.tolist():[];let E=0,O=0;for(let z=0;zy[z][I]==1),j=D.reduce((W,I,R)=>(I==d&&W.push(R),W),[]).map(W=>D[W+1]),G=j.filter(W=>W==c).length,K=j.filter(W=>W==u).length;let k=[],ce=0,oe=G,he=K;for(let W=0;Wxt>ce&&Rt==c),R=D.findIndex((Rt,xt)=>xt>ce&&Rt==u),te=oe>0&&I!==-1?I:D.length+1,F=he>0&&R!==-1?R:D.length+1;let H,ue,de,be;te0?Qt(k.at(-1))[0]+1:0;k.push(Array.from({length:3*Qe},(Rt,xt)=>ht+xt%Qe));const Ct=Qe+ht,Ue=Oe*Ne*at,ze=Array.from({length:Ue},(Rt,xt)=>Ct+Math.floor(xt/(Ne*at))),Ye=Array.from({length:Ue},(Rt,xt)=>Ct+Math.floor(xt/at)%Ne),Ht=Array.from({length:Ue},(Rt,xt)=>Ct+xt%at);k.push([ze,Ye,Ht].flat()),ce=H+Ue}if(ce0?Qt(k.at(-1))[0]+1:0,I=D.length-ce;k.push(Array.from({length:3*I},(R,te)=>W+te%I))}const me=k.reduce((W,I)=>W+I.length,0),pe=new Array(me);let ne=0;for(let W=0;W<3;++W)for(let I=0;Ig[E%g.length]),b=Array.from({length:y[0]},(S,E)=>Qt(g.subarray(y[1]*E,y[1]*(E+1)))[0]+1n+BigInt(y[1]));return[new we("int64",w,[3,...y]),new we("int64",b,[b.length,1])]}else{const[g,y]=e.dims,w=BigInt64Array.from({length:3*g*y},(b,S)=>BigInt(Math.floor(S%y/g)));return[new we("int64",w,[3,...e.dims]),bx([g,1])]}}async encode_image({pixel_values:e,image_grid_thw:n}){return(await rt(this.sessions.vision_encoder,{pixel_values:e,grid_thw:n})).image_features}_merge_input_ids_with_image_features(e){return Xu({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,n,r){if(n.attention_mask&&!n.position_ids)if(!n.past_key_values)[n.position_ids,n.rope_deltas]=this.get_rope_index(n.input_ids,n.image_grid_thw,n.video_grid_thw,n.attention_mask);else{n.pixel_values=null;const s=BigInt(Object.values(n.past_key_values)[0].dims.at(-2)),o=n.rope_deltas.map(c=>s+c);n.position_ids=Cl([o,o,o],0)}return n}},xy=class extends Y{},hP=class extends xy{},pP=class extends xy{},Ty=class extends Y{},mP=class extends Ty{},_P=class extends Ty{async _call(e){return new Pe(await super._call(e))}},Sy=class extends Y{},gP=class extends Sy{},vP=class extends Sy{async _call(e){return new tT(await super._call(e))}},tT=class extends Wu{},Rl=class extends Y{},yP=class extends Rl{},wP=class extends Rl{async _call(e){return new dn(await super._call(e))}},bP=class extends Rl{async _call(e){return new Pe(await super._call(e))}},MP=class extends Rl{async _call(e){return new sn(await super._call(e))}},xP=class extends Rl{async _call(e){return new Ln(await super._call(e))}},Ul=class extends Y{},TP=class extends Ul{},SP=class extends Ul{async _call(e){return new dn(await super._call(e))}},EP=class extends Ul{async _call(e){return new Pe(await super._call(e))}},AP=class extends Ul{async _call(e){return new sn(await super._call(e))}},CP=class extends Ul{async _call(e){return new Ln(await super._call(e))}},Ey=class extends Y{},kP=class extends Ey{},OP=class extends Ey{async _call(e){return new nT(await super._call(e))}},nT=class extends Wu{},aT=class extends rn{constructor({iou_scores:e,pred_masks:n}){super(),this.iou_scores=e,this.pred_masks=n}},rT=class extends Y{},zP=class extends rT{async get_image_embeddings({pixel_values:e}){return await ci(this,{pixel_values:e})}async forward(e){!e.image_embeddings||!e.image_positional_embeddings?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_labels??(e.input_labels=Fa(e.input_points.dims.slice(0,-1)));const n={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(n.input_points=e.input_points),e.input_labels&&(n.input_labels=e.input_labels),e.input_boxes&&(n.input_boxes=e.input_boxes),await rt(this.sessions.prompt_encoder_mask_decoder,n)}async _call(e){return new aT(await super._call(e))}},sT=class extends rn{constructor({iou_scores:e,pred_masks:n,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=n,this.object_score_logits=r}},iT=class extends Y{},Ay=class extends iT{async get_image_embeddings({pixel_values:e}){return await ci(this,{pixel_values:e})}async forward(e){const{num_feature_levels:n}=this.config.vision_config;if(Array.from({length:n},(c,u)=>`image_embeddings.${u}`).some(c=>!e[c])?e={...e,...await this.get_image_embeddings(e)}:e={...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");const c=e.input_points.dims;e.input_labels??(e.input_labels=Fa(c.slice(0,-1))),e.input_boxes??(e.input_boxes=zn([c[0],0,4],0))}else if(e.input_boxes){const c=e.input_boxes.dims;e.input_labels=zn([c[0],c[1],0],-1n),e.input_points=zn([c[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const s=this.sessions.prompt_encoder_mask_decoder,o=Kn(e,s.inputNames);return await rt(s,o)}async _call(e){return new sT(await super._call(e))}},LP=class extends Ay{},NP=class extends Ay{},jh=class extends Y{},DP=class extends jh{},FP=class extends jh{},BP=class extends jh{},Vh=class extends Y{},PP=class extends Vh{},RP=class extends Vh{},UP=class extends Vh{},Cy=class extends Y{},IP=class extends Cy{},oT=class extends Cy{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"text_model"})}},GP=class extends ro{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"vision_model"})}},ky=class extends Y{},jP=class extends ky{},VP=class extends ky{},qh=class extends Y{constructor(){super(...arguments);L(this,"main_input_name","input_values");L(this,"forward_params",["input_values"])}},qP=class extends qh{async encode(e){return await rt(this.sessions.encoder_model,e)}async decode(e){return await rt(this.sessions.decoder_model,e)}},lT=class extends qh{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"encoder_model"})}},cT=class extends qh{static async from_pretrained(e,n={}){return super.from_pretrained(e,{...n,model_file_name:n.model_file_name??"decoder_model"})}},$h=class extends Y{},$P=class extends $h{},HP=class extends $h{},YP=class extends $h{async generate_speech(e,n,{threshold:r=.5,minlenratio:s=0,maxlenratio:o=20,vocoder:c=null}={}){const u={input_ids:e},{encoder_outputs:d,encoder_attention_mask:h}=await ci(this,u),p=d.dims[1]/this.config.reduction_factor,g=Math.floor(p*o),y=Math.floor(p*s),w=this.config.num_mel_bins;let b=[],S=null,E=null,O=0;for(;;){++O;const P=o2(!!E);let j;E?j=E.output_sequence_out:j=new we("float32",new Float32Array(w),[1,1,w]);let G={use_cache_branch:P,output_sequence:j,encoder_attention_mask:h,speaker_embeddings:n,encoder_hidden_states:d};this.addPastKeyValues(G,S),E=await rt(this.sessions.decoder_model_merged,G),S=this.getPastKeyValues(E,S);const{prob:K,spectrum:k}=E;if(b.push(k),O>=y&&(Array.from(K.data).filter(ce=>ce>=r).length>0||O>=g))break}const z=Pt(b),{waveform:D}=await rt(c.sessions.model,{spectrogram:z});return{spectrogram:z,waveform:D}}},XP=class extends Y{constructor(){super(...arguments);L(this,"main_input_name","spectrogram")}},td=class extends Y{},QP=class extends td{},WP=class extends td{async _call(e){return new dn(await super._call(e))}},ZP=class extends td{async _call(e){return new Pe(await super._call(e))}},KP=class extends td{async _call(e){return new Ln(await super._call(e))}},Oy=class extends Y{},JP=class extends Oy{},e8=class extends Oy{},zy=class extends Y{},t8=class extends zy{},n8=class extends zy{},uT=class extends Y{},a8=class extends uT{},dT=class extends Y{},fT=class extends dT{async generate_speech({input_ids:e,attention_mask:n,style:r,num_inference_steps:s=5,speed:o=1.05}){const{sampling_rate:c,chunk_compress_factor:u,base_chunk_size:d,latent_dim:h}=this.config,{last_hidden_state:p,durations:g}=await rt(this.sessions.text_encoder,{input_ids:e,attention_mask:n,style:r}),y=g.div(o).mul_(c),w=d*u,b=y.data,S=Int32Array.from(b,oe=>Math.ceil(oe/w)),E=Math.max(...S),O=e.dims[0],z=new BigInt64Array(O*E);for(let oe=0;oe`;n.push(e.lang_to_id[c]),n.push(e.task_to_id[s??"transcribe"])}else if(r||s)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&n.at(-1)!==e.no_timestamps_token_id?n.push(e.no_timestamps_token_id):e.return_timestamps&&n.at(-1)===e.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),n.pop()),n.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:n=null,logits_processor:r=null,stopping_criteria:s=null,...o}){n=this._prepare_generation_config(n,o);const c=o.decoder_input_ids??this._retrieve_init_tokens(n);if(n.return_timestamps&&(r??(r=new vg),r.push(new Q4(n,c))),n.begin_suppress_tokens&&(r??(r=new vg),r.push(new r2(n.begin_suppress_tokens,c.length))),n.return_token_timestamps){if(!n.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");n.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),n.output_attentions=!0,n.return_dict_in_generate=!0}const u=await super.generate({inputs:e,generation_config:n,logits_processor:r,decoder_input_ids:c,...o});return n.return_token_timestamps&&(u.token_timestamps=this._extract_token_timestamps(u,n.alignment_heads,n.num_frames)),u}_extract_token_timestamps(e,n,r=null,s=.02){if(!e.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");r==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let o=this.config.median_filter_width;o===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),o=7);const c=e.cross_attentions,u=Array.from({length:this.config.decoder_layers},(S,E)=>Pt(c.map(O=>O[E]),2)),d=Cl(n.map(([S,E])=>{if(S>=u.length)throw new Error(`Layer index ${S} is out of bounds for cross attentions (length ${u.length}).`);return r?u[S].slice(null,E,null,[0,r]):u[S].slice(null,E)})).transpose(1,0,2,3),[h,p]=I3(d,-2,0,!0),g=d.clone();for(let S=0;SO[K+1]-O[K]),P=zr([1],D).map(G=>!!G),j=[];for(let G=0;Ge[0])),L(ah,"BASE_IF_FAIL",!0),ah),C_,G1=(C_=class extends dt{},L(C_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]),C_),k_,hR=(k_=class extends dt{},L(k_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]),k_),O_,T_=(O_=class extends dt{},L(O_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]),O_),z_,pR=(z_=class extends dt{},L(z_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]),z_),L_,mR=(L_=class extends dt{},L(L_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]),L_),N_,_R=(N_=class extends dt{},L(N_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]),N_),D_,gR=(D_=class extends dt{},L(D_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]),D_),F_,vR=(F_=class extends dt{},L(F_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_MASKED_LM_MAPPING_NAMES]),F_),B_,yR=(B_=class extends dt{},L(B_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]),B_),P_,wR=(P_=class extends dt{},L(P_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]),P_),R_,bR=(R_=class extends dt{},L(R_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]),R_),U_,j1=(U_=class extends dt{},L(U_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]),U_),I_,V1=(I_=class extends dt{},L(I_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]),I_),G_,q1=(G_=class extends dt{},L(G_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]),G_),j_,MR=(j_=class extends dt{},L(j_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]),j_),V_,xR=(V_=class extends dt{},L(V_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]),V_),q_;q_=class extends dt{},L(q_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]);var $_,TR=($_=class extends dt{},L($_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_CTC_MAPPING_NAMES]),$_),H_,SR=(H_=class extends dt{},L(H_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]),H_),Y_;Y_=class extends dt{},L(Y_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]);var X_;X_=class extends dt{},L(X_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]);var Q_,ER=(Q_=class extends dt{},L(Q_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]),Q_),W_;W_=class extends dt{},L(W_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]);var Z_,AR=(Z_=class extends dt{},L(Z_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]),Z_),K_,CR=(K_=class extends dt{},L(K_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]),K_),J_;J_=class extends dt{},L(J_,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]);var eg;eg=class extends dt{},L(eg,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]);var tg,kR=(tg=class extends dt{},L(tg,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]),tg),ng;ng=class extends dt{},L(ng,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]);var ag;ag=class extends dt{},L(ag,"MODEL_CLASS_MAPPINGS",[ut.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]);async function lr(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(n=>rr.read(n)))}async function ju(e,n){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?qz(r,n):r instanceof Float64Array?new Float32Array(r):r))}function wg(e,n){n&&(e=e.map(u=>u|0));const[r,s,o,c]=e;return{xmin:r,ymin:s,xmax:o,ymax:c}}var $t=class extends Ba{constructor({task:e,model:n,tokenizer:r=null,processor:s=null}){super(),this.task=e,this.model=n,this.tokenizer=r,this.processor=s}async dispose(){await this.model.dispose()}},OR=class extends $t{async _call(e,{top_k:n=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(r),{problem_type:o,id2label:c}=this.model.config,u=o==="multi_label_classification"?h=>h.sigmoid():h=>new we("float32",bn(h.data),h.dims),d=[];for(const h of s.logits){const p=u(h),g=await Al(p,n),y=g[0].tolist(),b=g[1].tolist().map((S,E)=>({label:c?c[S]:`LABEL_${S}`,score:y[E]}));n===1?d.push(...b):d.push(b)}return Array.isArray(e)||n===1?d:d[0]}},zR=class extends $t{async _call(e,{ignore_labels:n=["O"]}={}){const r=Array.isArray(e),s=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),c=(await this.model(s)).logits,u=this.model.config.id2label,d=[];for(let h=0;hG==g),E=c[w].tolist(),O=u[w].tolist();for(let G=1;GK==b[G])!==-1)&&(E[G]=-1/0,O[G]=-1/0);const z=bn(E).map((G,K)=>[G,K]),D=bn(O).map((G,K)=>[G,K]);z[0][0]=0,D[0][0]=0;const P=JO(z,D).filter(G=>G[0][1]<=G[1][1]).map(G=>[G[0][1],G[1][1],G[0][0]*G[1][0]]).sort((G,K)=>K[2]-G[2]),j=[];for(let G=0;GE==r);if(g===-1)throw Error(`Mask token (${s}) not found in text.`);const y=c[h][g],w=await Al(new we("float32",bn(y.data),y.dims),n),b=w[0].tolist(),S=w[1].tolist();u.push(S.map((E,O)=>{const z=p.slice();return z[g]=E,{score:b[O],token:Number(E),token_str:this.tokenizer.decode([E]),sequence:this.tokenizer.decode(z,{skip_special_tokens:!0})}}))}return Array.isArray(e)?u:u[0]}},Gy=class extends $t{constructor(){super(...arguments);L(this,"_key","generated_text")}async _call(n,r={}){Array.isArray(n)||(n=[n]),this.model.config.prefix&&(n=n.map(h=>this.model.config.prefix+h));const s=this.model.config.task_specific_params;s&&s[this.task]&&s[this.task].prefix&&(n=n.map(h=>s[this.task].prefix+h));const o=this.tokenizer,c={padding:!0,truncation:!0};let u;this.task==="translation"&&"_build_translation_inputs"in o?u=o._build_translation_inputs(n,c,r):u=o(n,c);const d=await this.model.generate({...u,...r});return o.batch_decode(d,{skip_special_tokens:!0}).map(h=>({[this._key]:h}))}},DR=class extends Gy{constructor(){super(...arguments);L(this,"_key","summary_text")}},FR=class extends Gy{constructor(){super(...arguments);L(this,"_key","translation_text")}};function $1(e){return Array.isArray(e)&&e.every(n=>"role"in n&&"content"in n)}var BR=class extends $t{async _call(e,n={}){let r=!1,s=!1,o=n.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,c=n.tokenizer_encode_kwargs,u;if(typeof e=="string")u=e=[e];else if(Array.isArray(e)&&e.every(b=>typeof b=="string"))r=!0,u=e;else{if($1(e))e=[e];else if(Array.isArray(e)&&e.every($1))r=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");s=!0,u=e.map(b=>this.tokenizer.apply_chat_template(b,{tokenize:!1,add_generation_prompt:!0,...c})),o=!1,c=void 0}const d=s?!1:n.return_full_text??!0;this.tokenizer.padding_side="left";const h=this.tokenizer(u,{add_special_tokens:o,padding:!0,truncation:!0,...c}),p=await this.model.generate({...h,...n}),g=this.tokenizer.batch_decode(p,{skip_special_tokens:!0});let y;!d&&h.input_ids.dims.at(-1)>0&&(y=this.tokenizer.batch_decode(h.input_ids,{skip_special_tokens:!0}).map(b=>b.length));const w=Array.from({length:e.length},b=>[]);for(let b=0;b[n.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,n,{hypothesis_template:r="This example is {}.",multi_label:s=!1}={}){const o=Array.isArray(e);o||(e=[e]),Array.isArray(n)||(n=[n]);const c=n.map(h=>r.replace("{}",h)),u=s||n.length===1,d=[];for(const h of e){const p=[];for(const w of c){const b=this.tokenizer(h,{text_pair:w,padding:!0,truncation:!0}),S=await this.model(b);u?p.push([S.logits.data[this.contradiction_id],S.logits.data[this.entailment_id]]):p.push(S.logits.data[this.entailment_id])}const y=(u?p.map(w=>bn(w)[1]):bn(p)).map((w,b)=>[w,b]).sort((w,b)=>b[0]-w[0]);d.push({sequence:h,labels:y.map(w=>n[w[1]]),scores:y.map(w=>w[0])})}return o?d:d[0]}},RR=class extends $t{async _call(e,{top_k:n=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,s=await ju(e,r),o=this.model.config.id2label,c=[];for(const u of s){const d=await this.processor(u),p=(await this.model(d)).logits[0],g=await Al(new we("float32",bn(p.data),p.dims),n),y=g[0].tolist(),b=g[1].tolist().map((S,E)=>({label:o?o[S]:`LABEL_${S}`,score:y[E]}));c.push(b)}return Array.isArray(e)?c:c[0]}},UR=class extends $t{async _call(e,n,{hypothesis_template:r="This is a sound of {}."}={}){const s=!Array.isArray(e);s&&(e=[e]);const o=n.map(p=>r.replace("{}",p)),c=this.tokenizer(o,{padding:!0,truncation:!0}),u=this.processor.feature_extractor.config.sampling_rate,d=await ju(e,u),h=[];for(const p of d){const g=await this.processor(p),y=await this.model({...c,...g}),w=bn(y.logits_per_audio.data);h.push([...w].map((b,S)=>({score:b,label:n[S]})))}return s?h[0]:h}},IR=class extends $t{async _call(e,n={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,n);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,n);case"moonshine":return this._call_moonshine(e,n);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,n){n.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),n.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const r=!Array.isArray(e),s=r?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,c=await ju(s,o),u=[];for(const d of c){const h=await this.processor(d),g=(await this.model(h)).logits[0],y=[];for(const b of g)y.push(Qt(b.data)[1]);const w=this.tokenizer.decode(y,{skip_special_tokens:!0}).trim();u.push({text:w})}return r?u[0]:u}async _call_whisper(e,n){const r=n.return_timestamps??!1,s=n.chunk_length_s??0,o=n.force_full_sequences??!1;let c=n.stride_length_s??null;const u={...n};r==="word"&&(u.return_token_timestamps=!0,u.return_timestamps=!1);const d=!Array.isArray(e),h=d?[e]:e,p=this.processor.feature_extractor.config,g=p.chunk_length/this.model.config.max_source_positions,y=p.hop_length,w=p.sampling_rate,b=await ju(h,w),S=[];for(const E of b){let O=[];if(s>0){if(c===null)c=s/6;else if(s<=c)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const P=w*s,j=w*c,G=P-2*j;let K=0;for(;;){const k=K+P,ce=E.subarray(K,k),oe=await this.processor(ce),he=K===0,me=k>=E.length;if(O.push({stride:[ce.length,he?0:j,me?0:j],input_features:oe.input_features,is_last:me}),me)break;K+=G}}else O=[{stride:[E.length,0,0],input_features:(await this.processor(E)).input_features,is_last:!0}];for(const P of O){u.num_frames=Math.floor(P.stride[0]/y);const j=await this.model.generate({inputs:P.input_features,...u});r==="word"?(P.tokens=j.sequences.tolist()[0],P.token_timestamps=j.token_timestamps.tolist()[0].map(G=>Pu(G,2))):P.tokens=j[0].tolist(),P.stride=P.stride.map(G=>G/w)}const[z,D]=this.tokenizer._decode_asr(O,{time_precision:g,return_timestamps:r,force_full_sequences:o});S.push({text:z,...D})}return d?S[0]:S}async _call_moonshine(e,n){const r=!Array.isArray(e),s=r?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,c=await ju(s,o),u=[];for(const d of c){const h=await this.processor(d),p=Math.floor(d.length/o)*6,g=await this.model.generate({max_new_tokens:p,...n,...h}),y=this.processor.batch_decode(g,{skip_special_tokens:!0})[0];u.push({text:y})}return r?u[0]:u}},GR=class extends $t{constructor(n){super(n);L(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=n.vocoder??null}async _prepare_speaker_embeddings(n,r){if((typeof n=="string"||n instanceof URL)&&(n=new Float32Array(await(await fetch(n)).arrayBuffer())),n instanceof Float32Array)n=new we("float32",n,[n.length]);else if(!(n instanceof we))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(r>1){if(n.dims[0]===1)n=n.repeat(r,1);else if(n.dims[0]!==r)throw new Error(`Expected speaker embeddings batch size to be 1 or ${r}, but got ${n.dims[0]}.`)}return n}_postprocess_waveform(n,r,s,o=null){const c=r.data,[u,d]=r.dims,h=o?o.data:null,p=[];for(let g=0;g({generated_text:p.trim()}));c.push(h)}return r?c:c[0]}},VR=class extends $t{async _call(e,{top_k:n=5}={}){const r=await lr(e),{pixel_values:s}=await this.processor(r),o=await this.model({pixel_values:s}),{id2label:c}=this.model.config,u=[];for(const d of o.logits){const h=await Al(new we("float32",bn(d.data),d.dims),n),p=h[0].tolist(),y=h[1].tolist().map((w,b)=>({label:c?c[w]:`LABEL_${w}`,score:p[b]}));u.push(y)}return Array.isArray(e)?u:u[0]}},H1={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},nS=class extends $t{async _call(e,{threshold:n=.5,mask_threshold:r=.5,overlap_mask_area_threshold:s=.8,label_ids_to_fuse:o=null,target_sizes:c=null,subtask:u=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const h=await lr(e),p=h.map(z=>[z.height,z.width]),g=await this.processor(h),{inputNames:y,outputNames:w}=this.model.sessions.model;if(!y.includes("pixel_values")){if(y.length!==1)throw Error(`Expected a single input name, but got ${y.length} inputs: ${y}.`);const z=y[0];if(z in g)throw Error(`Input name ${z} already exists in the inputs.`);g[z]=g.pixel_values}const b=await this.model(g);let S=null;if(u!==null)S=H1[u];else if(this.processor.image_processor){for(const[z,D]of Object.entries(H1))if(D in this.processor.image_processor){S=this.processor.image_processor[D].bind(this.processor.image_processor),u=z;break}}const E=this.model.config.id2label,O=[];if(u)if(u==="panoptic"||u==="instance"){const z=S(b,n,r,s,o,c??p)[0],D=z.segmentation;for(const P of z.segments_info){const j=new Uint8ClampedArray(D.data.length);for(let K=0;Kk<-1e-5||k>1+1e-5)&&G.sigmoid_();const K=await rr.fromTensor(G.mul_(255).to("uint8")).resize(j[1],j[0]);O.push({label:null,score:null,mask:K})}}return O}},qR=class extends nS{async _call(e,n={}){const r=await lr(e),s=await super._call(e,n),o=r.map((c,u)=>{const d=c.clone();return d.putAlpha(s[u].mask),d});return Array.isArray(e)?o:o[0]}},$R=class extends $t{async _call(e,n,{hypothesis_template:r="This is a photo of {}"}={}){const s=Array.isArray(e),o=await lr(e),c=n.map(y=>r.replace("{}",y)),u=this.tokenizer(c,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:d}=await this.processor(o),h=await this.model({...u,pixel_values:d}),p=this.model.config.model_type==="siglip"?y=>y.sigmoid().data:y=>bn(y.data),g=[];for(const y of h.logits_per_image){const b=[...p(y)].map((S,E)=>({score:S,label:n[E]}));b.sort((S,E)=>E.score-S.score),g.push(b)}return s?g:g[0]}},HR=class extends $t{async _call(e,{threshold:n=.9,percentage:r=!1}={}){const s=Array.isArray(e);if(s&&e.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const o=await lr(e),c=r?null:o.map(w=>[w.height,w.width]),{pixel_values:u,pixel_mask:d}=await this.processor(o),h=await this.model({pixel_values:u,pixel_mask:d}),p=this.processor.image_processor.post_process_object_detection(h,n,c),{id2label:g}=this.model.config,y=p.map(w=>w.boxes.map((b,S)=>({score:w.scores[S],label:g[w.classes[S]],box:wg(b,!r)})));return s?y:y[0]}},YR=class extends $t{async _call(e,n,{threshold:r=.1,top_k:s=null,percentage:o=!1}={}){const c=Array.isArray(e),u=await lr(e),d=this.tokenizer(n,{padding:!0,truncation:!0}),h=await this.processor(u),p=[];for(let g=0;g({score:O.scores[D],label:O.labels[D],box:wg(z,!o)}))}else{const O=this.processor.image_processor.post_process_object_detection(S,r,w,!0)[0];E=O.boxes.map((z,D)=>({score:O.scores[D],label:n[O.classes[D]],box:wg(z,!o)}))}E.sort((O,z)=>z.score-O.score),s!==null&&(E=E.slice(0,s)),p.push(E)}return c?p:p[0]}},XR=class extends $t{async _call(e,n,r={}){if(Array.isArray(e)){if(e.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");e=e[0]}const s=(await lr(e))[0],{pixel_values:o}=await this.processor(s),c=`${n}`,u=this.tokenizer(c,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,d=await this.model.generate({inputs:o,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:u,...r}),p=this.tokenizer.batch_decode(d)[0].match(/(.*?)<\/s_answer>/);let g=null;return p&&p.length>=2&&(g=p[1].trim()),[{answer:g}]}},QR=class extends $t{async _call(e){const n=await lr(e),r=await this.processor(n),s=await this.model(r),o=[];for(const c of s.reconstruction){const u=c.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(rr.fromTensor(u))}return Array.isArray(e)?o:o[0]}},WR=class extends $t{async _call(e){const n=await lr(e),r=await this.processor(n),{predicted_depth:s}=await this.model(r),o=[];for(let c=0;c{var y,w;let g;for(const b of u){if(b===null){h(null);return}try{h(await b.from_pretrained(n,r));return}catch(S){if((y=S.message)!=null&&y.includes("Unsupported model type"))g=S;else if((w=S.message)!=null&&w.includes("Could not locate file"))g=S;else{p(S);return}}}p(g)}):d=u.from_pretrained(n,r),s[c]=d,o.push(d)}await Promise.all(o);for(const[c,u]of Object.entries(s))s[c]=await u;return s}Nt.IS_PROCESS_AVAILABLE;const La=class La{constructor(){L(this,"pipeline",null)}static getInstance(){return La.instance||(La.instance=new La),La.instance}async init(n){this.pipeline||(this.pipeline=await eU("text-generation",La.modelId,{progress_callback:n,device:"webgpu",dtype:La.dtype}))}async translate(n,r,s){if(!this.pipeline)throw new Error("Translator not initialized. Call init() first.");console.log(`Translating from ${r} to ${s}`,n);const o=[{role:"user",content:[{type:"text",source_lang_code:r,target_lang_code:s,text:n}]}];return(await this.pipeline(o,{max_new_tokens:1024}))[0].generated_text.pop().content}};L(La,"instance",null),L(La,"modelId","onnx-community/translategemma-text-4b-it-ONNX"),L(La,"dtype","q4"),L(La,"size",3111894696);let qu=La;function nU({progress:e,onInitialize:n,isInitializing:r=!1,className:s=""}){return _e.jsx("div",{className:Sh("max-w-2xl mx-auto px-8",s),children:_e.jsx("div",{className:"bg-white rounded-lg shadow-md p-8 border border-border",children:_e.jsxs("div",{className:"flex flex-col items-center gap-6",children:[_e.jsxs("div",{className:"space-y-4 text-left w-full",children:[_e.jsxs("div",{children:[_e.jsx("h3",{className:"font-semibold text-base mb-1",children:"About TranslateGemma 4B"}),_e.jsxs("p",{className:"text-sm text-secondary-foreground",children:["TranslateGemma is a family of translation models from Google, built on top of Gemma 2B. This 4B parameter model supports translations across 100+ languages with state-of-the-art quality."," ",_e.jsx("a",{href:"https://blog.google/innovation-and-ai/technology/developers-tools/translategemma/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"Learn more"})]})]}),_e.jsxs("div",{children:[_e.jsx("h3",{className:"font-semibold text-base mb-1",children:"Completely private & offline-capable"}),_e.jsx("p",{className:"text-sm text-secondary-foreground",children:"Everything runs entirely in your browser with 🤗 Transformers.js and ONNX Runtime Web — no data is ever sent to a server. Once loaded, it works offline."})]}),_e.jsxs("div",{children:[_e.jsx("h3",{className:"font-semibold text-base mb-1",children:"Experimental — WebGPU required"}),_e.jsx("p",{className:"text-sm text-secondary-foreground",children:"This is experimental and requires a browser with WebGPU support and enough VRAM to run the model."})]})]}),r?_e.jsxs("div",{className:"w-full space-y-2",children:[_e.jsxs("div",{className:"flex justify-between items-center",children:[_e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"Loading model..."}),_e.jsxs("span",{className:"text-sm font-medium text-primary",children:[e,"%"]})]}),_e.jsx("div",{className:"w-full bg-muted rounded-full h-2 overflow-hidden",children:_e.jsx("div",{className:"bg-primary h-full transition-all duration-300 ease-out",style:{width:`${e}%`}})}),_e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"This may take a few moments. Please don't close the page."})]}):_e.jsx(rg,{variant:"primary",onClick:n,disabled:r,className:"text-lg mt-8",children:r?"Initializing...":`Download TranslateGemma (${jE(qu.size)})`})]})})})}function aU(){const[e,n]=Mt.useState(null),[r,s]=Mt.useState(0),[o,c]=Mt.useState(!1),u=async()=>{c(!0);const d=qu.getInstance(),h=new Map;let p=0;await d.init(g=>{if(g.status==="progress"){h.set(g.file,g.loaded);const y=Array.from(h.values()).reduce((b,S)=>b+S,0),w=Math.round(100/qu.size*y);p!==w&&(p=w,s(p))}}),n(d),c(!1)};return _e.jsxs("div",{className:"min-h-screen bg-neutral-100 flex flex-col justify-between gap-2",children:[_e.jsx("header",{className:"bg-white border-b border-border shadow-sm p-4",children:_e.jsxs("h1",{className:"text-md md:text-3xl font-sans text-center flex justify-center items-center gap-2 md:gap-6",children:[_e.jsxs("span",{className:"font-bold flex items-center justify-center gap-1",children:[_e.jsx("img",{src:"gemma.svg",alt:"Gemma Logo",className:"block",style:{width:"1.2em",height:"1.2em"}}),_e.jsxs("span",{children:["Translate",_e.jsx("span",{className:"text-primary",children:"Gemma"})]})]}),_e.jsx("span",{children:"//"}),_e.jsxs("span",{className:"font-bold flex items-center justify-center gap-1",children:[_e.jsx("img",{src:"hf-logo.svg",alt:"Gemma Logo",className:"block",style:{width:"1.2em",height:"1.2em"}}),"Transformers.js"]})]})}),e?_e.jsx($E,{className:"w-full",translator:e}):_e.jsx(nU,{onInitialize:u,progress:r,isInitializing:o}),_e.jsx("footer",{className:"p-8 pt-0 text-center text-muted-foreground text-xs md:text-sm",children:_e.jsxs("p",{children:["High-quality translations across 56 languages powered by"," ",_e.jsx("a",{href:"https://blog.google/technology/developers/gemma-open-models/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"Google's TranslateGemma"})," ","model, running entirely in your browser with"," ",_e.jsx("a",{href:"https://huggingface.co/docs/transformers.js",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"Transformers.js"})," ","and complete privacy."]})})]})}ME.createRoot(document.getElementById("root")).render(_e.jsx(Mt.StrictMode,{children:_e.jsx(aU,{})}));