diff --git "a/assets/index-DXLF5hH7.js" "b/assets/index-DXLF5hH7.js" new file mode 100644--- /dev/null +++ "b/assets/index-DXLF5hH7.js" @@ -0,0 +1,57 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const u of l.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&s(u)}).observe(document,{childList:!0,subtree:!0});function r(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function s(o){if(o.ep)return;o.ep=!0;const l=r(o);fetch(o.href,l)}})();var _m={exports:{}},au={};var P0;function lE(){if(P0)return au;P0=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(s,o,l){var u=null;if(l!==void 0&&(u=""+l),o.key!==void 0&&(u=""+o.key),"key"in o){l={};for(var d in o)d!=="key"&&(l[d]=o[d])}else l=o;return o=l.ref,{$$typeof:e,type:s,key:u,ref:o!==void 0?o:null,props:l}}return au.Fragment=t,au.jsx=r,au.jsxs=r,au}var I0;function cE(){return I0||(I0=1,_m.exports=lE()),_m.exports}var Z=cE(),gm={exports:{}},Ie={};var U0;function uE(){if(U0)return Ie;U0=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),w=Symbol.iterator;function b(D){return D===null||typeof D!="object"?null:(D=w&&D[w]||D["@@iterator"],typeof D=="function"?D:null)}var S={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,z={};function k(D,te,ae){this.props=D,this.context=te,this.refs=z,this.updater=ae||S}k.prototype.isReactComponent={},k.prototype.setState=function(D,te){if(typeof D!="object"&&typeof D!="function"&&D!=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,D,te,"setState")},k.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function L(){}L.prototype=k.prototype;function R(D,te,ae){this.props=D,this.context=te,this.refs=z,this.updater=ae||S}var N=R.prototype=new L;N.constructor=R,E(N,k.prototype),N.isPureReactComponent=!0;var B=Array.isArray;function j(){}var C={H:null,A:null,T:null,S:null},ue=Object.prototype.hasOwnProperty;function oe(D,te,ae){var ge=ae.ref;return{$$typeof:e,type:D,key:te,ref:ge!==void 0?ge:null,props:ae}}function he(D,te){return oe(D.type,te,D.props)}function _e(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function de(D){var te={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function(ae){return te[ae]})}var re=/\/+/g;function W(D,te){return typeof D=="object"&&D!==null&&D.key!=null?de(""+D.key):te.toString(36)}function pe(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(j,j):(D.status="pending",D.then(function(te){D.status==="pending"&&(D.status="fulfilled",D.value=te)},function(te){D.status==="pending"&&(D.status="rejected",D.reason=te)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function V(D,te,ae,ge,Me){var Ee=typeof D;(Ee==="undefined"||Ee==="boolean")&&(D=null);var ze=!1;if(D===null)ze=!0;else switch(Ee){case"bigint":case"string":case"number":ze=!0;break;case"object":switch(D.$$typeof){case e:case t:ze=!0;break;case g:return ze=D._init,V(ze(D._payload),te,ae,ge,Me)}}if(ze)return Me=Me(D),ze=ge===""?"."+W(D,0):ge,B(Me)?(ae="",ze!=null&&(ae=ze.replace(re,"$&/")+"/"),V(Me,te,ae,"",function(Ue){return Ue})):Me!=null&&(_e(Me)&&(Me=he(Me,ae+(Me.key==null||D&&D.key===Me.key?"":(""+Me.key).replace(re,"$&/")+"/")+ze)),te.push(Me)),1;ze=0;var et=ge===""?".":ge+":";if(B(D))for(var ke=0;ke>>1,J=V[$];if(0>>1;$o(ae,I))geo(Me,ae)?(V[$]=Me,V[ge]=I,$=ge):(V[$]=ae,V[te]=I,$=te);else if(geo(Me,I))V[$]=Me,V[ge]=I,$=ge;else break e}}return ee}function o(V,ee){var I=V.sortIndex-ee.sortIndex;return I!==0?I:V.id-ee.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var u=Date,d=u.now();e.unstable_now=function(){return u.now()-d}}var f=[],p=[],g=1,y=null,w=3,b=!1,S=!1,E=!1,z=!1,k=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function N(V){for(var ee=r(p);ee!==null;){if(ee.callback===null)s(p);else if(ee.startTime<=V)s(p),ee.sortIndex=ee.expirationTime,t(f,ee);else break;ee=r(p)}}function B(V){if(E=!1,N(V),!S)if(r(f)!==null)S=!0,j||(j=!0,de());else{var ee=r(p);ee!==null&&pe(B,ee.startTime-V)}}var j=!1,C=-1,ue=5,oe=-1;function he(){return z?!0:!(e.unstable_now()-oeV&&he());){var $=y.callback;if(typeof $=="function"){y.callback=null,w=y.priorityLevel;var J=$(y.expirationTime<=V);if(V=e.unstable_now(),typeof J=="function"){y.callback=J,N(V),ee=!0;break t}y===r(f)&&s(f),N(V)}else s(f);y=r(f)}if(y!==null)ee=!0;else{var D=r(p);D!==null&&pe(B,D.startTime-V),ee=!1}}break e}finally{y=null,w=I,b=!1}ee=void 0}}finally{ee?de():j=!1}}}var de;if(typeof R=="function")de=function(){R(_e)};else if(typeof MessageChannel<"u"){var re=new MessageChannel,W=re.port2;re.port1.onmessage=_e,de=function(){W.postMessage(null)}}else de=function(){k(_e,0)};function pe(V,ee){C=k(function(){V(e.unstable_now())},ee)}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||125$?(V.sortIndex=I,t(p,V),r(f)===null&&V===r(p)&&(E?(L(C),C=-1):E=!0,pe(B,I-$))):(V.sortIndex=J,t(f,V),S||b||(S=!0,j||(j=!0,de()))),V},e.unstable_shouldYield=he,e.unstable_wrapCallback=function(V){var ee=w;return function(){var I=w;w=ee;try{return V.apply(this,arguments)}finally{w=I}}}})(wm)),wm}var V0;function fE(){return V0||(V0=1,vm.exports=dE()),vm.exports}var bm={exports:{}},An={};var q0;function hE(){if(q0)return An;q0=1;var e=x_();function t(f){var p="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),bm.exports=hE(),bm.exports}var $0;function mE(){if($0)return ru;$0=1;var e=fE(),t=x_(),r=pE();function s(n){var a="https://react.dev/errors/"+n;if(1J||(n.current=$[J],$[J]=null,J--)}function ae(n,a){J++,$[J]=n.current,n.current=a}var ge=D(null),Me=D(null),Ee=D(null),ze=D(null);function et(n,a){switch(ae(Ee,a),ae(Me,n),ae(ge,null),a.nodeType){case 9:case 11:n=(n=a.documentElement)&&(n=n.namespaceURI)?o0(n):0;break;default:if(n=a.tagName,a=a.namespaceURI)a=o0(a),n=l0(a,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}te(ge),ae(ge,n)}function ke(){te(ge),te(Me),te(Ee)}function Ue(n){n.memoizedState!==null&&ae(ze,n);var a=ge.current,i=l0(a,n.type);a!==i&&(ae(Me,n),ae(ge,i))}function xt(n){Me.current===n&&(te(ge),te(Me)),ze.current===n&&(te(ze),Jc._currentValue=I)}var He,Ye;function bn(n){if(He===void 0)try{throw Error()}catch(i){var a=i.stack.trim().match(/\n( *(at )?)/);He=a&&a[1]||"",Ye=-1)":-1h||P[c]!==Y[h]){var se=` +`+P[c].replace(" at new "," at ");return n.displayName&&se.includes("")&&(se=se.replace("",n.displayName)),se}while(1<=c&&0<=h);break}}}finally{za=!1,Error.prepareStackTrace=i}return(i=n?n.displayName||n.name:"")?bn(i):""}function Dt(n,a){switch(n.tag){case 26:case 27:case 5:return bn(n.type);case 16:return bn("Lazy");case 13:return n.child!==a&&a!==null?bn("Suspense Fallback"):bn("Suspense");case 19:return bn("SuspenseList");case 0:case 15:return an(n.type,!1);case 11:return an(n.type.render,!1);case 1:return an(n.type,!0);case 31:return bn("Activity");default:return""}}function ls(n){try{var a="",i=null;do a+=Dt(n,i),i=n,n=n.return;while(n);return a}catch(c){return` +Error generating stack: `+c.message+` +`+c.stack}}var no=Object.prototype.hasOwnProperty,La=e.unstable_scheduleCallback,ao=e.unstable_cancelCallback,Du=e.unstable_shouldYield,Ru=e.unstable_requestPaint,Mn=e.unstable_now,nr=e.unstable_getCurrentPriorityLevel,Bu=e.unstable_ImmediatePriority,ti=e.unstable_UserBlockingPriority,kr=e.unstable_NormalPriority,fn=e.unstable_LowPriority,Pu=e.unstable_IdlePriority,cs=e.log,wh=e.unstable_setDisableYieldValue,us=null,xn=null;function ma(n){if(typeof cs=="function"&&wh(n),xn&&typeof xn.setStrictMode=="function")try{xn.setStrictMode(us,n)}catch{}}var hn=Math.clz32?Math.clz32:xh,bh=Math.log,Mh=Math.LN2;function xh(n){return n>>>=0,n===0?32:31-(bh(n)/Mh|0)|0}var ro=256,so=262144,io=4194304;function ar(n){var a=n&42;if(a!==0)return a;switch(n&-n){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 n&261888;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function ni(n,a,i){var c=n.pendingLanes;if(c===0)return 0;var h=0,m=n.suspendedLanes,T=n.pingedLanes;n=n.warmLanes;var A=c&134217727;return A!==0?(c=A&~m,c!==0?h=ar(c):(T&=A,T!==0?h=ar(T):i||(i=A&~n,i!==0&&(h=ar(i))))):(A=c&~m,A!==0?h=ar(A):T!==0?h=ar(T):i||(i=c&~n,i!==0&&(h=ar(i)))),h===0?0:a!==0&&a!==h&&(a&m)===0&&(m=h&-h,i=a&-a,m>=i||m===32&&(i&4194048)!==0)?a:h}function ai(n,a){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&a)===0}function Iu(n,a){switch(n){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 Hl(){var n=io;return io<<=1,(io&62914560)===0&&(io=4194304),n}function oo(n){for(var a=[],i=0;31>i;i++)a.push(n);return a}function _a(n,a){n.pendingLanes|=a,a!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Uu(n,a,i,c,h,m){var T=n.pendingLanes;n.pendingLanes=i,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=i,n.entangledLanes&=i,n.errorRecoveryDisabledLanes&=i,n.shellSuspendCounter=0;var A=n.entanglements,P=n.expirationTimes,Y=n.hiddenUpdates;for(i=T&~i;0"u")return null;try{return n.activeElement||n.body}catch{return n.body}}var Ah=/[\n"\\]/g;function $n(n){return n.replace(Ah,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Kl(n,a,i,c,h,m,T,A){n.name="",T!=null&&typeof T!="function"&&typeof T!="symbol"&&typeof T!="boolean"?n.type=T:n.removeAttribute("type"),a!=null?T==="number"?(a===0&&n.value===""||n.value!=a)&&(n.value=""+Rt(a)):n.value!==""+Rt(a)&&(n.value=""+Rt(a)):T!=="submit"&&T!=="reset"||n.removeAttribute("value"),a!=null?Jl(n,T,Rt(a)):i!=null?Jl(n,T,Rt(i)):c!=null&&n.removeAttribute("value"),h==null&&m!=null&&(n.defaultChecked=!!m),h!=null&&(n.checked=h&&typeof h!="function"&&typeof h!="symbol"),A!=null&&typeof A!="function"&&typeof A!="symbol"&&typeof A!="boolean"?n.name=""+Rt(A):n.removeAttribute("name")}function qu(n,a,i,c,h,m,T,A){if(m!=null&&typeof m!="function"&&typeof m!="symbol"&&typeof m!="boolean"&&(n.type=m),a!=null||i!=null){if(!(m!=="submit"&&m!=="reset"||a!=null)){_o(n);return}i=i!=null?""+Rt(i):"",a=a!=null?""+Rt(a):i,A||a===n.value||(n.value=a),n.defaultValue=a}c=c??h,c=typeof c!="function"&&typeof c!="symbol"&&!!c,n.checked=A?n.checked:!!c,n.defaultChecked=!!c,T!=null&&typeof T!="function"&&typeof T!="symbol"&&typeof T!="boolean"&&(n.name=T),_o(n)}function Jl(n,a,i){a==="number"&&go(n.ownerDocument)===n||n.defaultValue===""+i||(n.defaultValue=""+i)}function fs(n,a,i,c){if(n=n.options,a){a={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ac=!1;if(va)try{var Fr={};Object.defineProperty(Fr,"passive",{get:function(){ac=!0}}),window.addEventListener("test",Fr,Fr),window.removeEventListener("test",Fr,Fr)}catch{ac=!1}var ir=null,wo=null,bo=null;function Mo(){if(bo)return bo;var n,a=wo,i=a.length,c,h="value"in ir?ir.value:ir.textContent,m=h.length;for(n=0;n=ui),Eo=" ",gs=!1;function Wt(n,a){switch(n){case"keyup":return Qh.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function nd(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var En=!1;function Ao(n,a){switch(n){case"compositionend":return nd(a);case"keypress":return a.which!==32?null:(gs=!0,Eo);case"textInput":return n=a.data,n===Eo&&gs?null:n;default:return null}}function ys(n,a){if(En)return n==="compositionend"||!cc&&Wt(n,a)?(n=Mo(),bo=wo=ir=null,En=!1,n):null;switch(n){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-n};n=c}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=cd(i)}}function dd(n,a){return n&&a?n===a?!0:n&&n.nodeType===3?!1:a&&a.nodeType===3?dd(n,a.parentNode):"contains"in n?n.contains(a):n.compareDocumentPosition?!!(n.compareDocumentPosition(a)&16):!1:!1}function fd(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var a=go(n.document);a instanceof n.HTMLIFrameElement;){try{var i=typeof a.contentWindow.location.href=="string"}catch{i=!1}if(i)n=a.contentWindow;else break;a=go(n.document)}return a}function dc(n){var a=n&&n.nodeName&&n.nodeName.toLowerCase();return a&&(a==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||a==="textarea"||n.contentEditable==="true")}var tp=va&&"documentMode"in document&&11>=document.documentMode,or=null,pi=null,ws=null,ko=!1;function fc(n,a,i){var c=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;ko||or==null||or!==go(c)||(c=or,"selectionStart"in c&&dc(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset}),ws&&hi(ws,c)||(ws=c,c=Zd(pi,"onSelect"),0>=T,h-=T,aa=1<<32-hn(a)+h|i<qe?(nt=Te,Te=null):nt=Te.sibling;var lt=K(q,Te,Q[qe],le);if(lt===null){Te===null&&(Te=nt);break}n&&Te&<.alternate===null&&a(q,Te),G=m(lt,G,qe),ot===null?Oe=lt:ot.sibling=lt,ot=lt,Te=nt}if(qe===Q.length)return i(q,Te),Qe&&ba(q,qe),Oe;if(Te===null){for(;qeqe?(nt=Te,Te=null):nt=Te.sibling;var qs=K(q,Te,lt.value,le);if(qs===null){Te===null&&(Te=nt);break}n&&Te&&qs.alternate===null&&a(q,Te),G=m(qs,G,qe),ot===null?Oe=qs:ot.sibling=qs,ot=qs,Te=nt}if(lt.done)return i(q,Te),Qe&&ba(q,qe),Oe;if(Te===null){for(;!lt.done;qe++,lt=Q.next())lt=ce(q,lt.value,le),lt!==null&&(G=m(lt,G,qe),ot===null?Oe=lt:ot.sibling=lt,ot=lt);return Qe&&ba(q,qe),Oe}for(Te=c(Te);!lt.done;qe++,lt=Q.next())lt=ne(Te,q,qe,lt.value,le),lt!==null&&(n&<.alternate!==null&&Te.delete(lt.key===null?qe:lt.key),G=m(lt,G,qe),ot===null?Oe=lt:ot.sibling=lt,ot=lt);return n&&Te.forEach(function(oE){return a(q,oE)}),Qe&&ba(q,qe),Oe}function wt(q,G,Q,le){if(typeof Q=="object"&&Q!==null&&Q.type===E&&Q.key===null&&(Q=Q.props.children),typeof Q=="object"&&Q!==null){switch(Q.$$typeof){case b:e:{for(var Oe=Q.key;G!==null;){if(G.key===Oe){if(Oe=Q.type,Oe===E){if(G.tag===7){i(q,G.sibling),le=h(G,Q.props.children),le.return=q,q=le;break e}}else if(G.elementType===Oe||typeof Oe=="object"&&Oe!==null&&Oe.$$typeof===ue&&fr(Oe)===G.type){i(q,G.sibling),le=h(G,Q.props),As(le,Q),le.return=q,q=le;break e}i(q,G);break}else a(q,G);G=G.sibling}Q.type===E?(le=ur(Q.props.children,q.mode,le,Q.key),le.return=q,q=le):(le=mi(Q.type,Q.key,Q.props,null,q.mode,le),As(le,Q),le.return=q,q=le)}return T(q);case S:e:{for(Oe=Q.key;G!==null;){if(G.key===Oe)if(G.tag===4&&G.stateNode.containerInfo===Q.containerInfo&&G.stateNode.implementation===Q.implementation){i(q,G.sibling),le=h(G,Q.children||[]),le.return=q,q=le;break e}else{i(q,G);break}else a(q,G);G=G.sibling}le=Bn(Q,q.mode,le),le.return=q,q=le}return T(q);case ue:return Q=fr(Q),wt(q,G,Q,le)}if(pe(Q))return xe(q,G,Q,le);if(de(Q)){if(Oe=de(Q),typeof Oe!="function")throw Error(s(150));return Q=Oe.call(Q),Le(q,G,Q,le)}if(typeof Q.then=="function")return wt(q,G,Ai(Q),le);if(Q.$$typeof===R)return wt(q,G,xi(q,Q),le);Ci(q,Q)}return typeof Q=="string"&&Q!==""||typeof Q=="number"||typeof Q=="bigint"?(Q=""+Q,G!==null&&G.tag===6?(i(q,G.sibling),le=h(G,Q),le.return=q,q=le):(i(q,G),le=_i(Q,q.mode,le),le.return=q,q=le),T(q)):i(q,G)}return function(q,G,Q,le){try{Es=0;var Oe=wt(q,G,Q,le);return Hr=null,Oe}catch(Te){if(Te===qr||Te===Si)throw Te;var ot=Rn(29,Te,null,q.mode);return ot.lanes=le,ot.return=q,ot}}}var pr=Ec(!0),Ac=Ec(!1),on=!1;function Cc(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ki(n,a){n=n.updateQueue,a.updateQueue===n&&(a.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function mr(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function _r(n,a,i){var c=n.updateQueue;if(c===null)return null;if(c=c.shared,(ut&2)!==0){var h=c.pending;return h===null?a.next=a:(a.next=h.next,h.next=a),c.pending=a,a=No(n),vd(n,null,i),a}return Fo(n,c,a,i),No(n)}function Oi(n,a,i){if(a=a.updateQueue,a!==null&&(a=a.shared,(i&4194048)!==0)){var c=a.lanes;c&=n.pendingLanes,i|=c,a.lanes=i,Ql(n,i)}}function kc(n,a){var i=n.updateQueue,c=n.alternate;if(c!==null&&(c=c.updateQueue,i===c)){var h=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?h=m=T:m=m.next=T,i=i.next}while(i!==null);m===null?h=m=a:m=m.next=a}else h=m=a;i={baseState:c.baseState,firstBaseUpdate:h,lastBaseUpdate:m,shared:c.shared,callbacks:c.callbacks},n.updateQueue=i;return}n=i.lastBaseUpdate,n===null?i.firstBaseUpdate=a:n.next=a,i.lastBaseUpdate=a}var Oc=!1;function zi(){if(Oc){var n=Vr;if(n!==null)throw n}}function Li(n,a,i,c){Oc=!1;var h=n.updateQueue;on=!1;var m=h.firstBaseUpdate,T=h.lastBaseUpdate,A=h.shared.pending;if(A!==null){h.shared.pending=null;var P=A,Y=P.next;P.next=null,T===null?m=Y:T.next=Y,T=P;var se=n.alternate;se!==null&&(se=se.updateQueue,A=se.lastBaseUpdate,A!==T&&(A===null?se.firstBaseUpdate=Y:A.next=Y,se.lastBaseUpdate=P))}if(m!==null){var ce=h.baseState;T=0,se=Y=P=null,A=m;do{var K=A.lane&-536870913,ne=K!==A.lane;if(ne?(tt&K)===K:(c&K)===K){K!==0&&K===jr&&(Oc=!0),se!==null&&(se=se.next={lane:0,tag:A.tag,payload:A.payload,callback:null,next:null});e:{var xe=n,Le=A;K=a;var wt=i;switch(Le.tag){case 1:if(xe=Le.payload,typeof xe=="function"){ce=xe.call(wt,ce,K);break e}ce=xe;break e;case 3:xe.flags=xe.flags&-65537|128;case 0:if(xe=Le.payload,K=typeof xe=="function"?xe.call(wt,ce,K):xe,K==null)break e;ce=y({},ce,K);break e;case 2:on=!0}}K=A.callback,K!==null&&(n.flags|=64,ne&&(n.flags|=8192),ne=h.callbacks,ne===null?h.callbacks=[K]:ne.push(K))}else ne={lane:K,tag:A.tag,payload:A.payload,callback:A.callback,next:null},se===null?(Y=se=ne,P=ce):se=se.next=ne,T|=K;if(A=A.next,A===null){if(A=h.shared.pending,A===null)break;ne=A,A=ne.next,ne.next=null,h.lastBaseUpdate=ne,h.shared.pending=null}}while(!0);se===null&&(P=ce),h.baseState=P,h.firstBaseUpdate=Y,h.lastBaseUpdate=se,m===null&&(h.shared.lanes=0),Ns|=T,n.lanes=T,n.memoizedState=ce}}function Ed(n,a){if(typeof n!="function")throw Error(s(191,n));n.call(a)}function Ad(n,a){var i=n.callbacks;if(i!==null)for(n.callbacks=null,n=0;nm?m:8;var T=V.T,A={};V.T=A,pp(n,!1,a,i);try{var P=h(),Y=V.S;if(Y!==null&&Y(A,P),P!==null&&typeof P=="object"&&typeof P.then=="function"){var se=Sd(P,c);Rc(n,a,se,oa(n))}else Rc(n,a,c,oa(n))}catch(ce){Rc(n,a,{then:function(){},status:"rejected",reason:ce},oa())}finally{ee.p=m,T!==null&&A.types!==null&&(T.types=A.types),V.T=T}}function nS(){}function fp(n,a,i,c){if(n.tag!==5)throw Error(s(476));var h=Fv(n).queue;Lv(n,h,a,I,i===null?nS:function(){return Nv(n),i(c)})}function Fv(n){var a=n.memoizedState;if(a!==null)return a;a={memoizedState:I,baseState:I,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ye,lastRenderedState:I},next:null};var i={};return a.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ye,lastRenderedState:i},next:null},n.memoizedState=a,n=n.alternate,n!==null&&(n.memoizedState=a),a}function Nv(n){var a=Fv(n);a.next===null&&(a=n.alternate.memoizedState),Rc(n,a.next.queue,{},oa())}function hp(){return Yt(Jc)}function Dv(){return U().memoizedState}function Rv(){return U().memoizedState}function aS(n){for(var a=n.return;a!==null;){switch(a.tag){case 24:case 3:var i=oa();n=mr(i);var c=_r(a,n,i);c!==null&&(ea(c,a,i),Oi(c,a,i)),a={cache:Go()},n.payload=a;return}a=a.return}}function rS(n,a,i){var c=oa();i={lane:c,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},Ld(n)?Pv(a,i):(i=mc(n,a,i,c),i!==null&&(ea(i,n,c),Iv(i,a,c)))}function Bv(n,a,i){var c=oa();Rc(n,a,i,c)}function Rc(n,a,i,c){var h={lane:c,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(Ld(n))Pv(a,h);else{var m=n.alternate;if(n.lanes===0&&(m===null||m.lanes===0)&&(m=a.lastRenderedReducer,m!==null))try{var T=a.lastRenderedState,A=m(T,i);if(h.hasEagerState=!0,h.eagerState=A,Dn(A,T))return Fo(n,a,h,0),Mt===null&&Lo(),!1}catch{}if(i=mc(n,a,h,c),i!==null)return ea(i,n,c),Iv(i,a,c),!0}return!1}function pp(n,a,i,c){if(c={lane:2,revertLane:$p(),gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Ld(n)){if(a)throw Error(s(479))}else a=mc(n,i,c,2),a!==null&&ea(a,n,2)}function Ld(n){var a=n.alternate;return n===Be||a!==null&&a===Be}function Pv(n,a){ks=Qo=!0;var i=n.pending;i===null?a.next=a:(a.next=i.next,i.next=a),n.pending=a}function Iv(n,a,i){if((i&4194048)!==0){var c=a.lanes;c&=n.pendingLanes,i|=c,a.lanes=i,Ql(n,i)}}var Bc={readContext:Yt,use:we,useCallback:At,useContext:At,useEffect:At,useImperativeHandle:At,useLayoutEffect:At,useInsertionEffect:At,useMemo:At,useReducer:At,useRef:At,useState:At,useDebugValue:At,useDeferredValue:At,useTransition:At,useSyncExternalStore:At,useId:At,useHostTransitionStatus:At,useFormState:At,useActionState:At,useOptimistic:At,useMemoCache:At,useCacheRefresh:At};Bc.useEffectEvent=At;var Uv={readContext:Yt,use:we,useCallback:function(n,a){return F().memoizedState=[n,a===void 0?null:a],n},useContext:Yt,useEffect:xv,useImperativeHandle:function(n,a,i){i=i!=null?i.concat([n]):null,Od(4194308,4,Av.bind(null,a,n),i)},useLayoutEffect:function(n,a){return Od(4194308,4,n,a)},useInsertionEffect:function(n,a){Od(4,2,n,a)},useMemo:function(n,a){var i=F();a=a===void 0?null:a;var c=n();if($r){ma(!0);try{n()}finally{ma(!1)}}return i.memoizedState=[c,a],c},useReducer:function(n,a,i){var c=F();if(i!==void 0){var h=i(a);if($r){ma(!0);try{i(a)}finally{ma(!1)}}}else h=a;return c.memoizedState=c.baseState=h,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:h},c.queue=n,n=n.dispatch=rS.bind(null,Be,n),[c.memoizedState,n]},useRef:function(n){var a=F();return n={current:n},a.memoizedState=n},useState:function(n){n=op(n);var a=n.queue,i=Bv.bind(null,Be,a);return a.dispatch=i,[n.memoizedState,i]},useDebugValue:up,useDeferredValue:function(n,a){var i=F();return dp(i,n,a)},useTransition:function(){var n=op(!1);return n=Lv.bind(null,Be,n.queue,!0,!1),F().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,a,i){var c=Be,h=F();if(Qe){if(i===void 0)throw Error(s(407));i=i()}else{if(i=a(),Mt===null)throw Error(s(349));(tt&127)!==0||Yo(c,a,i)}h.memoizedState=i;var m={value:i,getSnapshot:a};return h.queue=m,xv(cv.bind(null,c,m,n),[n]),c.flags|=2048,Zo(9,{destroy:void 0},Xo.bind(null,c,m,i,a),null),i},useId:function(){var n=F(),a=Mt.identifierPrefix;if(Qe){var i=ra,c=aa;i=(c&~(1<<32-hn(c)-1)).toString(32)+i,a="_"+a+"R_"+i,i=Wo++,0<\/script>",m=m.removeChild(m.firstChild);break;case"select":m=typeof c.is=="string"?T.createElement("select",{is:c.is}):T.createElement("select"),c.multiple?m.multiple=!0:c.size&&(m.size=c.size);break;default:m=typeof c.is=="string"?T.createElement(h,{is:c.is}):T.createElement(h)}}m[$t]=a,m[pn]=c;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(gn(m,h,c),h){case"button":case"input":case"select":case"textarea":c=!!c.autoFocus;break e;case"img":c=!0;break e;default:c=!1}c&&Wr(a)}}return Tt(a),Cp(a,a.type,n===null?null:n.memoizedProps,a.pendingProps,i),null;case 6:if(n&&a.stateNode!=null)n.memoizedProps!==c&&Wr(a);else{if(typeof c!="string"&&a.stateNode===null)throw Error(s(166));if(n=Ee.current,Ur(a)){if(n=a.stateNode,i=a.memoizedProps,c=null,h=Lt,h!==null)switch(h.tag){case 27:case 5:c=h.memoizedProps}n[$t]=a,n=!!(n.nodeValue===i||c!==null&&c.suppressHydrationWarning===!0||s0(n.nodeValue,i)),n||Pa(a,!0)}else n=Kd(n).createTextNode(c),n[$t]=a,a.stateNode=n}return Tt(a),null;case 31:if(i=a.memoizedState,n===null||n.memoizedState!==null){if(c=Ur(a),i!==null){if(n===null){if(!c)throw Error(s(318));if(n=a.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(s(557));n[$t]=a}else Ia(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tt(a),n=!1}else i=Ge(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=i),n=!0;if(!n)return a.flags&256?(Vn(a),a):(Vn(a),null);if((a.flags&128)!==0)throw Error(s(558))}return Tt(a),null;case 13:if(c=a.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(h=Ur(a),c!==null&&c.dehydrated!==null){if(n===null){if(!h)throw Error(s(318));if(h=a.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(s(317));h[$t]=a}else Ia(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Tt(a),h=!1}else h=Ge(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=h),h=!0;if(!h)return a.flags&256?(Vn(a),a):(Vn(a),null)}return Vn(a),(a.flags&128)!==0?(a.lanes=i,a):(i=c!==null,n=n!==null&&n.memoizedState!==null,i&&(c=a.child,h=null,c.alternate!==null&&c.alternate.memoizedState!==null&&c.alternate.memoizedState.cachePool!==null&&(h=c.alternate.memoizedState.cachePool.pool),m=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(m=c.memoizedState.cachePool.pool),m!==h&&(c.flags|=2048)),i!==n&&i&&(a.child.flags|=8192),Bd(a,a.updateQueue),Tt(a),null);case 4:return ke(),n===null&&Xp(a.stateNode.containerInfo),Tt(a),null;case 10:return xa(a.type),Tt(a),null;case 19:if(te(Nt),c=a.memoizedState,c===null)return Tt(a),null;if(h=(a.flags&128)!==0,m=c.rendering,m===null)if(h)Ic(c,!1);else{if(It!==0||n!==null&&(n.flags&128)!==0)for(n=a.child;n!==null;){if(m=$o(n),m!==null){for(a.flags|=128,Ic(c,!1),n=m.updateQueue,a.updateQueue=n,Bd(a,n),a.subtreeFlags=0,n=i,i=a.child;i!==null;)wd(i,n),i=i.sibling;return ae(Nt,Nt.current&1|2),Qe&&ba(a,c.treeForkCount),a.child}n=n.sibling}c.tail!==null&&Mn()>jd&&(a.flags|=128,h=!0,Ic(c,!1),a.lanes=4194304)}else{if(!h)if(n=$o(m),n!==null){if(a.flags|=128,h=!0,n=n.updateQueue,a.updateQueue=n,Bd(a,n),Ic(c,!0),c.tail===null&&c.tailMode==="hidden"&&!m.alternate&&!Qe)return Tt(a),null}else 2*Mn()-c.renderingStartTime>jd&&i!==536870912&&(a.flags|=128,h=!0,Ic(c,!1),a.lanes=4194304);c.isBackwards?(m.sibling=a.child,a.child=m):(n=c.last,n!==null?n.sibling=m:a.child=m,c.last=m)}return c.tail!==null?(n=c.tail,c.rendering=n,c.tail=n.sibling,c.renderingStartTime=Mn(),n.sibling=null,i=Nt.current,ae(Nt,h?i&1|2:i&1),Qe&&ba(a,c.treeForkCount),n):(Tt(a),null);case 22:case 23:return Vn(a),Lc(),c=a.memoizedState!==null,n!==null?n.memoizedState!==null!==c&&(a.flags|=8192):c&&(a.flags|=8192),c?(i&536870912)!==0&&(a.flags&128)===0&&(Tt(a),a.subtreeFlags&6&&(a.flags|=8192)):Tt(a),i=a.updateQueue,i!==null&&Bd(a,i.retryQueue),i=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(i=n.memoizedState.cachePool.pool),c=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(c=a.memoizedState.cachePool.pool),c!==i&&(a.flags|=2048),n!==null&&te(dr),null;case 24:return i=null,n!==null&&(i=n.memoizedState.cache),a.memoizedState.cache!==i&&(a.flags|=2048),xa(Ft),Tt(a),null;case 25:return null;case 30:return null}throw Error(s(156,a.tag))}function cS(n,a){switch(wi(a),a.tag){case 1:return n=a.flags,n&65536?(a.flags=n&-65537|128,a):null;case 3:return xa(Ft),ke(),n=a.flags,(n&65536)!==0&&(n&128)===0?(a.flags=n&-65537|128,a):null;case 26:case 27:case 5:return xt(a),null;case 31:if(a.memoizedState!==null){if(Vn(a),a.alternate===null)throw Error(s(340));Ia()}return n=a.flags,n&65536?(a.flags=n&-65537|128,a):null;case 13:if(Vn(a),n=a.memoizedState,n!==null&&n.dehydrated!==null){if(a.alternate===null)throw Error(s(340));Ia()}return n=a.flags,n&65536?(a.flags=n&-65537|128,a):null;case 19:return te(Nt),null;case 4:return ke(),null;case 10:return xa(a.type),null;case 22:case 23:return Vn(a),Lc(),n!==null&&te(dr),n=a.flags,n&65536?(a.flags=n&-65537|128,a):null;case 24:return xa(Ft),null;case 25:return null;default:return null}}function uw(n,a){switch(wi(a),a.tag){case 3:xa(Ft),ke();break;case 26:case 27:case 5:xt(a);break;case 4:ke();break;case 31:a.memoizedState!==null&&Vn(a);break;case 13:Vn(a);break;case 19:te(Nt);break;case 10:xa(a.type);break;case 22:case 23:Vn(a),Lc(),n!==null&&te(dr);break;case 24:xa(Ft)}}function Uc(n,a){try{var i=a.updateQueue,c=i!==null?i.lastEffect:null;if(c!==null){var h=c.next;i=h;do{if((i.tag&n)===n){c=void 0;var m=i.create,T=i.inst;c=m(),T.destroy=c}i=i.next}while(i!==h)}}catch(A){_t(a,a.return,A)}}function Ls(n,a,i){try{var c=a.updateQueue,h=c!==null?c.lastEffect:null;if(h!==null){var m=h.next;c=m;do{if((c.tag&n)===n){var T=c.inst,A=T.destroy;if(A!==void 0){T.destroy=void 0,h=a;var P=i,Y=A;try{Y()}catch(se){_t(h,P,se)}}}c=c.next}while(c!==m)}}catch(se){_t(a,a.return,se)}}function dw(n){var a=n.updateQueue;if(a!==null){var i=n.stateNode;try{Ad(a,i)}catch(c){_t(n,n.return,c)}}}function fw(n,a,i){i.props=Di(n.type,n.memoizedProps),i.state=n.memoizedState;try{i.componentWillUnmount()}catch(c){_t(n,a,c)}}function Gc(n,a){try{var i=n.ref;if(i!==null){switch(n.tag){case 26:case 27:case 5:var c=n.stateNode;break;case 30:c=n.stateNode;break;default:c=n.stateNode}typeof i=="function"?n.refCleanup=i(c):i.current=c}}catch(h){_t(n,a,h)}}function vr(n,a){var i=n.ref,c=n.refCleanup;if(i!==null)if(typeof c=="function")try{c()}catch(h){_t(n,a,h)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(h){_t(n,a,h)}else i.current=null}function hw(n){var a=n.type,i=n.memoizedProps,c=n.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":i.autoFocus&&c.focus();break e;case"img":i.src?c.src=i.src:i.srcSet&&(c.srcset=i.srcSet)}}catch(h){_t(n,n.return,h)}}function kp(n,a,i){try{var c=n.stateNode;zS(c,n.type,i,a),c[pn]=a}catch(h){_t(n,n.return,h)}}function pw(n){return n.tag===5||n.tag===3||n.tag===26||n.tag===27&&Is(n.type)||n.tag===4}function Op(n){e:for(;;){for(;n.sibling===null;){if(n.return===null||pw(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;n.tag!==5&&n.tag!==6&&n.tag!==18;){if(n.tag===27&&Is(n.type)||n.flags&2||n.child===null||n.tag===4)continue e;n.child.return=n,n=n.child}if(!(n.flags&2))return n.stateNode}}function zp(n,a,i){var c=n.tag;if(c===5||c===6)n=n.stateNode,a?(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i).insertBefore(n,a):(a=i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,a.appendChild(n),i=i._reactRootContainer,i!=null||a.onclick!==null||(a.onclick=Da));else if(c!==4&&(c===27&&Is(n.type)&&(i=n.stateNode,a=null),n=n.child,n!==null))for(zp(n,a,i),n=n.sibling;n!==null;)zp(n,a,i),n=n.sibling}function Pd(n,a,i){var c=n.tag;if(c===5||c===6)n=n.stateNode,a?i.insertBefore(n,a):i.appendChild(n);else if(c!==4&&(c===27&&Is(n.type)&&(i=n.stateNode),n=n.child,n!==null))for(Pd(n,a,i),n=n.sibling;n!==null;)Pd(n,a,i),n=n.sibling}function mw(n){var a=n.stateNode,i=n.memoizedProps;try{for(var c=n.type,h=a.attributes;h.length;)a.removeAttributeNode(h[0]);gn(a,c,i),a[$t]=n,a[pn]=i}catch(m){_t(n,n.return,m)}}var Yr=!1,Zt=!1,Lp=!1,_w=typeof WeakSet=="function"?WeakSet:Set,ln=null;function uS(n,a){if(n=n.containerInfo,Jp=sf,n=fd(n),dc(n)){if("selectionStart"in n)var i={start:n.selectionStart,end:n.selectionEnd};else e:{i=(i=n.ownerDocument)&&i.defaultView||window;var c=i.getSelection&&i.getSelection();if(c&&c.rangeCount!==0){i=c.anchorNode;var h=c.anchorOffset,m=c.focusNode;c=c.focusOffset;try{i.nodeType,m.nodeType}catch{i=null;break e}var T=0,A=-1,P=-1,Y=0,se=0,ce=n,K=null;t:for(;;){for(var ne;ce!==i||h!==0&&ce.nodeType!==3||(A=T+h),ce!==m||c!==0&&ce.nodeType!==3||(P=T+c),ce.nodeType===3&&(T+=ce.nodeValue.length),(ne=ce.firstChild)!==null;)K=ce,ce=ne;for(;;){if(ce===n)break t;if(K===i&&++Y===h&&(A=T),K===m&&++se===c&&(P=T),(ne=ce.nextSibling)!==null)break;ce=K,K=ce.parentNode}ce=ne}i=A===-1||P===-1?null:{start:A,end:P}}else i=null}i=i||{start:0,end:0}}else i=null;for(em={focusedElem:n,selectionRange:i},sf=!1,ln=a;ln!==null;)if(a=ln,n=a.child,(a.subtreeFlags&1028)!==0&&n!==null)n.return=a,ln=n;else for(;ln!==null;){switch(a=ln,m=a.alternate,n=a.flags,a.tag){case 0:if((n&4)!==0&&(n=a.updateQueue,n=n!==null?n.events:null,n!==null))for(i=0;i title"))),gn(m,c,i),m[$t]=n,qt(m),c=m;break e;case"link":var T=M0("link","href",h).get(c+(i.href||""));if(T){for(var A=0;Awt&&(T=wt,wt=Le,Le=T);var q=ud(A,Le),G=ud(A,wt);if(q&&G&&(ne.rangeCount!==1||ne.anchorNode!==q.node||ne.anchorOffset!==q.offset||ne.focusNode!==G.node||ne.focusOffset!==G.offset)){var Q=ce.createRange();Q.setStart(q.node,q.offset),ne.removeAllRanges(),Le>wt?(ne.addRange(Q),ne.extend(G.node,G.offset)):(Q.setEnd(G.node,G.offset),ne.addRange(Q))}}}}for(ce=[],ne=A;ne=ne.parentNode;)ne.nodeType===1&&ce.push({element:ne,left:ne.scrollLeft,top:ne.scrollTop});for(typeof A.focus=="function"&&A.focus(),A=0;Ai?32:i,V.T=null,i=Ip,Ip=null;var m=Rs,T=es;if(Kt=0,nl=Rs=null,es=0,(ut&6)!==0)throw Error(s(331));var A=ut;if(ut|=4,Aw(m.current),Tw(m,m.current,T,i),ut=A,Qc(0,!1),xn&&typeof xn.onPostCommitFiberRoot=="function")try{xn.onPostCommitFiberRoot(us,m)}catch{}return!0}finally{ee.p=h,V.T=c,Hw(n,a)}}function Qw(n,a,i){a=Pn(i,a),a=yp(n.stateNode,a,2),n=_r(n,a,2),n!==null&&(_a(n,2),wr(n))}function _t(n,a,i){if(n.tag===3)Qw(n,n,i);else for(;a!==null;){if(a.tag===3){Qw(a,n,i);break}else if(a.tag===1){var c=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof c.componentDidCatch=="function"&&(Ds===null||!Ds.has(c))){n=Pn(i,n),i=Wv(2),c=_r(a,i,2),c!==null&&(Yv(i,c,a,n),_a(c,2),wr(c));break}}a=a.return}}function Vp(n,a,i){var c=n.pingCache;if(c===null){c=n.pingCache=new hS;var h=new Set;c.set(a,h)}else h=c.get(a),h===void 0&&(h=new Set,c.set(a,h));h.has(i)||(Dp=!0,h.add(i),n=yS.bind(null,n,a,i),a.then(n,n))}function yS(n,a,i){var c=n.pingCache;c!==null&&c.delete(a),n.pingedLanes|=n.suspendedLanes&i,n.warmLanes&=~i,Mt===n&&(tt&i)===i&&(It===4||It===3&&(tt&62914560)===tt&&300>Mn()-Gd?(ut&2)===0&&al(n,0):Rp|=i,tl===tt&&(tl=0)),wr(n)}function Ww(n,a){a===0&&(a=Hl()),n=Rr(n,a),n!==null&&(_a(n,a),wr(n))}function vS(n){var a=n.memoizedState,i=0;a!==null&&(i=a.retryLane),Ww(n,i)}function wS(n,a){var i=0;switch(n.tag){case 31:case 13:var c=n.stateNode,h=n.memoizedState;h!==null&&(i=h.retryLane);break;case 19:c=n.stateNode;break;case 22:c=n.stateNode._retryCache;break;default:throw Error(s(314))}c!==null&&c.delete(a),Ww(n,i)}function bS(n,a){return La(n,a)}var Wd=null,sl=null,qp=!1,Yd=!1,Hp=!1,Ps=0;function wr(n){n!==sl&&n.next===null&&(sl===null?Wd=sl=n:sl=sl.next=n),Yd=!0,qp||(qp=!0,xS())}function Qc(n,a){if(!Hp&&Yd){Hp=!0;do for(var i=!1,c=Wd;c!==null;){if(n!==0){var h=c.pendingLanes;if(h===0)var m=0;else{var T=c.suspendedLanes,A=c.pingedLanes;m=(1<<31-hn(42|n)+1)-1,m&=h&~(T&~A),m=m&201326741?m&201326741|1:m?m|2:0}m!==0&&(i=!0,Kw(c,m))}else m=tt,m=ni(c,c===Mt?m:0,c.cancelPendingCommit!==null||c.timeoutHandle!==-1),(m&3)===0||ai(c,m)||(i=!0,Kw(c,m));c=c.next}while(i);Hp=!1}}function MS(){Yw()}function Yw(){Yd=qp=!1;var n=0;Ps!==0&&FS()&&(n=Ps);for(var a=Mn(),i=null,c=Wd;c!==null;){var h=c.next,m=Xw(c,a);m===0?(c.next=null,i===null?Wd=h:i.next=h,h===null&&(sl=i)):(i=c,(n!==0||(m&3)!==0)&&(Yd=!0)),c=h}Kt!==0&&Kt!==5||Qc(n),Ps!==0&&(Ps=0)}function Xw(n,a){for(var i=n.suspendedLanes,c=n.pingedLanes,h=n.expirationTimes,m=n.pendingLanes&-62914561;0A)break;var se=P.transferSize,ce=P.initiatorType;se&&i0(ce)&&(P=P.responseEnd,T+=se*(P"u"?null:document;function y0(n,a,i){var c=il;if(c&&typeof a=="string"&&a){var h=$n(a);h='link[rel="'+n+'"][href="'+h+'"]',typeof i=="string"&&(h+='[crossorigin="'+i+'"]'),g0.has(h)||(g0.add(h),n={rel:n,crossOrigin:i,href:a},c.querySelector(h)===null&&(a=c.createElement("link"),gn(a,"link",n),qt(a),c.head.appendChild(a)))}}function jS(n){ts.D(n),y0("dns-prefetch",n,null)}function VS(n,a){ts.C(n,a),y0("preconnect",n,a)}function qS(n,a,i){ts.L(n,a,i);var c=il;if(c&&n&&a){var h='link[rel="preload"][as="'+$n(a)+'"]';a==="image"&&i&&i.imageSrcSet?(h+='[imagesrcset="'+$n(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(h+='[imagesizes="'+$n(i.imageSizes)+'"]')):h+='[href="'+$n(n)+'"]';var m=h;switch(a){case"style":m=ol(n);break;case"script":m=ll(n)}Sa.has(m)||(n=y({rel:"preload",href:a==="image"&&i&&i.imageSrcSet?void 0:n,as:a},i),Sa.set(m,n),c.querySelector(h)!==null||a==="style"&&c.querySelector(Zc(m))||a==="script"&&c.querySelector(Kc(m))||(a=c.createElement("link"),gn(a,"link",n),qt(a),c.head.appendChild(a)))}}function HS(n,a){ts.m(n,a);var i=il;if(i&&n){var c=a&&typeof a.as=="string"?a.as:"script",h='link[rel="modulepreload"][as="'+$n(c)+'"][href="'+$n(n)+'"]',m=h;switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":m=ll(n)}if(!Sa.has(m)&&(n=y({rel:"modulepreload",href:n},a),Sa.set(m,n),i.querySelector(h)===null)){switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Kc(m)))return}c=i.createElement("link"),gn(c,"link",n),qt(c),i.head.appendChild(c)}}}function $S(n,a,i){ts.S(n,a,i);var c=il;if(c&&n){var h=ds(c).hoistableStyles,m=ol(n);a=a||"default";var T=h.get(m);if(!T){var A={loading:0,preload:null};if(T=c.querySelector(Zc(m)))A.loading=5;else{n=y({rel:"stylesheet",href:n,"data-precedence":a},i),(i=Sa.get(m))&&om(n,i);var P=T=c.createElement("link");qt(P),gn(P,"link",n),P._p=new Promise(function(Y,se){P.onload=Y,P.onerror=se}),P.addEventListener("load",function(){A.loading|=1}),P.addEventListener("error",function(){A.loading|=2}),A.loading|=4,ef(T,a,c)}T={type:"stylesheet",instance:T,count:1,state:A},h.set(m,T)}}}function QS(n,a){ts.X(n,a);var i=il;if(i&&n){var c=ds(i).hoistableScripts,h=ll(n),m=c.get(h);m||(m=i.querySelector(Kc(h)),m||(n=y({src:n,async:!0},a),(a=Sa.get(h))&&lm(n,a),m=i.createElement("script"),qt(m),gn(m,"link",n),i.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},c.set(h,m))}}function WS(n,a){ts.M(n,a);var i=il;if(i&&n){var c=ds(i).hoistableScripts,h=ll(n),m=c.get(h);m||(m=i.querySelector(Kc(h)),m||(n=y({src:n,async:!0,type:"module"},a),(a=Sa.get(h))&&lm(n,a),m=i.createElement("script"),qt(m),gn(m,"link",n),i.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},c.set(h,m))}}function v0(n,a,i,c){var h=(h=Ee.current)?Jd(h):null;if(!h)throw Error(s(446));switch(n){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(a=ol(i.href),i=ds(h).hoistableStyles,c=i.get(a),c||(c={type:"style",instance:null,count:0,state:null},i.set(a,c)),c):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){n=ol(i.href);var m=ds(h).hoistableStyles,T=m.get(n);if(T||(h=h.ownerDocument||h,T={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},m.set(n,T),(m=h.querySelector(Zc(n)))&&!m._p&&(T.instance=m,T.state.loading=5),Sa.has(n)||(i={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},Sa.set(n,i),m||YS(h,n,i,T.state))),a&&c===null)throw Error(s(528,""));return T}if(a&&c!==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=ll(i),i=ds(h).hoistableScripts,c=i.get(a),c||(c={type:"script",instance:null,count:0,state:null},i.set(a,c)),c):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,n))}}function ol(n){return'href="'+$n(n)+'"'}function Zc(n){return'link[rel="stylesheet"]['+n+"]"}function w0(n){return y({},n,{"data-precedence":n.precedence,precedence:null})}function YS(n,a,i,c){n.querySelector('link[rel="preload"][as="style"]['+a+"]")?c.loading=1:(a=n.createElement("link"),c.preload=a,a.addEventListener("load",function(){return c.loading|=1}),a.addEventListener("error",function(){return c.loading|=2}),gn(a,"link",i),qt(a),n.head.appendChild(a))}function ll(n){return'[src="'+$n(n)+'"]'}function Kc(n){return"script[async]"+n}function b0(n,a,i){if(a.count++,a.instance===null)switch(a.type){case"style":var c=n.querySelector('style[data-href~="'+$n(i.href)+'"]');if(c)return a.instance=c,qt(c),c;var h=y({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return c=(n.ownerDocument||n).createElement("style"),qt(c),gn(c,"style",h),ef(c,i.precedence,n),a.instance=c;case"stylesheet":h=ol(i.href);var m=n.querySelector(Zc(h));if(m)return a.state.loading|=4,a.instance=m,qt(m),m;c=w0(i),(h=Sa.get(h))&&om(c,h),m=(n.ownerDocument||n).createElement("link"),qt(m);var T=m;return T._p=new Promise(function(A,P){T.onload=A,T.onerror=P}),gn(m,"link",c),a.state.loading|=4,ef(m,i.precedence,n),a.instance=m;case"script":return m=ll(i.src),(h=n.querySelector(Kc(m)))?(a.instance=h,qt(h),h):(c=i,(h=Sa.get(m))&&(c=y({},i),lm(c,h)),n=n.ownerDocument||n,h=n.createElement("script"),qt(h),gn(h,"link",c),n.head.appendChild(h),a.instance=h);case"void":return null;default:throw Error(s(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(c=a.instance,a.state.loading|=4,ef(c,i.precedence,n));return a.instance}function ef(n,a,i){for(var c=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=c.length?c[c.length-1]:null,m=h,T=0;T title"):null)}function XS(n,a,i){if(i===1||a.itemProp!=null)return!1;switch(n){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;return a.rel==="stylesheet"?(n=a.disabled,typeof a.precedence=="string"&&n==null):!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 T0(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function ZS(n,a,i,c){if(i.type==="stylesheet"&&(typeof c.media!="string"||matchMedia(c.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var h=ol(c.href),m=a.querySelector(Zc(h));if(m){a=m._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(n.count++,n=nf.bind(n),a.then(n,n)),i.state.loading|=4,i.instance=m,qt(m);return}m=a.ownerDocument||a,c=w0(c),(h=Sa.get(h))&&om(c,h),m=m.createElement("link"),qt(m);var T=m;T._p=new Promise(function(A,P){T.onload=A,T.onerror=P}),gn(m,"link",c),i.instance=m}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(i,a),(a=i.state.preload)&&(i.state.loading&3)===0&&(n.count++,i=nf.bind(n),a.addEventListener("load",i),a.addEventListener("error",i))}}var cm=0;function KS(n,a){return n.stylesheets&&n.count===0&&rf(n,n.stylesheets),0cm?50:800)+a);return n.unsuspend=i,function(){n.unsuspend=null,clearTimeout(c),clearTimeout(h)}}:null}function nf(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)rf(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var af=null;function rf(n,a){n.stylesheets=null,n.unsuspend!==null&&(n.count++,af=new Map,a.forEach(JS,n),af=null,nf.call(n))}function JS(n,a){if(!(a.state.loading&4)){var i=af.get(n);if(i)var c=i.get(null);else{i=new Map,af.set(n,i);for(var h=n.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(t){console.error(t)}}return e(),ym.exports=mE(),ym.exports}var gE=_E();var T_=Object.defineProperty,yE=Object.getOwnPropertyDescriptor,vE=Object.getOwnPropertyNames,wE=Object.prototype.hasOwnProperty,bE=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Je=(e,t)=>()=>(e&&(t=e(e=0)),t),Tu=(e,t)=>{for(var r in t)T_(e,r,{get:t[r],enumerable:!0})},ME=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vE(t))!wE.call(e,o)&&o!==r&&T_(e,o,{get:()=>t[o],enumerable:!(s=yE(t,o))||s.enumerable});return e},Of=e=>ME(T_({},"__esModule",{value:!0}),e),su,Hs,Hi,W0,O1,z1=Je(()=>{su=new Map,Hs=[],Hi=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let s=su.get(e);if(s===void 0)su.set(e,{backend:t,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let o=Hs.indexOf(e);o!==-1&&Hs.splice(o,1);for(let l=0;l{let t=su.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(s){return r||(t.error=`${s}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},O1=async e=>{let t=e.executionProviders||[],r=t.map(f=>typeof f=="string"?f:f.name),s=r.length===0?Hs:r,o,l=[],u=new Set;for(let f of s){let p=await W0(f);typeof p=="string"?l.push({name:f,err:p}):(o||(o=p),o===p&&u.add(f))}if(!o)throw new Error(`no available backend found. ERR: ${l.map(f=>`[${f.name}] ${f.err}`).join(", ")}`);for(let{name:f,err:p}of l)r.includes(f)&&console.warn(`removing requested execution provider "${f}" from session options because it is not available: ${p}`);let d=t.filter(f=>u.has(typeof f=="string"?f:f.name));return[o,new Proxy(e,{get:(f,p)=>p==="executionProviders"?d:Reflect.get(f,p)})]}}),xE=Je(()=>{z1()}),L1,TE=Je(()=>{L1="1.24.0-dev.20251116-b39e144322"}),Mm,cn,F1=Je(()=>{TE(),Mm="warning",cn={wasm:{},webgl:{},webgpu:{},versions:{common:L1},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}`);Mm=e}},get logLevel(){return Mm}},Object.defineProperty(cn,"logLevel",{enumerable:!0})}),kt,SE=Je(()=>{F1(),kt=cn}),N1,D1,EE=Je(()=>{N1=(e,t)=>{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,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[3]):(o=e.dims[3],l=e.dims[2]);let u=t?.format!==void 0?t.format:"RGB",d=t?.norm,f,p;d===void 0||d.mean===void 0?f=[255,255,255,255]:typeof d.mean=="number"?f=[d.mean,d.mean,d.mean,d.mean]:(f=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(f[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=l*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,l,u;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[1],u=e.dims[3]):(o=e.dims[3],l=e.dims[2],u=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",f=t?.norm,p,g;f===void 0||f.mean===void 0?p=[255,255,255,255]:typeof f.mean=="number"?p=[f.mean,f.mean,f.mean,f.mean]:(p=[f.mean[0],f.mean[1],f.mean[2],255],f.mean[3]!==void 0&&(p[3]=f.mean[3])),f===void 0||f.bias===void 0?g=[0,0,0,0]:typeof f.bias=="number"?g=[f.bias,f.bias,f.bias,f.bias]:(g=[f.bias[0],f.bias[1],f.bias[2],0],f.bias[3]!==void 0&&(g[3]=f.bias[3]));let y=l*o;if(t!==void 0&&(t.format!==void 0&&u===4&&t.format!=="RGBA"||u===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,b=0,S=1,E=2,z=3,k=0,L=y,R=y*2,N=-1;d==="RGBA"?(k=0,L=y,R=y*2,N=y*3):d==="RGB"?(k=0,L=y,R=y*2):d==="RBG"&&(k=0,R=y,L=y*2),s=r.createImageData(o,l);for(let B=0;B{S_(),hf=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:s}=t,o=t.norm??{mean:255,bias:0},l,u;typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:l=[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=t.format!==void 0?t.format:"RGBA",f=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*s,g=f==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),y=4,w=0,b=1,S=2,E=3,z=0,k=p,L=p*2,R=-1;d==="RGB"&&(y=3,w=0,b=1,S=2,E=-1),f==="RGBA"?R=p*3:f==="RBG"?(z=0,L=p,k=p*2):f==="BGR"&&(L=0,k=p,z=p*2);for(let N=0;N{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",u,d=t??{},f=()=>{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=f();g.width=e.width,g.height=e.height;let y=p(g);if(y!=null){let w=e.height,b=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,b=t.resizedWidth),t!==void 0){if(d=t,t.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(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,y=t.resizedWidth):(g=e.height,y=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=g,d.width=y,t!==void 0){let w=f();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(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=f();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,hf(u,d)}else throw new Error("Can not access image data")}else{if(l)return new Promise((g,y)=>{let w=f(),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(hf(E.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return hf(u,d);throw new Error("Input data provided is not supported - aborted tensor creation")},B1=(e,t)=>{let{width:r,height:s,download:o,dispose:l}=t,u=[1,s,r,4];return new da({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},P1=(e,t)=>{let{dataType:r,dims:s,download:o,dispose:l}=t;return new da({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:o,dispose:l})},I1=(e,t)=>{let{dataType:r,dims:s,download:o,dispose:l}=t;return new da({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:o,dispose:l})},U1=(e,t,r)=>new da({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Vi,hu,xm,G1,CE=Je(()=>{Vi=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),hu=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),xm=!1,G1=()=>{if(!xm){xm=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(Vi.set("int64",BigInt64Array),hu.set(BigInt64Array,"int64")),t&&(Vi.set("uint64",BigUint64Array),hu.set(BigUint64Array,"uint64")),s?(Vi.set("float16",r),hu.set(r,"float16")):Vi.set("float16",Uint16Array)}}}),j1,V1,kE=Je(()=>{S_(),j1=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new da(e.type,e.data,t);case"cpu-pinned":return new da({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new da({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new da({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new da({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),da,S_=Je(()=>{EE(),AE(),CE(),kE(),da=class{constructor(e,t,r){G1();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=Vi.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(t))throw new TypeError("A string tensor's data must be a string array.");u=t}else{let f=Vi.get(e);if(f===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&f===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${f.name} as data.`);e==="uint64"||e==="int64"?u=f.from(t,BigInt):u=f.from(t)}else if(t instanceof f)u=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")u=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&f!==Uint16Array)u=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${s} tensor's data must be type of ${f}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let f=typeof e[0];if(f==="string")s="string",u=e;else if(f==="boolean")s="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${f}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",u=Uint8Array.from(e);else{let f=hu.get(e.constructor);if(f===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=f,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 l=j1(o);if(this.cpuData&&l!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=o,this.size=l}static async fromImage(e,t){return R1(e,t)}static fromTexture(e,t){return B1(e,t)}static fromGpuBuffer(e,t){return P1(e,t)}static fromMLTensor(e,t){return I1(e,t)}static fromPinnedBuffer(e,t,r){return U1(e,t,r)}toDataURL(e){return N1(this,e)}toImageData(e){return D1(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 t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}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 V1(this,e)}}}),Ha,q1=Je(()=>{S_(),Ha=da}),zf,Tm,Wi,Yi,Zs,Ks,H1=Je(()=>{F1(),zf=(e,t)=>{(typeof cn.trace>"u"?!cn.wasm.trace:!cn.trace)||console.timeStamp(`${e}::ORT::${t}`)},Tm=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let o=0;o{(typeof cn.trace>"u"?!cn.wasm.trace:!cn.trace)||Tm("BEGIN",e)},Yi=e=>{(typeof cn.trace>"u"?!cn.wasm.trace:!cn.trace)||Tm("END",e)},Zs=e=>{(typeof cn.trace>"u"?!cn.wasm.trace:!cn.trace)||console.time(`ORT::${e}`)},Ks=e=>{(typeof cn.trace>"u"?!cn.wasm.trace:!cn.trace)||console.timeEnd(`ORT::${e}`)}}),$1,OE=Je(()=>{z1(),q1(),H1(),$1=class Q1{constructor(t){this.handler=t}async run(t,r,s){Wi(),Zs("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof Ha||Array.isArray(t))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 Ha)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)l=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 Ha)&&(p=!0,u=!1,o[y]=w)}if(p){if(typeof s=="object"&&s!==null)l=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else l=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 t[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(t,o,l),f={};for(let p in d)if(Object.hasOwnProperty.call(d,p)){let g=d[p];g instanceof Ha?f[p]=g:f[p]=new Ha(g.type,g.data,g.dims)}return Ks("InferenceSession.run"),Yi(),f}async release(){return this.handler.dispose()}static async create(t,r,s,o){Wi(),Zs("InferenceSession.create");let l,u={};if(typeof t=="string"){if(l=t,typeof r=="object"&&r!==null)u=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof r=="object"&&r!==null)u=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let g=t,y=0,w=t.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=t.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.");l=new Uint8Array(g,y,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,f]=await O1(u),p=await d.createInferenceSessionHandler(l,f);return Ks("InferenceSession.create"),Yi(),new Q1(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}}}),E_,zE=Je(()=>{OE(),E_=$1}),LE=Je(()=>{}),FE=Je(()=>{}),NE=Je(()=>{}),DE=Je(()=>{}),W1={};Tu(W1,{InferenceSession:()=>E_,TRACE:()=>zf,TRACE_EVENT_BEGIN:()=>Zs,TRACE_EVENT_END:()=>Ks,TRACE_FUNC_BEGIN:()=>Wi,TRACE_FUNC_END:()=>Yi,Tensor:()=>Ha,env:()=>kt,registerBackend:()=>Hi});var Zi=Je(()=>{xE(),SE(),zE(),q1(),LE(),FE(),H1(),NE(),DE()}),A_=Je(()=>{}),Y1={};Tu(Y1,{default:()=>X1});var Sm,Em,X1,RE=Je(()=>{dM(),Ki(),C_(),Sm="ort-wasm-proxy-worker",Em=globalThis.self?.name===Sm,Em&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":k_(r.wasm).then(()=>{N_(r).then(()=>{postMessage({type:t})},s=>{postMessage({type:t,err:s})})},s=>{postMessage({type:t,err:s})});break;case"init-ep":{let{epName:s,env:o}=r;D_(o,s).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:s}=r,o=Nf(s);postMessage({type:t,out:o});break}case"create":{let{model:s,options:o}=r;R_(s,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":B_(r),postMessage({type:t});break;case"run":{let{sessionId:s,inputIndices:o,inputs:l,outputIndices:u,options:d}=r;P_(s,o,l,u,new Array(u.length).fill(null),d).then(f=>{f.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:f},U_([...l,...f]))},f=>{postMessage({type:t,err:f})});break}case"end-profiling":I_(r),postMessage({type:t});break;default:}}catch(s){postMessage({type:t,err:s})}}),X1=Em?null:e=>new Worker(e??ca,{type:"module",name:Sm})}),Z1={};Tu(Z1,{default:()=>K1});async function Y0(e={}){var t=e,r=!!globalThis.window,s=!!globalThis.WorkerGlobalScope,o=s&&self.name?.startsWith("em-pthread");t.mountExternalData=(_,v)=>{_.startsWith("./")&&(_=_.substring(2)),(t.Uc||(t.Uc=new Map)).set(_,v)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let l=()=>{let _=v=>(...M)=>{let x=mn;return M=v(...M),mn!=x?new Promise((O,F)=>{Fr={resolve:O,reject:F}}):M};(()=>{for(let v of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[v]=_(t[v])})(),typeof jsepRunAsync<"u"&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),l=void 0};t.asyncInit=()=>{l?.()};var u,d,f=(_,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(j(_))return new Promise((M,x)=>{var O=new XMLHttpRequest;O.open("GET",_,!0),O.responseType="arraybuffer",O.onload=()=>{O.status==200||O.status==0&&O.response?M(O.response):x(O.status)},O.onerror=x,O.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,z,k=console.log.bind(console),L=console.error.bind(console),R=k,N=L,B=!1,j=_=>_.startsWith("file://");function C(){nr.buffer!=oe.buffer&&D()}if(o){let _=function(v){try{var M=v.data,x=M.Oc;if(x==="load"){let O=[];self.onmessage=F=>O.push(F),z=()=>{postMessage({Oc:"loaded"});for(let F of O)_(F);self.onmessage=_};for(let F of M.de)t[F]&&!t[F].proxy||(t[F]=(...U)=>{postMessage({Oc:"callHandler",ce:F,args:U})},F=="print"&&(R=t[F]),F=="printErr"&&(N=t[F]));nr=M.je,D(),w=M.ke,Me(),Ni()}else if(x==="run"){(function(O){var F=(C(),W)[O+52>>>2>>>0];O=(C(),W)[O+56>>>2>>>0],Io(F,F-O),Ce(F)})(M.Nc),Ma(M.Nc,0,0,1,0,0),Du(),ec(M.Nc),ue||(ur(),ue=!0);try{Bu(M.he,M.Wc)}catch(O){if(O!="unwind")throw O}}else M.target!=="setimmediate"&&(x==="checkMailbox"?ue&&si():x&&(N(`worker: received unknown command ${x}`),N(M)))}catch(O){throw Gn(),O}};var ue=!1;self.onunhandledrejection=v=>{throw v.reason||v},self.onmessage=_}var oe,he,_e,de,re,W,pe,V,ee,I,$,J=!1;function D(){var _=nr.buffer;t.HEAP8=oe=new Int8Array(_),_e=new Int16Array(_),t.HEAPU8=he=new Uint8Array(_),de=new Uint16Array(_),t.HEAP32=re=new Int32Array(_),t.HEAPU32=W=new Uint32Array(_),pe=new Float32Array(_),V=new Float64Array(_),ee=new BigInt64Array(_),I=new BigUint64Array(_)}function te(){J=!0,o?z():on._b()}function ae(_){throw N(_="Aborted("+_+")"),B=!0,_=new WebAssembly.RuntimeError(_+". Build with -sASSERTIONS for more info."),E?.(_),_}function ge(){return{a:{f:Pu,J:wh,k:bh,p:Mh,l:xh,ta:ro,b:so,ca:io,Ka:ni,s:ai,da:Uu,_a:$l,Ga:Ql,Ia:Wl,$a:lo,Ya:co,Ra:Yl,Xa:Xl,pa:Fa,Ha:$t,Yb:pn,Za:Or,Fa:uo,eb:Th,Da:ri,Tb:ds,Rb:ju,Ca:po,M:mo,I:Na,Sb:Eh,ka:Jl,Ub:fs,Ua:Hu,Wb:$u,La:Ch,Pb:kh,la:yo,Ta:ec,bb:Da,U:bo,n:So,c:ho,sb:oi,w:Oh,L:rc,z:sc,j:li,o:ci,tb:Wu,G:zh,T:Lh,h:Fh,u:ic,m:Nh,i:Dh,Oa:Rh,Pa:Bh,Qa:Ph,Ma:Zu,Na:Ku,Qb:Ju,fb:Uh,db:Gh,Y:jh,rb:Vh,ma:qh,cb:ed,gb:Hh,ab:$h,Xb:Qh,N:Ih,hb:cc,X:ui,Vb:Wh,ob:ld,C:Xh,sa:Zh,ra:Kh,qb:Jh,W:ep,v:Dn,nb:hi,mb:cd,lb:ud,pb:dd,kb:fd,jb:dc,ib:tp,Va:ko,Wa:fc,Ja:an,ea:lr,oa:Dr,Sa:Oo,na:cr,Db:Nc,xa:Qo,Eb:At,ya:Bt,F:gr,e:kc,r:_r,x:mr,D:Lc,Ib:ja,ba:Nt,B:zi,za:Be,$:ks,ha:$o,Fb:Os,Gb:Fi,Ba:Fc,Aa:Vn,Jb:kd,wa:ip,aa:ht,d:Oc,A:Li,q:Oi,Cb:Dc,t:Ad,y:jn,H:Ed,E:Cs,K:Yn,S:$r,ja:zc,_:Wo,Kb:Cd,Lb:Ho,P:yr,g:pd,a:nr,Ob:bn,Hb:md,ia:_d,O:np,qa:ap,Mb:rp,Q:gd,zb:yd,Ab:hc,ua:na,fa:zo,R:Qn,Ea:bs,va:pc,Z:Lo,xb:Fo,Zb:mc,V:Rr,Bb:vd,ub:No,vb:sp,wb:Rn,ga:_c,yb:Ra,Nb:wd}}}async function Me(){function _(x,O){var F=on=x.exports;x={};for(let[U,X]of Object.entries(F))typeof X=="function"?(F=tc(X),x[U]=F):x[U]=X;return on=x,on=(function(){var U=on,X=we=>$e=>we($e)>>>0,fe=we=>()=>we()>>>0;return(U=Object.assign({},U)).$b=X(U.$b),U.Cc=fe(U.Cc),U.Ec=X(U.Ec),U.rd=(we=>($e,ye)=>we($e,ye)>>>0)(U.rd),U.wd=X(U.wd),U.xd=fe(U.xd),U.Bd=X(U.Bd),U})(),no.push(on.id),mi=(x=on).$b,ur=x.ac,t._OrtInit=x.bc,t._OrtGetLastError=x.cc,t._OrtCreateSessionOptions=x.dc,t._OrtAppendExecutionProvider=x.ec,t._OrtAddFreeDimensionOverride=x.fc,t._OrtAddSessionConfigEntry=x.gc,t._OrtReleaseSessionOptions=x.hc,t._OrtCreateSession=x.ic,t._OrtReleaseSession=x.jc,t._OrtGetInputOutputCount=x.kc,t._OrtGetInputOutputMetadata=x.lc,t._OrtFree=x.mc,t._OrtCreateTensor=x.nc,t._OrtGetTensorData=x.oc,t._OrtReleaseTensor=x.pc,t._OrtCreateRunOptions=x.qc,t._OrtAddRunConfigEntry=x.rc,t._OrtReleaseRunOptions=x.sc,t._OrtCreateBinding=x.tc,t._OrtBindInput=x.uc,t._OrtBindOutput=x.vc,t._OrtClearBoundOutputs=x.wc,t._OrtReleaseBinding=x.xc,t._OrtRunWithBinding=x.yc,t._OrtRun=x.zc,t._OrtEndProfiling=x.Ac,_i=t._OrtGetWebGpuDevice=x.Bc,gi=x.Cc,Bn=t._free=x.Dc,Br=t._malloc=x.Ec,Pn=t._wgpuBufferRelease=x.Fc,Pr=t._wgpuCreateInstance=x.Gc,Ir=x.Hc,yi=x.Ic,xs=x.Jc,In=x.Kc,Un=x.Lc,Ba=x.Pc,aa=x.Zc,ra=x._c,ba=x.$c,Do=x.bd,vi=x.cd,wi=x.dd,Ro=x.ed,Lt=x.fd,pt=x.gd,Qe=x.hd,Ma=x.kd,Gn=x.ld,Bo=x.md,Pa=x.nd,Po=x.od,gc=x.pd,Ur=x.qd,Ia=x.rd,Ge=x.sd,Ua=x.td,Io=x.ud,Ce=x.vd,Wn=x.wd,Se=x.xd,xa=x.yd,bi=x.zd,Uo=x.Ad,Gr=x.Bd,Mi=x.Cd,Ga=x.Dd,Yt=x.Ed,xi=x.Fd,yc=x.Gd,bd=x.Hd,Md=x.Id,xd=x.Jd,Ft=x.Kd,Go=x.Ld,Ts=x.Md,Ss=x.Nd,jo=x.Od,jr=x.Pd,Vr=x.Qd,Td=x.Rd,vc=x.Td,Sd=x.Ud,wc=x.Vd,dr=x.Wd,Vo=x.Yd,Ti=x.Zd,bc=x._d,qr=x.$d,qo=x.ae,Si=x.be,Ei=x.pe,Mc=x.qe,xc=x.re,fr=x.se,hr=x.te,Tc=x.ue,Sc=x.ve,Hr=x.we,Es=x.xe,Ai=x.ye,As=x.ze,Ci=x.Xe,Ec=x.Ye,pr=x.Ze,Ac=x._e,w=O,on}var v,M=ge();return t.instantiateWasm?new Promise(x=>{t.instantiateWasm(M,(O,F)=>{x(_(O,F))})}):o?_(new WebAssembly.Instance(w,ge()),w):($??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.asyncify.wasm",g):g+"ort-wasm-simd-threaded.asyncify.wasm":new URL(""+new URL("ort-wasm-simd-threaded.asyncify-DFMnNRgU.wasm",import.meta.url).href,import.meta.url).href,v=await(async function(x){var O=$;if(!y&&!j(O))try{var F=fetch(O,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(F,x)}catch(U){N(`wasm streaming compile failed: ${U}`),N("falling back to ArrayBuffer instantiation")}return(async function(U,X){try{var fe=await(async function(we){if(!y)try{var $e=await u(we);return new Uint8Array($e)}catch{}if(we==$&&y)we=new Uint8Array(y);else{if(!d)throw"both async and sync fetching of the wasm failed";we=d(we)}return we})(U);return await WebAssembly.instantiate(fe,X)}catch(we){N(`failed to asynchronously prepare wasm: ${we}`),ae(we)}})(O,x)})(M),_(v.instance,v.module))}class Ee{name="ExitStatus";constructor(v){this.message=`Program terminated with exit(${v})`,this.status=v}}var ze=_=>{_.terminate(),_.onmessage=()=>{}},et=[],ke=0,Ue=null,xt=_=>{Dt.length==0&&(Mn(),Ru(Dt[0]));var v=Dt.pop();if(!v)return 6;ls.push(v),La[_.Nc]=v,v.Nc=_.Nc;var M={Oc:"run",he:_.ge,Wc:_.Wc,Nc:_.Nc};return v.postMessage(M,_.Yc),0},He=0,Ye=(_,v,...M)=>{var x,O=16*M.length,F=Se(),U=Wn(O),X=U>>>3;for(x of M)typeof x=="bigint"?((C(),ee)[X++>>>0]=1n,(C(),ee)[X++>>>0]=x):((C(),ee)[X++>>>0]=0n,(C(),V)[X++>>>0]=x);return _=Bo(_,0,O,U,v),Ce(F),_};function bn(_){if(o)return Ye(0,1,_);if(b=_,!(0{if(b=_,o)throw za(_),"unwind";bn(_)},Dt=[],ls=[],no=[],La={},ao=_=>{var v=_.Nc;delete La[v],Dt.push(_),ls.splice(ls.indexOf(_),1),_.Nc=0,Pa(v)};function Du(){no.forEach(_=>_())}var Ru=_=>new Promise(v=>{_.onmessage=O=>{var F=O.data;if(O=F.Oc,F.Vc&&F.Vc!=gi()){var U=La[F.Vc];U?U.postMessage(F,F.Yc):N(`Internal error! Worker sent a message "${O}" to target pthread ${F.Vc}, but that thread no longer exists!`)}else O==="checkMailbox"?si():O==="spawnThread"?xt(F):O==="cleanupThread"?sn(()=>{ao(La[F.ie])}):O==="loaded"?(_.loaded=!0,v(_)):F.target==="setimmediate"?_.postMessage(F):O==="uncaughtException"?_.onerror(F.error):O==="callHandler"?t[F.ce](...F.args):O&&N(`worker sent an unknown command ${O}`)},_.onerror=O=>{throw N(`worker sent an error! ${O.filename}:${O.lineno}: ${O.message}`),O};var M,x=[];for(M of[])t.propertyIsEnumerable(M)&&x.push(M);_.postMessage({Oc:"load",de:x,je:nr,ke: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"});Dt.push(_)}var nr,Bu=(_,v)=>{He=0,_=Ga(_,v),0-9007199254740992>_||9007199254740992<_?NaN:Number(_);function Pu(_){var v=new ma(_>>>=0);return(C(),oe)[v.Qc+12>>>0]==0&&(us(v,!0),kr--),xn(v,!1),ti.push(v),Gr(_)}var cs=0,wh=()=>{Ge(0,0);var _=ti.pop();xa(_.Xc),cs=0};function us(_,v){v=v?1:0,(C(),oe)[_.Qc+12>>>0]=v}function xn(_,v){v=v?1:0,(C(),oe)[_.Qc+13>>>0]=v}class ma{constructor(v){this.Xc=v,this.Qc=v-24}}var hn=_=>{var v=cs;if(!v)return Ua(0),0;var M=new ma(v);(C(),W)[M.Qc+16>>>2>>>0]=v;var x=(C(),W)[M.Qc+4>>>2>>>0];if(!x)return Ua(0),v;for(var O of _){if(O===0||O===x)break;if(Uo(O,x,M.Qc+16))return Ua(O),v}return Ua(x),v};function bh(){return hn([])}function Mh(_){return hn([_>>>0])}function xh(_,v,M,x){return hn([_>>>0,v>>>0,M>>>0,x>>>0])}var ro=()=>{var _=ti.pop();_||ae("no exception to throw");var v=_.Xc;throw(C(),oe)[_.Qc+13>>>0]==0&&(ti.push(_),xn(_,!0),us(_,!1),kr++),bi(v),cs=v};function so(_,v,M){var x=new ma(_>>>=0);throw v>>>=0,M>>>=0,(C(),W)[x.Qc+16>>>2>>>0]=0,(C(),W)[x.Qc+4>>>2>>>0]=v,(C(),W)[x.Qc+8>>>2>>>0]=M,bi(_),kr++,cs=_}var io=()=>kr;function ar(_,v,M,x){return o?Ye(2,1,_,v,M,x):ni(_,v,M,x)}function ni(_,v,M,x){if(_>>>=0,v>>>=0,M>>>=0,x>>>=0,!globalThis.SharedArrayBuffer)return 6;var O=[];return o&&O.length===0?ar(_,v,M,x):(_={ge:M,Nc:_,Wc:x,Yc:O},o?(_.Oc="spawnThread",postMessage(_,O),0):xt(_))}function ai(_){throw cs||=_>>>0,cs}var Iu=globalThis.TextDecoder&&new TextDecoder,Hl=(_,v,M,x)=>{if(M=v+M,x)return M;for(;_[v]&&!(v>=M);)++v;return v},oo=(_,v=0,M,x)=>{if(16<(M=Hl(_,v>>>=0,M,x))-v&&_.buffer&&Iu)return Iu.decode(_.buffer instanceof ArrayBuffer?_.subarray(v,M):_.slice(v,M));for(x="";v(O=(240&O)==224?(15&O)<<12|F<<6|U:(7&O)<<18|F<<12|U<<6|63&_[v++])?x+=String.fromCharCode(O):(O-=65536,x+=String.fromCharCode(55296|O>>10,56320|1023&O))}}else x+=String.fromCharCode(O)}return x},_a=(_,v,M)=>(_>>>=0)?oo((C(),he),_,v,M):"";function Uu(_,v,M){return o?Ye(3,1,_,v,M):0}function $l(_,v){if(o)return Ye(4,1,_,v)}function Ql(_,v){if(o)return Ye(5,1,_,v)}function Wl(_,v,M){if(o)return Ye(6,1,_,v,M)}function lo(_,v,M){return o?Ye(7,1,_,v,M):0}function co(_,v){if(o)return Ye(8,1,_,v)}function Yl(_,v,M){if(o)return Ye(9,1,_,v,M)}function Xl(_,v,M,x){if(o)return Ye(10,1,_,v,M,x)}function Fa(_,v,M,x){if(o)return Ye(11,1,_,v,M,x)}function $t(_,v,M,x){if(o)return Ye(12,1,_,v,M,x)}function pn(_){if(o)return Ye(13,1,_)}function Or(_,v){if(o)return Ye(14,1,_,v)}function uo(_,v,M){if(o)return Ye(15,1,_,v,M)}var Th=()=>ae(""),ga=_=>{_>>>=0;for(var v="";;){var M=(C(),he)[_++>>>0];if(!M)return v;v+=String.fromCharCode(M)}},fo={},zr={},rr=class extends Error{constructor(_){super(_),this.name="BindingError"}};function Tn(_,v,M={}){return(function(x,O,F={}){var U=O.name;if(!x)throw new rr(`type "${U}" must have a positive integer typeid pointer`);if(zr.hasOwnProperty(x)){if(F.ee)return;throw new rr(`Cannot register type '${U}' twice`)}zr[x]=O,fo.hasOwnProperty(x)&&(O=fo[x],delete fo[x],O.forEach(X=>X()))})(_,v,M)}var Lr=(_,v,M)=>{switch(v){case 1:return M?x=>(C(),oe)[x>>>0]:x=>(C(),he)[x>>>0];case 2:return M?x=>(C(),_e)[x>>>1>>>0]:x=>(C(),de)[x>>>1>>>0];case 4:return M?x=>(C(),re)[x>>>2>>>0]:x=>(C(),W)[x>>>2>>>0];case 8:return M?x=>(C(),ee)[x>>>3>>>0]:x=>(C(),I)[x>>>3>>>0];default:throw new TypeError(`invalid integer width (${v}): ${_}`)}};function ri(_,v,M,x,O){_>>>=0,M>>>=0,v=ga(v>>>0);let F=U=>U;if(x=x===0n){let U=8*M;F=X=>BigInt.asUintN(U,X),O=F(O)}Tn(_,{name:v,Mc:F,Sc:(U,X)=>(typeof X=="number"&&(X=BigInt(X)),X),Rc:Lr(v,M,!x),Tc:null})}function ds(_,v,M,x){Tn(_>>>=0,{name:v=ga(v>>>0),Mc:function(O){return!!O},Sc:function(O,F){return F?M:x},Rc:function(O){return this.Mc((C(),he)[O>>>0])},Tc:null})}var qt=[],sr=[0,1,,1,null,1,!0,1,!1,1];function ho(_){9<(_>>>=0)&&--sr[_+1]==0&&(sr[_]=void 0,qt.push(_))}var Qt=_=>{if(!_)throw new rr(`Cannot use deleted val. handle = ${_}`);return sr[_]},rn=_=>{switch(_){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let v=qt.pop()||sr.length;return sr[v]=_,sr[v+1]=1,v}};function Zl(_){return this.Mc((C(),W)[_>>>2>>>0])}var Gu={name:"emscripten::val",Mc:_=>{var v=Qt(_);return ho(_),v},Sc:(_,v)=>rn(v),Rc:Zl,Tc:null};function ju(_){return Tn(_>>>0,Gu)}var Sh=(_,v)=>{switch(v){case 4:return function(M){return this.Mc((C(),pe)[M>>>2>>>0])};case 8:return function(M){return this.Mc((C(),V)[M>>>3>>>0])};default:throw new TypeError(`invalid float width (${v}): ${_}`)}};function po(_,v,M){M>>>=0,Tn(_>>>=0,{name:v=ga(v>>>0),Mc:x=>x,Sc:(x,O)=>O,Rc:Sh(v,M),Tc:null})}function mo(_,v,M,x,O){_>>>=0,M>>>=0,v=ga(v>>>0);let F=X=>X;if(x===0){var U=32-8*M;F=X=>X<>>U,O=F(O)}Tn(_,{name:v,Mc:F,Sc:(X,fe)=>fe,Rc:Lr(v,M,x!==0),Tc:null})}function Na(_,v,M){function x(F){var U=(C(),W)[F>>>2>>>0];return F=(C(),W)[F+4>>>2>>>0],new O((C(),oe).buffer,F,U)}var O=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][v];Tn(_>>>=0,{name:M=ga(M>>>0),Mc:x,Rc:x},{ee:!0})}var Rt=(_,v,M)=>{var x=(C(),he);if(v>>>=0,0=U){if(v>=M)break;x[v++>>>0]=U}else if(2047>=U){if(v+1>=M)break;x[v++>>>0]=192|U>>6,x[v++>>>0]=128|63&U}else if(65535>=U){if(v+2>=M)break;x[v++>>>0]=224|U>>12,x[v++>>>0]=128|U>>6&63,x[v++>>>0]=128|63&U}else{if(v+3>=M)break;x[v++>>>0]=240|U>>18,x[v++>>>0]=128|U>>12&63,x[v++>>>0]=128|U>>6&63,x[v++>>>0]=128|63&U,F++}}x[v>>>0]=0,_=v-O}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 Eh(_,v){Tn(_>>>=0,{name:v=ga(v>>>0),Mc(M){var x=(C(),W)[M>>>2>>>0];return x=_a(M+4,x,!0),Bn(M),x},Sc(M,x){x instanceof ArrayBuffer&&(x=new Uint8Array(x));var O=typeof x=="string";if(!(O||ArrayBuffer.isView(x)&&x.BYTES_PER_ELEMENT==1))throw new rr("Cannot pass non-string to std::string");var F=O?ya(x):x.length,U=Br(4+F+1),X=U+4;return(C(),W)[U>>>2>>>0]=F,O?Rt(x,X,F+1):(C(),he).set(x,X>>>0),M!==null&&M.push(Bn,U),U},Rc:Zl,Tc(M){Bn(M)}})}var _o=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Vu=(_,v,M)=>{if(_>>>=1,16<(v=Hl((C(),de),_,v/2,M))-_&&_o)return _o.decode((C(),de).slice(_,v));for(M="";_>>0];M+=String.fromCharCode(x)}return M},go=(_,v,M)=>{if(M??=2147483647,2>M)return 0;var x=v;M=(M-=2)<2*_.length?M/2:_.length;for(var O=0;O>>1>>>0]=F,v+=2}return(C(),_e)[v>>>1>>>0]=0,v-x},Ah=_=>2*_.length,$n=(_,v,M)=>{var x="";_>>>=2;for(var O=0;!(O>=v/4);O++){var F=(C(),W)[_+O>>>0];if(!F&&!M)break;x+=String.fromCodePoint(F)}return x},Kl=(_,v,M)=>{if(v>>>=0,M??=2147483647,4>M)return 0;var x=v;M=x+M-4;for(var O=0;O<_.length;++O){var F=_.codePointAt(O);if(65535>>2>>>0]=F,(v+=4)+4>M)break}return(C(),re)[v>>>2>>>0]=0,v-x},qu=_=>{for(var v=0,M=0;M<_.length;++M)65535<_.codePointAt(M)&&M++,v+=4;return v};function Jl(_,v,M){if(_>>>=0,v>>>=0,M=ga(M>>>=0),v===2)var x=Vu,O=go,F=Ah;else x=$n,O=Kl,F=qu;Tn(_,{name:M,Mc:U=>{var X=(C(),W)[U>>>2>>>0];return X=x(U+4,X*v,!0),Bn(U),X},Sc:(U,X)=>{if(typeof X!="string")throw new rr(`Cannot pass non-string to C++ string type ${M}`);var fe=F(X),we=Br(4+fe+v);return(C(),W)[we>>>2>>>0]=fe/v,O(X,we+4,fe+v),U!==null&&U.push(Bn,we),we},Rc:Zl,Tc(U){Bn(U)}})}function fs(_,v){Tn(_>>>=0,{fe:!0,name:v=ga(v>>>0),Mc:()=>{},Sc:()=>{}})}function Hu(_){Ma(_>>>0,!s,1,!r,131072,!1),Du()}var sn=_=>{if(!B)try{if(_(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function ec(_){_>>>=0,hs||(Atomics.waitAsync((C(),re),_>>>2,_).value.then(si),_+=128,Atomics.store((C(),re),_>>>2,1))}var si=()=>sn(()=>{var _=gi();_&&(ec(_),Ur())});function $u(_,v){(_>>>=0)==v>>>0?setTimeout(si):o?postMessage({Vc:_,Oc:"checkMailbox"}):(_=La[_])&&_.postMessage({Oc:"checkMailbox"})}var ii=[];function Ch(_,v,M,x,O){for(v>>>=0,O>>>=0,ii.length=0,M=O>>>3,x=O+x>>>3;M>>0]?(C(),ee)[M++>>>0]:(C(),V)[M++>>>0],ii.push(F)}return(v?ki[v]:Cc[_])(...ii)}var kh=()=>{He=0};function yo(_){_>>>=0,o?postMessage({Oc:"cleanupThread",ie:_}):ao(La[_])}function Da(_){}var ps=_=>{try{_()}catch(v){ae(v)}};function tc(_){var v=(...M)=>{ms.push(_);try{return _(...M)}finally{B||(ms.pop(),mn&&Fn===1&&ms.length===0&&(Fn=0,He+=1,ps(Ec),typeof Fibers<"u"&&Fibers.De()))}};return va.set(_,v),v}var Fn=0,mn=null,nc=0,ms=[],vo=new Map,_s=new Map,va=new Map,ac=0,Fr=null,ir=[],wo=_=>(function(v){if(!B){if(Fn===0){var M=!1,x=!1;v((O=0)=>{if(!B&&(nc=O,M=!0,x)){Fn=2,ps(()=>pr(mn)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),O=!1;try{var F=(function(){var fe=(C(),re)[mn+8>>>2>>>0];return fe=_s.get(fe),fe=va.get(fe),--He,fe()})()}catch(fe){F=fe,O=!0}var U=!1;if(!mn){var X=Fr;X&&(Fr=null,(O?X.reject:X.resolve)(F),U=!0)}if(O&&!U)throw F}}),x=!0,M||(Fn=1,mn=(function(){var O=Br(65548),F=O+12;if((C(),W)[O>>>2>>>0]=F,(C(),W)[O+4>>>2>>>0]=F+65536,F=ms[0],!vo.has(F)){var U=ac++;vo.set(F,U),_s.set(U,F)}return F=vo.get(F),(C(),re)[O+8>>>2>>>0]=F,O})(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),ps(()=>Ci(mn)))}else Fn===2?(Fn=0,ps(Ac),Bn(mn),mn=null,ir.forEach(sn)):ae(`invalid state: ${Fn}`);return nc}})(v=>{_().then(v)});function bo(_){return _>>>=0,wo(async()=>{var v=await Qt(_);return rn(v)})}var Mo=[],xo=_=>{var v=Mo.length;return Mo.push(_),v},To=(_,v)=>{for(var M=Array(_),x=0;x<_;++x){var O=x,F=(C(),W)[v+4*x>>>2>>>0],U=zr[F];if(U===void 0)throw _=`parameter ${x}`,F=mi(F),v=ga(F),Bn(F),new rr(`${_} has unknown type ${v}`);M[O]=U}return M},Qu=(_,v,M)=>{var x=[];return _=_(x,M),x.length&&((C(),W)[v>>>2>>>0]=rn(x)),_},Sn={},wa=_=>{var v=Sn[_];return v===void 0?ga(_):v};function So(_,v,M){var[x,...O]=To(_,v>>>0);v=x.Sc.bind(x);var F=O.map(fe=>fe.Rc.bind(fe));_--;var U={toValue:Qt};switch(_=F.map((fe,we)=>{var $e=`argFromPtr${we}`;return U[$e]=fe,`${$e}(args${we?"+"+8*we:""})`}),M){case 0:var X="toValue(handle)";break;case 2:X="new (toValue(handle))";break;case 3:X="";break;case 1:U.getStringOrSymbol=wa,X="toValue(handle)[getStringOrSymbol(methodName)]"}return X+=`(${_})`,x.fe||(U.toReturnWire=v,U.emval_returnValue=Qu,X=`return emval_returnValue(toReturnWire, destructorsRef, ${X})`),X=`return function (handle, methodName, destructorsRef, args) { + ${X} + }`,M=new Function(Object.keys(U),X)(...Object.values(U)),X=`methodCaller<(${O.map(fe=>fe.name)}) => ${x.name}>`,xo(Object.defineProperty(M,"name",{value:X}))}function oi(_,v){return v>>>=0,(_=Qt(_>>>0))==Qt(v)}function Oh(_){return(_>>>=0)?(_=wa(_),rn(globalThis[_])):rn(globalThis)}function rc(_){return _=wa(_>>>0),rn(t[_])}function sc(_,v){return v>>>=0,_=Qt(_>>>0),v=Qt(v),rn(_[v])}function li(_){9<(_>>>=0)&&(sr[_+1]+=1)}function ci(_,v,M,x,O){return Mo[_>>>0](v>>>0,M>>>0,x>>>0,O>>>0)}function Wu(_,v,M,x,O){return ci(_>>>0,v>>>0,M>>>0,x>>>0,O>>>0)}function zh(){return rn([])}function Lh(_){_=Qt(_>>>0);for(var v=Array(_.length),M=0;M<_.length;M++)v[M]=_[M];return rn(v)}function Fh(_){return rn(wa(_>>>0))}function ic(){return rn({})}function Nh(_){for(var v=Qt(_>>>=0);v.length;){var M=v.pop();v.pop()(M)}ho(_)}function Dh(_,v,M){v>>>=0,M>>>=0,_=Qt(_>>>0),v=Qt(v),M=Qt(M),_[v]=M}function Rh(_,v){_=fn(_),v>>>=0,_=new Date(1e3*_),(C(),re)[v>>>2>>>0]=_.getUTCSeconds(),(C(),re)[v+4>>>2>>>0]=_.getUTCMinutes(),(C(),re)[v+8>>>2>>>0]=_.getUTCHours(),(C(),re)[v+12>>>2>>>0]=_.getUTCDate(),(C(),re)[v+16>>>2>>>0]=_.getUTCMonth(),(C(),re)[v+20>>>2>>>0]=_.getUTCFullYear()-1900,(C(),re)[v+24>>>2>>>0]=_.getUTCDay(),_=(_.getTime()-Date.UTC(_.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(C(),re)[v+28>>>2>>>0]=_}var Yu=_=>_%4==0&&(_%100!=0||_%400==0),Xu=[0,31,60,91,121,152,182,213,244,274,305,335],oc=[0,31,59,90,120,151,181,212,243,273,304,334];function Bh(_,v){_=fn(_),v>>>=0,_=new Date(1e3*_),(C(),re)[v>>>2>>>0]=_.getSeconds(),(C(),re)[v+4>>>2>>>0]=_.getMinutes(),(C(),re)[v+8>>>2>>>0]=_.getHours(),(C(),re)[v+12>>>2>>>0]=_.getDate(),(C(),re)[v+16>>>2>>>0]=_.getMonth(),(C(),re)[v+20>>>2>>>0]=_.getFullYear()-1900,(C(),re)[v+24>>>2>>>0]=_.getDay();var M=(Yu(_.getFullYear())?Xu:oc)[_.getMonth()]+_.getDate()-1|0;(C(),re)[v+28>>>2>>>0]=M,(C(),re)[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)),(C(),re)[v+32>>>2>>>0]=_}function Ph(_){_>>>=0;var v=new Date((C(),re)[_+20>>>2>>>0]+1900,(C(),re)[_+16>>>2>>>0],(C(),re)[_+12>>>2>>>0],(C(),re)[_+8>>>2>>>0],(C(),re)[_+4>>>2>>>0],(C(),re)[_>>>2>>>0],0),M=(C(),re)[_+32>>>2>>>0],x=v.getTimezoneOffset(),O=new Date(v.getFullYear(),6,1).getTimezoneOffset(),F=new Date(v.getFullYear(),0,1).getTimezoneOffset(),U=Math.min(F,O);return 0>M?(C(),re)[_+32>>>2>>>0]=+(O!=F&&U==x):0>>2>>>0]=v.getDay(),M=(Yu(v.getFullYear())?Xu:oc)[v.getMonth()]+v.getDate()-1|0,(C(),re)[_+28>>>2>>>0]=M,(C(),re)[_>>>2>>>0]=v.getSeconds(),(C(),re)[_+4>>>2>>>0]=v.getMinutes(),(C(),re)[_+8>>>2>>>0]=v.getHours(),(C(),re)[_+12>>>2>>>0]=v.getDate(),(C(),re)[_+16>>>2>>>0]=v.getMonth(),(C(),re)[_+20>>>2>>>0]=v.getYear(),_=v.getTime(),BigInt(isNaN(_)?-1:_/1e3)}function Zu(_,v,M,x,O,F,U){return o?Ye(16,1,_,v,M,x,O,F,U):-52}function Ku(_,v,M,x,O,F){if(o)return Ye(17,1,_,v,M,x,O,F)}var Nr={},Ih=()=>performance.timeOrigin+performance.now();function Ju(_,v){if(o)return Ye(18,1,_,v);if(Nr[_]&&(clearTimeout(Nr[_].id),delete Nr[_]),!v)return 0;var M=setTimeout(()=>{delete Nr[_],sn(()=>gc(_,performance.timeOrigin+performance.now()))},v);return Nr[_]={id:M,Ce:v},0}function Uh(_,v,M,x){_>>>=0,v>>>=0,M>>>=0,x>>>=0;var O=new Date().getFullYear(),F=new Date(O,0,1).getTimezoneOffset();O=new Date(O,6,1).getTimezoneOffset();var U=Math.max(F,O);(C(),W)[_>>>2>>>0]=60*U,(C(),re)[v>>>2>>>0]=+(F!=O),_=(v=X=>{var fe=Math.abs(X);return`UTC${0<=X?"-":"+"}${String(Math.floor(fe/60)).padStart(2,"0")}${String(fe%60).padStart(2,"0")}`})(F),v=v(O),ODate.now();function Gh(_,v,M){return M>>>=0,0<=_&&3>=_?(_===0?_=Date.now():_=performance.timeOrigin+performance.now(),_=Math.round(1e6*_),(C(),ee)[M>>>3>>>0]=BigInt(_),0):28}var lc=[],td=(_,v)=>{lc.length=0;for(var M;M=(C(),he)[_++>>>0];){var x=M!=105;v+=(x&=M!=112)&&v%8?4:0,lc.push(M==112?(C(),W)[v>>>2>>>0]:M==106?(C(),ee)[v>>>3>>>0]:M==105?(C(),re)[v>>>2>>>0]:(C(),V)[v>>>3>>>0]),v+=x?8:4}return lc};function jh(_,v,M){return _>>>=0,v=td(v>>>0,M>>>0),ki[_](...v)}function Vh(_,v,M){return _>>>=0,v=td(v>>>0,M>>>0),ki[_](...v)}var qh=()=>{};function Hh(_,v){return N(_a(_>>>0,v>>>0))}var $h=()=>{throw He+=1,"unwind"};function Qh(){return 4294901760}var cc=()=>1,ui=()=>navigator.hardwareConcurrency;function Wh(_){_>>>=0;var v=(C(),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))-nr.buffer.byteLength+65535)/65536|0;try{nr.grow(x),D();var O=1;break e}catch{}O=void 0}if(O)return!0}return!1}var ta=_=>{var v=ya(_)+1,M=Wn(v);return Rt(_,M,v),M},Eo=(_,v)=>{(C(),W)[_>>>2>>>0]=v;var M=(C(),W)[_>>>2>>>0];(C(),W)[_+4>>>2>>>0]=(v-M)/4294967296},gs=_=>(C(),W)[_>>>2>>>0]+4294967296*(C(),re)[_+4>>>2>>>0],Wt=[],nd=(_,v)=>{Wt[_>>>0]=v},En=[],Ao=[],ys=(_,v)=>{Ao[_]=new Promise(M=>v.finally(()=>M(_)))},Ae=_=>{if(_)return Wt[_>>>0]},ad=(_,v)=>{for(_=(C(),W)[_>>>2>>>0];_;_=(C(),W)[_>>>2>>>0])v[(C(),re)[_+4>>>2>>>0]](_)},di=(_,v,M)=>{(C(),W)[_>>>2>>>0]=v,(C(),W)[_+4>>>2>>>0]=M},vs=_=>{var v=(C(),W)[_>>>2>>>0];return _=(C(),W)[_+4>>>2>>>0],_a(v,_)},Nn=_=>{var v=(C(),W)[_>>>2>>>0];return _=(C(),W)[_+4>>>2>>>0],v?_a(v,_):_===0?"":void 0},Yh=_=>{var v=Nn(_+4),M=(M=(C(),W)[_+12>>>2>>>0])?Ae(M):"auto";if(_+=16){var x=Ae((C(),W)[_+4>>>2>>>0]),O=(C(),W)[_+16>>>2>>>0],F=(C(),W)[_+20>>>2>>>0];if(O){for(var U={},X=0;X>>3>>>0]}O=U}else O=void 0;_={module:x,constants:O,entryPoint:Nn(_+8)}}else _=void 0;return{label:v,layout:M,compute:_}},fi=(_,v)=>{function M(x,O){x=_[x],(C(),W)[v+O>>>2>>>0]=x}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),Eo(v+64,_.maxUniformBufferBindingSize),Eo(v+72,_.maxStorageBufferBindingSize),M("maxVertexBuffers",88),Eo(v+96,_.maxBufferSize),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),_.Ae!==void 0&&M("maxImmediateSize",148)},rd=[,"validation","out-of-memory","internal"],sd=[,"compatibility","core"],Co={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},uc=[,"low-power","high-performance"],id=[,"occlusion","timestamp"],od={undefined:1,unknown:1,destroyed:2};function ld(_,v,M,x,O,F){v=fn(v),M=fn(M),x>>>=0,O>>>=0,F>>>=0;var U=Ae(_>>>0);if(_={},F){var X=(C(),W)[F+12>>>2>>>0];if(X){var fe=(C(),W)[F+16>>>2>>>0];_.requiredFeatures=Array.from((C(),W).subarray(fe>>>2>>>0,fe+4*X>>>2>>>0),ye=>Co[ye])}var we=(C(),W)[F+20>>>2>>>0];if(we){let ye=function(it,Pt,zs=!1){Pt=we+Pt,(Pt=(C(),W)[Pt>>>2>>>0])==4294967295||zs&&Pt==0||($e[it]=Pt)},Pe=function(it,Pt){Pt=we+Pt;var zs=(C(),W)[Pt>>>2>>>0],Yo=(C(),W)[Pt+4>>>2>>>0];zs==4294967295&&Yo==4294967295||($e[it]=gs(Pt))};var $e={};ye("maxTextureDimension1D",4),ye("maxTextureDimension2D",8),ye("maxTextureDimension3D",12),ye("maxTextureArrayLayers",16),ye("maxBindGroups",20),ye("maxBindGroupsPlusVertexBuffers",24),ye("maxDynamicUniformBuffersPerPipelineLayout",32),ye("maxDynamicStorageBuffersPerPipelineLayout",36),ye("maxSampledTexturesPerShaderStage",40),ye("maxSamplersPerShaderStage",44),ye("maxStorageBuffersPerShaderStage",48),ye("maxStorageTexturesPerShaderStage",52),ye("maxUniformBuffersPerShaderStage",56),ye("minUniformBufferOffsetAlignment",80),ye("minStorageBufferOffsetAlignment",84),Pe("maxUniformBufferBindingSize",64),Pe("maxStorageBufferBindingSize",72),ye("maxVertexBuffers",88),Pe("maxBufferSize",96),ye("maxVertexAttributes",104),ye("maxVertexBufferArrayStride",108),ye("maxInterStageShaderVariables",112),ye("maxColorAttachments",116),ye("maxColorAttachmentBytesPerSample",120),ye("maxComputeWorkgroupStorageSize",124),ye("maxComputeInvocationsPerWorkgroup",128),ye("maxComputeWorkgroupSizeX",132),ye("maxComputeWorkgroupSizeY",136),ye("maxComputeWorkgroupSizeZ",140),ye("maxComputeWorkgroupsPerDimension",144),ye("maxImmediateSize",148,!0),_.requiredLimits=$e}(X=(C(),W)[F+24>>>2>>>0])&&(X={label:Nn(X+4)},_.defaultQueue=X),_.label=Nn(F+4)}He+=1,ys(v,U.requestDevice(_).then(ye=>{--He,sn(()=>{Wt[O>>>0]=ye.queue,Wt[x>>>0]=ye,ys(M,ye.lost.then(Pe=>{sn(()=>{ye.onuncapturederror=()=>{};var it=Se(),Pt=ta(Pe.message);vi(M,od[Pe.reason],Pt),Ce(it)})})),ye.onuncapturederror=Pe=>{var it=5;Pe.error instanceof GPUValidationError?it=2:Pe.error instanceof GPUOutOfMemoryError?it=3:Pe.error instanceof GPUInternalError&&(it=4);var Pt=Se();Pe=ta(Pe.error.message),Qe(x,it,Pe),Ce(Pt)},"adapterInfo"in ye||(ye.adapterInfo=U.info),pt(v,1,x,0)})},ye=>{--He,sn(()=>{var Pe=Se(),it=ta(ye.message);pt(v,3,x,it),M&&vi(M,4,it),Ce(Pe)})}))}function Xh(_){var v=Ae(_>>>=0),M=En[_];if(M){for(var x=0;x>>=0;var x=Ae(_>>>=0);M==4294967295&&(M=void 0);try{var O=x.getMappedRange(v>>>0,M)}catch{return 0}var F=Ia(16,O.byteLength);return(C(),he).set(new Uint8Array(O),F>>>0),En[_].push(()=>Bn(F)),F}function Kh(_,v,M){M>>>=0;var x=Ae(_>>>=0);M==4294967295&&(M=void 0);try{var O=x.getMappedRange(v>>>0,M)}catch{return 0}var F=Ia(16,O.byteLength);return(C(),he).fill(0,F,O.byteLength),En[_].push(()=>{new Uint8Array(O).set((C(),he).subarray(F>>>0,F+O.byteLength>>>0)),Bn(F)}),F}function Jh(_,v,M,x,O){_>>>=0,v=fn(v),M=fn(M),O>>>=0;var F=Ae(_);En[_]=[],O==4294967295&&(O=void 0),He+=1,ys(v,F.mapAsync(M,x>>>0,O).then(()=>{--He,sn(()=>{wi(v,1,0)})},U=>{--He,sn(()=>{Se();var X=ta(U.message);wi(v,U.name==="AbortError"?4:U.name==="OperationError"?3:0,X),delete En[_]})}))}function ep(_){var v=Ae(_>>>=0),M=En[_];if(M){for(var x=0;x>>0]}function hi(_,v,M){_>>>=0,v>>>=0,M>>>=0;var x=!!(C(),W)[v+32>>>2>>>0];v={label:Nn(v+4),usage:(C(),W)[v+16>>>2>>>0],size:gs(v+24),mappedAtCreation:x},_=Ae(_);try{var O=_.createBuffer(v)}catch{return!1}return Wt[M>>>0]=O,x&&(En[M]=[]),!0}function cd(_,v,M,x){_>>>=0,v=fn(v),x>>>=0,M=Yh(M>>>0),_=Ae(_),He+=1,ys(v,_.createComputePipelineAsync(M).then(O=>{--He,sn(()=>{Wt[x>>>0]=O,Do(v,1,x,0)})},O=>{--He,sn(()=>{var F=Se(),U=ta(O.message);Do(v,O.reason==="validation"?3:O.reason==="internal"?4:0,x,U),Ce(F)})}))}function ud(_,v,M){_>>>=0,v>>>=0,M>>>=0;var x=(C(),W)[v>>>2>>>0],O=(C(),re)[x+4>>>2>>>0];v={label:Nn(v+4),code:""},O===2&&(v.code=vs(x+8)),_=Ae(_).createShaderModule(v),Wt[M>>>0]=_}var dd=_=>{(_=Ae(_)).onuncapturederror=null,_.destroy()};function fd(_,v){v=fn(v),_=Ae(_>>>0),He+=1,ys(v,_.popErrorScope().then(M=>{--He,sn(()=>{var x=5;M?M instanceof GPUValidationError?x=2:M instanceof GPUOutOfMemoryError?x=3:M instanceof GPUInternalError&&(x=4):x=1;var O=Se(),F=M?ta(M.message):0;Ro(v,1,x,F),Ce(O)})},M=>{--He,sn(()=>{var x=Se(),O=ta(M.message);Ro(v,1,5,O),Ce(x)})}))}function dc(_,v,M,x){if(v=fn(v),x>>>=0,M>>>=0){var O={featureLevel:sd[(C(),re)[M+4>>>2>>>0]],powerPreference:uc[(C(),re)[M+8>>>2>>>0]],forceFallbackAdapter:!!(C(),W)[M+12>>>2>>>0]};(_=(C(),W)[M>>>2>>>0])!==0&&(C(),O.Fe=!!(C(),W)[_+8>>>2>>>0])}"gpu"in navigator?(He+=1,ys(v,navigator.gpu.requestAdapter(O).then(F=>{--He,sn(()=>{if(F)Wt[x>>>0]=F,Lt(v,1,x,0);else{var U=Se(),X=ta("WebGPU not available on this browser (requestAdapter returned null)");Lt(v,3,x,X),Ce(U)}})},F=>{--He,sn(()=>{var U=Se(),X=ta(F.message);Lt(v,4,x,X),Ce(U)})}))):(O=Se(),_=ta("WebGPU not available on this browser (navigator.gpu is not available)"),Lt(v,3,x,_),Ce(O))}function tp(_,v,M){return _>>>=0,v>>>=0,M>>>=0,wo(async()=>{var x=[];if(M){var O=(C(),re)[M>>>2>>>0];x.length=v+1,x[v]=new Promise(X=>setTimeout(X,O,0))}else x.length=v;for(var F=0;F{if(!or){var _,v={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(_ in pi)pi[_]===void 0?delete v[_]:v[_]=pi[_];var M=[];for(_ in v)M.push(`${_}=${v[_]}`);or=M}return or};function ko(_,v){if(o)return Ye(19,1,_,v);_>>>=0,v>>>=0;var M,x=0,O=0;for(M of ws()){var F=v+x;(C(),W)[_+O>>>2>>>0]=F,x+=Rt(M,F,1/0)+1,O+=4}return 0}function fc(_,v){if(o)return Ye(20,1,_,v);_>>>=0,v>>>=0;var M=ws();for(var x of((C(),W)[_>>>2>>>0]=M.length,_=0,M))_+=ya(x)+1;return(C(),W)[v>>>2>>>0]=_,0}function lr(_){return o?Ye(21,1,_):52}function Dr(_,v,M,x){return o?Ye(22,1,_,v,M,x):52}function Oo(_,v,M,x){return o?Ye(23,1,_,v,M,x):70}var hd=[null,[],[]];function cr(_,v,M,x){if(o)return Ye(24,1,_,v,M,x);v>>>=0,M>>>=0,x>>>=0;for(var O=0,F=0;F>>2>>>0],X=(C(),W)[v+4>>>2>>>0];v+=8;for(var fe=0;fe>>0],ye=hd[we];$e===0||$e===10?((we===1?R:N)(oo(ye)),ye.length=0):ye.push($e)}O+=X}return(C(),W)[x>>>2>>>0]=O,0}function pd(_){return _>>>0}function md(_,v){return fi(Ae(_>>>0).limits,v>>>0),1}function _d(_,v){return Ae(_>>>0).features.has(Co[v])}function np(_){return BigInt(Ae(_>>>0).size)}function ap(_){return BigInt(Ae(_>>>0).usage)}function rp(_,v){if(_>>>=0,v>>>=0){var M=Nn(v+4);M={label:M,timestampWrites:v=(v=(C(),W)[v+12>>>2>>>0])!==0?{querySet:Ae((C(),W)[v+4>>>2>>>0]),beginningOfPassWriteIndex:(C(),W)[v+8>>>2>>>0],endOfPassWriteIndex:(C(),W)[v+12>>>2>>>0]}:void 0}}return v=Ae(_),_=Un(0),M=v.beginComputePass(M),Wt[_>>>0]=M,_}function gd(_,v,M,x,O,F){M=fn(M),O=fn(O),F=fn(F),Ae(_>>>0).copyBufferToBuffer(Ae(v>>>0),M,Ae(x>>>0),O,F)}function yd(_){var v=Ae(_>>>0);return _=xs(0),v=v.finish(),Wt[_>>>0]=v,_}function hc(_,v,M,x,O,F){F=fn(F),Ae(_>>>0).resolveQuerySet(Ae(v>>>0),M,x,Ae(O>>>0),F)}function na(_,v,M,x){Ae(_>>>0).dispatchWorkgroups(v,M,x)}function zo(_,v,M){M=fn(M),Ae(_>>>0).dispatchWorkgroupsIndirect(Ae(v>>>0),M)}function Qn(_){Ae(_>>>0).end()}function bs(_,v,M,x,O){x>>>=0,O>>>=0,_=Ae(_>>>0),M=Ae(M>>>0),x==0?_.setBindGroup(v,M):_.setBindGroup(v,M,(C(),W),O>>>2,x)}function pc(_,v){Ae(_>>>0).setPipeline(Ae(v>>>0))}function Lo(_,v,M){Ae(_>>>0).Ee(Ae(v>>>0),M)}function Fo(_,v){var M=Ae(_>>>0);return _=yi(0),v=M.getBindGroupLayout(v),Wt[_>>>0]=v,_}function mc(_,v){function M(O){var F=(C(),W)[O+8>>>2>>>0],U=(C(),W)[O+32>>>2>>>0],X=(C(),W)[O+36>>>2>>>0],fe=0;return ad(O,{327681:we=>{fe=(C(),W)[we+8>>>2>>>0]}}),F?((U=gs(O+24))==-1&&(U=void 0),F={buffer:Ae(F),offset:gs(O+16),size:U}):F=Ae(U||X||fe),{binding:(C(),W)[O+4>>>2>>>0],resource:F}}_>>>=0,v={label:Nn(4+(v>>>=0)),layout:Ae((C(),W)[v+12>>>2>>>0]),entries:(function(O,F){for(var U=[],X=0;X>>2>>>0],(C(),W)[v+20>>>2>>>0])},_=Ae(_);var x=Ir(0);return nd(x,_.createBindGroup(v)),x}function Rr(_,v){var M;return _>>>=0,(v>>>=0)&&(M={label:Nn(v+4)}),v=Ae(_),_=In(0),M=v.createCommandEncoder(M),Wt[_>>>0]=M,_}function vd(_,v){_>>>=0,v>>>=0,v={type:id[(C(),re)[v+12>>>2>>>0]],count:(C(),W)[v+16>>>2>>>0]};var M=Ae(_);return _=Ba(0),v=M.createQuerySet(v),Wt[_>>>0]=v,_}function No(_,v){_=Ae(_>>>0).adapterInfo,v>>>=0,(C(),W)[v+52>>>2>>>0]=_.subgroupMinSize,(C(),W)[v+56>>>2>>>0]=_.subgroupMaxSize;var M=_.vendor+_.architecture+_.device+_.description,x=ya(M)+1,O=Br(x);return O&&Rt(M,O,x),M=O,x=ya(_.vendor),di(v+4,M,x),M+=x,x=ya(_.architecture),di(v+12,M,x),M+=x,x=ya(_.device),di(v+20,M,x),di(v+28,M+x,ya(_.description)),(C(),re)[v+36>>>2>>>0]=2,_=_.isFallbackAdapter?3:4,(C(),re)[v+40>>>2>>>0]=_,(C(),W)[v+44>>>2>>>0]=0,(C(),W)[v+48>>>2>>>0]=0,1}var Ms={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function sp(_,v){v>>>=0;var M=Ae(_>>>0);_=Br(4*M.features.size);var x=0,O=0;for(let F of M.features)0<=(M=Ms[F])&&((C(),re)[_+x>>>2>>>0]=M,x+=4,O++);(C(),W)[v+4>>>2>>>0]=_,(C(),W)[v>>>2>>>0]=O}function Rn(_,v){return fi(Ae(_>>>0).limits,v>>>0),1}function _c(_,v){Ae(_>>>0).pushErrorScope(rd[v])}function Ra(_,v,M){v>>>=0,M>>>=0,_=Ae(_>>>0),v=Array.from((C(),re).subarray(M>>>2>>>0,M+4*v>>>2>>>0),x=>Ae(x)),_.submit(v)}function wd(_,v,M,x,O){M=fn(M),x>>>=0,O>>>=0,_=Ae(_>>>0),v=Ae(v>>>0),x=(C(),he).subarray(x>>>0,x+O>>>0),_.writeBuffer(v,M,x,0,O)}o||(function(){for(var _=t.numThreads-1;_--;)Mn();et.push(async()=>{var v=(async function(){if(!o)return Promise.all(Dt.map(Ru))})();ke++,await v,--ke==0&&Ue&&(v=Ue,Ue=null,v())})})(),o||(nr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),D()),t.wasmBinary&&(y=t.wasmBinary),t.stackSave=()=>Se(),t.stackRestore=_=>Ce(_),t.stackAlloc=_=>Wn(_),t.setValue=function(_,v,M="i8"){switch(M.endsWith("*")&&(M="*"),M){case"i1":case"i8":(C(),oe)[_>>>0]=v;break;case"i16":(C(),_e)[_>>>1>>>0]=v;break;case"i32":(C(),re)[_>>>2>>>0]=v;break;case"i64":(C(),ee)[_>>>3>>>0]=BigInt(v);break;case"float":(C(),pe)[_>>>2>>>0]=v;break;case"double":(C(),V)[_>>>3>>>0]=v;break;case"*":(C(),W)[_>>>2>>>0]=v;break;default:ae(`invalid type for setValue: ${M}`)}},t.getValue=function(_,v="i8"){switch(v.endsWith("*")&&(v="*"),v){case"i1":case"i8":return(C(),oe)[_>>>0];case"i16":return(C(),_e)[_>>>1>>>0];case"i32":return(C(),re)[_>>>2>>>0];case"i64":return(C(),ee)[_>>>3>>>0];case"float":return(C(),pe)[_>>>2>>>0];case"double":return(C(),V)[_>>>3>>>0];case"*":return(C(),W)[_>>>2>>>0];default:ae(`invalid type for getValue: ${v}`)}},t.UTF8ToString=_a,t.stringToUTF8=Rt,t.lengthBytesUTF8=ya;var mi,ur,_i,gi,Bn,Br,Pn,Pr,Ir,yi,xs,In,Un,Ba,aa,ra,ba,Do,vi,wi,Ro,Lt,pt,Qe,Ma,Gn,Bo,Pa,Po,gc,Ur,Ia,Ge,Ua,Io,Ce,Wn,Se,xa,bi,Uo,Gr,Mi,Ga,Yt,xi,yc,bd,Md,xd,Ft,Go,Ts,Ss,jo,jr,Vr,Td,vc,Sd,wc,dr,Vo,Ti,bc,qr,qo,Si,Ei,Mc,xc,fr,hr,Tc,Sc,Hr,Es,Ai,As,Ci,Ec,pr,Ac,on,Cc=[bn,za,ar,Uu,$l,Ql,Wl,lo,co,Yl,Xl,Fa,$t,pn,Or,uo,Zu,Ku,Ju,ko,fc,lr,Dr,Oo,cr],ki={925676:(_,v,M,x,O)=>{if(t===void 0||!t.Uc)return 1;if((_=_a(Number(_>>>0))).startsWith("./")&&(_=_.substring(2)),!(_=t.Uc.get(_)))return 2;if(v=Number(v>>>0),M=Number(M>>>0),x=Number(x>>>0),v+M>_.byteLength)return 3;try{let F=_.subarray(v,v+M);switch(O){case 0:(C(),he).set(F,x>>>0);break;case 1:t.ad?t.ad(x,F):t.oe(x,F);break;default:return 4}return 0}catch{return 4}},926500:(_,v,M)=>{t.Sd(_,(C(),he).subarray(v>>>0,v+M>>>0))},926564:()=>t.me(),926606:_=>{t.jd(_)},926643:()=>typeof wasmOffsetConverter<"u"};function mr(_,v,M,x){var O=Se();try{return Go(_,v,M,x)}catch(F){if(Ce(O),F!==F+0)throw F;Ge(1,0)}}function _r(_,v,M){var x=Se();try{return Md(_,v,M)}catch(O){if(Ce(x),O!==O+0)throw O;Ge(1,0)}}function Oi(_,v,M){var x=Se();try{Mi(_,v,M)}catch(O){if(Ce(x),O!==O+0)throw O;Ge(1,0)}}function kc(_,v){var M=Se();try{return Ga(_,v)}catch(x){if(Ce(M),x!==x+0)throw x;Ge(1,0)}}function Oc(_){var v=Se();try{Yt(_)}catch(M){if(Ce(v),M!==M+0)throw M;Ge(1,0)}}function zi(_,v,M,x,O,F,U){var X=Se();try{return bd(_,v,M,x,O,F,U)}catch(fe){if(Ce(X),fe!==fe+0)throw fe;Ge(1,0)}}function Li(_,v){var M=Se();try{Ts(_,v)}catch(x){if(Ce(M),x!==x+0)throw x;Ge(1,0)}}function Ed(_,v,M,x,O,F){var U=Se();try{xi(_,v,M,x,O,F)}catch(X){if(Ce(U),X!==X+0)throw X;Ge(1,0)}}function Ad(_,v,M,x){var O=Se();try{Ft(_,v,M,x)}catch(F){if(Ce(O),F!==F+0)throw F;Ge(1,0)}}function Cs(_,v,M,x,O,F,U){var X=Se();try{jo(_,v,M,x,O,F,U)}catch(fe){if(Ce(X),fe!==fe+0)throw fe;Ge(1,0)}}function Ho(_,v,M,x,O,F,U){var X=Se();try{jr(_,v,M,x,O,F,U)}catch(fe){if(Ce(X),fe!==fe+0)throw fe;Ge(1,0)}}function Cd(_,v,M,x,O,F,U,X){var fe=Se();try{bc(_,v,M,x,O,F,U,X)}catch(we){if(Ce(fe),we!==we+0)throw we;Ge(1,0)}}function zc(_,v,M,x,O,F,U,X,fe,we,$e,ye){var Pe=Se();try{Vr(_,v,M,x,O,F,U,X,fe,we,$e,ye)}catch(it){if(Ce(Pe),it!==it+0)throw it;Ge(1,0)}}function Lc(_,v,M,x,O){var F=Se();try{return Ss(_,v,M,x,O)}catch(U){if(Ce(F),U!==U+0)throw U;Ge(1,0)}}function jn(_,v,M,x,O){var F=Se();try{yc(_,v,M,x,O)}catch(U){if(Ce(F),U!==U+0)throw U;Ge(1,0)}}function Yn(_,v,M,x,O,F,U,X){var fe=Se();try{xd(_,v,M,x,O,F,U,X)}catch(we){if(Ce(fe),we!==we+0)throw we;Ge(1,0)}}function gr(_){var v=Se();try{return qr(_)}catch(M){if(Ce(v),M!==M+0)throw M;Ge(1,0)}}function Fc(_,v,M){var x=Se();try{return qo(_,v,M)}catch(O){if(Ce(x),O!==O+0)throw O;Ge(1,0)}}function kd(_,v){var M=Se();try{return As(_,v)}catch(x){if(Ce(M),x!==x+0)throw x;return Ge(1,0),0n}}function yr(_,v,M,x,O){var F=Se();try{Si(_,v,M,x,O)}catch(U){if(Ce(F),U!==U+0)throw U;Ge(1,0)}}function Vn(_){var v=Se();try{return Td(_)}catch(M){if(Ce(v),M!==M+0)throw M;return Ge(1,0),0n}}function Nt(_,v,M,x,O,F){var U=Se();try{return Vo(_,v,M,x,O,F)}catch(X){if(Ce(U),X!==X+0)throw X;Ge(1,0)}}function $o(_,v,M,x,O,F){var U=Se();try{return Ei(_,v,M,x,O,F)}catch(X){if(Ce(U),X!==X+0)throw X;Ge(1,0)}}function ja(_,v,M,x,O,F){var U=Se();try{return Mc(_,v,M,x,O,F)}catch(X){if(Ce(U),X!==X+0)throw X;Ge(1,0)}}function Be(_,v,M,x,O,F,U,X){var fe=Se();try{return Ti(_,v,M,x,O,F,U,X)}catch(we){if(Ce(fe),we!==we+0)throw we;Ge(1,0)}}function ht(_,v,M,x,O){var F=Se();try{return xc(_,v,M,x,O)}catch(U){if(Ce(F),U!==U+0)throw U;return Ge(1,0),0n}}function Bt(_,v,M,x){var O=Se();try{return fr(_,v,M,x)}catch(F){if(Ce(O),F!==F+0)throw F;Ge(1,0)}}function Qo(_,v,M,x){var O=Se();try{return hr(_,v,M,x)}catch(F){if(Ce(O),F!==F+0)throw F;Ge(1,0)}}function ks(_,v,M,x,O,F,U,X,fe,we,$e,ye){var Pe=Se();try{return Tc(_,v,M,x,O,F,U,X,fe,we,$e,ye)}catch(it){if(Ce(Pe),it!==it+0)throw it;Ge(1,0)}}function $r(_,v,M,x,O,F,U,X,fe,we,$e){var ye=Se();try{Sc(_,v,M,x,O,F,U,X,fe,we,$e)}catch(Pe){if(Ce(ye),Pe!==Pe+0)throw Pe;Ge(1,0)}}function Wo(_,v,M,x,O,F,U,X,fe,we,$e,ye,Pe,it,Pt,zs){var Yo=Se();try{Hr(_,v,M,x,O,F,U,X,fe,we,$e,ye,Pe,it,Pt,zs)}catch(Xo){if(Ce(Yo),Xo!==Xo+0)throw Xo;Ge(1,0)}}function Fi(_,v,M,x){var O=Se();try{return Es(_,v,M,x)}catch(F){if(Ce(O),F!==F+0)throw F;Ge(1,0)}}function Os(_,v,M,x,O){var F=Se();try{return Ai(_,v,M,x,O)}catch(U){if(Ce(F),U!==U+0)throw U;Ge(1,0)}}function ip(_,v,M){var x=Se();try{return Sd(_,v,M)}catch(O){if(Ce(x),O!==O+0)throw O;return Ge(1,0),0n}}function At(_,v,M){var x=Se();try{return vc(_,v,M)}catch(O){if(Ce(x),O!==O+0)throw O;Ge(1,0)}}function Nc(_,v,M){var x=Se();try{return wc(_,v,M)}catch(O){if(Ce(x),O!==O+0)throw O;Ge(1,0)}}function Dc(_,v,M,x){var O=Se();try{dr(_,v,M,x)}catch(F){if(Ce(O),F!==F+0)throw F;Ge(1,0)}}function Ni(){if(0{let v=new WeakMap,M,x,O=1;t.webgpuRegisterDevice=X=>{if(x!==void 0)throw Error("another WebGPU EP inference session is being created.");if(X){var fe=v.get(X);if(!fe){let we=(($e,ye=0)=>{var Pe=ba(ye);return ye=ra(ye,Pe),Wt[Pe>>>0]=$e.queue,Wt[ye>>>0]=$e,ye})(X,fe=Pr(0));fe=[O++,fe,we],v.set(X,fe)}return M=X,x=fe[0],fe}M=void 0,x=0};let F=new Map;t.webgpuOnCreateSession=X=>{if(x!==void 0){var fe=x;if(x=void 0,X){let we=_i(fe);F.set(X,we),fe===0&&_(M??Ae(we))}M=void 0}},t.webgpuOnReleaseSession=X=>{F.delete(X)};let U=Symbol("gpuBufferMetadata");t.webgpuRegisterBuffer=(X,fe,we)=>{if(we)return X[U]=[we,NaN],we;if(we=X[U])return we[1]++,we[0];if((fe=F.get(fe))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return fe=(($e,ye=0)=>($e.mapState==="unmapped"||ae(),ye=aa(ye),Wt[ye>>>0]=$e,ye))(X,fe),X[U]=[fe,1],fe},t.webgpuUnregisterBuffer=X=>{let fe=X[U];if(!fe)throw Error("Buffer is not registered");fe[1]--,fe[1]===0&&(Pn(fe[0]),delete X[U])},t.webgpuGetBuffer=X=>Ae(X),t.webgpuCreateDownloader=(X,fe,we)=>{if((we=F.get(we))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let $e=Ae(we),ye=16*Math.ceil(Number(fe)/16);return async()=>{let Pe=$e.createBuffer({size:ye,usage:9});try{let it=$e.createCommandEncoder();return it.copyBufferToBuffer(X,0,Pe,0,ye),$e.queue.submit([it.finish()]),await Pe.mapAsync(GPUMapMode.READ),Pe.getMappedRange().slice(0,fe)}finally{Pe.destroy()}}},t.ad=(X,fe)=>{var we=fe.buffer;let $e=fe.byteOffset,ye=fe.byteLength;if(fe=16*Math.ceil(Number(ye)/16),X=Ae(X),!M){var Pe=_i(x);M=Ae(Pe)}let it=(Pe=M.createBuffer({mappedAtCreation:!0,size:fe,usage:6})).getMappedRange();new Uint8Array(it).set(new Uint8Array(we,$e,ye)),Pe.unmap(),(we=M.createCommandEncoder()).copyBufferToBuffer(Pe,0,X,0,fe),M.queue.submit([we.finish()]),Pe.destroy()}},t.webnnInit=_=>{let v=_[0];[t.me,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.le,t.webnnEnableTraceEvent]=_.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.le,t.webnnOnRunStart=M=>v.onRunStart(M),t.webnnOnRunEnd=v.onRunEnd.bind(v),t.webnnOnReleaseSession=M=>{v.onReleaseSession(M)},t.webnnCreateMLTensorDownloader=(M,x)=>v.createMLTensorDownloader(M,x),t.webnnRegisterMLTensor=(M,x,O,F)=>v.registerMLTensor(M,x,O,F),t.webnnCreateMLContext=M=>v.createMLContext(M),t.webnnRegisterMLConstant=(M,x,O,F,U,X)=>v.registerMLConstant(M,x,O,F,U,t.Uc,X),t.webnnRegisterGraphInput=v.registerGraphInput.bind(v),t.webnnIsGraphInput=v.isGraphInput.bind(v),t.webnnRegisterGraphOutput=v.registerGraphOutput.bind(v),t.webnnIsGraphOutput=v.isGraphOutput.bind(v),t.webnnCreateTemporaryTensor=v.createTemporaryTensor.bind(v),t.webnnIsGraphInputOutputTypeSupported=v.isGraphInputOutputTypeSupported.bind(v)},J?t:new Promise((_,v)=>{S=_,E=v})}var K1,X0,BE=Je(()=>{K1=Y0,X0=globalThis.self?.name?.startsWith("em-pthread"),X0&&Y0()}),Am,i_,Z0,ca,J1,pf,K0,J0,Cm,eb,km,eM,Om,tM,C_=Je(()=>{A_(),Am=typeof location>"u"?void 0:location.origin,i_=import.meta.url>"file:"&&import.meta.url<"file;",Z0=()=>{{if(i_){let e=URL;return new URL(new e("ort.webgpu.bundle.min.mjs",import.meta.url).href,Am).href}return import.meta.url}},ca=Z0(),J1=()=>{if(ca&&!ca.startsWith("blob:"))return ca.substring(0,ca.lastIndexOf("/")+1)},pf=(e,t)=>{try{let r=t??ca;return(r?new URL(e,r):new URL(e)).origin===Am}catch{return!1}},K0=(e,t)=>{let r=t??ca;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},J0=(e,t)=>`${t??"./"}${e}`,Cm=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},eb=async e=>(await import(e)).default,km=(RE(),Of(Y1)).default,eM=async()=>{if(!ca)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(pf(ca))return[void 0,km()];let e=await Cm(ca);return[e,km(e)]},Om=(BE(),Of(Z1)).default,tM=async(e,t,r,s)=>{let o=Om&&!(e||t);if(o)if(ca)o=pf(ca)||s&&!r;else if(s&&!r)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,Om];{let l="ort-wasm-simd-threaded.asyncify.mjs",u=e??K0(l,t),d=r&&u&&!pf(u,t),f=d?await Cm(u):u??J0(l,t);return[d?f:void 0,await eb(f)]}}}),zm,mf,iu,Lm,tb,nb,ab,k_,gt,Ki=Je(()=>{C_(),mf=!1,iu=!1,Lm=!1,tb=()=>{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}},nb=()=>{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}},ab=()=>{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}},k_=async e=>{if(mf)return Promise.resolve();if(iu)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Lm)throw new Error("previous call to 'initializeWebAssembly()' failed.");iu=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ab())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!nb())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=tb();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,l=typeof o=="string"?o:void 0,u=o?.mjs,d=u?.href??u,f=o?.wasm,p=f?.href??f,g=e.wasmBinary,[y,w]=await tM(d,l,r>1,!!g||!!p),b=!1,S=[];if(t>0&&S.push(new Promise(E=>{setTimeout(()=>{b=!0,E()},t)})),S.push(new Promise((E,z)=>{let k={numThreads:r};if(g)k.wasmBinary=g,k.locateFile=L=>L;else if(p||l)k.locateFile=L=>p??l+L;else if(d&&d.indexOf("blob:")!==0)k.locateFile=L=>new URL(L,d).href;else if(y){let L=J1();L&&(k.locateFile=R=>L+R)}w(k).then(L=>{iu=!1,mf=!0,zm=L,E(),y&&URL.revokeObjectURL(y)},L=>{iu=!1,Lm=!0,z(L)})})),await Promise.race(S),b)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},gt=()=>{if(mf&&zm)return zm;throw new Error("WebAssembly is not initialized yet.")}}),ua,Lf,ct,O_=Je(()=>{Ki(),ua=(e,t)=>{let r=gt(),s=r.lengthBytesUTF8(e)+1,o=r._malloc(s);return r.stringToUTF8(e,o,s),t.push(o),o},Lf=(e,t,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,l])=>{let u=t?t+o:o;if(typeof l=="object")Lf(l,u+".",r,s);else if(typeof l=="string"||typeof l=="number")s(u,l.toString());else if(typeof l=="boolean")s(u,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},ct=e=>{let t=gt(),r=t.stackSave();try{let s=t.PTR_SIZE,o=t.stackAlloc(2*s);t._OrtGetLastError(o,o+s);let l=Number(t.getValue(o,s===4?"i32":"i64")),u=t.getValue(o+s,"*"),d=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(r)}}}),nM,PE=Je(()=>{Ki(),O_(),nM=e=>{let t=gt(),r=0,s=[],o=e||{};try{if(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?.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?.terminate===void 0&&(o.terminate=!1);let l=0;return e?.tag!==void 0&&(l=ua(e.tag,s)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),r===0&&ct("Can't create run options."),e?.extra!==void 0&&Lf(e.extra,"",new WeakSet,(u,d)=>{let f=ua(u,s),p=ua(d,s);t._OrtAddRunConfigEntry(r,f,p)!==0&&ct(`Can't set a run config entry: ${u} - ${d}.`)}),[r,s]}catch(l){throw r!==0&&t._OrtReleaseRunOptions(r),s.forEach(u=>t._free(u)),l}}}),rb,sb,ib,_f,$s,ob,aM,IE=Je(()=>{Ki(),O_(),rb=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}`)}},sb=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ib=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},_f=(e,t,r,s)=>{let o=ua(t,s),l=ua(r,s);gt()._OrtAddSessionConfigEntry(e,o,l)!==0&&ct(`Can't set a session config entry: ${t} - ${r}.`)},$s=(e,t,r,s)=>{let o=ua(t,s),l=ua(r,s);e.push([o,l])},ob=async(e,t,r)=>{let s=t.executionProviders;for(let o of s){let l=typeof o=="string"?o:o.name,u=[];switch(l){case"webnn":if(l="WEBNN",typeof o!="string"){let y=o?.deviceType;y&&_f(e,"deviceType",y,r)}break;case"webgpu":{l="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}=t;if(typeof S=="boolean"&&S&&$s(u,"enableGraphCapture","1",r),typeof b.preferredLayout=="string"&&$s(u,"preferredLayout",b.preferredLayout,r),b.forceCpuNodeNames){let E=Array.isArray(b.forceCpuNodeNames)?b.forceCpuNodeNames:[b.forceCpuNodeNames];$s(u,"forceCpuNodeNames",E.join(` +`),r)}b.validationMode&&$s(u,"validationMode",b.validationMode,r)}let w=gt().webgpuRegisterDevice(y);if(w){let[b,S,E]=w;$s(u,"deviceId",b.toString(),r),$s(u,"webgpuInstance",S.toString(),r),$s(u,"webgpuDevice",E.toString(),r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let d=ua(l,r),f=u.length,p=0,g=0;if(f>0){p=gt()._malloc(f*gt().PTR_SIZE),r.push(p),g=gt()._malloc(f*gt().PTR_SIZE),r.push(g);for(let y=0;y{let t=gt(),r=0,s=[],o=e||{};ib(o);try{let l=rb(o.graphOptimizationLevel??"all"),u=sb(o.executionMode??"sequential"),d=typeof o.logId=="string"?ua(o.logId,s):0,f=o.logSeverityLevel??2;if(!Number.isInteger(f)||f<0||f>4)throw new Error(`log severity level is not valid: ${f}`);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"?ua(o.optimizedModelFilePath,s):0;if(r=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,d,f,p,g),r===0&&ct("Can't create session options."),o.executionProviders&&await ob(r,o,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);_f(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=ua(y,s);t._OrtAddFreeDimensionOverride(r,b,w)!==0&&ct(`Can't set a free dimension override: ${y} - ${w}.`)}return o.extra!==void 0&&Lf(o.extra,"",new WeakSet,(y,w)=>{_f(r,y,w,s)}),[r,s]}catch(l){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&ct("Can't release session options."),s.forEach(u=>t._free(u)),l}}}),qi,Sf,ml,wu,Ff,z_,L_,o_,El=Je(()=>{qi=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}`)}},Sf=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}`)}},ml=(e,t)=>{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 t=="number"?t:t.reduce((o,l)=>o*l,1);return r>0?Math.ceil(s*r):void 0},wu=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}`)}},Ff=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}`)}},z_=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",L_=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",o_=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}`)}}}),F_,rM=Je(()=>{A_(),F_=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),s=r?parseInt(r,10):0;if(s<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),l;try{l=new ArrayBuffer(s)}catch(d){if(d instanceof RangeError){let f=Math.ceil(s/65536);l=new WebAssembly.Memory({initial:f,maximum:f}).buffer}else throw d}let u=0;for(;;){let{done:d,value:f}=await o.read();if(d)break;let p=f.byteLength;new Uint8Array(l,u,p).set(f),u+=p}return new Uint8Array(l,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),sM,UE=Je(()=>{El(),sM=(e,t)=>new(wu(t))(e)}),lb,cb,ub,db,iM,fb,Cn,oM=Je(()=>{El(),lb=["V","I","W","E","F"],cb=(e,t)=>{console.log(`[${lb[e]},${new Date().toISOString()}]${t}`)},iM=(e,t)=>{ub=e,db=t},fb=(e,t)=>{let r=Ff(e),s=Ff(ub);r>=s&&cb(r,typeof t=="function"?t():t)},Cn=(...e)=>{db&&fb(...e)}}),Fm,l_,Nm,hb,Dm,pb,Rm,Bm,Pm,mb,lM,GE=Je(()=>{El(),oM(),Fm=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),l_=(e,t)=>{if(t==="int32")return e;let r=Fm.get(t);if(!r)throw new Error(`WebNN backend does not support data type: ${t}`);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,l=new(wu(t))(e.buffer,e.byteOffset,o);switch(t){case"int64":case"uint64":{let u=new Int32Array(o);for(let d=0;d2147483647n||f<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[d]=Number(f)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(d=>d>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let u=Int32Array.from(l,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Nm=(e,t)=>{if(t==="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(t){case"int64":{let o=BigInt64Array.from(s,BigInt);return new Uint8Array(o.buffer)}case"uint64":{if(s.some(l=>l<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(l=>l<-128||l>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(l=>l<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 ${t}`)}},hb=1,Dm=()=>hb++,pb=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Rm=(e,t)=>{let r=Fm.get(e);if(!r)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((s,o)=>s*o)*r/8):0},Bm=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:r,tensor:s,dataType:o,shape:l,fallbackDataType:u}=e;this.sessionId=t,this.mlContext=r,this.mlTensor=s,this.dataType=o,this.tensorShape=l,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 Rm(this.dataType,this.tensorShape)}destroy(){Cn("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),r=Nm(new Uint8Array(t),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,t,r){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===r.length&&this.tensorShape.every((s,o)=>s===r[o])}setIsDataConverted(e){this.isDataConverted=e}},Pm=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,r,s){let o=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),u;if(!l?.input.dataTypes.includes(t)){if(u=pb.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);Cn("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,t,r))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Rm(t,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,t,r,d,!0,!0,u),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=l_(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(t);return}else Cn("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Nm(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},mb=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Dm();return this.tensorTrackersById.set(e,new Pm(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,r,s,o){Cn("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${r}, shape: ${s}, copyOld: ${o}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,r,s,o)}upload(e,t){let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");r.upload(t)}async download(e,t){Cn("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let r=this.tensorTrackersById.get(e);if(!r)throw new Error("Tensor not found.");return r.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,r,s){let o=this.getMLContext(e),l=Dm(),u=new Bm({sessionId:e,context:o,tensor:t,dataType:r,shape:s});return this.tensorTrackersById.set(l,new Pm(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,r,s,o,l,u){let d=this.getMLContext(e);for(let[p,g]of this.freeTensors.entries())if(g.canReuseTensor(d,t,r)){Cn("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${r}`);let y=this.freeTensors.splice(p,1)[0];return y.sessionId=e,y}Cn("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${r}}`);let f=await d.createTensor({dataType:u??t,shape:r,dimensions:r,usage:s,writable:o,readable:l});return new Bm({sessionId:e,context:d,tensor:f,dataType:t,shape:r,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},lM=(...e)=>new mb(...e)}),cM={};Tu(cM,{WebNNBackend:()=>uM});var ou,_b,uM,jE=Je(()=>{El(),Ki(),UE(),GE(),oM(),ou=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),_b=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),s=Object.keys(t).sort();return r.length===s.length&&r.every((o,l)=>o===s[l]&&e[o]===t[o])},uM=class{constructor(e){this.tensorManager=lM(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,iM(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Cn("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Cn("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let r of t)Cn("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 t=this.mlContextCache.findIndex(r=>_b(r.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let r=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:r}),r}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.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 t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);if(r.delete(e),r.size===0){this.sessionIdsByMLContext.delete(t);let s=this.mlContextCache.findIndex(o=>o.mlContext===t);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){Cn("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,s,o){let l=ou.get(r);if(!l)throw new Error(`Unsupported ONNX data type: ${r}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,s,o)}async createTemporaryTensor(e,t,r){Cn("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${r}}`);let s=ou.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,r,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,t){if(!gt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Cn("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return sM(r,t)}}registerMLTensor(e,t,r,s){let o=ou.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let l=this.tensorManager.registerTensor(e,t,o,s);return Cn("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${l}}`),l}registerMLConstant(e,t,r,s,o,l,u=!1){if(!l)throw new Error("External mounted files are not available.");let d=e;e.startsWith("./")&&(d=e.substring(2));let f=l.get(d);if(!f)throw new Error(`File with name ${d} not found in preloaded files.`);if(t+r>f.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=f.slice(t,t+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=l_(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 Cn("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,t){let r=this.sessionGraphInputs.get(e);return r?r.includes(t):!1}isGraphOutput(e,t){let r=this.sessionGraphOutputs.get(e);return r?r.includes(t):!1}isGraphInputOutputTypeSupported(e,t,r=!0){let s=ou.get(qi(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof s>"u"?!1:r?!!o?.input.dataTypes.includes(s):!!o?.output.dataTypes.includes(s)}flush(){}}}),gb,N_,D_,Qs,yb,Im,Nf,R_,B_,Um,P_,I_,U_,dM=Je(()=>{Zi(),PE(),IE(),El(),Ki(),O_(),rM(),gb=(e,t)=>{gt()._OrtInit(e,t)!==0&&ct("Can't initialize onnxruntime.")},N_=async e=>{gb(e.wasm.numThreads,Ff(e.logLevel))},D_=async(e,t)=>{gt().asyncInit?.();let r=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(r){if(typeof r.limits!="object"||typeof r.features!="object"||typeof r.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(r=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:o}),!r)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");if(t==="webgpu"&>().webgpuInit(s=>{e.webgpu.device=s}),t==="webnn"){let s=new(jE(),Of(cM)).WebNNBackend(e);gt().webnnInit([s,()=>s.reserveTensorId(),o=>s.releaseTensorId(o),async(o,l,u,d,f)=>s.ensureTensor(o,l,u,d,f),(o,l)=>{s.uploadTensor(o,l)},async(o,l)=>s.downloadTensor(o,l),(o,l)=>s.registerMLContext(o,l),!!e.trace])}},Qs=new Map,yb=e=>{let t=gt(),r=t.stackSave();try{let s=t.PTR_SIZE,o=t.stackAlloc(2*s);t._OrtGetInputOutputCount(e,o,o+s)!==0&&ct("Can't get session input/output count.");let l=s===4?"i32":"i64";return[Number(t.getValue(o,l)),Number(t.getValue(o+s,l))]}finally{t.stackRestore(r)}},Im=(e,t)=>{let r=gt(),s=r.stackSave(),o=0;try{let l=r.PTR_SIZE,u=r.stackAlloc(2*l);r._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&ct("Can't get session input/output metadata.");let d=Number(r.getValue(u,"*"));o=Number(r.getValue(u+l,"*"));let f=r.HEAP32[o/4];if(f===0)return[d,0];let p=r.HEAPU32[o/4+1],g=[];for(let y=0;y{let t=gt(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},R_=async(e,t)=>{let r,s,o=gt();Array.isArray(e)?[r,s]=e:e.buffer===o.HEAPU8.buffer?[r,s]=[e.byteOffset,e.byteLength]:[r,s]=Nf(e);let l=0,u=0,d=0,f=[],p=[],g=[];try{if([u,f]=await aM(t),t?.externalData&&o.mountExternalData){let N=[];for(let B of t.externalData){let j=typeof B=="string"?B:B.path;N.push(F_(typeof B=="string"?B:B.data).then(C=>{o.mountExternalData(j,C)}))}await Promise.all(N)}for(let N of t?.executionProviders??[])if((typeof N=="string"?N:N.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof N!="string"){let B=N,j=B?.context,C=B?.gpuDevice,ue=B?.deviceType,oe=B?.powerPreference;j?o.currentContext=j:C?o.currentContext=await o.webnnCreateMLContext(C):o.currentContext=await o.webnnCreateMLContext({deviceType:ue,powerPreference:oe})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(r,s,u),o.webgpuOnCreateSession?.(l),l===0&&ct("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[y,w]=yb(l),b=!!t?.enableGraphCapture,S=[],E=[],z=[],k=[],L=[];for(let N=0;NN==="gpu-buffer"||N==="ml-tensor"||N==="ml-tensor-cpu-output")&&(d=o._OrtCreateBinding(l),d===0&&ct("Can't create IO binding."),R={handle:d,outputPreferredLocations:L,outputPreferredLocationsEncoded:L.map(N=>N==="ml-tensor-cpu-output"?"ml-tensor":N).map(N=>o_(N))}),Qs.set(l,[l,p,g,R,b,!1]),[l,S,E,z,k]}catch(y){throw p.forEach(w=>o._OrtFree(w)),g.forEach(w=>o._OrtFree(w)),d!==0&&o._OrtReleaseBinding(d)!==0&&ct("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&ct("Can't release session."),y}finally{o._free(r),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&ct("Can't release session options."),f.forEach(y=>o._free(y)),o.unmountExternalData?.()}},B_=e=>{let t=gt(),r=Qs.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,l,u,d]=r;u&&(d&&t._OrtClearBoundOutputs(u.handle)!==0&&ct("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&ct("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),o.forEach(f=>t._OrtFree(f)),l.forEach(f=>t._OrtFree(f)),t._OrtReleaseSession(s)!==0&&ct("Can't release session."),Qs.delete(e)},Um=async(e,t,r,s,o,l,u=!1)=>{if(!e){t.push(0);return}let d=gt(),f=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 ${l} when enableGraphCapture is true.`);if(y==="gpu-buffer"){let k=e[2].gpuBuffer;S=ml(qi(p),g);{let L=d.webgpuRegisterBuffer;if(!L)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');b=L(k,s)}}else if(y==="ml-tensor"){let k=e[2].mlTensor;S=ml(qi(p),g);let L=d.webnnRegisterMLTensor;if(!L)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');b=L(s,k,qi(p),g)}else{let k=e[2];if(Array.isArray(k)){S=f*k.length,b=d._malloc(S),r.push(b);for(let L=0;Ld.setValue(z+R*f,L,f===4?"i32":"i64"));let k=d._OrtCreateTensor(qi(p),b,S,z,g.length,o_(w));k===0&&ct(`Can't create tensor for input/output. session=${s}, index=${l}.`),t.push(k)}finally{d.stackRestore(E)}},P_=async(e,t,r,s,o,l)=>{let u=gt(),d=u.PTR_SIZE,f=Qs.get(e);if(!f)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=f[0],g=f[1],y=f[2],w=f[3],b=f[4],S=f[5],E=t.length,z=s.length,k=0,L=[],R=[],N=[],B=[],j=[],C=u.stackSave(),ue=u.stackAlloc(E*d),oe=u.stackAlloc(E*d),he=u.stackAlloc(z*d),_e=u.stackAlloc(z*d);try{[k,L]=nM(l),Zs("wasm prepareInputOutputTensor");for(let pe=0;peke*Ue,1);J=Sf(ae);let et=w?.outputPreferredLocations[s[pe]];if(J==="string"){if(et==="gpu-buffer"||et==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ke=[];for(let Ue=0;Ue0){let ke=u.webgpuGetBuffer;if(!ke)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ue=ke(D),xt=ml(ae,ze);if(xt===void 0||!z_(J))throw new Error(`Unsupported data type: ${J}`);$=!0;{u.webgpuRegisterBuffer(Ue,e,D);let He=u.webgpuCreateDownloader(Ue,xt,e);re.push([J,Ee,{gpuBuffer:Ue,download:async()=>{let Ye=await He();return new(wu(J))(Ye)},dispose:()=>{u._OrtReleaseTensor(V)!==0&&ct("Can't release tensor.")}},"gpu-buffer"])}}else if(et==="ml-tensor"&&ze>0){let ke=u.webnnEnsureTensor,Ue=u.webnnIsGraphInputOutputTypeSupported;if(!ke||!Ue)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ml(ae,ze)===void 0||!L_(J))throw new Error(`Unsupported data type: ${J}`);if(!Ue(e,J,!1))throw new Error(`preferredLocation "ml-tensor" for ${J} output is not supported by current WebNN Context.`);let xt=await ke(e,D,ae,Ee,!1);$=!0,re.push([J,Ee,{mlTensor:xt,download:u.webnnCreateMLTensorDownloader(D,J),dispose:()=>{u.webnnReleaseTensorId(D),u._OrtReleaseTensor(V)}},"ml-tensor"])}else if(et==="ml-tensor-cpu-output"&&ze>0){let ke=u.webnnCreateMLTensorDownloader(D,J)(),Ue=re.length;$=!0,W.push((async()=>{let xt=[Ue,await ke];return u.webnnReleaseTensorId(D),u._OrtReleaseTensor(V),xt})()),re.push([J,Ee,[],"cpu"])}else{let ke=wu(J),Ue=new ke(ze);new Uint8Array(Ue.buffer,Ue.byteOffset,Ue.byteLength).set(u.HEAPU8.subarray(D,D+Ue.byteLength)),re.push([J,Ee,Ue,"cpu"])}}finally{u.stackRestore(ee),J==="string"&&D&&u._free(D),$||u._OrtReleaseTensor(V)}}w&&!b&&(u._OrtClearBoundOutputs(w.handle)!==0&&ct("Can't clear bound outputs."),Qs.set(e,[p,g,y,w,b,!1]));for(let[pe,V]of await Promise.all(W))re[pe][2]=V;return Ks("wasm ProcessOutputTensor"),re}finally{u.webnnOnRunEnd?.(p),u.stackRestore(C),r.forEach(de=>{de&&de[3]==="gpu-buffer"&&u.webgpuUnregisterBuffer(de[2].gpuBuffer)}),o.forEach(de=>{de&&de[3]==="gpu-buffer"&&u.webgpuUnregisterBuffer(de[2].gpuBuffer)}),R.forEach(de=>u._OrtReleaseTensor(de)),N.forEach(de=>u._OrtReleaseTensor(de)),B.forEach(de=>u._free(de)),k!==0&&u._OrtReleaseRunOptions(k),L.forEach(de=>u._free(de))}},I_=e=>{let t=gt(),r=Qs.get(e);if(!r)throw new Error("invalid session id");let s=r[0],o=t._OrtEndProfiling(s);o===0&&ct("Can't get an profile file name."),t._OrtFree(o)},U_=e=>{let t=[];for(let r of e){let s=r[2];!Array.isArray(s)&&"buffer"in s&&t.push(s.buffer)}return t}}),Ws,Ea,ul,lu,cu,gf,Gm,yf,Pi,Ii,vb,fM,hM,pM,mM,_M,gM,yM,vM=Je(()=>{Zi(),dM(),Ki(),C_(),Ws=()=>!!kt.wasm.proxy&&typeof document<"u",ul=!1,lu=!1,cu=!1,yf=new Map,Pi=(e,t)=>{let r=yf.get(e);r?r.push(t):yf.set(e,[t])},Ii=()=>{if(ul||!lu||cu||!Ea)throw new Error("worker not ready")},vb=e=>{switch(e.data.type){case"init-wasm":ul=!1,e.data.err?(cu=!0,Gm[1](e.data.err)):(lu=!0,Gm[0]()),gf&&(URL.revokeObjectURL(gf),gf=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=yf.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},fM=async()=>{if(!lu){if(ul)throw new Error("multiple calls to 'initWasm()' detected.");if(cu)throw new Error("previous call to 'initWasm()' failed.");if(ul=!0,Ws())return new Promise((e,t)=>{Ea?.terminate(),eM().then(([r,s])=>{try{Ea=s,Ea.onerror=l=>t(l),Ea.onmessage=vb,Gm=[e,t];let o={type:"init-wasm",in:kt};!o.in.wasm.wasmPaths&&(r||i_)&&(o.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.asyncify-DFMnNRgU.wasm",import.meta.url).href,import.meta.url).href}),Ea.postMessage(o),gf=r}catch(o){t(o)}},t)});try{await k_(kt.wasm),await N_(kt),lu=!0}catch(e){throw cu=!0,e}finally{ul=!1}}},hM=async e=>{if(Ws())return Ii(),new Promise((t,r)=>{Pi("init-ep",[t,r]);let s={type:"init-ep",in:{epName:e,env:kt}};Ea.postMessage(s)});await D_(kt,e)},pM=async e=>Ws()?(Ii(),new Promise((t,r)=>{Pi("copy-from",[t,r]);let s={type:"copy-from",in:{buffer:e}};Ea.postMessage(s,[e.buffer])})):Nf(e),mM=async(e,t)=>{if(Ws()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ii(),new Promise((r,s)=>{Pi("create",[r,s]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),Ea.postMessage(o,l)})}else return R_(e,t)},_M=async e=>{if(Ws())return Ii(),new Promise((t,r)=>{Pi("release",[t,r]);let s={type:"release",in:e};Ea.postMessage(s)});B_(e)},gM=async(e,t,r,s,o,l)=>{if(Ws()){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)=>{Pi("run",[u,d]);let f=r,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:f,outputIndices:s,options:l}};Ea.postMessage(p,U_(f))})}else return P_(e,t,r,s,o,l)},yM=async e=>{if(Ws())return Ii(),new Promise((t,r)=>{Pi("end-profiling",[t,r]);let s={type:"end-profiling",in:e};Ea.postMessage(s)});I_(e)}}),jm,wb,wM,VE=Je(()=>{Zi(),vM(),El(),A_(),rM(),jm=(e,t)=>{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 ${t()}`)}},wb=e=>{switch(e[3]){case"cpu":return new Ha(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!z_(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:s,dispose:o}=e[2];return Ha.fromGpuBuffer(r,{dataType:t,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let t=e[0];if(!L_(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:s,dispose:o}=e[2];return Ha.fromMLTensor(r,{dataType:t,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},wM=class{async fetchModelAndCopyToWasmMemory(e){return pM(await F_(e))}async loadModel(e,t){Wi();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await mM(r,t),Yi()}async dispose(){return _M(this.sessionId)}async run(e,t,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 l=[],u=[];Object.entries(t).forEach(y=>{let w=y[0],b=y[1],S=this.outputNames.indexOf(w);if(S===-1)throw new Error(`invalid output '${w}'`);l.push(b),u.push(S)});let d=s.map((y,w)=>jm(y,()=>`input "${this.inputNames[o[w]]}"`)),f=l.map((y,w)=>y?jm(y,()=>`output "${this.outputNames[u[w]]}"`):null),p=await gM(this.sessionId,o,d,u,f,r),g={};for(let y=0;yu_,initializeFlags:()=>c_,wasmBackend:()=>MM});var c_,u_,MM,qE=Je(()=>{Zi(),vM(),VE(),c_=()=>{(typeof kt.wasm.initTimeout!="number"||kt.wasm.initTimeout<0)&&(kt.wasm.initTimeout=0);let e=kt.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.`),kt.wasm.simd=!1),typeof kt.wasm.proxy!="boolean"&&(kt.wasm.proxy=!1),typeof kt.wasm.trace!="boolean"&&(kt.wasm.trace=!1),typeof kt.wasm.numThreads!="number"||!Number.isInteger(kt.wasm.numThreads)||kt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)kt.wasm.numThreads=1;else{let t=typeof navigator>"u"?bE("node:os").cpus().length:navigator.hardwareConcurrency;kt.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},u_=class{async init(e){c_(),await fM(),await hM(e)}async createInferenceSessionHandler(e,t){let r=new wM;return await r.loadModel(e,t),r}},MM=new u_});Zi();Zi();Zi();var HE="1.25.0-dev.20260307-d626b568e0",$E=W1;{let e=(qE(),Of(bM)).wasmBackend;Hi("webgpu",e,5),Hi("webnn",e,5),Hi("cpu",e,10),Hi("wasm",e,10)}Object.defineProperty(kt.versions,"web",{value:HE,enumerable:!0});const QE=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return E_},get TRACE(){return zf},get TRACE_EVENT_BEGIN(){return Zs},get TRACE_EVENT_END(){return Ks},get TRACE_FUNC_BEGIN(){return Wi},get TRACE_FUNC_END(){return Yi},get Tensor(){return Ha},default:$E,get env(){return kt},get registerBackend(){return Hi}},Symbol.toStringTag,{value:"Module"})),WE=(e,t)=>{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,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[3]):(o=e.dims[3],l=e.dims[2]);const u=t?.format!==void 0?t.format:"RGB",d=t?.norm;let f,p;d===void 0||d.mean===void 0?f=[255,255,255,255]:typeof d.mean=="number"?f=[d.mean,d.mean,d.mean,d.mean]:(f=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(f[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=l*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,l,u;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[1],u=e.dims[3]):(o=e.dims[3],l=e.dims[2],u=e.dims[1]);const d=t!==void 0&&t.format!==void 0?t.format:"RGB",f=t?.norm;let p,g;f===void 0||f.mean===void 0?p=[255,255,255,255]:typeof f.mean=="number"?p=[f.mean,f.mean,f.mean,f.mean]:(p=[f.mean[0],f.mean[1],f.mean[2],255],f.mean[3]!==void 0&&(p[3]=f.mean[3])),f===void 0||f.bias===void 0?g=[0,0,0,0]:typeof f.bias=="number"?g=[f.bias,f.bias,f.bias,f.bias]:(g=[f.bias[0],f.bias[1],f.bias[2],0],f.bias[3]!==void 0&&(g[3]=f.bias[3]));const y=l*o;if(t!==void 0&&(t.format!==void 0&&u===4&&t.format!=="RGBA"||u===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const w=4;let b=0,S=1,E=2,z=3,k=0,L=y,R=y*2,N=-1;d==="RGBA"?(k=0,L=y,R=y*2,N=y*3):d==="RGB"?(k=0,L=y,R=y*2):d==="RBG"&&(k=0,R=y,L=y*2),s=r.createImageData(o,l);for(let B=0;B{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:s}=t,o=t.norm??{mean:255,bias:0};let l,u;typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:l=[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=t.format!==void 0?t.format:"RGBA",f=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*s,g=f==="RGBA"?new Float32Array(p*4):new Float32Array(p*3);let y=4,w=0,b=1,S=2,E=3,z=0,k=p,L=p*2,R=-1;d==="RGB"&&(y=3,w=0,b=1,S=2,E=-1),f==="RGBA"?R=p*3:f==="RBG"?(z=0,L=p,k=p*2):f==="BGR"&&(L=0,k=p,z=p*2);for(let B=0;B{const r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string";let u,d=t??{};const f=()=>{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=f();g.width=e.width,g.height=e.height;const y=p(g);if(y!=null){let w=e.height,b=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,b=t.resizedWidth),t!==void 0){if(d=t,t.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(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,y=t.resizedWidth):(g=e.height,y=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=g,d.width=y,t!==void 0){const w=f();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(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const g=f();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,Vm(u,d)}else throw new Error("Can not access image data")}else{if(l)return new Promise((g,y)=>{const w=f(),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(Vm(E.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return Vm(u,d);throw new Error("Input data provided is not supported - aborted tensor creation")},ZE=(e,t)=>{const{width:r,height:s,download:o,dispose:l}=t,u=[1,s,r,4];return new ka({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},KE=(e,t)=>{const{dataType:r,dims:s,download:o,dispose:l}=t;return new ka({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:s,download:o,dispose:l})},JE=(e,t)=>{const{dataType:r,dims:s,download:o,dispose:l}=t;return new ka({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:s,download:o,dispose:l})},eA=(e,t,r)=>new ka({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]}),gl=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ef=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let bb=!1;const tA=()=>{if(!bb){bb=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,s=typeof r<"u"&&r.from;e&&(gl.set("int64",BigInt64Array),Ef.set(BigInt64Array,"int64")),t&&(gl.set("uint64",BigUint64Array),Ef.set(BigUint64Array,"uint64")),s?(gl.set("float16",r),Ef.set(r,"float16")):gl.set("float16",Uint16Array)}},nA=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new ka(e.type,e.data,t);case"cpu-pinned":return new ka({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new ka({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new ka({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new ka({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let ka=class{constructor(t,r,s){tA();let o,l;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,o=t.type,l=t.dims,t.location){case"cpu-pinned":{const d=gl.get(o);if(!d)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(t.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=t.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.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=t.gpuBuffer,this.downloader=t.download,this.disposer=t.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=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,f;if(typeof t=="string")if(o=t,f=s,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");d=r}else{const p=gl.get(t);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&p===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${p.name} as data.`);t==="uint64"||t==="int64"?d=p.from(r,BigInt):d=p.from(r)}else if(r instanceof p)d=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")d=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="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(f=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const p=typeof t[0];if(p==="string")o="string",d=t;else if(p==="boolean")o="bool",d=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(t instanceof Uint8ClampedArray)o="uint8",d=Uint8Array.from(t);else{const p=Ef.get(t.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=p,d=t}if(f===void 0)f=[d.length];else if(!Array.isArray(f))throw new TypeError("A tensor's dims must be a number array");l=f,this.cpuData=d,this.dataLocation="cpu"}const u=nA(l);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=l,this.size=u}static async fromImage(t,r){return XE(t,r)}static fromTexture(t,r){return ZE(t,r)}static fromGpuBuffer(t,r){return KE(t,r)}static fromMLTensor(t,r){return JE(t,r)}static fromPinnedBuffer(t,r,s){return eA(t,r,s)}toDataURL(t){return WE(this,t)}toImageData(t){return YE(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,t&&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(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return aA(this,t)}};const rA=ka;var qm={},sA=Object.defineProperty,Al=(e,t)=>{for(var r in t)sA(e,r,{get:t[r],enumerable:!0})},fa={},Tr={},iA={},oA="4.0.0-next.7",G_=typeof self<"u",bl=!EM(fa),xM=!EM(Tr),Df=G_&&"caches"in self,lA=typeof globalThis.Deno<"u",Qf=lA&&Df&&!bl,TM=typeof process<"u",SM=TM&&process?.release?.name==="node"&&!Qf,j_=typeof window<"u"&&typeof window.document<"u",V_=G_&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),cA=j_||V_||Qf,uA=SM||typeof navigator<"u"&&"gpu"in navigator,dA=typeof navigator<"u"&&"ml"in navigator,fA=typeof crypto<"u"&&typeof crypto.getRandomValues=="function",hA=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id=="string",pA=typeof ServiceWorkerGlobalScope<"u"&&G_&&self instanceof ServiceWorkerGlobalScope,mA=()=>{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},_A=mA(),We=Object.freeze({IS_BROWSER_ENV:j_,IS_WEBWORKER_ENV:V_,IS_WEB_ENV:cA,IS_SERVICE_WORKER_ENV:pA,IS_DENO_WEB_RUNTIME:Qf,IS_WEB_CACHE_AVAILABLE:Df,IS_WEBGPU_AVAILABLE:uA,IS_WEBNN_AVAILABLE:dA,IS_SAFARI:_A,IS_PROCESS_AVAILABLE:TM,IS_NODE_ENV:SM,IS_FS_AVAILABLE:bl,IS_PATH_AVAILABLE:xM,IS_CRYPTO_AVAILABLE:fA,IS_CHROME_AVAILABLE:hA}),q_=bl&&xM,Rf="./";if(q_){const e=Object(import.meta).url;e?Rf=Tr.dirname(Tr.dirname(iA.fileURLToPath(e))):typeof __dirname<"u"&&(Rf=Tr.dirname(__dirname))}var gA=q_?Tr.join(Rf,"/.cache/"):null,Mb="/models/",yA=q_?Tr.join(Rf,Mb):Mb,vA=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):void 0,$a=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),xb=$a.WARNING,rt={version:oA,backends:{onnx:{}},get logLevel(){return xb},set logLevel(e){xb=e,rt.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(j_||V_||Qf),localModelPath:yA,useFS:bl,useBrowserCache:Df,useFSCache:bl,cacheDir:gA,useCustomCache:!1,customCache:null,useWasmCache:Df||bl,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:vA};function EM(e){return Object.keys(e).length===0}function $i(e,t){e&&e(t)}function wA(e){return Number.isInteger(e)||typeof e=="bigint"}function Tb(e){return e==null||e===-1}function Sb(e){const t=[];let r=e;for(;Array.isArray(r);)t.push(r.length),r=r[0];return t}function Sr(...e){return Array.prototype.concat.apply([],e)}function bA(...e){return e.reduce((t,r)=>t.flatMap(s=>r.map(o=>[s,o])))}function Bf(e,t){return Math.abs((e+t)%(2*t)-t)}function yn(e,t){return Object.assign({},...t.map(r=>{if(e[r]!==void 0)return{[r]:e[r]}}))}function MA(e,t){let r=0;for(const s of e)s===t&&++r;return r}var Re={error(...e){rt.logLevel<=$a.ERROR&&console.error(...e)},warn(...e){rt.logLevel<=$a.WARNING&&console.warn(...e)},info(...e){rt.logLevel<=$a.INFO&&console.log(...e)},debug(...e){rt.logLevel<=$a.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},xA=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){const t=Object.create(null);for(const r of e){let s=t;for(let o=0;os&&t.push(e.slice(s,o)),t.push(u),o+=u.length,s=o):++o}return s{const e=[...Array.from({length:94},(o,l)=>l+33),...Array.from({length:12},(o,l)=>l+161),...Array.from({length:82},(o,l)=>l+174)],t=e.slice();let r=0;for(let o=0;o<256;++o)e.includes(o)||(e.push(o),t.push(256+r),r+=1);const s=t.map(o=>String.fromCharCode(o));return Object.fromEntries(e.map((o,l)=>[o,s[l]]))})(),EA=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[r,t])),AA=EA(AM),Ab=".,!?…。,、।۔،",CA=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}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${Ab}])]+`,` ?[^\\s${Ab}]+`]]),Pf="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",H_=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"),Wf=(e,t=!0)=>{if(e.Regex!==void 0){let r=e.Regex.replace(/\\([#&~])/g,"$1");r=r.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(const[s,o]of CA)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 l=r.replace(/(\\[pP])\{([^}=]+)\}/g,(u,d,f)=>{try{return new RegExp(`\\p{${f}}`,"u"),`${d}{${f}}`}catch{return o=!0,`${d}{Script=${f}}`}});if(!o)throw s;try{return new RegExp(l,"gu")}catch{throw s}}}else if(e.String!==void 0){const r=kA(e.String);return new RegExp(t?r:`(${r})`,"gu")}else return console.warn("Unknown pattern type:",e),null},kA=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),OA=(e,t,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,LA=e=>Number.isInteger(e)||typeof e=="bigint",FA=e=>{let t=0;for(const r of e)++t;return t},NA=e=>CM(e.toLowerCase()),Qa=(...e)=>Array.prototype.concat.apply([],e),$_=e=>new Map(Object.entries(e)),DA=(e,t)=>{const r=[];let s=0;for(const o of e.matchAll(t)){const l=o[0];s0&&r.push(l),s=o.index+l.length}return se.replace(new RegExp("\\p{M}","gu"),""),Cb=(e,t,r=[])=>{if(!e||Array.isArray(e)||typeof e!="object")return`${t} must be a valid object`;for(const s of r)if(!(s in e))return`${t} must contain a "${s}" property`;return null},RA=e=>e.match(/\S+/g)||[],BA=class{constructor(){const e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},Su=BA,PA=class extends Su{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},rs=PA,IA=class extends rs{tokenize_chinese_chars(e){const t=[];for(let r=0;rr.normalize("NFKC")).join("~"):e=e.normalize("NFKC"),e}},jA=GA,VA=class extends rs{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(t=>kM(t))}normalize(e){return this.normalizers.reduce((t,r)=>r?r.normalize(t):t,e)}},qA=VA,HA=class extends rs{normalize(e){const t=Wf(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??"")}},$A=HA,QA=class extends rs{constructor(){super(...arguments),this.form="NFC"}normalize(e){return e=e.normalize(this.form),e}},Yf=QA,WA=class extends Yf{constructor(){super(...arguments),this.form="NFC"}},YA=WA,XA=class extends Yf{constructor(){super(...arguments),this.form="NFD"}},ZA=XA,KA=class extends Yf{constructor(){super(...arguments),this.form="NFKC"}},JA=KA,eC=class extends Yf{constructor(){super(...arguments),this.form="NFKD"}},tC=eC,nC=class extends rs{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}},aC=nC,rC=class extends rs{normalize(e){return CM(e)}},sC=rC,iC=class extends rs{normalize(e){return e.toLowerCase()}},oC=iC,lC=class extends rs{normalize(e){return e=this.config.prepend+e,e}},cC=lC;function uC(e){if(e===null)return null;switch(e.type){case"BertNormalizer":return new UA(e);case"Precompiled":return new jA(e);case"Sequence":return new qA(e);case"Replace":return new $A(e);case"NFC":return new YA(e);case"NFD":return new ZA(e);case"NFKC":return new JA(e);case"NFKD":return new tC(e);case"Strip":return new aC(e);case"StripAccents":return new sC(e);case"Lowercase":return new oC(e);case"Prepend":return new cC(e);default:throw new Error(`Unknown Normalizer type: ${e.type}`)}}var kM=uC,dC=class extends Su{pre_tokenize(e,t){return(Array.isArray(e)?e.map(r=>this.pre_tokenize_text(r,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},Za=dC,fC=class extends Za{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=AM,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(" ")&&(e=" "+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(s=>Array.from(this.text_encoder.encode(s),o=>this.byte_encoder[o]).join(""))}},hC=fC,pC=class extends Za{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},mC=pC,_C=class extends Za{constructor(e){super(),this.replacement=e.replacement??"▁",this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??"always"}pre_tokenize_text(e,t){const{section_index:r=void 0}=t??{};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]}},gC=_C,yC=class extends Za{constructor(e){super(),this.config=e,this.pattern=Wf(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?e.split(this.pattern).filter(t=>t):DA(e,this.pattern)}},vC=yC,wC=class extends Za{constructor(e){super(),this.config=e,this.pattern=new RegExp(`[^${Pf}]+|[${Pf}]+`,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},bC=wC,MC=class extends Za{constructor(e){super(),this.config=e;const t=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(t,"gu")}pre_tokenize_text(e){return e.match(this.pattern)||[]}},xC=MC,TC=class extends Za{constructor(){super(),this.pattern=new RegExp(`[^\\s${Pf}]+|[${Pf}]`,"gu")}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},SC=TC,EC=class extends Za{constructor(e){super(),this.config=e,this.pattern=Wf(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??"")]}},AC=EC,CC=class extends Za{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(t=>OM(t))}pre_tokenize_text(e,t){return this.tokenizers.reduce((r,s)=>s?s.pre_tokenize(r,t):r,[e])}},kC=CC,OC=class extends Za{pre_tokenize_text(e){return RA(e)}},zC=OC,LC=class extends Za{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){const t=[];for(let r=0;rthis.max_input_chars_per_word){t.push(this.unk_token);continue}let o=!1,l=0;const u=[];for(;l0&&(p=this.config.continuing_subword_prefix+p),this.tokens_to_ids.has(p)){f=p;break}--d}if(f===null){o=!0;break}u.push(f),l=d}o?t.push(this.unk_token):t.push(...u)}return t}},kb=RC,Ob=class zM{constructor(t,r){this.is_leaf=t,this.children=r}static default(){return new zM(!1,new Map)}},BC=class{constructor(){this.root=Ob.default()}extend(e){for(const t of e)this.push(t)}push(e){let t=this.root;for(const r of e){let s=t.children.get(r);s===void 0&&(s=Ob.default(),t.children.set(r,s)),t=s}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let r="";for(const s of e){if(r+=s,t=t.children.get(s),t===void 0)return;t.is_leaf&&(yield r)}}},PC=BC,Hm=class LM{constructor(t,r,s,o,l){this.token_id=t,this.node_id=r,this.pos=s,this.length=o,this.score=l,this.prev=null,this.backtrace_score=0}clone(){const t=new LM(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},IC=class{constructor(e,t,r){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,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 Hm(this.bos_token_id??0,0,0,0,0),o=new Hm(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,t,r,s){const o=this.nodes.length,l=new Hm(s,o,e,t,r);this.begin_nodes[e].push(l),this.end_nodes[e+t].push(l),this.nodes.push(l)}viterbi(){const e=this.len;let t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let u of this.begin_nodes[t]){u.prev=null;let d=0,f=null;for(let p of this.end_nodes[t]){const g=p.backtrace_score+u.score;(f===null||g>d)&&(f=p.clone(),d=g)}if(f!==null)u.prev=f,u.backtrace_score=d;else return[]}++t}const r=[],o=this.begin_nodes[e][0].prev;if(o===null)return[];let l=o.clone();for(;l.prev!==null;)r.push(l.clone()),l=l.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(t=>this.piece(t))}token_ids(){return this.viterbi().map(t=>t.token_id)}},UC=IC;function GC(e){if(e.length===0)throw new Error("Array must not be empty");let t=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=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=GC(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new PC,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){const t=e.chars,r=1;let s=0;for(;sr>s,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}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 t of e)if(this.size0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){const t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){const r=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=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()}},$C=HC,QC=class extends Xf{constructor(e){super(e),this.tokens_to_ids=$_(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 t=Array.isArray(e.merges[0]);this.merges=t?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 $C(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];const t=this.cache.get(e);if(t!==void 0)return t;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 qC((d,f)=>d.score`<0x${u.toString(16).toUpperCase().padStart(2,"0")}>`);l.every(u=>this.tokens_to_ids.has(u))?t.push(...l):t.push(this.unk_token)}else t.push(this.unk_token)}return t}},Lb=QC,WC=class extends Xf{constructor(e,t){super(e);const r=e.vocab;this.tokens_to_ids=$_(t.target_lang?r[t.target_lang]:r),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[s,o]of this.tokens_to_ids)this.vocab[o]=s}encode(e){return e}},YC=WC;function XC(e,t){switch(e.type){case"WordPiece":return new kb(e);case"Unigram":return new zb(e,t.eos_token);case"BPE":return new Lb(e);default:if(e.vocab)return Array.isArray(e.vocab)?new zb(e,t.eos_token):Object.hasOwn(e,"continuing_subword_prefix")&&Object.hasOwn(e,"unk_token")?Object.hasOwn(e,"merges")?new Lb(e):new kb(e):new YC(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw new Error(`Unknown TokenizerModel type: ${e?.type}`)}}var ZC=XC,KC=class extends Su{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},Eu=KC,JC=class extends Eu{post_process(e,t=null,r=!0){const s=t===null?this.config.single:this.config.pair;let o=[],l=[];for(const u of s)"SpecialToken"in u?r&&(o.push(u.SpecialToken.id),l.push(u.SpecialToken.type_id)):"Sequence"in u&&(u.Sequence.id==="A"?(o=Qa(o,e),l=Qa(l,new Array(e.length).fill(u.Sequence.type_id))):u.Sequence.id==="B"&&(o=Qa(o,t),l=Qa(l,new Array(t.length).fill(u.Sequence.type_id))));return{tokens:o,token_type_ids:l}}},ek=JC,tk=class extends Eu{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},nk=tk,ak=class extends Eu{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,r=!0){r&&(e=Qa([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){const o=[],l=r?[this.sep[0]]:[];e=Qa(e,o,t,l),s=Qa(s,new Array(t.length+o.length+l.length).fill(1))}return{tokens:e,token_type_ids:s}}},rk=ak,sk=class extends Eu{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,r=!0){r&&(e=Qa([this.cls[0]],e,[this.sep[0]]));let s=new Array(e.length).fill(0);if(t){const o=r?[this.sep[0]]:[],l=r?[this.sep[0]]:[];e=Qa(e,o,t,l),s=Qa(s,new Array(t.length+o.length+l.length).fill(1))}return{tokens:e,token_type_ids:s}}},ik=sk,ok=class extends Eu{constructor(e){super(e),this.processors=(e.processors??[]).map(t=>FM(t))}post_process(e,t=null,r=!0){let s={tokens:e,tokens_pair:t};for(const o of this.processors)s=o.post_process(s.tokens,s.tokens_pair,r);return s}},lk=ok;function ck(e){if(e===null)return null;switch(e.type){case"TemplateProcessing":return new ek(e);case"ByteLevel":return new nk(e);case"BertProcessing":return new rk(e);case"RobertaProcessing":return new ik(e);case"Sequence":return new lk(e);default:throw new Error(`Unknown PostProcessor type: ${e.type}`)}}var FM=ck,uk=class extends Su{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("")}},Ka=uk,dk=class extends Ka{constructor(e){super(e),this.byte_decoder=AA,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){const t=e.join(""),r=new Uint8Array([...t].map(s=>this.byte_decoder[s]));return this.text_decoder.decode(r)}decode_chain(e){const t=[];let r=[];for(const s of e)this.added_tokens.find(o=>o.content===s)!==void 0?(r.length>0&&(t.push(this.convert_tokens_to_string(r)),r=[]),t.push(s)):r.push(s);return r.length>0&&t.push(this.convert_tokens_to_string(r)),t}},fk=dk,hk=class extends Ka{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((t,r)=>{if(r!==0){const s=this.config.prefix;s&&t.startsWith(s)?t=t.replace(s,""):t=" "+t}return this.cleanup&&(t=H_(t)),t})}},pk=hk,mk=class extends Ka{constructor(e){super(e),this.replacement=e.replacement??"▁"}decode_chain(e){const t=[];for(let r=0;rt.replaceAll(this.suffix,r===e.length-1?"":" "))}},yk=gk,vk=class extends Ka{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 t=[e[0]];for(let o=1;oo!==this.pad_token).join("");return this.cleanup&&(s=H_(s).replaceAll(this.word_delimiter_token," ").trim()),s}decode_chain(e){return[this.convert_tokens_to_string(e)]}},wk=vk,bk=class extends Ka{constructor(e){super(e),this.decoders=(e.decoders??[]).map(t=>NM(t))}decode_chain(e){return this.decoders.reduce((t,r)=>r.decode_chain(t),e)}},Mk=bk,xk=class extends Ka{decode_chain(e){const t=Wf(this.config.pattern),r=this.config.content??"";return t===null?e:e.map(s=>s.replaceAll(t,r))}},Tk=xk,Sk=class extends Ka{decode_chain(e){return[e.join("")]}},Ek=Sk,Ak=class extends Ka{constructor(e){super(e),this.content=e.content??"",this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(t=>{let r=0;for(let o=0;o")){const l=parseInt(s.slice(3,5),16);isNaN(l)||(o=l)}if(o!==null)r.push(o);else{if(r.length>0){const l=this.text_decoder.decode(Uint8Array.from(r));t.push(l),r=[]}t.push(s)}}if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));t.push(s),r=[]}return t}},Ok=kk;function zk(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 _k(e);case"BPEDecoder":return new yk(e);case"CTC":return new wk(e);case"Sequence":return new Mk(e);case"Replace":return new Tk(e);case"Fuse":return new Ek(e);case"Strip":return new Ck(e);case"ByteFallback":return new Ok(e);default:throw new Error(`Unknown Decoder type: ${e.type}`)}}var NM=zk,Lk=class{constructor(e,t){const r=Cb(e,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(r)throw new Error(r);const s=Cb(t,"Config");if(s)throw new Error(s);this.tokenizer=e,this.config=t,this.normalizer=kM(this.tokenizer.normalizer),this.pre_tokenizer=OM(this.tokenizer.pre_tokenizer),this.model=ZC(this.tokenizer.model,this.config),this.post_processor=FM(this.tokenizer.post_processor),this.decoder=NM(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];const o=[],l=[];this.added_tokens_map=new Map;for(const u of this.tokenizer.added_tokens){const d=new SA(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 f=this.normalizer(d.content);l.push(f),this.added_tokens_map.set(f,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 Eb(o),this.splitter_normalized=new Eb(l),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){const{tokens:o,token_type_ids:l}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}),u=o.map(f=>this.added_tokens_map.get(f)?.id??this.model.tokens_to_ids.get(f)??this.model.unk_token_id),d={ids:u,tokens:o,attention_mask:new Array(u.length).fill(1)};return s&&l&&(d.token_type_ids=l),d}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!LA(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);t.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," "),t.skip_special_tokens&&(s=s.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(s=H_(s)),s}tokenize(e,{text_pair:t=null,add_special_tokens:r=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:r}).tokens}encode_text(e){if(e===null)return null;const t=this.splitter_unnormalized.split(e);return t.forEach((r,s)=>{const o=this.added_tokens_map.get(r);o&&(o.lstrip&&s>0&&(t[s-1]=t[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=NA(r)),this.normalizer!==null&&(r=this.normalizer(r)),r.length===0)return[];const o=this.splitter_normalized.split(r);return o.forEach((l,u)=>{const d=this.added_tokens_map.get(l);d&&(d.lstrip&&u>0&&(o[u-1]=o[u-1].trimEnd()),d.rstrip&&u{if(l.length===0)return[];if(this.added_tokens_map.has(l))return[l];const u=this.pre_tokenizer!==null?this.pre_tokenizer(l,{section_index:s}):[l];return this.model(u)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:r=!0}){const s=this.encode_text(e),o=this.encode_text(t||null);return this.post_processor?this.post_processor(s,o,r):{tokens:Qa(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 t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){const t=new Map;for(let r=0;r=",ie.ComparisonBinaryOperator],["==",ie.ComparisonBinaryOperator],["!=",ie.ComparisonBinaryOperator],["<",ie.ComparisonBinaryOperator],[">",ie.ComparisonBinaryOperator],["+",ie.AdditiveBinaryOperator],["-",ie.AdditiveBinaryOperator],["~",ie.AdditiveBinaryOperator],["*",ie.MultiplicativeBinaryOperator],["/",ie.MultiplicativeBinaryOperator],["%",ie.MultiplicativeBinaryOperator],["=",ie.Equals]],Dk=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function Rk(e,t={}){return e.endsWith(` +`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,"$1")),e.replace(/{%\s*(end)?generation\s*%}/gs,"")}function Bk(e,t={}){const r=[],s=Rk(e,t);let o=0,l=0;const u=p=>{let g="";for(;p(s[o]);){if(s[o]==="\\"){if(++o,o>=s.length)throw new SyntaxError("Unexpected end of input");const y=s[o++],w=Dk.get(y);if(w===void 0)throw new SyntaxError(`Unexpected escaped character: ${y}`);g+=w;continue}if(g+=s[o++],o>=s.length)throw new SyntaxError("Unexpected end of input")}return g},d=()=>{const p=r.at(-1);p&&p.type===ie.Text&&(p.value=p.value.trimEnd(),p.value===""&&r.pop())},f=()=>{for(;o0){r.push(new Aa(y,ie.Text));continue}}if(s[o]==="{"&&s[o+1]==="#"){o+=2;const y=s[o]==="-";y&&++o;let w="";for(;s[o]!=="#"||s[o+1]!=="}";){if(o+2>=s.length)throw new SyntaxError("Missing end of comment tag");w+=s[o++]}const b=w.endsWith("-");b&&(w=w.slice(0,-1)),y&&d(),r.push(new Aa(w,ie.Comment)),o+=2,b&&f();continue}if(s.slice(o,o+3)==="{%-"){d(),r.push(new Aa("{%",ie.OpenStatement)),o+=3;continue}if(s.slice(o,o+3)==="{{-"){d(),r.push(new Aa("{{",ie.OpenExpression)),l=0,o+=3;continue}if(u(Nb),s.slice(o,o+3)==="-%}"){r.push(new Aa("%}",ie.CloseStatement)),o+=3,f();continue}if(s.slice(o,o+3)==="-}}"){r.push(new Aa("}}",ie.CloseExpression)),o+=3,f();continue}const g=s[o];if(g==="-"||g==="+"){const y=r.at(-1)?.type;if(y===ie.Text||y===void 0)throw new SyntaxError(`Unexpected character: ${g}`);switch(y){case ie.Identifier:case ie.NumericLiteral:case ie.StringLiteral:case ie.CloseParen:case ie.CloseSquareBracket:break;default:{++o;const w=u(uu);r.push(new Aa(`${g}${w}`,w.length>0?ie.NumericLiteral:ie.UnaryOperator));continue}}}for(const[y,w]of Nk){if(y==="}}"&&l>0)continue;if(s.slice(o,o+y.length)===y){r.push(new Aa(y,w)),w===ie.OpenExpression?l=0:w===ie.OpenCurlyBracket?++l:w===ie.CloseCurlyBracket&&--l,o+=y.length;continue e}}if(g==="'"||g==='"'){++o;const y=u(w=>w!==g);r.push(new Aa(y,ie.StringLiteral)),++o;continue}if(uu(g)){let y=u(uu);if(s[o]==="."&&uu(s[o+1])){++o;const w=u(uu);y=`${y}.${w}`}r.push(new Aa(y,ie.NumericLiteral));continue}if(Fb(g)){const y=u(Fb);r.push(new Aa(y,ie.Identifier));continue}throw new SyntaxError(`Unexpected character: ${g}`)}return r}var Ja=class{type="Statement"},Pk=class extends Ja{constructor(e){super(),this.body=e}type="Program"},Ik=class extends Ja{constructor(e,t,r){super(),this.test=e,this.body=t,this.alternate=r}type="If"},Uk=class extends Ja{constructor(e,t,r,s){super(),this.loopvar=e,this.iterable=t,this.body=r,this.defaultBlock=s}type="For"},Gk=class extends Ja{type="Break"},jk=class extends Ja{type="Continue"},Vk=class extends Ja{constructor(e,t,r){super(),this.assignee=e,this.value=t,this.body=r}type="Set"},qk=class extends Ja{constructor(e,t,r){super(),this.name=e,this.args=t,this.body=r}type="Macro"},Hk=class extends Ja{constructor(e){super(),this.value=e}type="Comment"},pa=class extends Ja{type="Expression"},$k=class extends pa{constructor(e,t,r){super(),this.object=e,this.property=t,this.computed=r}type="MemberExpression"},Db=class extends pa{constructor(e,t){super(),this.callee=e,this.args=t}type="CallExpression"},dl=class extends pa{constructor(e){super(),this.value=e}type="Identifier"},Cl=class extends pa{constructor(e){super(),this.value=e}type="Literal"},Qk=class extends Cl{type="IntegerLiteral"},Wk=class extends Cl{type="FloatLiteral"},Rb=class extends Cl{type="StringLiteral"},Yk=class extends Cl{type="ArrayLiteral"},Bb=class extends Cl{type="TupleLiteral"},Xk=class extends Cl{type="ObjectLiteral"},du=class extends pa{constructor(e,t,r){super(),this.operator=e,this.left=t,this.right=r}type="BinaryExpression"},Zk=class extends pa{constructor(e,t){super(),this.operand=e,this.filter=t}type="FilterExpression"},Kk=class extends Ja{constructor(e,t){super(),this.filter=e,this.body=t}type="FilterStatement"},Jk=class extends pa{constructor(e,t){super(),this.lhs=e,this.test=t}type="SelectExpression"},e3=class extends pa{constructor(e,t,r){super(),this.operand=e,this.negate=t,this.test=r}type="TestExpression"},t3=class extends pa{constructor(e,t){super(),this.operator=e,this.argument=t}type="UnaryExpression"},n3=class extends pa{constructor(e=void 0,t=void 0,r=void 0){super(),this.start=e,this.stop=t,this.step=r}type="SliceExpression"},a3=class extends pa{constructor(e,t){super(),this.key=e,this.value=t}type="KeywordArgumentExpression"},r3=class extends pa{constructor(e){super(),this.argument=e}type="SpreadExpression"},s3=class extends Ja{constructor(e,t,r){super(),this.call=e,this.callerArgs=t,this.body=r}type="CallStatement"},i3=class extends pa{constructor(e,t,r){super(),this.condition=e,this.trueExpr=t,this.falseExpr=r}type="Ternary"};function o3(e){const t=new Pk([]);let r=0;function s(I,$){const J=e[r++];if(!J||J.type!==I)throw new Error(`Parser Error: ${$}. ${J.type} !== ${I}.`);return J}function o(I){if(!f(I))throw new SyntaxError(`Expected ${I}`);++r}function l(){switch(e[r].type){case ie.Comment:return new Hk(e[r++].value);case ie.Text:return p();case ie.OpenStatement:return g();case ie.OpenExpression:return y();default:throw new SyntaxError(`Unexpected token type: ${e[r].type}`)}}function u(...I){return r+I.length<=e.length&&I.every(($,J)=>$===e[r+J].type)}function d(...I){return e[r]?.type===ie.OpenStatement&&e[r+1]?.type===ie.Identifier&&I.includes(e[r+1]?.value)}function f(...I){return r+I.length<=e.length&&I.every(($,J)=>e[r+J].type==="Identifier"&&$===e[r+J].value)}function p(){return new Rb(s(ie.Text,"Expected text token").value)}function g(){if(s(ie.OpenStatement,"Expected opening statement token"),e[r].type!==ie.Identifier)throw new SyntaxError(`Unknown statement, got ${e[r].type}`);const I=e[r].value;let $;switch(I){case"set":++r,$=w();break;case"if":++r,$=b(),s(ie.OpenStatement,"Expected {% token"),o("endif"),s(ie.CloseStatement,"Expected %} token");break;case"macro":++r,$=S(),s(ie.OpenStatement,"Expected {% token"),o("endmacro"),s(ie.CloseStatement,"Expected %} token");break;case"for":++r,$=z(),s(ie.OpenStatement,"Expected {% token"),o("endfor"),s(ie.CloseStatement,"Expected %} token");break;case"call":{++r;let J=null;u(ie.OpenParen)&&(J=he());const D=ee();if(D.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const te=he();s(ie.CloseStatement,"Expected closing statement token");const ae=[];for(;!d("endcall");)ae.push(l());s(ie.OpenStatement,"Expected '{%'"),o("endcall"),s(ie.CloseStatement,"Expected closing statement token");const ge=new Db(D,te);$=new s3(ge,J,ae);break}case"break":++r,s(ie.CloseStatement,"Expected closing statement token"),$=new Gk;break;case"continue":++r,s(ie.CloseStatement,"Expected closing statement token"),$=new jk;break;case"filter":{++r;let J=ee();J instanceof dl&&u(ie.OpenParen)&&(J=oe(J)),s(ie.CloseStatement,"Expected closing statement token");const D=[];for(;!d("endfilter");)D.push(l());s(ie.OpenStatement,"Expected '{%'"),o("endfilter"),s(ie.CloseStatement,"Expected '%}'"),$=new Kk(J,D);break}default:throw new SyntaxError(`Unknown statement type: ${I}`)}return $}function y(){s(ie.OpenExpression,"Expected opening expression token");const I=k();return s(ie.CloseExpression,"Expected closing expression token"),I}function w(){const I=E();let $=null;const J=[];if(u(ie.Equals))++r,$=E();else{for(s(ie.CloseStatement,"Expected %} token");!d("endset");)J.push(l());s(ie.OpenStatement,"Expected {% token"),o("endset")}return s(ie.CloseStatement,"Expected closing statement token"),new Vk(I,$,J)}function b(){const I=k();s(ie.CloseStatement,"Expected closing statement token");const $=[],J=[];for(;!d("elif","else","endif");)$.push(l());if(d("elif")){++r,++r;const D=b();J.push(D)}else if(d("else"))for(++r,++r,s(ie.CloseStatement,"Expected closing statement token");!d("endif");)J.push(l());return new Ik(I,$,J)}function S(){const I=ee();if(I.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const $=he();s(ie.CloseStatement,"Expected closing statement token");const J=[];for(;!d("endmacro");)J.push(l());return new qk(I,$,J)}function E(I=!1){const $=I?ee:k,J=[$()],D=u(ie.Comma);for(;D&&(++r,J.push($()),!!u(ie.Comma)););return D?new Bb(J):J[0]}function z(){const I=E(!0);if(!(I instanceof dl||I instanceof Bb))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${I.type} instead`);if(!f("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++r;const $=k();s(ie.CloseStatement,"Expected closing statement token");const J=[];for(;!d("endfor","else");)J.push(l());const D=[];if(d("else"))for(++r,++r,s(ie.CloseStatement,"Expected closing statement token");!d("endfor");)D.push(l());return new Uk(I,$,J,D)}function k(){return L()}function L(){const I=R();if(f("if")){++r;const $=R();if(f("else")){++r;const J=L();return new i3($,I,J)}else return new Jk(I,$)}return I}function R(){let I=N();for(;f("or");){const $=e[r];++r;const J=N();I=new du($,I,J)}return I}function N(){let I=B();for(;f("and");){const $=e[r];++r;const J=B();I=new du($,I,J)}return I}function B(){let I;for(;f("not");){const $=e[r];++r;const J=B();I=new t3($,J)}return I??j()}function j(){let I=C();for(;;){let $;if(f("not","in"))$=new Aa("not in",ie.Identifier),r+=2;else if(f("in"))$=e[r++];else if(u(ie.ComparisonBinaryOperator))$=e[r++];else break;const J=C();I=new du($,I,J)}return I}function C(){let I=W();for(;u(ie.AdditiveBinaryOperator);){const $=e[r];++r;const J=W();I=new du($,I,J)}return I}function ue(){const I=re(ee());return u(ie.OpenParen)?oe(I):I}function oe(I){let $=new Db(I,he());return $=re($),u(ie.OpenParen)&&($=oe($)),$}function he(){s(ie.OpenParen,"Expected opening parenthesis for arguments list");const I=_e();return s(ie.CloseParen,"Expected closing parenthesis for arguments list"),I}function _e(){const I=[];for(;!u(ie.CloseParen);){let $;if(e[r].type===ie.MultiplicativeBinaryOperator&&e[r].value==="*"){++r;const J=k();$=new r3(J)}else if($=k(),u(ie.Equals)){if(++r,!($ instanceof dl))throw new SyntaxError("Expected identifier for keyword argument");const J=k();$=new a3($,J)}I.push($),u(ie.Comma)&&++r}return I}function de(){const I=[];let $=!1;for(;!u(ie.CloseSquareBracket);)u(ie.Colon)?(I.push(void 0),++r,$=!0):(I.push(k()),u(ie.Colon)&&(++r,$=!0));if(I.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($){if(I.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new n3(...I)}return I[0]}function re(I){for(;u(ie.Dot)||u(ie.OpenSquareBracket);){const $=e[r];++r;let J;const D=$.type===ie.OpenSquareBracket;if(D)J=de(),s(ie.CloseSquareBracket,"Expected closing square bracket");else if(J=ee(),J.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");I=new $k(I,J,D)}return I}function W(){let I=pe();for(;u(ie.MultiplicativeBinaryOperator);){const $=e[r++],J=pe();I=new du($,I,J)}return I}function pe(){let I=V();for(;f("is");){++r;const $=f("not");$&&++r;const J=ee();if(!(J instanceof dl))throw new SyntaxError("Expected identifier for the test");I=new e3(I,$,J)}return I}function V(){let I=ue();for(;u(ie.Pipe);){++r;let $=ee();if(!($ instanceof dl))throw new SyntaxError("Expected identifier for the filter");u(ie.OpenParen)&&($=oe($)),I=new Zk(I,$)}return I}function ee(){const I=e[r++];switch(I.type){case ie.NumericLiteral:{const $=I.value;return $.includes(".")?new Wk(Number($)):new Qk(Number($))}case ie.StringLiteral:{let $=I.value;for(;u(ie.StringLiteral);)$+=e[r++].value;return new Rb($)}case ie.Identifier:return new dl(I.value);case ie.OpenParen:{const $=E();return s(ie.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),$}case ie.OpenSquareBracket:{const $=[];for(;!u(ie.CloseSquareBracket);)$.push(k()),u(ie.Comma)&&++r;return++r,new Yk($)}case ie.OpenCurlyBracket:{const $=new Map;for(;!u(ie.CloseCurlyBracket);){const J=k();s(ie.Colon,"Expected colon between key and value in object literal");const D=k();$.set(J,D),u(ie.Comma)&&++r}return++r,new Xk($)}default:throw new SyntaxError(`Unexpected token: ${I.type}`)}}for(;r0)for(let o=e;ot;o+=r)s.push(o);return s}function Pb(e,t,r,s=1){const o=Math.sign(s);o>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),r=(r??=e.length)<0?Math.max(e.length+r,0):Math.min(r,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),r=(r??=-1)<-1?Math.max(e.length+r,-1):Math.min(r,e.length-1));const l=[];for(let u=t;o*ut.toUpperCase())}function u3(e){return d3(new Date,e)}function d3(e,t){const r=new Intl.DateTimeFormat(void 0,{month:"long"}),s=new Intl.DateTimeFormat(void 0,{month:"short"}),o=l=>l<10?"0"+l:l.toString();return t.replace(/%[YmdbBHM%]/g,l=>{switch(l){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 l}})}function f3(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function h3(e,t,r,s){if(s===0)return e;let o=s==null||s<0?1/0:s;const l=t.length===0?new RegExp("(?=)","gu"):new RegExp(f3(t),"gu");return e.replaceAll(l,u=>o>0?(--o,r):u)}var Ib=class extends Error{},Ub=class extends Error{},Ar=class{type="RuntimeValue";value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new Fe(!!this.value)}toString(){return String(this.value)}},je=class extends Ar{type="IntegerValue"},Gt=class extends Ar{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},be=class extends Ar{type="StringValue";builtins=new Map([["upper",new Et(()=>new be(this.value.toUpperCase()))],["lower",new Et(()=>new be(this.value.toLowerCase()))],["strip",new Et(()=>new be(this.value.trim()))],["title",new Et(()=>new be(c3(this.value)))],["capitalize",new Et(()=>new be(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new je(this.value.length)],["rstrip",new Et(()=>new be(this.value.trimEnd()))],["lstrip",new Et(()=>new be(this.value.trimStart()))],["startswith",new Et(e=>{if(e.length===0)throw new Error("startswith() requires at least one argument");const t=e[0];if(t instanceof be)return new Fe(this.value.startsWith(t.value));if(t instanceof Ke){for(const r of t.value){if(!(r instanceof be))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(r.value))return new Fe(!0)}return new Fe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Et(e=>{if(e.length===0)throw new Error("endswith() requires at least one argument");const t=e[0];if(t instanceof be)return new Fe(this.value.endsWith(t.value));if(t instanceof Ke){for(const r of t.value){if(!(r instanceof be))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(r.value))return new Fe(!0)}return new Fe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Et(e=>{const t=e[0]??new Ot;if(!(t instanceof be||t instanceof Ot))throw new Error("sep argument must be a string or null");const r=e[1]??new je(-1);if(!(r instanceof je))throw new Error("maxsplit argument must be a number");let s=[];if(t instanceof Ot){const o=this.value.trimStart();for(const{0:l,index:u}of o.matchAll(/\S+/g)){if(r.value!==-1&&s.length>=r.value&&u!==void 0){s.push(l+o.slice(u+l.length));break}s.push(l)}}else{if(t.value==="")throw new Error("empty separator");s=this.value.split(t.value),r.value!==-1&&s.length>r.value&&s.push(s.splice(r.value).join(t.value))}return new Ke(s.map(o=>new be(o)))})],["replace",new Et(e=>{if(e.length<2)throw new Error("replace() requires at least two arguments");const t=e[0],r=e[1];if(!(t instanceof be&&r instanceof be))throw new Error("replace() arguments must be strings");let s;if(e.length>2?e[2].type==="KeywordArgumentsValue"?s=e[2].value.get("count")??new Ot:s=e[2]:s=new Ot,!(s instanceof je||s instanceof Ot))throw new Error("replace() count argument must be a number or null");return new be(h3(this.value,t.value,r.value,s.value))})]])},Fe=class extends Ar{type="BooleanValue"},p3=/[\x7f-\uffff]/g;function Gb(e){return e.replace(p3,t=>"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function Qi(e,t={},r=0,s=!0){const{indent:o=null,ensureAscii:l=!1,separators:u=null,sortKeys:d=!1}=t;let f,p;switch(u?[f,p]=u:o?(f=",",p=": "):(f=", ",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 l&&(g=Gb(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,t,r+1,s));return o?`[${w}${b.join(`${f}${w}`)}${y}]`:`[${b.join(f)}]`}else{let b=Array.from(e.value.entries());d&&(b=b.sort(([E],[z])=>E.localeCompare(z)));const S=b.map(([E,z])=>{let k=JSON.stringify(E);l&&(k=Gb(k));const L=`${k}${p}${Qi(z,t,r+1,s)}`;return o?`${w}${L}`:L});return o?`{${S.join(f)}${y}}`:`{${S.join(f)}}`}}default:throw new Error(`Cannot convert to JSON: ${e.type}`)}}var un=class extends Ar{type="ObjectValue";__bool__(){return new Fe(this.value.size>0)}builtins=new Map([["get",new Et(([e,t])=>{if(!(e instanceof be))throw new Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new Ot})],["items",new Et(()=>this.items())],["keys",new Et(()=>this.keys())],["values",new Et(()=>this.values())],["dictsort",new Et(e=>{let t=new Map;const r=e.filter(d=>d instanceof pu?(t=d.value,!1):!0),s=r.at(0)??t.get("case_sensitive")??new Fe(!1);if(!(s instanceof Fe))throw new Error("case_sensitive must be a boolean");const o=r.at(1)??t.get("by")??new be("key");if(!(o instanceof be))throw new Error("by must be a string");if(!["key","value"].includes(o.value))throw new Error("by must be either 'key' or 'value'");const l=r.at(2)??t.get("reverse")??new Fe(!1);if(!(l instanceof Fe))throw new Error("reverse must be a boolean");const u=Array.from(this.value.entries()).map(([d,f])=>new Ke([new be(d),f])).sort((d,f)=>{const p=o.value==="key"?0:1,g=d.value[p],y=f.value[p],w=d_(g,y,s.value);return l.value?-w:w});return new Ke(u)})]]);items(){return new Ke(Array.from(this.value.entries()).map(([e,t])=>new Ke([new be(e),t])))}keys(){return new Ke(Array.from(this.value.keys()).map(e=>new be(e)))}values(){return new Ke(Array.from(this.value.values()))}toString(){return Qi(this,{},0,!1)}},pu=class extends un{type="KeywordArgumentsValue"},Ke=class extends Ar{type="ArrayValue";builtins=new Map([["length",new je(this.value.length)]]);__bool__(){return new Fe(this.value.length>0)}toString(){return Qi(this,{},0,!1)}},jb=class extends Ke{type="TupleValue"},Et=class extends Ar{type="FunctionValue"},Ot=class extends Ar{type="NullValue"},St=class extends Ar{type="UndefinedValue"},Gi=class{constructor(e){this.parent=e}variables=new Map([["namespace",new Et(e=>{if(e.length===0)return new un(new Map);if(e.length!==1||!(e[0]instanceof un))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof Et],["odd",e=>{if(!(e instanceof je))throw new Error(`cannot odd on ${e.type}`);return e.value%2!==0}],["even",e=>{if(!(e instanceof je))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 je||e instanceof Gt],["integer",e=>e instanceof je],["iterable",e=>e.type==="ArrayValue"||e.type==="StringValue"],["mapping",e=>e instanceof un],["sequence",e=>e instanceof Ke||e instanceof un||e instanceof be],["lower",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value],["eq",(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,Af(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new St}catch{return new St}}};function m3(e){e.set("false",!1),e.set("true",!0),e.set("none",null),e.set("raise_exception",t=>{throw new Error(t)}),e.set("range",l3),e.set("strftime_now",u3),e.set("True",!0),e.set("False",!1),e.set("None",null)}function Vb(e,t){const r=t.split(".");let s=e;for(const o of r)if(s instanceof un)s=s.value.get(o)??new St;else if(s instanceof Ke){const l=parseInt(o,10);if(!isNaN(l)&&l>=0&&ll instanceof je||l instanceof Gt||l instanceof Fe,o=l=>l instanceof Fe?l.value?1:0:l.value;if(s(e)&&s(t)){const l=o(e),u=o(t);return lu?1:0}if(e.type!==t.type)throw new Error(`Cannot compare different types: ${e.type} and ${t.type}`);if(e.type==="StringValue"){let l=e.value,u=t.value;return r||(l=l.toLowerCase(),u=u.toLowerCase()),lu?1:0}else throw new Error(`Cannot compare type: ${e.type}`)}var _3=class{global;constructor(e){this.global=e??new Gi}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const r=this.evaluate(e.left,t);switch(e.operator.value){case"and":return r.__bool__().value?this.evaluate(e.right,t):r;case"or":return r.__bool__().value?r:this.evaluate(e.right,t)}const s=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new Fe(r.value==s.value);case"!=":return new Fe(r.value!=s.value)}if(r instanceof St||s instanceof St){if(s instanceof St&&["in","not in"].includes(e.operator.value))return new Fe(e.operator.value==="not in");throw new Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else{if(r instanceof Ot||s instanceof Ot)throw new Error("Cannot perform operation on null values");if(e.operator.value==="~")return new be(r.value.toString()+s.value.toString());if((r instanceof je||r instanceof Gt)&&(s instanceof je||s instanceof Gt)){const o=r.value,l=s.value;switch(e.operator.value){case"+":case"-":case"*":{const u=e.operator.value==="+"?o+l:e.operator.value==="-"?o-l:o*l;return r instanceof Gt||s instanceof Gt?new Gt(u):new je(u)}case"/":return new Gt(o/l);case"%":{const u=o%l;return r instanceof Gt||s instanceof Gt?new Gt(u):new je(u)}case"<":return new Fe(o":return new Fe(o>l);case">=":return new Fe(o>=l);case"<=":return new Fe(o<=l)}}else if(r instanceof Ke&&s instanceof Ke){if(e.operator.value==="+")return new Ke(r.value.concat(s.value))}else if(s instanceof Ke){const o=s.value.find(l=>l.value===r.value)!==void 0;switch(e.operator.value){case"in":return new Fe(o);case"not in":return new Fe(!o)}}}if((r instanceof be||s instanceof be)&&e.operator.value==="+")return new be(r.value.toString()+s.value.toString());if(r instanceof be&&s instanceof be)switch(e.operator.value){case"in":return new Fe(s.value.includes(r.value));case"not in":return new Fe(!s.value.includes(r.value))}if(r instanceof be&&s instanceof un)switch(e.operator.value){case"in":return new Fe(s.value.has(r.value));case"not in":return new Fe(!s.value.has(r.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${r.type} and ${s.type}`)}evaluateArguments(e,t){const r=[],s=new Map;for(const o of e)if(o.type==="SpreadExpression"){const l=o,u=this.evaluate(l.argument,t);if(!(u instanceof Ke))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 l=o;s.set(l.key.value,this.evaluate(l.value,t))}else{if(s.size>0)throw new Error("Positional arguments must come before keyword arguments");r.push(this.evaluate(o,t))}return[r,s]}applyFilter(e,t,r){if(t.type==="Identifier"){const s=t;if(s.value==="safe")return e;if(s.value==="tojson")return new be(Qi(e,{}));if(e instanceof Ke)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 je(e.value.length);case"reverse":return new Ke(e.value.slice().reverse());case"sort":return new Ke(e.value.slice().sort((o,l)=>d_(o,l,!1)));case"join":return new be(e.value.map(o=>o.value).join(""));case"string":return new be(Qi(e,{},0,!1));case"unique":{const o=new Set,l=[];for(const u of e.value)o.has(u.value)||(o.add(u.value),l.push(u));return new Ke(l)}default:throw new Error(`Unknown ArrayValue filter: ${s.value}`)}else if(e instanceof be)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 je)return o;throw new Error(`Unknown StringValue filter: ${s.value}`)}case"trim":return new be(e.value.trim());case"indent":return new be(e.value.split(` +`).map((o,l)=>l===0||o.length===0?o:" "+o).join(` +`));case"join":case"string":return e;case"int":{const o=parseInt(e.value,10);return new je(isNaN(o)?0:o)}case"float":{const o=parseFloat(e.value);return new Gt(isNaN(o)?0:o)}default:throw new Error(`Unknown StringValue filter: ${s.value}`)}else if(e instanceof je||e instanceof Gt)switch(s.value){case"abs":return e instanceof je?new je(Math.abs(e.value)):new Gt(Math.abs(e.value));case"int":return new je(Math.floor(e.value));case"float":return new Gt(e.value);case"string":return new be(e.toString());default:throw new Error(`Unknown NumericValue filter: ${s.value}`)}else if(e instanceof un)switch(s.value){case"items":return new Ke(Array.from(e.value.entries()).map(([o,l])=>new Ke([new be(o),l])));case"length":return new je(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 Fe)switch(s.value){case"bool":return new Fe(e.value);case"int":return new je(e.value?1:0);case"float":return new Gt(e.value?1:0);case"string":return new be(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(t.type==="CallExpression"){const s=t;if(s.callee.type!=="Identifier")throw new Error(`Unknown filter: ${s.callee.type}`);const o=s.callee.value;if(o==="tojson"){const[,l]=this.evaluateArguments(s.args,r),u=l.get("indent")??new Ot;if(!(u instanceof je||u instanceof Ot))throw new Error("If set, indent must be a number");const d=l.get("ensure_ascii")??new Fe(!1);if(!(d instanceof Fe))throw new Error("If set, ensure_ascii must be a boolean");const f=l.get("sort_keys")??new Fe(!1);if(!(f instanceof Fe))throw new Error("If set, sort_keys must be a boolean");const p=l.get("separators")??new Ot;let g=null;if(p instanceof Ke||p instanceof jb){if(p.value.length!==2)throw new Error("separators must be a tuple of two strings");const[y,w]=p.value;if(!(y instanceof be)||!(w instanceof be))throw new Error("separators must be a tuple of two strings");g=[y.value,w.value]}else if(!(p instanceof Ot))throw new Error("If set, separators must be a tuple of two strings");return new be(Qi(e,{indent:u.value,ensureAscii:d.value,sortKeys:f.value,separators:g}))}else if(o==="join"){let l;if(e instanceof be)l=Array.from(e.value);else if(e instanceof Ke)l=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),f=u.at(0)??d.get("separator")??new be("");if(!(f instanceof be))throw new Error("separator must be a string");return new be(l.join(f.value))}else if(o==="int"||o==="float"){const[l,u]=this.evaluateArguments(s.args,r),d=l.at(0)??u.get("default")??(o==="int"?new je(0):new Gt(0));if(e instanceof be){const f=o==="int"?parseInt(e.value,10):parseFloat(e.value);return isNaN(f)?d:o==="int"?new je(f):new Gt(f)}else{if(e instanceof je||e instanceof Gt)return e;if(e instanceof Fe)return o==="int"?new je(e.value?1:0):new Gt(e.value?1:0);throw new Error(`Cannot apply filter "${o}" to type: ${e.type}`)}}else if(o==="default"){const[l,u]=this.evaluateArguments(s.args,r),d=l[0]??new be(""),f=l[1]??u.get("boolean")??new Fe(!1);if(!(f instanceof Fe))throw new Error("`default` filter flag must be a boolean");return e instanceof St||f.value&&!e.__bool__().value?d:e}if(e instanceof Ke){switch(o){case"sort":{const[l,u]=this.evaluateArguments(s.args,r),d=l.at(0)??u.get("reverse")??new Fe(!1);if(!(d instanceof Fe))throw new Error("reverse must be a boolean");const f=l.at(1)??u.get("case_sensitive")??new Fe(!1);if(!(f instanceof Fe))throw new Error("case_sensitive must be a boolean");const p=l.at(2)??u.get("attribute")??new Ot;if(!(p instanceof be||p instanceof je||p instanceof Ot))throw new Error("attribute must be a string, integer, or null");const g=y=>{if(p instanceof Ot)return y;const w=p instanceof je?String(p.value):p.value;return Vb(y,w)};return new Ke(e.value.slice().sort((y,w)=>{const b=g(y),S=g(w),E=d_(b,S,f.value);return d.value?-E:E}))}case"selectattr":case"rejectattr":{const l=o==="selectattr";if(e.value.some(y=>!(y instanceof un)))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,f]=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,f):!1;return l?b:!b});return new Ke(g)}case"map":{const[,l]=this.evaluateArguments(s.args,r);if(l.has("attribute")){const u=l.get("attribute");if(!(u instanceof be))throw new Error("attribute must be a string");const d=l.get("default"),f=e.value.map(p=>{if(!(p instanceof un))throw new Error("items in map must be an object");const g=Vb(p,u.value);return g instanceof St?d??new St:g});return new Ke(f)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${o}`)}else if(e instanceof be){switch(o){case"indent":{const[l,u]=this.evaluateArguments(s.args,r),d=l.at(0)??u.get("width")??new je(4);if(!(d instanceof je))throw new Error("width must be a number");const f=l.at(1)??u.get("first")??new Fe(!1),p=l.at(2)??u.get("blank")??new Fe(!1),g=e.value.split(` +`),y=" ".repeat(d.value),w=g.map((b,S)=>!f.value&&S===0||!p.value&&b.length===0?b:y+b);return new be(w.join(` +`))}case"replace":{const l=e.builtins.get("replace");if(!(l instanceof Et))throw new Error("replace filter not available");const[u,d]=this.evaluateArguments(s.args,r);return l.value([...u,new pu(d)],r)}}throw new Error(`Unknown StringValue filter: ${o}`)}else if(e instanceof un){const l=e.builtins.get(o);if(l&&l instanceof Et){const[u,d]=this.evaluateArguments(s.args,r);return d.size>0&&u.push(new pu(d)),l.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: ${t.type}`)}evaluateFilterExpression(e,t){const r=this.evaluate(e.operand,t);return this.applyFilter(r,e.filter,t)}evaluateTestExpression(e,t){const r=this.evaluate(e.operand,t),s=t.tests.get(e.test.value);if(!s)throw new Error(`Unknown test: ${e.test.value}`);const o=s(r);return new Fe(e.negate?!o:o)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new St}evaluateUnaryExpression(e,t){const r=this.evaluate(e.argument,t);if(e.operator.value==="not")return new Fe(!r.value);throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let r="";for(const s of e){const o=this.evaluate(s,t);o.type!=="NullValue"&&o.type!=="UndefinedValue"&&(r+=o.toString())}return new be(r)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const[r,s]=this.evaluateArguments(e.args,t);s.size>0&&r.push(new pu(s));const o=this.evaluate(e.callee,t);if(o.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${o.type}`);return o.value(r,t)}evaluateSliceExpression(e,t,r){if(!(e instanceof Ke||e instanceof be))throw new Error("Slice object must be an array or string");const s=this.evaluate(t.start,r),o=this.evaluate(t.stop,r),l=this.evaluate(t.step,r);if(!(s instanceof je||s instanceof St))throw new Error("Slice start must be numeric or undefined");if(!(o instanceof je||o instanceof St))throw new Error("Slice stop must be numeric or undefined");if(!(l instanceof je||l instanceof St))throw new Error("Slice step must be numeric or undefined");return e instanceof Ke?new Ke(Pb(e.value,s.value,o.value,l.value)):new be(Pb(Array.from(e.value),s.value,o.value,l.value).join(""))}evaluateMemberExpression(e,t){const r=this.evaluate(e.object,t);let s;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(r,e.property,t);s=this.evaluate(e.property,t)}else s=new be(e.property.value);let o;if(r instanceof un){if(!(s instanceof be))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 Ke||r instanceof be)if(s instanceof je)o=r.value.at(s.value),r instanceof be&&(o=new be(r.value.at(s.value)));else if(s instanceof be)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 be))throw new Error(`Cannot access property with non-string: got ${s.type}`);o=r.builtins.get(s.value)}return o instanceof Ar?o:new St}evaluateSet(e,t){const r=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type==="Identifier"){const s=e.assignee.value;t.setVariable(s,r)}else if(e.assignee.type==="TupleLiteral"){const s=e.assignee;if(!(r instanceof Ke))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 l=0;lb.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 z=0;z0?l[p-1]:new St],["nextitem",p{const o=new Gi(s);r=r.slice();let l;r.at(-1)?.type==="KeywordArgumentsValue"&&(l=r.pop());for(let u=0;u{const p=new Gi(f);if(e.callerArgs)for(let g=0;gthis.evaluate(r,t)));case"TupleLiteral":return new jb(e.value.map(r=>this.evaluate(r,t)));case"ObjectLiteral":{const r=new Map;for(const[s,o]of e.value){const l=this.evaluate(s,t);if(!(l instanceof be))throw new Error(`Object keys must be strings: got ${l.type}`);r.set(l.value,this.evaluate(o,t))}return new un(r)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"FilterStatement":return this.evaluateFilterStatement(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);case"SelectExpression":return this.evaluateSelectExpression(e,t);case"Ternary":return this.evaluateTernaryExpression(e,t);case"Comment":return new Ot;default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function Af(e){switch(typeof e){case"number":return Number.isInteger(e)?new je(e):new Gt(e);case"string":return new be(e);case"boolean":return new Fe(e);case"undefined":return new St;case"object":return e===null?new Ot:Array.isArray(e)?new Ke(e.map(Af)):new un(new Map(Object.entries(e).map(([t,r])=>[t,Af(r)])));case"function":return new Et((t,r)=>{const s=e(...t.map(o=>o.value))??null;return Af(s)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var en=` +`,g3="{%- ",y3=" -%}";function v3(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 w3(e,t=" "){const r=typeof t=="number"?" ".repeat(t):t;return Wa(e.body,0,r).replace(/\n$/,"")}function vn(...e){return g3+e.join(" ")+y3}function Wa(e,t,r){return e.map(s=>b3(s,t,r)).join(en)}function b3(e,t,r){const s=r.repeat(t);switch(e.type){case"Program":return Wa(e.body,t,r);case"If":return M3(e,t,r);case"For":return x3(e,t,r);case"Set":return T3(e,t,r);case"Macro":return S3(e,t,r);case"Break":return s+vn("break");case"Continue":return s+vn("continue");case"CallStatement":return E3(e,t,r);case"FilterStatement":return A3(e,t,r);case"Comment":return s+"{# "+e.value+" #}";default:return s+"{{- "+at(e)+" -}}"}}function M3(e,t,r){const s=r.repeat(t),o=[];let l=e;for(;l&&(o.push({test:l.test,body:l.body}),l.alternate.length===1&&l.alternate[0].type==="If");)l=l.alternate[0];let u=s+vn("if",at(o[0].test))+en+Wa(o[0].body,t+1,r);for(let d=1;d0&&(u+=en+s+vn("else")+en+Wa(l.alternate,t+1,r)),u+=en+s+vn("endif"),u}function x3(e,t,r){const s=r.repeat(t);let o="";if(e.iterable.type==="SelectExpression"){const u=e.iterable;o=`${at(u.lhs)} if ${at(u.test)}`}else o=at(e.iterable);let l=s+vn("for",at(e.loopvar),"in",o)+en+Wa(e.body,t+1,r);return e.defaultBlock.length>0&&(l+=en+s+vn("else")+en+Wa(e.defaultBlock,t+1,r)),l+=en+s+vn("endfor"),l}function T3(e,t,r){const s=r.repeat(t),o=at(e.assignee),l=e.value?at(e.value):"",u=s+vn("set",`${o}${e.value?" = "+l:""}`);return e.body.length===0?u:u+en+Wa(e.body,t+1,r)+en+s+vn("endset")}function S3(e,t,r){const s=r.repeat(t),o=e.args.map(at).join(", ");return s+vn("macro",`${e.name.value}(${o})`)+en+Wa(e.body,t+1,r)+en+s+vn("endmacro")}function E3(e,t,r){const s=r.repeat(t),o=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(at).join(", ")})`:"",l=at(e.call);let u=s+vn(`call${o}`,l)+en;return u+=Wa(e.body,t+1,r)+en,u+=s+vn("endcall"),u}function A3(e,t,r){const s=r.repeat(t),o=e.filter.type==="Identifier"?e.filter.value:at(e.filter);let l=s+vn("filter",o)+en;return l+=Wa(e.body,t+1,r)+en,l+=s+vn("endfilter"),l}function at(e,t=-1){switch(e.type){case"SpreadExpression":return`*${at(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=v3(r),o=at(r.left,s),l=at(r.right,s+1),u=`${o} ${r.operator.value} ${l}`;return s`${at(s)}: ${at(o)}`).join(", ")}}`;case"SliceExpression":{const r=e,s=r.start?at(r.start):"",o=r.stop?at(r.stop):"",l=r.step?`:${at(r.step)}`:"";return`${s}:${o}${l}`}case"KeywordArgumentExpression":{const r=e;return`${r.key.value}=${at(r.value)}`}case"Ternary":{const r=e,s=`${at(r.trueExpr)} if ${at(r.condition,0)} else ${at(r.falseExpr)}`;return t>-1?`(${s})`:s}default:throw new Error(`Unknown expression type: ${e.type}`)}}var C3=class{parsed;constructor(e){const t=Bk(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=o3(t)}render(e){const t=new Gi;if(m3(t),e)for(const[o,l]of Object.entries(e))t.set(o,l);return new _3(t).run(this.parsed).value}format(e){return w3(this.parsed,e?.indent||" ")}},Oa=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}},k3={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"},If=class DM{constructor(t){if(this.filePath=t,this.headers=new Headers,this.exists=fa.existsSync(t),this.exists){this.status=200,this.statusText="OK";let r=fa.statSync(t);this.headers.set("content-length",r.size.toString()),this.updateContentType();const s=fa.createReadStream(t);this.body=new ReadableStream({start(o){s.on("data",l=>o.enqueue(l)),s.on("end",()=>o.close()),s.on("error",l=>o.error(l))},cancel(){s.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",k3[t]??"application/octet-stream")}clone(){let t=new DM(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await fa.promises.readFile(this.filePath)).buffer}async blob(){const t=await fa.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await fa.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},Q_=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(We.IS_CRYPTO_AVAILABLE){const u=new Uint32Array(1);crypto.getRandomValues(u),e=u[0]}else e=Date.now()>>>0;const t=this._mt,r=(u,d)=>Math.imul(u,d)>>>0,s=[];for(let u=e||0;u>0;u=Math.floor(u/4294967296))s.push(u&4294967295);s.length||s.push(0),t[0]=19650218;for(let u=1;u<624;++u)t[u]=r(1812433253,t[u-1]^t[u-1]>>>30)+u>>>0;let o=1,l=0;for(let u=Math.max(624,s.length);u>0;--u,++o,++l)o>=624&&(t[0]=t[623],o=1),l>=s.length&&(l=0),t[o]=(t[o]^r(t[o-1]^t[o-1]>>>30,1664525))+s[l]+l>>>0;for(let u=623;u>0;--u,++o)o>=624&&(t[0]=t[623],o=1),t[o]=(t[o]^r(t[o-1]^t[o-1]>>>30,1566083941))-o>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){const e=this._mt;if(this._idx>=624){for(let r=0;r<624;++r){const s=e[r]&2147483648|e[(r+1)%624]&2147483647;e[r]=(e[(r+397)%624]^s>>>1^(s&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let r=this._gauss_next;if(this._gauss_next=null,r===null){const s=this.random()*2*Math.PI,o=Math.sqrt(-2*Math.log(1-this.random()));r=Math.cos(s)*o,this._gauss_next=Math.sin(s)*o}return e+r*t}shuffle(e){for(let t=e.length-1;t>0;--t){const r=32-Math.clz32(t+1);let s=this._int32()>>>32-r;for(;s>t;)s=this._int32()>>>32-r;const o=e[t];e[t]=e[s],e[s]=o}}choices(e,t){return e[RM(this._random_fn,t)]}};function RM(e,t){let r=0;for(let o=0;oRM(W_.random,e),z3=new Q_,BM=class{constructor(e){this.path=e}async match(e){let t=Tr.join(this.path,e),r=new If(t);if(r.exists)return r}async put(e,t,r=void 0){const s=Tr.join(this.path,e),o=We.IS_PROCESS_AVAILABLE?process.pid:Date.now(),l=z3._int32().toString(36),u=s+`.tmp.${o}.${l}`;try{const d=t.headers.get("Content-Length"),f=parseInt(d??"0");let p=0;await fa.promises.mkdir(Tr.dirname(s),{recursive:!0});const g=fa.createWriteStream(u),y=t.body.getReader();for(;;){const{done:w,value:b}=await y.read();if(w)break;await new Promise((E,z)=>{g.write(b,k=>{if(k){z(k);return}E()})}),p+=b.length;const S=f?p/f*100:0;r?.({progress:S,loaded:p,total:f})}await new Promise((w,b)=>{g.close(S=>S?b(S):w())}),await fa.promises.rename(u,s)}catch(d){try{await fa.promises.unlink(u)}catch{}throw d}}async delete(e){let t=Tr.join(this.path,e);try{return await fa.promises.unlink(t),!0}catch{return!1}}},L3={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"},qb=100,F3=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function vf(...e){return e=e.map((t,r)=>(r&&(t=t.replace(new RegExp("^/"),"")),r!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function kl(e,t=null,r=null){let s;try{s=new URL(e)}catch{return!1}return!(t&&!t.includes(s.protocol)||r&&!r.includes(s.hostname))}function N3(e){return!(!F3.test(e)||e.includes("..")||e.includes("--")||e.endsWith(".git")||e.endsWith(".ipynb"))}function D3(e,t,r){if(!r)return null;const s=L3[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${s}: "${t}".`)}async function R3(e,t,r){const s=e.headers.get("Content-Length");let o=s?parseInt(s,10):r??0;s===null&&!r&&Re.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let l=new Uint8Array(o),u=0;const d=e.body.getReader();async function f(){const{done:p,value:g}=await d.read();if(p)return;const y=u+g.length;if(y>o){o=y;const b=new Uint8Array(o);b.set(l),l=b}l.set(g,u),u=y;const w=u/o*100;return t({progress:w,loaded:u,total:o}),f()}return await f(),l}function Hb(e){return kl(e,["blob:"])}function $b(e){let t;if(typeof location<"u"&&location.href)t=location.href;else if(typeof import.meta<"u"&&import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var PM="SHA-256",B3="experimental_transformers-hash-cache",Qb=e=>({algorithm:PM,value:e}),Wb=class{#t=null;_getHashCache=()=>(this.#t??=caches.open(B3),this.#t);static isAvailable=()=>typeof navigator<"u"&&"crossOriginStorage"in navigator;match=async e=>{const t=await this._getFileHash(e);if(t)try{const[r]=await navigator.crossOriginStorage.requestFileHandles([Qb(t)]),s=await r.getFile();return new Response(s,{headers:{"Content-Length":String(s.size)}})}catch{return}};put=async(e,t)=>{const r=await this._getFileHash(e);if(r){const s=await t.blob();await this._storeBlobInCOS(s,r)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{const[r]=await navigator.crossOriginStorage.requestFileHandles([Qb(t)],{create:!0}),s=await r.createWritable();await s.write(e),await s.close()};_processAndStore=async(e,t)=>{try{const r=[];for await(const l of t)r.push(l);const s=new Blob(r),o=await this._getBlobHash(s);await this._storeBlobInCOS(s,o);try{await(await this._getHashCache()).put(e,new Response(o))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{const t=await this._getHashCache(),r=await t.match(e);if(r)return r.text();const s=await this._getLfsFileHash(e);return s?(await t.put(e,new Response(s)),s):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes("/resolve/"))return null;const t=e.replace("/resolve/","/raw/");try{const s=(await fetch(t).then(o=>o.text())).match(/^oid sha256:([0-9a-f]+)$/m);return s?s[1]:null}catch{return null}};_getBlobHash=async e=>{const t=await e.arrayBuffer(),r=await crypto.subtle.digest(PM,t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}};async function Y_(e=null){let t=null;if(rt.useCustomCache){if(!rt.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!rt.customCache.match||!rt.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=rt.customCache}if(!t&&rt.experimental_useCrossOriginStorage&&Wb.isAvailable()&&(t=new Wb),!t&&rt.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{t=await caches.open(rt.cacheKey)}catch(r){Re.warn("An error occurred while opening the browser cache:",r)}}if(!t&&rt.useFSCache){if(!We.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");t=new BM(e??rt.cacheDir)}return t}async function P3(e,...t){for(let r of t)try{let s=await e.match(r);if(s)return s}catch{continue}}var I3=class{#t;#e;constructor(e){this.#t=e,this.#e=new Map}get(e){if(!this.#e.has(e))return;const t=this.#e.get(e);return this.#e.delete(e),this.#e.set(e,t),t}put(e,t){this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,t),this.#e.size>this.#t&&this.#e.delete(this.#e.keys().next().value)}delete(e){return this.#e.delete(e)}clear(){this.#e.clear()}},U3=100,$m=new I3(U3);function IM(e,t){const r=$m.get(e);if(r!==void 0)return r;const s=t().then(o=>o,o=>($m.delete(e),Promise.reject(o)));return $m.put(e,s),s}async function G3(e){if(!kl(e,["http:","https:"]))return null;const t=UM(e);return t.set("Range","bytes=0-0"),rt.fetch(e,{method:"GET",headers:t,cache:"no-store"})}function Zf(e,t,r={}){const s=JSON.stringify([e,t,r?.revision,r?.cache_dir,r?.local_files_only]);return IM(s,()=>j3(e,t,r))}async function j3(e,t,r){const s=await Y_(r?.cache_dir),{localPath:o,remoteURL:l,proposedCacheKey:u,validModelId:d}=GM(e,t,r,s),f=await jM(s,o,u);if(f!==void 0&&typeof f!="string"){const p=f.headers.get("content-length"),g=f.headers.get("content-type");return{exists:!0,size:p?parseInt(p,10):void 0,contentType:g||void 0,fromCache:!0}}if(rt.allowLocalModels&&!kl(o,["http:","https:"]))try{const g=await bu(o);if(typeof g!="string"&&g.status!==404){const y=g.headers.get("content-length"),w=g.headers.get("content-type");return{exists:!0,size:y?parseInt(y,10):void 0,contentType:w||void 0,fromCache:!1}}}catch{}if(rt.allowRemoteModels&&!r.local_files_only&&d)try{const p=await G3(l);if(p&&p.status>=200&&p.status<300){let g;const y=p.headers.get("content-type");if(p.status===206){const w=p.headers.get("content-range");if(w){const b=w.match(/bytes \d+-\d+\/(\d+)/);b&&(g=parseInt(b[1],10))}}else if(p.status===200)try{await p.body?.cancel()}catch{}if(g===void 0){const w=p.headers.get("content-length");g=w?parseInt(w,10):void 0}return{exists:!0,size:g,contentType:y||void 0,fromCache:!1}}}catch(p){Re.warn(`Unable to fetch file metadata for "${l}": ${p}`)}return{exists:!1,fromCache:!1}}async function bu(e){return rt.useFS&&!kl(e,["http:","https:","blob:"])?new If(e instanceof URL?e.protocol==="file:"?e.pathname:e.toString():e):rt.fetch(e,{headers:UM(e)})}function UM(e){const t=typeof process<"u"&&process?.release?.name==="node",r=new Headers;if(t){const s=!!qm?.TESTING_REMOTELY,o=rt.version;if(r.set("User-Agent",`transformers.js/${o}; is_ci/${s};`),kl(e,["http:","https:"],["huggingface.co","hf.co"])){const u=qm?.HF_TOKEN??qm?.HF_ACCESS_TOKEN;u&&r.set("Authorization",`Bearer ${u}`)}}return r}function GM(e,t,r={},s=null){const o=r.revision??"main",l=vf(e,t),u=N3(e),d=u?vf(rt.localModelPath,l):l,f=vf(rt.remoteHost,rt.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(o)),t),p=s instanceof BM?o==="main"?l:vf(e,o,t):f;return{requestURL:l,localPath:d,remoteURL:f,proposedCacheKey:p,validModelId:u}}async function jM(e,t,r){if(e)return await P3(e,t,r)}async function V3(e,t,r,s,o,l,u={}){if(await r.match(s)===void 0)if(l)typeof o!="string"&&await r.put(s,new Response(l,{headers:o.headers})).catch(d=>{Re.warn(`Unable to add response to browser cache: ${d}.`)});else{const d=u.progress_callback?f=>$i(u.progress_callback,{status:"progress",name:e,file:t,...f}):void 0;await r.put(s,o,d)}}async function q3(e,t,r=!0,s={},o=!1,l=null){const{requestURL:u,localPath:d,remoteURL:f,proposedCacheKey:p,validModelId:g}=GM(e,t,s,l);let y,w=!1,b;b=await jM(l,d,p);const S=b!==void 0;if(!S){if(rt.allowLocalModels)if(kl(u,["http:","https:"])){if(s.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${u}.`);if(!rt.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${u}.`)}else try{b=await bu(d),y=d}catch(L){Re.warn(`Unable to load from local path "${d}": "${L}"`)}if(b===void 0||typeof b!="string"&&b.status===404){if(s.local_files_only||!rt.allowRemoteModels){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 bu(f),b.status!==200)return D3(b.status,f,r);y=p}w=l&&typeof Response<"u"&&b instanceof Response&&b.status===200}$i(s.progress_callback,{status:"download",name:e,file:t});let E;if(!(We.IS_NODE_ENV&&o)){let k;if(typeof b!="string")if(!s.progress_callback)k=new Uint8Array(await b.arrayBuffer());else if(S&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))k=new Uint8Array(await b.arrayBuffer()),$i(s.progress_callback,{status:"progress",name:e,file:t,progress:100,loaded:k.length,total:k.length});else{let L;const R=b.headers.get("content-length");if(R)L=parseInt(R,10);else try{const N=await Zf(e,t,s);N.size&&(L=N.size)}catch{}k=await R3(b,N=>{$i(s.progress_callback,{status:"progress",name:e,file:t,...N})},L)}E=k}if(w&&y&&typeof b!="string"&&await V3(e,t,l,y,b,E,s),$i(s.progress_callback,{status:"done",name:e,file:t}),E){if(!We.IS_NODE_ENV&&o)throw new Error("Cannot return path in a browser environment.");return E}if(b instanceof If)return b.filePath;const z=await l?.match(y);if(z instanceof If)return z.filePath;if(z instanceof Response)return new Uint8Array(await z.arrayBuffer());if(typeof z=="string")return z;throw new Error("Unable to get model file path or buffer.")}async function Uf(e,t,r=!0,s={},o=!1){if(!rt.allowLocalModels){if(s.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!rt.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}$i(s.progress_callback,{status:"initiate",name:e,file:t});const l=await Y_(s?.cache_dir);return await q3(e,t,r,s,o,l)}async function VM(e,t,r=!0,s={}){const o=await Uf(e,t,r,s,!1);return o===null?null:new TextDecoder("utf-8").decode(o)}async function ss(e,t,r=!0,s={}){const o=await VM(e,t,r,s);return o===null?{}:JSON.parse(o)}function H3(e,[t,r,s],[o,l],u="bilinear",d=!1){const f=l/s,p=o/r,g=new e.constructor(o*l*t),y=r*s,w=o*l;for(let b=0;b=0;--d)o[d]=f,s[d]=t[r[d]],f*=s[d];const l=r.map((d,f)=>o[r.indexOf(f)]),u=new e.constructor(e.length);for(let d=0;d=0;--p)f+=g%t[p]*l[p],g=Math.floor(g/t[p]);u[f]=e[d]}return[u,s]}function wn(e){const t=Ht(e)[0],r=e.map(l=>Math.exp(l-t)),s=r.reduce((l,u)=>l+u,0);return r.map(l=>l/s)}function Q3(e){const t=Ht(e)[0];let r=0;for(let l=0;ll-t-s)}function f_(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],r=0;for(let s=1;st&&(t=e[s],r=s);return[t,r]}function qM(e){return e>0&&(e&e-1)===0}var HM=class{constructor(e){if(this.size=e|0,this.size<=1||!qM(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)++t;this._width=t%2===0?t-1:t,this._bitrev=new Int32Array(1<>>s&3)<>>1);for(let s=0;s>>1]=e[s];return r}toComplexArray(e,t){const r=t||this.createComplexArray();for(let s=0;s>>1],r[s+1]=0;return r}transform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw new Error("Input and output buffers must be different");this._transform4(e,t,-1);for(let r=0;r>=2;l>=2;l>>=2){u=s/l<<1;const y=u>>>2;for(d=0;d>>1,l>>>1)}else for(d=0,f=0;d>>1,l>>>1,r)}const g=this.table;for(l>>=2;l>=2;l>>=2){u=s/l<<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+f**2)**g,w=g*Math.atan2(f,d),b=2*p;o[b]=y*Math.cos(w),o[b+1]=y*Math.sin(w),l[b]=o[b],l[b+1]=-o[b+1]}this._slicedChirpBuffer=o.subarray(t,r),this._f=new HM(s>>1),this._f.transform(this._chirpBuffer,l)}_transform(e,t,r){const s=this._buffer1,o=this._buffer2,l=this._outBuffer1,u=this._outBuffer2,d=this._chirpBuffer,f=this._slicedChirpBuffer,p=this._a;if(r)for(let g=0;g>1,b=t[w];s[g]=b*f[g],s[y]=b*f[y]}else for(let g=0;g=e.length&&(f=2*(e.length-1)-f),s[u++]=e[f]}s.sort(),r[l]=s[o]}return r}function mu(e,t){const r=Math.pow(10,t);return Math.round(e*r)/r}function Z3(e){const t=Math.round(e);return Math.abs(e)%1===.5?t%2===0?t:t-1:t}function K3(e){const t=e.length,r=e[0].length,s=[t+1,r+1],o=Array.from({length:s[0]},()=>Array(s[1]).fill(1/0));o[0][0]=0;const l=Array.from({length:s[0]},()=>Array(s[1]).fill(-1));for(let g=1;g0||d>0;)switch(f.push(u-1),p.push(d-1),l[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 f.reverse(),p.reverse(),[f,p]}var J3=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);const l=new ArrayBuffer(4),u=new Uint32Array(l),d=new Float32Array(l);for(let f=0;f>10;let w=f&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[f]=d[0]}}const r=t.length,s=e,o=new Float32Array(r);for(let l=0;leO});var eO={};async function QM(e){const t=e.split("/").pop();let r;try{if(r=await Y_(),r){const o=await r.match(e);if(o)return o}}catch(o){Re.warn(`Failed to load ${t} from cache:`,o)}const s=await rt.fetch(e);if(!s.ok)throw new Error(`Failed to fetch ${t}: ${s.status} ${s.statusText}`);if(r)try{await r.put(e,s.clone())}catch(o){Re.warn(`Failed to cache ${t}:`,o)}return s}async function tO(e){const t=await QM(e);if(!t||typeof t=="string")return null;try{return await t.arrayBuffer()}catch(r){return Re.warn("Failed to read WASM binary:",r),null}}async function nO(e){if(We.IS_SERVICE_WORKER_ENV||We.IS_CHROME_AVAILABLE)return e;const t=await QM(e);if(!t||typeof t=="string")return null;try{let r=await t.text();r=r.replaceAll("globalThis.process?.versions?.node","false");const s=new Blob([r],{type:"text/javascript"});return URL.createObjectURL(s)}catch(r){return Re.warn("Failed to read WASM factory:",r),null}}var aO=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function WM(e){return e<=$a.DEBUG?0:e<=$a.INFO?2:e<=$a.WARNING||e<=$a.ERROR?3:4}var rO={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},Ca=[],h_,Ml,Yb=Symbol.for("onnxruntime");if(Yb in globalThis)Ml=globalThis[Yb];else if(We.IS_NODE_ENV){switch(Ml=$M,process.platform){case"win32":Ca.push("dml");break;case"linux":process.arch==="x64"&&Ca.push("cuda");break;case"darwin":Ca.push("coreml");break}Ca.push("webgpu"),Ca.push("cpu"),h_=["cpu"]}else Ml=QE,We.IS_WEBNN_AVAILABLE&&Ca.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),We.IS_WEBGPU_AVAILABLE&&Ca.push("webgpu"),Ca.push("wasm"),h_=["wasm"];var sO=Ml.InferenceSession;function iO(e=null){if(!e)return h_;switch(e){case"auto":return Ca;case"gpu":return Ca.filter(t=>["webgpu","cuda","dml","webnn-gpu"].includes(t))}if(Ca.includes(e))return[aO[e]??e];throw new Error(`Unsupported device: "${e}". Should be one of: ${Ca.join(", ")}.`)}var Xb=Promise.resolve(),fl=null;async function oO(){if(fl)return fl;if(!(rt.useWasmCache&&typeof Jt?.wasm?.wasmPaths=="object"&&Jt?.wasm?.wasmPaths?.wasm&&Jt?.wasm?.wasmPaths?.mjs)){if(We.IS_DENO_WEB_RUNTIME)throw new Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return fl=Promise.resolve(),fl}return fl=(async()=>{const t=Jt.wasm.wasmPaths;let r=!1;await Promise.all([t.wasm&&!Hb(t.wasm)?(async()=>{try{const s=await tO($b(t.wasm));s&&(Jt.wasm.wasmBinary=s,r=!0)}catch(s){Re.warn("Failed to pre-load WASM binary:",s)}})():Promise.resolve(),t.mjs&&!Hb(t.mjs)?(async()=>{try{const s=await nO($b(t.mjs));s&&(Jt.wasm.wasmPaths.mjs=s)}catch(s){Re.warn("Failed to pre-load WASM factory:",s)}})():Promise.resolve()]),r||(Jt.wasm.wasmPaths.mjs=t.mjs)})(),fl}async function YM(e,t,r){await oO();const s=WM(rt.logLevel??$a.WARNING),o=()=>sO.create(e,{logSeverityLevel:s,...t}),l=await(We.IS_WEB_ENV?Xb=Xb.then(o):o());return l.config=r,l}var Zb=Promise.resolve();async function XM(e,t){const r=()=>e.run(t);return We.IS_WEB_ENV?Zb=Zb.then(r):r()}function ZM(e){return e instanceof Ml.Tensor}var Jt=Ml?.env;function X_(){return Jt?.wasm?.proxy}if(Jt){let e=function(t){const r=WM(t);Jt.logLevel=rO[r]};if(Jt.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&Jt.versions?.web&&!Jt.wasm.wasmPaths){const t=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Jt.versions.web}/dist/`;Jt.wasm.wasmPaths=We.IS_SAFARI?{mjs:`${t}ort-wasm-simd-threaded.mjs`,wasm:`${t}ort-wasm-simd-threaded.wasm`}:{mjs:`${t}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${t}ort-wasm-simd-threaded.asyncify.wasm`}}Jt.wasm.proxy=!1}Jt.webgpu&&(Jt.webgpu.powerPreference="high-performance"),e(rt.logLevel??$a.WARNING),rt.backends.onnx={...Jt,setLogLevel:e}}var Ys=async(e,t,r)=>{const s=await YM(new Uint8Array(e),t);return(async o=>{const l=X_(),u=Object.fromEntries(Object.entries(o).map(([f,p])=>[f,(l?p.clone():p).ort_tensor])),d=await XM(s,u);return Array.isArray(r)?r.map(f=>new me(d[f])):new me(d[r])})},xl=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=Ys([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=Ys([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=Ys([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=Ys([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=Ys([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=Ys([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=Ys([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=Ys([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}},lO=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"}),Qm=We.IS_NODE_ENV?"cpu":"wasm";function KM(e,t,{warn:r}={}){return e?typeof e=="string"?e:e.hasOwnProperty(t)?e[t]:(r&&r(`device not specified for "${t}". Using the default device (${Qm}).`),Qm):Qm}var cO=(function(){let e;return async function(){if(e===void 0)if(!We.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}})(),kn=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Kb=kn.fp32,Jb=Object.freeze({[lO.wasm]:kn.q8}),p_=Object.freeze({[kn.fp32]:"",[kn.fp16]:"_fp16",[kn.int8]:"_int8",[kn.uint8]:"_uint8",[kn.q8]:"_quantized",[kn.q4]:"_q4",[kn.q4f16]:"_q4f16",[kn.bnb4]:"_bnb4"});function JM(e,t,r,{configDtype:s=null,warn:o}={}){let l,u=!1;e&&typeof e!="string"?e.hasOwnProperty(t)?l=e[t]:(l=null,u=!0):l=e;let d;if(l===kn.auto){if(s){const f=typeof s=="string"?s:s?.[t];if(f&&f!==kn.auto&&kn.hasOwnProperty(f))return f}d=Jb[r]??Kb}else l&&kn.hasOwnProperty(l)?d=l:d=Jb[r]??Kb;return u&&o&&o(`dtype not specified for "${t}". Using the default dtype (${d}) for this device (${r}).`),d}var Sl=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}),me=class Ut{get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...t){return ZM(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new rA(t[0],t[1],t[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})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...r]=this.dims;if(r.length>0){const s=r.reduce((o,l)=>o*l);for(let o=0;o0){const o=s.reduce((l,u)=>l*u);return this._subarray(t,o,s)}else return new Ut(this.type,[this.data[t]],s)}indexOf(t){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),l=o.reduce((g,y)=>g*y),u=this.data,d=new u.constructor(l),f=this.stride();let p=!0;for(let g=1;g=0;--w){const S=o[w];y+=(b%S+s[w][0])*f[w],b=Math.floor(b/S)}d[g]=u[y]}return new Ut(this.type,d,r)}permute(...t){return dO(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,r=!1){return this.norm(1,t,r)}norm(t="fro",r=null,s=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);const o=this.data,l=o instanceof BigInt64Array||o instanceof BigUint64Array;if(l&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let u,d;if(l?(u=(y,w)=>y+w,d=0n):(u=(y,w)=>y+w**t,d=0),r===null){let y=o.reduce(u,d);return t!==1&&(y=y**(1/t)),new Ut(this.type,[y],[])}const[f,p,g]=gu(u,this,r,s);if(t!==1)for(let y=0;y=0;--f){const y=this.dims[f];if(f!==r){const w=p%y;d+=w*g,g*=this.dims[f]}p=Math.floor(p/y)}o[u]/=l[d]}return this}normalize(t=2,r=1){return this.clone().normalize_(t,r)}stride(){return Wm(this.dims)}squeeze(t=null){return new Ut(this.type,this.data,e1(this.dims,t))}squeeze_(t=null){return this.dims=e1(this.dims,t),this}unsqueeze(t){return new Ut(this.type,this.data,t1(this.dims,t))}unsqueeze_(t){return this.dims=t1(this.dims,t),this}flatten_(t=0,r=-1){r=(r+this.dims.length)%this.dims.length;let s=this.dims.slice(0,t),o=this.dims.slice(t,r+1),l=this.dims.slice(r+1);return this.dims=[...s,o.reduce((u,d)=>u*d,1),...l],this}flatten(t=0,r=-1){return this.clone().flatten_(t,r)}view(...t){let r=-1;for(let o=0;od!==r?l*u:l,1);t[r]=s.length/o}return new Ut(this.type,s,t)}neg_(){const t=this.data;for(let r=0;rt?1:0;return new Ut("bool",r,this.dims)}lt(t){const r=new Uint8Array(this.data.length),s=this.data;for(let o=0;oMath.min(u,d),this,t,r,1/0);return new Ut(s,o,l)}max(t=null,r=!1){if(t===null){const u=Ht(this.data)[0];return new Ut(this.type,[u],[])}const[s,o,l]=gu((u,d)=>Math.max(u,d),this,t,r,-1/0);return new Ut(s,o,l)}argmin(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const s=f_(this.data)[1];return new Ut("int64",[BigInt(s)],[])}argmax(t=null,r=!1){if(t!==null)throw new Error("`dim !== null` not yet implemented.");const s=Ht(this.data)[1];return new Ut("int64",[BigInt(s)],[])}repeat(...t){if(t.lengthg===1)){if(t.length===this.dims.length)return this.clone();const g=t.length-this.dims.length,y=Array(g).fill(1).concat(this.dims);return new Ut(this.type,this.data.slice(),y)}const r=t.length-this.dims.length,s=Array(r).fill(1).concat(this.dims),o=s.map((g,y)=>g*t[y]),l=o.reduce((g,y)=>g*y,1),u=this.data,d=new u.constructor(l),f=Wm(s),p=Wm(o);for(let g=0;gBigInt(Math.floor(l)):r=BigInt;else if(this.type==="float16"&&t=="float32"&&this.data instanceof Uint16Array)return new Ut(t,J3(this.data),this.dims);return new Ut(t,Sl[t].from(this.data,r),this.dims)}};function uO(e,t){const r=e.length,s=t.reduce((l,u)=>l*u);if(r!==s)throw Error(`cannot reshape array of size ${r} into shape (${t})`);let o=e;for(let l=t.length-1;l>=0;l--)o=o.reduce((u,d)=>{let f=u[u.length-1];return f.lengthnew me("int64",e,[e.length]);async function tx(e,t,r,s,o){return await(await xl.slice)({x:e,s:wf(t),e:wf(r),a:wf(s),t:wf(new Array(s.length).fill(1))})}function hO(e,t){const r=e.data,s=t.data,o=[e.dims[0],e.dims[2]],l=new r.constructor(o[0]*o[1]),[u,d,f]=e.dims;let p=0;for(let g=0;gr!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((r,s)=>r!==1||!t.includes(s))),e}function t1(e,t){return t=xr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function xr(e,t,r=null,s=!0){if(e<-t||e>=t){if(s)throw new Error(`IndexError: index ${e} is out of bounds for dimension${r===null?"":" "+r} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function zt(e,t=0){t=xr(t,e[0].dims.length);const r=e[0].dims.slice();r[t]=e.reduce((u,d)=>u+d.dims[t],0);const s=r.reduce((u,d)=>u*d,1),o=new e[0].data.constructor(s),l=e[0].type;if(t===0){let u=0;for(const d of e){const f=d.data;o.set(f,u),u+=f.length}}else{let u=0;for(let d=0;d=0;--w){const E=p[w];let z=b%E;w===t&&(z+=u),y+=z*S,S*=r[w],b=Math.floor(b/E)}o[y]=f[g]}u+=p[t]}}return new me(l,o,r)}function Ji(e,t=0){return zt(e.map(r=>r.unsqueeze(t)),t)}function gu(e,t,r,s=!1,o=null){const l=t.data,u=t.dims;r=xr(r,u.length);const d=u.slice();d[r]=1;const f=new l.constructor(l.length/u[r]);o!==null&&f.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)}f[g]=e(f[g],l[p],p,g)}return s||d.splice(r,1),[t.type,f,d]}function pO(e,t=null,r=1,s=!1){const o=e.data,l=e.dims;if(t===null){const b=o.reduce((k,L)=>k+L,0)/o.length,S=Math.sqrt(o.reduce((k,L)=>k+(L-b)**2,0)/(o.length-r)),E=new me(e.type,[b],[]);return[new me(e.type,[S],[]),E]}t=xr(t,l.length);const u=Z_(e,t,s),d=u.data,[f,p,g]=gu((w,b,S,E)=>w+(b-d[E])**2,e,t,s);for(let w=0;wp+g,0);return new me(e.type,[f/o.length],[])}t=xr(t,s.length);const[l,u,d]=gu((f,p)=>f+p,e,t,r);if(s[t]!==1)for(let f=0;f=0;--r)t[r]=s,s*=e[r];return t}function K_(e,t,r,s){const o=e.reduce((l,u)=>l*u,1);return new me(r,new s(o).fill(t),e)}function On(e,t){let r,s;if(typeof t=="number")r="float32",s=Float32Array;else if(typeof t=="bigint")r="int64",s=BigInt64Array;else if(typeof t=="boolean")r="bool",s=Uint8Array;else throw new Error(`Unsupported data type: ${typeof t}`);return K_(e,t,r,s)}function m_(e,t){return On(e.dims,t)}function ha(e){return K_(e,1n,"int64",BigInt64Array)}function nx(e){return ha(e.dims)}function ax(e){return K_(e,0n,"int64",BigInt64Array)}function rx(e){return ax(e.dims)}function mO(e){const t=e.reduce((r,s)=>r*s,1);return new me("float32",Float32Array.from({length:t},()=>W_.gauss()),e)}function _O(e,t){if(e.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(e.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(t))throw new Error("The precision must be either 'binary' or 'ubinary'");const r=t==="binary",s=r?"int8":"uint8",o=r?Int8Array:Uint8Array,l=e.data,u=new o(l.length/8);for(let d=0;d0?1:0,p=Math.floor(d/8),g=d%8;u[p]|=f<<7-g,r&&g===0&&(u[p]-=128)}return new me(s,u,[e.dims[0],e.dims[1]/8])}async function sx(e){if(!e)throw new Error("modelId is required for get_tokenizer_files");return(await Zf(e,"tokenizer_config.json",{})).exists?["tokenizer.json","tokenizer_config.json"]:[]}async function ix(e,t){const r=await sx(e);return await Promise.all(r.map(s=>ss(e,s,!0,t)))}function ox(e){const t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[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 ${t.length}.`)}}var gO=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function yO(e,t,r,s){for(const o of Object.keys(e)){const l=t-e[o].length,u=r(o),d=new Array(l).fill(u);e[o]=s==="right"?Sr(e[o],d):Sr(d,e[o])}}function vO(e,t){for(const r of Object.keys(e))e[r].length=t}function Ui(e,...t){for(const r of t){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 wO(e){const t=[];for(const r of e.get_added_tokens_decoder().values())r.special&&t.push(r);return t}var De=class extends Oa{return_token_type_ids=!1;padding_side="right";constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new Fk(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=Ui(t,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=Ui(t,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=Ui(t,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=Ui(t,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=Ui(t,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=Ui(t,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){const s=Object.create(null);for(const{name:o,template:l}of this.chat_template){if(typeof o!="string"||typeof l!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');s[o]=l}this.chat_template=s}this._compiled_template_cache=new Map;const r=wO(this._tokenizer);this.all_special_ids=r.map(s=>s.id),this.all_special_tokens=r.map(s=>s.content)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:o=!1,revision:l="main"}={}){const u=await ix(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:o,revision:l});return new this(...u)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e=="string"?this._tokenizer.token_to_id(e):e.map(t=>this._tokenizer.token_to_id(t))}_call(e,{text_pair:t=null,add_special_tokens:r=!0,padding:s=!1,truncation:o=null,max_length:l=null,return_tensor:u=!0,return_token_type_ids:d=null}={}){const f=Array.isArray(e);let p;if(f){if(e.length===0)throw Error("text array must be non-empty");if(t!==null){if(Array.isArray(t)){if(e.length!==t.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");p=e.map((y,w)=>this._encode_plus(y,{text_pair:t[w],add_special_tokens:r,return_token_type_ids:d}))}else p=e.map(y=>this._encode_plus(y,{add_special_tokens:r,return_token_type_ids:d}))}else{if(e==null)throw Error("text may not be null or undefined");if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");p=[this._encode_plus(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:d})]}if(l===null?l=this.model_max_length:o===null&&(s===!0?(Re.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),l=this.model_max_length):s===!1&&(Re.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),o=!0)),s===!0&&(l=Math.min(Ht(p.map(y=>y.input_ids.length))[0],l??1/0)),l=Math.min(l,this.model_max_length??1/0),s||o)for(let y=0;yl?o&&vO(p[y],l):s&&yO(p[y],l,w=>w==="input_ids"?this.pad_token_id:0,this.padding_side));const g={};if(u){if(!(s&&o)&&p.some(w=>{for(const b of Object.keys(w))if(w[b].length!==p[0][b]?.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 y=[p.length,p[0].input_ids.length];for(const w of Object.keys(p[0]))g[w]=new me("int64",BigInt64Array.from(p.flatMap(b=>b[w]).map(BigInt)),y)}else{for(const y of Object.keys(p[0]))g[y]=p.map(w=>w[y]);if(!f)for(const y of Object.keys(g))g[y]=g[y][0]}return g}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){const{ids:o,attention_mask:l,token_type_ids:u}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:s??this.return_token_type_ids});return{input_ids:o,attention_mask:l,...u?{token_type_ids:u}:{}}}tokenize(e,{pair:t=null,add_special_tokens:r=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:r})}encode(e,{text_pair:t=null,add_special_tokens:r=!0,return_token_type_ids:s=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:r,return_token_type_ids:s}).ids}batch_decode(e,t={}){return e instanceof me&&(e=e.tolist()),e.map(r=>this.decode(r,t))}decode(e,t={}){if(e instanceof me&&(e=ox(e)),!Array.isArray(e)||e.length===0||!wA(e[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:r=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:r})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const r=this.chat_template;if(e!==null&&Object.hasOwn(r,e))e=r[e];else if(e===null)if(t!==null&&"tool_use"in r)e=r.tool_use;else if("default"in r)e=r.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(r).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return e}apply_chat_template(e,{tools:t=null,documents:r=null,chat_template:s=null,add_generation_prompt:o=!1,tokenize:l=!0,padding:u=!1,truncation:d=!1,max_length:f=null,return_tensor:p=!0,return_dict:g=!0,tokenizer_kwargs:y={},...w}={}){if(s=this.get_chat_template({chat_template:s,tools:t}),typeof s!="string")throw Error(`chat_template must be a string, but got ${typeof s}`);let b=this._compiled_template_cache.get(s);b===void 0&&(b=new C3(s),this._compiled_template_cache.set(s,b));const S=Object.create(null);for(const z of gO){const k=Ui(this.config,z);k&&(S[z]=k)}const E=b.render({messages:e,add_generation_prompt:o,tools:t,documents:r,...S,...w});if(l){const z=this._call(E,{add_special_tokens:!1,padding:u,truncation:d,max_length:f,return_tensor:p,...y});return g?z:z.input_ids}return E}};function J_(e,t,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,l=s.tgt_lang;if(!e.language_codes.includes(l))throw new Error(`Target language code "${l}" 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(l)),e._call(t,r)}var lx={};Al(lx,{AlbertTokenizer:()=>bO,AutoTokenizer:()=>yt,BartTokenizer:()=>MO,BertTokenizer:()=>xO,BlenderbotSmallTokenizer:()=>TO,BlenderbotTokenizer:()=>SO,BloomTokenizer:()=>EO,CLIPTokenizer:()=>CO,CamembertTokenizer:()=>AO,CodeGenTokenizer:()=>OO,CodeLlamaTokenizer:()=>kO,CohereTokenizer:()=>zO,ConvBertTokenizer:()=>LO,DebertaTokenizer:()=>NO,DebertaV2Tokenizer:()=>FO,DistilBertTokenizer:()=>DO,ElectraTokenizer:()=>RO,EsmTokenizer:()=>BO,FalconTokenizer:()=>PO,GPT2Tokenizer:()=>GO,GPTNeoXTokenizer:()=>UO,GemmaTokenizer:()=>IO,HerbertTokenizer:()=>jO,LlamaTokenizer:()=>VO,M2M100Tokenizer:()=>qO,MBart50Tokenizer:()=>$O,MBartTokenizer:()=>cx,MPNetTokenizer:()=>YO,MarianTokenizer:()=>HO,MgpstrTokenizer:()=>QO,MobileBertTokenizer:()=>WO,NllbTokenizer:()=>XO,NougatTokenizer:()=>ZO,PreTrainedTokenizer:()=>De,Qwen2Tokenizer:()=>KO,RoFormerTokenizer:()=>ez,RobertaTokenizer:()=>JO,SiglipTokenizer:()=>tz,SpeechT5Tokenizer:()=>nz,SqueezeBertTokenizer:()=>az,T5Tokenizer:()=>rz,TokenizersBackend:()=>De,VitsTokenizer:()=>iz,Wav2Vec2CTCTokenizer:()=>oz,WhisperTokenizer:()=>dz,XLMRobertaTokenizer:()=>fz,XLMTokenizer:()=>hz});var bO=class extends De{return_token_type_ids=!0},MO=class extends De{},xO=class extends De{return_token_type_ids=!0},TO=class extends De{},SO=class extends De{},EO=class extends De{},AO=class extends De{},CO=class extends De{},kO=class extends De{},OO=class extends De{},zO=class extends De{},LO=class extends De{return_token_type_ids=!0},FO=class extends De{return_token_type_ids=!0},NO=class extends De{return_token_type_ids=!0},DO=class extends De{},RO=class extends De{return_token_type_ids=!0},BO=class extends De{},PO=class extends De{},IO=class extends De{},UO=class extends De{},GO=class extends De{},jO=class extends De{return_token_type_ids=!0},VO=class extends De{padding_side="left"},qO=class extends De{constructor(e,t){super(e,t),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,t,r){return J_(this,e,t,r)}},HO=class extends De{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(r=>this.languageRegex.test(r)),Re.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[t,...r]=e.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(t);if(r.length===2){const[s,o]=r;return this.supported_language_codes.includes(s)||Re.warn(`Unsupported language code "${s}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),Sr([s],super._encode_text(o))}}},cx=class extends De{constructor(e,t){super(e,t),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,t,r){return J_(this,e,t,r)}},$O=class extends cx{},QO=class extends De{},WO=class extends De{return_token_type_ids=!0},YO=class extends De{},XO=class extends De{constructor(e,t){super(e,t),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,t,r){return J_(this,e,t,r)}},ZO=class extends De{},KO=class extends De{},JO=class extends De{},ez=class extends De{return_token_type_ids=!0},tz=class extends De{},nz=class extends De{},az=class extends De{return_token_type_ids=!0},rz=class extends De{},sz=class extends Ka{decode_chain(e){let t="";for(let r=1;r[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function cz(e){e=e.toLowerCase();let t=lz.get(e);if(t===void 0){const r=e.match(/^<\|([a-z]{2})\|>$/);if(r&&(e=r[1]),Cf.has(e))t=e;else{const o=e.length===2?Cf.keys():Cf.values();throw new Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(o))}`)}}return t}var uz="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",n1=new RegExp(`^[${uz}]+$`,"gu"),dz=class extends De{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(e,{return_timestamps:t=!1,return_language:r=!1,time_precision:s=null,force_full_sequences:o=!0}={}){if(s===null)throw Error("Must specify time_precision");let l=null;const u=t==="word";function d(){return{language:l,timestamp:[null,null],text:""}}const f=[];let p=d(),g=0;const y=this.timestamp_begin,b=y+1500;let S=[],E=[],z=!1,k=null;const L=new Set(this.all_special_ids);for(const B of e){const j=B.tokens,C=u?B.token_timestamps:null;let ue=null,oe=y;if("stride"in B){const[de,re,W]=B.stride;if(g-=re,k=de-W,re&&(oe=re/s+y),W)for(let pe=j.length-1;pe>=0;--pe){const V=Number(j[pe]);if(V>=y){if(ue!==null&&(V-y)*s=y&&re<=b){const W=(re-y)*s+g,pe=mu(W,2);if(ue!==null&&re>=ue)z=!0;else if(z||S.length>0&&re0?(S.push(he),u&&E.push(_e)):S.every(de=>de.length===0)&&(p=d(),S=[],he=[],E=[],_e=[])}if(S.length>0){if(o&&t)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[B,j]=this.findLongestCommonSequence(S,E),C=this.decode(B);p.text=C,u&&(p.words=this.collateWordTimestamps(B,j,l)),f.push(p)}let R=Object.create(null);const N=f.map(B=>B.text).join("");if(t||r){for(let B=0;B0;let u=l?[]:null,d=l?t[0]:null;for(let f=1;fre===oe[W]&&d[N+W]<=t[f][C+W]).length:he=j.filter((re,W)=>re===oe[W]).length;const _e=R/1e4,de=he/R+_e;he>1&&de>g&&(g=de,y=[N,B,C,ue])}const[b,S,E,z]=y,k=Math.floor((S+b)/2),L=Math.floor((z+E)/2);o.push(...r.slice(0,k)),r=p.slice(L),s=r.length,l&&(u.push(...d.slice(0,k)),d=t[f].slice(L))}return o.push(...r),l?(u.push(...d),[o,u]):[o,[]]}collateWordTimestamps(e,t,r){const[s,o,l]=this.combineTokensIntoWords(e,r),u=[];for(let d=0;d=s){const u=((l-s)*r).toFixed(2);o.push(`<|${u}|>`),o.push([])}else o[o.length-1].push(l);return o=o.map(l=>typeof l=="string"?l:super.decode(l,t)),o.join("")}splitTokensOnUnicode(e){const t=this.decode(e,{decode_with_timestamps:!0}),r="�",s=[],o=[],l=[];let u=[],d=[],f=0;for(let p=0;p=this._tokenizer.token_to_id("<|endoftext|>"),w=f.startsWith(" "),b=f.trim(),S=n1.test(b);if(y||w||S||o.length===0)o.push(f),l.push(p),u.push(g);else{const E=o.length-1;o[E]+=f,l[E].push(...p),u[E].push(...g)}}return[o,l,u]}mergePunctuations(e,t,r,s,o){const l=structuredClone(e),u=structuredClone(t),d=structuredClone(r);let f=l.length-2,p=l.length-1;for(;f>=0;)l[f].startsWith(" ")&&s.includes(l[f].trim())?(l[p]=l[f]+l[p],u[p]=Sr(u[f],u[p]),d[p]=Sr(d[f],d[p]),l[f]="",u[f]=[],d[f]=[]):p=f,--f;for(f=0,p=1;pg),u.filter(g=>g.length>0),d.filter(g=>g.length>0)]}},fz=class extends De{},hz=class extends De{return_token_type_ids=!0;constructor(e,t){super(e,t),Re.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},yt=class{static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:o=!1,revision:l="main"}={}){const[u,d]=await ix(e,{progress_callback:t,config:r,cache_dir:s,local_files_only:o,revision:l}),f=d.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let p=lx[f];return p||(Re.warn(`Unknown tokenizer class "${f}", attempting to construct from base class.`),p=De),new p(u,d)}},Kf="https://github.com/huggingface/transformers.js/issues/new/choose",eg="preprocessor_config.json",Mu=eg,pz="processor_config.json",mz="chat_template.jinja",bt=class extends Oa{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,r){super(),this.config=e,this.components=t,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,t={}){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,...t})}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,...t){for(const r of[this.image_processor,this.feature_extractor,this.tokenizer])if(r)return r(e,...t);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(e,t={}){const[r,s,o]=await Promise.all([this.uses_processor_config?ss(e,pz,!0,t):{},Promise.all(this.classes.filter(l=>l in this).map(async l=>{const u=await this[l].from_pretrained(e,t);return[l.replace(/_class$/,""),u]})).then(Object.fromEntries),this.uses_chat_template_file?VM(e,mz,!0,t):null]);return new this(r,s,o)}},__={};Al(__,{ChatterboxProcessor:()=>qz,Florence2Processor:()=>GL,Gemma3nProcessor:()=>jL,GraniteSpeechProcessor:()=>VL,GroundingDinoProcessor:()=>HL,Idefics3Processor:()=>l1,JinaCLIPProcessor:()=>XL,Lfm2VlProcessor:()=>ZL,LlavaProcessor:()=>KL,MgpstrProcessor:()=>JL,MoonshineProcessor:()=>eF,OwlViTProcessor:()=>tF,PaliGemmaProcessor:()=>aF,Phi3VProcessor:()=>sF,PixtralProcessor:()=>iF,Processor:()=>bt,PyAnnoteProcessor:()=>oF,Qwen2VLProcessor:()=>Bx,Qwen2_5_VLProcessor:()=>Px,Qwen3VLProcessor:()=>lF,Sam2Processor:()=>Ux,Sam2VideoProcessor:()=>cF,SamProcessor:()=>Ix,SmolVLMProcessor:()=>l1,SpeechT5Processor:()=>uF,UltravoxProcessor:()=>dF,VLChatProcessor:()=>YL,VoxtralProcessor:()=>mF,VoxtralRealtimeProcessor:()=>yF,Wav2Vec2Processor:()=>vF,Wav2Vec2ProcessorWithLM:()=>wF,WhisperProcessor:()=>bF});var zn=class extends Oa{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){const r=await ss(e,eg,!0,t);return new this(r)}};function qn(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw new Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var tg={};Al(tg,{ASTFeatureExtractor:()=>kz,ChatterboxFeatureExtractor:()=>Oz,ClapFeatureExtractor:()=>zz,DacFeatureExtractor:()=>mx,EncodecFeatureExtractor:()=>px,FeatureExtractor:()=>zn,Gemma3nAudioFeatureExtractor:()=>Lz,GraniteSpeechFeatureExtractor:()=>Fz,MoonshineFeatureExtractor:()=>Nz,ParakeetFeatureExtractor:()=>Rz,PyAnnoteFeatureExtractor:()=>_x,SeamlessM4TFeatureExtractor:()=>Bz,SnacFeatureExtractor:()=>Pz,SpeechT5FeatureExtractor:()=>Iz,VoxtralRealtimeFeatureExtractor:()=>jz,Wav2Vec2FeatureExtractor:()=>Uz,WeSpeakerFeatureExtractor:()=>Gz,WhisperFeatureExtractor:()=>Vz});var _z=()=>{},gz=_z;async function dx(e,t){if(We.IS_BROWSER_ENV){if(We.IS_WEBWORKER_ENV)throw new Error("Unable to save a file from a Web Worker.");const r=URL.createObjectURL(t),s=document.createElement("a");s.href=r,s.download=e,s.click(),s.remove(),URL.revokeObjectURL(r)}else if(We.IS_FS_AVAILABLE)t.stream(),fa.createWriteStream(e),await gz();else throw new Error("Unable to save because filesystem is disabled in this environment.")}async function yz(e,t){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 bu(e)).arrayBuffer(),s=new AudioContext({sampleRate:t});typeof t>"u"&&Re.warn(`No sampling rate provided, using default of ${s.sampleRate}Hz.`);const o=await s.decodeAudioData(r);let l;if(o.numberOfChannels===2){const u=Math.sqrt(2),d=o.getChannelData(0),f=o.getChannelData(1);l=new Float32Array(d.length);for(let p=0;p2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,r=15,s=27/Math.log(6.4))=>e>=t?r+Math.log(e/t)*s:3*e/200};function Ym(e,t="htk"){const r=wz[t];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 bz={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,r=15,s=Math.log(6.4)/27)=>e>=r?t*Math.exp(s*(e-r)):200*e/3};function Mz(e,t="htk"){const r=bz[t];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 xz(e,t){const r=Float64Array.from({length:t.length-1},(u,d)=>t[d+1]-t[d]),s=Array.from({length:e.length},()=>new Array(t.length));for(let u=0;unew Array(e.length));for(let u=0;ue+s*l)}function Er(e,t,r,s,o,l=null,u="htk",d=!1){if(l!==null&&l!=="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 f=Ym(r,u),p=Ym(s,u),g=r1(f,p,t+2);let y=Mz(g,u),w;if(d){const S=o/((e-1)*2);w=Ym(Float64Array.from({length:e},(E,z)=>z*S),u),y=g}else w=r1(0,Math.floor(o/2),e);const b=xz(w,y);if(l!==null&&l==="slaney")for(let S=0;So)throw Error(`frame_length (${r}) may not be larger than fft_length (${o})`);if(ue!==r)throw new Error(`Length of the window (${ue}) must equal frame_length (${r})`);if(s<=0)throw new Error("hop_length must be greater than zero");if(l===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 J=Math.floor((o-1)/2)+1;e=Tz(e,J,J);break}case"constant":{const J=Math.floor(o/2),D=new e.constructor(e.length+2*J);D.set(e,J),e=D;break}default:throw new Error(`pad_mode="${d}" not implemented yet.`)}let oe=Math.floor(1+Math.floor((e.length-r)/s));R!==null&&oeoe?B&&(de=N):de=_e=N);const re=new Y3(o),W=new Float64Array(o),pe=new Float64Array(re.outputBufferSize),V=new Float32Array(he*de);for(let J=0;J<_e;++J){const D=J*s,te=Math.min(e.length-D,r);te!==r&&W.fill(0,0,r);for(let ae=0;ae=1;--ae)W[ae]-=p*W[ae-1];W[0]*=1-p}for(let ae=0;aeMath.pow(d,.85));break;default:throw new Error(`Unknown window type ${t}.`)}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 Az(e,t){const r=e.reduce((l,u)=>l+u.length,0),s=new ArrayBuffer(44),o=new DataView(s);return bf(o,0,"RIFF"),o.setUint32(4,36+r*4,!0),bf(o,8,"WAVE"),bf(o,12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,3,!0),o.setUint16(22,1,!0),o.setUint32(24,t,!0),o.setUint32(28,t*4,!0),o.setUint16(32,4,!0),o.setUint16(34,32,!0),bf(o,36,"data"),o.setUint32(40,r*4,!0),new Blob([s,...e.map(l=>l.buffer)],{type:"audio/wav"})}function bf(e,t,r){for(let s=0;ss+o.length,0),t=new Float32Array(e);let r=0;for(const s of this.audio)t.set(s,r),r+=s.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),Az(e,this.sampling_rate)}async save(e){return dx(e,this.toBlob())}},kz=class extends zn{constructor(e){super(e);const t=this.config.sampling_rate,r=Er(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=os(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return is(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){qn(e,"ASTFeatureExtractor");const t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){const r=this.std*2,s=t.data;for(let o=0;o0)if(r==="rand_trunc"){const u=Math.floor(W_.random()*(l+1));e=e.subarray(u,u+t),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(l<0){let u=new Float64Array(t);if(u.set(e),s==="repeat")for(let d=e.length;dt&&(e=e.slice(0,t)),s&&e.length%o!==0){const d=o-e.length%o,f=new Float64Array(e.length+d);f.set(e),this.config.padding_value!==0&&f.fill(this.config.padding_value,e.length),e=f}const l=await this._extract_fbank_features(e,this.config.max_length),u=On([1,l.dims[0]],!0);return{input_features:l.unsqueeze_(0),input_features_mask:u}}},Fz=class extends zn{constructor(e){super(e);const{n_fft:t,win_length:r,n_mels:s,sample_rate:o}=e.melspec_kwargs;this.mel_filters=Er(Math.floor(1+t/2),s,0,o/2,o,null,"htk");const l=os(r,"hann");this.window=new Float64Array(t);const u=Math.floor((t-r)/2);this.window.set(l,u)}async _call(e){qn(e,"GraniteSpeechFeatureExtractor");const{n_fft:t,hop_length:r,n_mels:s}=this.config.melspec_kwargs,o=1+Math.floor((e.length-1)/r),l=o-o%2;return{input_features:(await is(e,this.window,t,r,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:l,do_pad:!1})).view(-1,2*s).unsqueeze_(0)}}},Nz=class extends zn{async _call(e){qn(e,"MoonshineFeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));const t=[1,e.length];return{input_values:new me("float32",e,t)}}},Dz=1e-5,Rz=class extends zn{constructor(e){super(e),this.config.mel_filters??=Er(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 t=os(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(t,r)}async _extract_fbank_features(e){const t=this.config.preemphasis;e=new Float64Array(e);for(let s=e.length-1;s>=1;--s)e[s]-=t*e[s-1];return await is(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){qn(e,"ParakeetFeatureExtractor");const t=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=t.data;s.fill(0,r*t.dims[1]);const[o,l]=t.dims,u=new Float64Array(l),d=new Float64Array(l);for(let g=0;g1?r-1:1;for(let g=0;g({id:d,start:f*r,end:p*r,confidence:g/(p-f)})))}return s}},Bz=class extends zn{constructor(e){super(e);const t=this.config.sampling_rate,r=Er(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=os(400,"povey",{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(r=>r*32768),is(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:r=2,do_normalize_per_mel_bins:s=!0,return_attention_mask:o=!0}={}){qn(e,"SeamlessM4TFeatureExtractor");let l=await this._extract_fbank_features(e,this.config.max_length);if(s){const[b,S]=l.dims,E=l.data;for(let z=0;z0){const k=new Float32Array(S*(b+z));k.set(E),k.fill(this.config.padding_value,E.length);const L=b+z;l=new me(l.type,k,[L,S]),o&&(u=new me("int64",new BigInt64Array(L),[1,L]),u.data.fill(1n,0,b))}}const[d,f]=l.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=l.view(1,Math.floor(d/p),f*p),w={input_features:y};if(o){const b=y.dims[1],S=new BigInt64Array(b);if(u){const E=u.data;for(let z=1,k=0;zo+l,0)/e.length,s=e.reduce((o,l)=>o+(l-r)**2,0)/e.length;return e.map(o=>(o-r)/Math.sqrt(s+1e-7))}async _call(e){qn(e,"Wav2Vec2FeatureExtractor"),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));const r=[1,t.length];return{input_values:new me("float32",t,r),attention_mask:new me("int64",new BigInt64Array(t.length).fill(1n),r)}}},Gz=class extends zn{constructor(e){super(e);const t=this.config.sampling_rate,r=Er(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,"kaldi",!0);this.mel_filters=r,this.window=os(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(t=>t*32768),is(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){qn(e,"WeSpeakerFeatureExtractor");const t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const r=t.mean(1).data,s=t.data,[o,l,u]=t.dims;for(let d=0;ds?(e.length>this.config.n_samples&&Re.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)}}},er=class{static async from_pretrained(e,t={}){const r=await ss(e,eg,!0,t),s=r.feature_extractor_type,o=tg[s];if(!o)throw new Error(`Unknown feature_extractor_type: '${s}'. Please report this at ${Kf}.`);return new o(r)}},qz=class extends bt{static tokenizer_class=yt;static feature_extractor_class=er;async _call(e,t=null){const r=this.tokenizer(e),s=t?await this.feature_extractor(t):{};return{...r,...s}}},g_={},ji,gx,Xs;if(We.IS_WEB_ENV)ji=(e,t)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(e,t)},Xs=self.createImageBitmap,gx=self.ImageData;else if(g_)Xs=async e=>{const r=(await e.metadata()).channels,{data:s,info:o}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),l=new Xa(new Uint8ClampedArray(s),o.width,o.height,o.channels);return r!==void 0&&r!==o.channels&&l.convert(r),l};else throw new Error("Unable to load image processing library.");var Hz={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},$z=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),Xa=class Mr{constructor(t,r,s,o){this.data=t,this.width=r,this.height=s,this.channels=o}get size(){return[this.width,this.height]}static async read(t){if(t instanceof Mr)return t;if(typeof t=="string"||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw new Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!We.IS_WEB_ENV)throw new Error("fromCanvas() is only supported in browser environments.");const s=t.getContext("2d").getImageData(0,0,t.width,t.height).data;return new Mr(s,t.width,t.height,4)}static async fromURL(t){const r=await bu(t);if(r.status!==200)throw new Error(`Unable to read image from "${t}" (${r.status} ${r.statusText})`);const s=await r.blob();return this.fromBlob(s)}static async fromBlob(t){if(We.IS_WEB_ENV){const r=await Xs(t),s=ji(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 t.arrayBuffer());return await Xs(r)}}static fromTensor(t,r="CHW"){if(t.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(r==="CHW")t=t.transpose(1,2,0);else if(r!=="HWC")throw new Error(`Unsupported channel format: ${r}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new Mr(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw new Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const t=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let r=0,s=0;r=0?f=s:g=-s,o>=0?p=o:y=-o,d.drawImage(u,f,p,t,r,g,y,t,r),new Mr(d.getImageData(0,0,t,r).data,t,r,4).convert(l)}else{let l=this.toSharp();if(s>=0&&o>=0)l=l.extract({left:Math.floor(s),top:Math.floor(o),width:t,height:r});else if(s<=0&&o<=0){const u=Math.floor(-o),d=Math.floor(-s);l=l.extend({top:u,left:d,right:t-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 f=[0,0],p=0;s<0?(f[0]=Math.floor(-s),f[1]=t-this.width-f[0]):p=Math.floor(s),l=l.extend({top:u[0],bottom:u[1],left:f[0],right:f[1]}).extract({left:p,top:d,width:t,height:r})}return await Xs(l)}}async toBlob(t="image/png",r=1){if(!We.IS_WEB_ENV)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:t,quality:r})}toTensor(t="CHW"){let r=new me("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(t!=="HWC")if(t==="CHW")r=r.permute(2,0,1);else throw new Error(`Unsupported channel format: ${t}`);return r}toCanvas(){if(!We.IS_WEB_ENV)throw new Error("toCanvas() is only supported in browser environments.");const t=this.clone().rgba(),r=ji(t.width,t.height),s=new gx(t.data,t.width,t.height);return r.getContext("2d").putImageData(s,0,0),r}split(){const{data:t,width:r,height:s,channels:o}=this,l=t.constructor,u=t.length/o,d=Array.from({length:o},()=>new l(u));for(let f=0;fnew Mr(f,r,s,1))}_update(t,r,s,o=null){return this.data=t,this.width=r,this.height=s,o!==null&&(this.channels=o),this}clone(){return new Mr(this.data.slice(),this.width,this.height,this.channels)}convert(t){if(this.channels===t)return this;switch(t){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(t){if(We.IS_WEB_ENV){if(We.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const r=t.split(".").pop().toLowerCase(),s=$z.get(r)??"image/png",o=await this.toBlob(s);return dx(t,o)}else if(We.IS_FS_AVAILABLE)await this.toSharp().toFile(t);else throw new Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(We.IS_WEB_ENV)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}})}};Xa.read.bind(Xa);function s1(e,t,r=0,s=null){const o=e/t;let l=Z3(o)*t;return s!==null&&l>s&&(l=Math.floor(o)*t),lt&&k.push(R)}else{let R=Ht(z.data)[1];if(R===f-1||(L=wn(z.data),L[R]B*y[(j+1)%2])),w.boxes.push(N),w.classes.push(R),w.scores.push(L[R])}}p.push(w)}return p}function vx(e,t=null){const r=e.logits,s=r.dims[0];if(t!==null&&t.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 l=0;ly[k]&&(y[k]=z[k],w[k]=E)}const b=new Array(d.dims[0]);for(let E=0;EE!==void 0);o.push({segmentation:g,labels:S})}return o}function Qz(e,t,r,s){const o=[],l=[],u=[];for(let d=0;dr&&(o.push(p),l.push(w),u.push(g))}return[o,l,u]}function Wz(e,t,r,s=.5,o=.8){const l=[];let u=0,d=0;const f=t[r].data;for(let g=0;g=s&&++d;let p=u>0&&d>0;return p&&(p=u/d>o),[p,l]}function Yz(e,t,r,s,o,l=null,u=null){const[d,f]=u??e[0].dims,p=new me("int32",new Int32Array(d*f),[d,f]),g=[];if(u!==null)for(let E=0;Ew[L]&&(y[L]=E,w[L]=k[L])}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,t)/Math.min(e,t)}`);let l=Math.round(e/r)*r,u=Math.round(t/r)*r;if(l*u>o){const d=Math.sqrt(e*t/o);l=Math.floor(e/d/r)*r,u=Math.floor(t/d/r)*r}else if(l*uo?f=Math.floor(o*d/s):o>s&&(d=Math.floor(s*f/o)),await e.resize(f,d,{resample:r}))}async crop_margin(e,t=200){const r=e.clone().grayscale(),s=f_(r.data)[0],l=Ht(r.data)[0]-s;if(l===0)return e;const u=t/255;let d=r.width,f=r.height,p=0,g=0;const y=r.data;for(let w=0;wthis.preprocess(o)));return{pixel_values:Ji(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,t={}){const r=await ss(e,Mu,!0,t);return new this(r)}},Gf={};Al(Gf,{BeitFeatureExtractor:()=>Xz,BitImageProcessor:()=>Zz,CLIPFeatureExtractor:()=>Jz,CLIPImageProcessor:()=>xx,ChineseCLIPFeatureExtractor:()=>Kz,ConvNextFeatureExtractor:()=>eL,ConvNextImageProcessor:()=>Tx,DINOv3ViTImageProcessor:()=>aL,DPTFeatureExtractor:()=>sL,DPTImageProcessor:()=>Ax,DeiTFeatureExtractor:()=>tL,DeiTImageProcessor:()=>Sx,DetrFeatureExtractor:()=>nL,DetrImageProcessor:()=>Ex,DonutFeatureExtractor:()=>rL,DonutImageProcessor:()=>ng,EfficientNetImageProcessor:()=>iL,GLPNFeatureExtractor:()=>oL,GroundingDinoImageProcessor:()=>lL,Idefics3ImageProcessor:()=>i1,ImageFeatureExtractor:()=>Ve,ImageProcessor:()=>Ve,JinaCLIPImageProcessor:()=>uL,Lfm2VlImageProcessor:()=>mL,LlavaOnevisionImageProcessor:()=>_L,Mask2FormerImageProcessor:()=>yL,MaskFormerFeatureExtractor:()=>gL,MaskFormerImageProcessor:()=>ag,MobileNetV1FeatureExtractor:()=>vL,MobileNetV1ImageProcessor:()=>Cx,MobileNetV2FeatureExtractor:()=>wL,MobileNetV2ImageProcessor:()=>kx,MobileNetV3FeatureExtractor:()=>bL,MobileNetV3ImageProcessor:()=>Ox,MobileNetV4FeatureExtractor:()=>ML,MobileNetV4ImageProcessor:()=>zx,MobileViTFeatureExtractor:()=>xL,MobileViTImageProcessor:()=>Lx,NougatImageProcessor:()=>TL,OwlViTFeatureExtractor:()=>SL,OwlViTImageProcessor:()=>rg,Owlv2ImageProcessor:()=>EL,Phi3VImageProcessor:()=>CL,PixtralImageProcessor:()=>kL,PvtImageProcessor:()=>OL,Qwen2VLImageProcessor:()=>zL,RTDetrImageProcessor:()=>LL,Sam2ImageProcessor:()=>Jm,Sam3ImageProcessor:()=>Jm,SamImageProcessor:()=>Jm,SapiensFeatureExtractor:()=>FL,SapiensImageProcessor:()=>Fx,SegformerFeatureExtractor:()=>NL,SegformerImageProcessor:()=>Nx,SiglipImageProcessor:()=>DL,SmolVLMImageProcessor:()=>i1,Swin2SRImageProcessor:()=>RL,VLMImageProcessor:()=>cL,ViTFeatureExtractor:()=>BL,ViTImageProcessor:()=>Dx,VitMatteImageProcessor:()=>PL,VitPoseImageProcessor:()=>IL,YolosFeatureExtractor:()=>UL,YolosImageProcessor:()=>Rx});var Xz=class extends Ve{},Zz=class extends Ve{},Kz=class extends Ve{},xx=class extends Ve{},Jz=class extends xx{},Tx=class extends Ve{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){const t=this.size?.shortest_edge;if(t===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(t<384){const r=Math.floor(t/this.crop_pct),[s,o]=this.get_resize_output_image_size(e,{shortest_edge:r});e=await e.resize(s,o,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},eL=class extends Tx{},Sx=class extends Ve{},tL=class extends Sx{},Ex=class extends Ve{async _call(e){const t=await super._call(e),r=[t.pixel_values.dims[0],64,64],s=On(r,1n);return{...t,pixel_mask:s}}post_process_object_detection(...e){return Jf(...e)}post_process_panoptic_segmentation(...e){return bx(...e)}post_process_instance_segmentation(...e){return Mx(...e)}},nL=class extends Ex{},aL=class extends Ve{},ng=class extends Ve{pad_image(e,t,r,s={}){const[o,l,u]=t;let d=this.image_mean;Array.isArray(this.image_mean)||(d=new Array(u).fill(d));let f=this.image_std;Array.isArray(f)||(f=new Array(u).fill(d));const p=d.map((g,y)=>-g/f[y]);return super.pad_image(e,t,r,{center:!0,constant_values:p,...s})}},rL=class extends ng{},Ax=class extends Ve{},sL=class extends Ax{},iL=class extends Ve{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(t=>t*t))}},oL=class extends Ve{},lL=class extends Ve{async _call(e){const t=await super._call(e),r=t.pixel_values.dims,s=ha([r[0],r[2],r[3]]);return{...t,pixel_mask:s}}},i1=class extends Ve{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[r,s]=e.dims.slice(-2);const o=s/r;return s>=r?(s=Math.ceil(s/t)*t,r=Math.floor(s/o),r=Math.ceil(r/t)*t):(r=Math.ceil(r/t)*t,s=Math.floor(r*o),s=Math.ceil(s/t)*t),{height:r,width:s}}async _call(e,{do_image_splitting:t=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=[],l=[],u=[];const d=[],f=[];for(const z of s){let k=await Promise.all(z.map(N=>this.preprocess(N)));d.push(...k.map(N=>N.original_size)),f.push(...k.map(N=>N.reshaped_input_size)),k.forEach(N=>N.pixel_values.unsqueeze_(0));const{longest_edge:L}=this.max_image_size;let R;if(t??this.do_image_splitting){let N=new Array(k.length),B=new Array(k.length);R=await Promise.all(k.map(async(j,C)=>{const ue=this.get_resize_for_vision_encoder(j.pixel_values,L),oe=await Ya(j.pixel_values,{size:[ue.height,ue.width]}),{frames:he,num_splits_h:_e,num_splits_w:de}=await this.split_image(oe,this.max_image_size);return N[C]=_e,B[C]=de,zt(he,0)})),l.push(N),u.push(B)}else{const N=[L,L];R=await Promise.all(k.map(B=>Ya(B.pixel_values,{size:N}))),l.push(new Array(k.length).fill(0)),u.push(new Array(k.length).fill(0))}o.push(zt(R,0))}const p=o.length,[g,y,w,b]=o[0].dims;let S,E;if(p===1)S=o[0].unsqueeze_(0),E=On([p,g,w,b],!0);else{const z=Math.max(...o.map(R=>R.dims.at(0)));E=On([p,z,w,b],!0);const k=E.data,L=z*w*b;for(let R=0;Rr||u>s){d=Math.ceil(l/r),f=Math.ceil(u/s);const p=Math.ceil(l/d),g=Math.ceil(u/f);for(let b=0;bt*this.rescale_factor)}pad_image(e,t,r,s){return super.pad_image(e,t,r,{constant_values:this.constant_values,center:!0,...s})}},uL=class extends Ve{constructor(e){const{resize_mode:t,fill_color:r,interpolation:s,size:o,...l}=e,u=t==="squash"?{width:o,height:o}:t==="shortest"?{shortest_edge:o}:{longest_edge:o},d=s==="bicubic"?3:2;super({...l,size:u,resample:d,do_center_crop:!0,crop_size:o,do_normalize:!0})}};function o1(e,t){return Math.round(e/t)*t}function dL(e,t,r,s,o){let l=1/0,u=[1,1];const d=r*s;for(const f of t){const p=Math.abs(e-f[0]/f[1]);p.5*o*o*f[0]*f[1]&&(u=f)}return u}function fL(e,t){const r=[],s=new Set;for(let o=e;o<=t;++o)for(let l=1;l<=o;++l)for(let u=1;u<=o;++u){const d=l*u;if(d>=e&&d<=t){const f=l<<16|u;s.has(f)||(s.add(f),r.push([l,u]))}}return r.sort((o,l)=>o[0]*o[1]-l[0]*l[1])}function hL(e,t){const[r,s,o,l]=e.dims,u=Math.floor(o/t),d=Math.floor(l/t),f=t*t*s,p=e.data,g=new Float32Array(r*u*d*f),y=o*l;for(let w=0;wthis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){const r=fL(this.min_tiles,this.max_tiles),[s,o]=dL(t/e,r,t,e,this.tile_size);return{grid_width:s,grid_height:o,target_width:this.tile_size*s,target_height:this.tile_size*o}}async _call(e,{return_row_col_info:t=null}={}){let r;Array.isArray(e)?Array.isArray(e[0])?r=e:r=[e]:r=[[e]];const s=[],o=[],l=[],u=[],d=[],f=[];for(const g of r){const y=await Promise.all(g.map(w=>this.preprocess(w,{do_pad:!1})));for(const{pixel_values:w}of y){const[,b,S]=w.dims,E=w.unsqueeze_(0),z=this.encoder_patch_size*this.downsample_factor,k=z**2,[L,R]=wx(Math.max(z,b),Math.max(z,S),z,this.min_image_tokens*k,this.max_image_tokens*k).map(oe=>Math.max(z,oe));let N,B=1,j=1;const C=this._is_image_too_large(b,S),ue=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(C&&ue){const{grid_width:oe,grid_height:he,target_width:_e,target_height:de}=this._get_grid_layout(b,S);B=he,j=oe;const re=await Ya(E,{size:[de,_e]});N=[];for(let W=0;W(p-this.image_mean[g])/this.image_std[g]);return super.pad_image(e,t,{width:d,height:u},{center:!0,constant_values:f,...s})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||Km(t)%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),l=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 Ya(y,{size:[la,la],mode:"bicubic"});if(t>0){const E=[],z=Km(t),k=hl(b/z),L=hl(w/z);for(let N=0;Ny.map(w=>la*Zm(w/la))),p=new me("int64",f.flat(),[r,2]),g=f.map(([y,w])=>this.calc_num_image_tokens_from_image_size(w,y));return{pixel_values:d,original_sizes:o,reshaped_input_sizes:l,image_sizes:p,num_img_tokens:g}}},kL=class extends Ve{get_resize_output_image_size(e,t){const{longest_edge:r}=t;if(r===void 0)throw new Error("size must contain 'longest_edge'");const[s,o]=e.size,l=Math.max(s,o)/r;let u=s,d=o;l>1&&(u=Math.floor(s/l),d=Math.floor(o/l));const{patch_size:f,spatial_merge_size:p}=this.config;if(!p)throw new Error("config must contain 'spatial_merge_size'");const g=f*p,y=Math.floor((u-1)/g)+1,w=Math.floor((d-1)/g)+1;return[y*g,w*g]}},OL=class extends Ve{},zL=class extends Ve{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){const r=this.patch_size*this.merge_size;return wx(e.height,e.width,r,this.min_pixels,this.max_pixels)}async _call(e,...t){const{pixel_values:r,original_sizes:s,reshaped_input_sizes:o}=await super._call(e,...t);let l=r;const{temporal_patch_size:u,merge_size:d,patch_size:f}=this.config;l.dims[0]===1&&(l=zt(Array.from({length:u},()=>l),0));const p=l.dims[0]/u,g=l.dims[1],y=Math.floor(l.dims[2]/f),w=Math.floor(l.dims[3]/f),b=l.view(p,u,g,Math.floor(y/d),d,f,Math.floor(w/d),d,f).permute(0,3,6,4,7,2,1,5,8).view(p*y*w,g*u*f*f),S=new me("int64",[p,y,w],[1,3]);return{pixel_values:b,image_grid_thw:S,original_sizes:s,reshaped_input_sizes:o}}},LL=class extends Ve{post_process_object_detection(...e){return Jf(...e)}},Jm=class extends Ve{reshape_input_points(e,t,r,s=!1){e=structuredClone(e);let o=Sb(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 l=0;ls!==t.dims[o]))throw Error(`The first ${r.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new me("int64",e.flat(1/0).map(BigInt),r)}async _call(e,{input_points:t=null,input_labels:r=null,input_boxes:s=null}={}){const o=await super._call(e);if(t&&(o.input_points=this.reshape_input_points(t,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,t,r,{mask_threshold:s=0,binarize:o=!0,pad_size:l=null}={}){const u=[];l=l??this.pad_size??this.size;const d=[l.height,l.width];for(let f=0;fs&&(b[S]=1);y=new me("bool",b,y.dims)}u.push(y)}return u}generate_crop_boxes(e,t,{crop_n_layers:r=0,overlap_ratio:s=512/1500,points_per_crop:o=32,crop_n_points_downscale_factor:l=1}={}){}},Fx=class extends Ve{post_process_semantic_segmentation(...e){return vx(...e)}},FL=class extends Fx{},Nx=class extends Ve{post_process_semantic_segmentation(...e){return vx(...e)}},NL=class extends Nx{},DL=class extends Ve{},RL=class extends Ve{pad_image(e,t,r,s={}){const[o,l,u]=t;return super.pad_image(e,t,{width:l+(r-l%r)%r,height:o+(r-o%r)%r},{mode:"symmetric",center:!1,constant_values:-1,...s})}},Dx=class extends Ve{},BL=class extends Dx{},PL=class extends Ve{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const r=await Promise.all(e.map(l=>this.preprocess(l))),s=await Promise.all(t.map(l=>this.preprocess(l,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:Ji(r.map((l,u)=>zt([l.pixel_values,s[u].pixel_values],0)),0),original_sizes:r.map(l=>l.original_size),reshaped_input_sizes:r.map(l=>l.reshaped_input_size)}}},IL=class extends Ve{post_process_pose_estimation(e,t,{threshold:r=null}={}){const s=e.tolist(),[o,l,u,d]=e.dims,f=[];for(let p=0;p/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e=="string"&&(e=[e]);const t=[];for(const r of e)if(this.task_prompts_without_inputs.has(r))t.push(this.task_prompts_without_inputs.get(r));else{for(const[s,o]of this.task_prompts_with_input)if(r.includes(s)){t.push(o.replaceAll("{input}",r).replaceAll(s,""));break}t.length!==e.length&&t.push(r)}return t}post_process_generation(e,t,r){const s=this.tasks_answer_post_processing_type.get(t)??"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 l=s==="ocr"?"quad_boxes":"bboxes",u=e.matchAll(this.regexes[l]),d=[],f=[];for(const[p,g,...y]of u)d.push(g?g.trim():d.at(-1)??""),f.push(y.map((w,b)=>(Number(w)+.5)/this.size_per_bin*r[b%2]));o={labels:d,[l]:f};break;default:throw new Error(`Task "${t}" (of type "${s}") not yet implemented.`)}return{[t]:o}}async _call(e,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const s=await this.image_processor(e,r),o=t?this.tokenizer(this.construct_prompts(t),r):{};return{...s,...o}}},jL=class extends bt{static image_processor_class=Hn;static feature_extractor_class=er;static tokenizer_class=yt;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,r){super(e,t,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:l,eoa_token:u,image_token_id:d,boi_token:f,image_token:p,eoi_token:g}=this.tokenizer.config;this.audio_token_id=s,this.boa_token=o,this.audio_token=l;const y=l.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${o}${y}${u} + +`,this.image_token_id=d,this.boi_token=f,this.image_token=p;const w=p.repeat(this.image_seq_length);this.full_image_sequence=` + +${f}${w}${g} + +`}async _call(e,t=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 l;return t&&(l=await this.image_processor(t,s),e=e.map(d=>d.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,s),...l,...o}}},VL=class extends bt{static tokenizer_class=yt;static feature_extractor_class=er;static uses_processor_config=!0;_get_num_audio_features(e){const{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:r,projector_downsample_rate:s}=this.feature_extractor.config,o=Math.floor(r/s),l=Math.floor(e/t)+1,u=Math.floor(l/2);return Math.ceil(u/r)*o}async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){const{input_features:l}=await this.feature_extractor(t);s.input_features=l;const u=this._get_num_audio_features(t.length),d=new Uint8Array(u).fill(1);s.input_features_mask=new me("bool",d,[1,u]);const f=this.config.audio_token??"<|audio|>";if(!e.includes(f))throw new Error(`The input text does not contain the audio token ${f}.`);e=e.replaceAll(f,f.repeat(u))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}};function qL(e,t){const s=e.dims.at(-1)-1,o=e.tolist();o.fill(!1,0,1),o.fill(!1,s);const l=t.tolist();return o.map((u,d)=>u?d:null).filter(u=>u!==null).map(u=>l[u])}var HL=class extends bt{static tokenizer_class=yt;static image_processor_class=Hn;async _call(e,t,r={}){const s=e?await this.image_processor(e,r):{};return{...t?this.tokenizer(t,r):{},...s}}post_process_grounded_object_detection(e,t,{box_threshold:r=.25,text_threshold:s=.25,target_sizes:o=null}={}){const{logits:l,pred_boxes:u}=e,d=l.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 f=l.dims.at(1),p=l.sigmoid(),g=p.max(-1).tolist(),y=u.tolist().map(b=>b.map(S=>yx(S))),w=[];for(let b=0;bR.map((N,B)=>N*S[(B+1)%2])));const E=g[b],z=[],k=[],L=[];for(let R=0;R`+o.repeat(e);u+=` +`}return u+=` +${s}${l}`+o.repeat(e)+`${s}`,u}function QL(e,t,r,s){return`${t}${s}`+r.repeat(e)+`${t}`}function WL(e,t,r,s,o,l){return e===0&&t===0?QL(r,s,o,l):$L(r,e,t,s,o,l)}var l1=class extends bt{static image_processor_class=Hn;static tokenizer_class=yt;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(e,t=null,r={}){r.return_row_col_info??=!0;let s;t&&(s=await this.image_processor(t,r)),Array.isArray(e)||(e=[e]);const o=s.rows??[new Array(e.length).fill(0)],l=s.cols??[new Array(e.length).fill(0)],u=this.config.image_seq_len,d=[],f=[];for(let g=0;gWL(k,b[L],u,this.fake_image_token,this.image_token,this.global_img_token)),E=y.split(this.image_token);if(E.length===0)throw new Error("The image token should be present in the text.");let z=E[0];for(let k=0;kE.images).flatMap(E=>E.images).map(E=>Xa.read(E)));const s=this.tokenizer,o=s.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:r}),l=E=>s.encode(E,{add_special_tokens:!1}),u=o.split(this.image_tag),d=u.length-1;if(t.length!==d)throw new Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${d})`);const[f,p,g]=s.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let y=l(u[0]),w=new Array(y.length).fill(!1);for(let E=1;E0){const E=await this.image_processor(t);return E.pixel_values.unsqueeze_(0),{...S,...E}}return S}},XL=class extends bt{static tokenizer_class=yt;static image_processor_class=Hn;async _call(e=null,t=null,r={}){if(!e&&!t)throw new Error("Either text or images must be provided");const s=e?this.tokenizer(e,r):{},o=t?await this.image_processor(t,r):{};return{...s,...o}}},ZL=class extends bt{static tokenizer_class=yt;static image_processor_class=Hn;async _call(e,t=null,r={}){const{image_rows:s,image_cols:o,image_sizes:l,...u}=await this.image_processor(e,{...r,return_row_col_info:!0});if(t){const d=this.config.image_token??"",{tile_size:f=512,downsample_factor:p=2,encoder_patch_size:g=16,use_thumbnail:y=!0}=this.image_processor.config,w=L=>Math.ceil(Math.floor(L/g)/p),b=w(f)**2,S=this.config.image_start_token??"<|image_start|>",E=this.config.image_end_token??"<|image_end|>",z=this.config.image_thumbnail??"<|img_thumbnail|>";Array.isArray(t)||(t=[t]);let k=0;t=t.map(L=>{const R=L.split(d);return R[0]+R.slice(1).map(N=>{const B=k++,[j,C]=l[B],ue=s[B],oe=o[B],he=w(j)*w(C);let _e=S;if(ue>1||oe>1){const de=d.repeat(b);for(let re=0;re`+de;y&&(_e+=z+d.repeat(he))}else _e+=d.repeat(he);return _e+E+N}).join("")})}return{...u,...t?this.tokenizer(t,r):{}}}},KL=class extends bt{static tokenizer_class=yt;static image_processor_class=Hn;static uses_processor_config=!0;async _call(e,t=null,r={}){const s=await this.image_processor(e,r);if(t){const[l,u]=s.pixel_values.dims.slice(-2),{image_token:d,patch_size:f,num_additional_image_tokens:p}=this.config,g=Math.floor(l/f)*Math.floor(u/f)+p;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let y=0;y0?S.reduce((z,k)=>z*k,1):0;f.push(b),d.push(E)}return[o(f),d]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(t=>t.replaceAll(" ",""))}batch_decode([e,t,r]){const[s,o]=this._decode_helper(e,"char"),[l,u]=this._decode_helper(t,"bpe"),[d,f]=this._decode_helper(r,"wp"),p=[],g=[];for(let y=0;y";function nF(e,t,r,s,o){return`${s.repeat(r*o)}${t}${e} +`}var aF=class extends bt{static tokenizer_class=yt;static image_processor_class=Hn;static uses_processor_config=!1;async _call(e,t=null,r={}){t||(Re.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),t=""),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);const s=this.tokenizer.bos_token,o=this.image_processor.config.image_seq_length;let l;t.some(f=>f.includes(pl))?l=t.map(f=>{const p=f.replaceAll(pl,pl.repeat(o)),g=p.lastIndexOf(pl),y=g===-1?0:g+pl.length;return p.slice(0,y)+s+p.slice(y)+` +`}):(Re.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."),l=t.map(f=>nF(f,s,o,pl,e.length)));const u=this.tokenizer(l,r);return{...await this.image_processor(e,r),...u}}},u1="<|image|>",rF=/<\|image_\d+\|>/g,sF=class extends bt{static image_processor_class=Hn;static tokenizer_class=yt;async _call(e,t=null,{padding:r=!0,truncation:s=!0,num_crops:o=null}={}){Array.isArray(e)||(e=[e]);let l,u;if(t){u=await this.image_processor(t,{num_crops:o});const{num_img_tokens:d}=u,f=e.map((g,y)=>g.split(rF).join(u1.repeat(d[y])));l=this.tokenizer(f,{padding:r,truncation:s});const p=this.tokenizer._tokenizer.token_to_id(u1);l.input_ids.map_(g=>g==p?-g:g)}else l=this.tokenizer(e);return{...l,...u}}},iF=class extends bt{static tokenizer_class=yt;static image_processor_class=Hn;static uses_processor_config=!0;async _call(e,t=null,r={}){const s=await this.image_processor(e,r);if(t){const[l,u]=s.pixel_values.dims.slice(-2),{image_token:d,image_break_token:f,image_end_token:p,patch_size:g,spatial_merge_size:y}=this.config,w=g*y,b=Math.floor(l/w),S=Math.floor(u/w);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let E=0;E{for(;p.includes("<|image_pad|>");){const g=Number(f[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}}},Px=class extends Bx{},lF=class extends Px{},Ix=class extends bt{static image_processor_class=Hn;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)}},Ux=class extends Ix{},cF=class extends Ux{},uF=class extends bt{static tokenizer_class=yt;static feature_extractor_class=er;async _call(e){return await this.feature_extractor(e)}},dF=class extends bt{static tokenizer_class=yt;static feature_extractor_class=er;static uses_processor_config=!0;async _call(e,t=null,r={}){if(Array.isArray(e))throw new Error("Batched inputs are not supported yet.");let s={};if(t){const l=t.length,{input_features:u}=await this.feature_extractor(t,{...r,max_length:l}),d=Math.round(l/this.config.encoder_ds_factor+1e-4),f=1+Math.ceil(d/this.config.stack_factor);s.audio_token_len=[f],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(f))}return{...this.tokenizer(e,{add_special_tokens:!1,...r}),...s}}},Mf="[AUDIO]",fF="[BEGIN_AUDIO]",hF=375;function pF(e,t){const r=[];for(let s=0;spF(b,d)),p=f.map(b=>b.length),g=f.flat(),y=(await Promise.all(g.map(b=>this.feature_extractor(b,r)))).map(b=>b.input_features);s.audio_values=y.length>1?zt(y,0):y[0];let w=l[0];for(let b=0;b0){if(p>qb)throw new Error(`The number of external data chunks (${p}) exceeds the maximum allowed value (${qb}).`);const g=jx(u,p);for(const y of g){const w=`${s.subfolder??""}/${y}`;f.push(new Promise(async(b,S)=>{const E=await Uf(e,w,!0,s,d);b(E instanceof Uint8Array?{path:y,data:E}:y)}))}}else l.externalData!==void 0&&(f=l.externalData.map(async g=>{if(typeof g.data=="string"){const y=await Uf(e,g.data,!0,s);return{...g,data:y}}return g}));return Promise.all(f)}async function AF(e,t,r,s=!1,o=void 0){let l=r.config?.["transformers.js_config"]??{};const u=KM(r.device??l.device,t,{warn:N=>Re.info(N)}),d=iO(u),f=l.device_config??{};f.hasOwnProperty(u)&&(l={...l,...f[u]});const p=JM(r.dtype??l.dtype,t,u,{configDtype:l.dtype,warn:N=>Re.info(N)});if(p_.hasOwnProperty(p)){if(u==="webgpu"&&!We.IS_NODE_ENV&&p===kn.fp16&&!await cO())throw new Error(`The device (${u}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${p}. Should be one of: ${Object.keys(kn).join(", ")}`);const g=l.kv_cache_dtype,y=g?typeof g=="string"?g:g[p]??"float32":void 0;if(y&&!["float32","float16"].includes(y))throw new Error(`Invalid kv_cache_dtype: ${y}. Should be one of: float32, float16`);const w=p_[p],b={...r.session_options};b.executionProviders??=d;const S=l.free_dimension_overrides;S?b.freeDimensionOverrides??=S:u.startsWith("webnn")&&!b.freeDimensionOverrides&&Re.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 E=SF(e,t,r,w),z=r.use_external_data_format??l.use_external_data_format,k=await EF(e,t,w,r,z,b);if(k.length>0&&!We.IS_NODE_ENV&&(b.externalData=k),s&&u==="webgpu"&&g!==!1){const N=eh(r.config,{prefix:"present",session_name:o});if(Object.keys(N).length>0&&!X_()){const B={};for(const j in N)B[j]="gpu-buffer";b.preferredOutputLocation=B}}return{buffer_or_path:await E,session_options:b,session_config:{dtype:p,kv_cache_dtype:y,device:u}}}async function CF(e,t,r,s=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async o=>{const l=s?.[o]??!1,{buffer_or_path:u,session_options:d,session_config:f}=await AF(e,t[o],r,l,o),p=await YM(u,d,f);return[o,p]})))}function Vx(e){for(let t in e)ZM(e[t])?e[t]=new me(e[t]):typeof e[t]=="object"&&Vx(e[t]);return e}async function st(e,t){const r=kF(e,t);try{const s=Object.fromEntries(Object.entries(r).map(([l,u])=>{const d=u.ort_tensor;return We.IS_NODE_ENV&&typeof Float16Array<"u"&&d.cpuData instanceof Float16Array&&(d.cpuData=new Uint16Array(d.cpuData.buffer)),[l,d]})),o=await XM(e,s);return Vx(o)}catch(s){const o=Object.fromEntries(Object.entries(r).map(([l,u])=>{const d={type:u.type,dims:u.dims,location:u.location};return d.location!=="gpu-buffer"&&(d.data=u.data),[l,d]}));throw Re.error(`An error occurred during model execution: "${s}".`),Re.error("Inputs given to model:",o),s}}function kF(e,t){const r=Object.create(null),s=[];for(const u of e.inputNames){const d=t[u];if(!(d instanceof me)){s.push(u);continue}r[u]=X_()?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(t).length,l=e.inputNames.length;if(o>l){let u=Object.keys(t).filter(d=>!e.inputNames.includes(d));Re.warn(`WARNING: Too many inputs were provided (${o} > ${l}). The following inputs will be ignored: "${u.join(", ")}".`)}return r}var tn=class{},Ne=class extends tn{constructor({logits:e,...t}){super(),this.logits=e;const r=Object.values(t);r.length>0&&(this.attentions=r)}},nn=class extends tn{constructor({logits:e}){super(),this.logits=e}},dn=class extends tn{constructor({logits:e}){super(),this.logits=e}},Ln=class extends tn{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},eo=class extends tn{constructor({logits:e}){super(),this.logits=e}},OF=class extends tn{constructor({alphas:e}){super(),this.alphas=e}},Cr=class extends Oa{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},zF=class extends Oa{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},w_=class extends Oa{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let r=t;for(const s of this.processors)r=s(e,r);return r}[Symbol.iterator](){return this.processors.values()}},LF=class extends Cr{constructor(e){super(),this.bos_token_id=e}_call(e,t){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(l&&(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=Q3(s),f=Math.log(d.subarray(this.timestamp_begin).map(Math.exp).reduce((g,y)=>g+y)),p=Ht(d.subarray(0,this.timestamp_begin))[0];f>p&&s.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},DF=class extends Cr{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){const t=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,t){if(t.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 ${t.dims[0]} for the logits and ${e.length} for the input ids.`);const r=e.length,s=t.slice([0,r],null),o=t.slice([r,t.dims[0]],null);for(let l=0;lt.length>=this.max_length)}},VF=class extends th{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(r=>{const s=r.at(-1);return this.eos_token_id.some(o=>s==o)})}},nh=class extends Oa{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,t){let r=e.dims.at(-1),s=e.data;if(t===-1)s=s.slice(-r);else{let o=t*r;s=s.slice(o,o+r)}return s}randomSelect(e){return O3(e)}static getSampler(e){if(e.do_sample)return new HF(e);if(e.num_beams>1)return new $F(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 qF(e)}},qF=class extends nh{async sample(e){const t=Ht(e.data)[1];return[[BigInt(t),0]]}},HF=class extends nh{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,s]=await Ol(e,t),o=wn(r.data);return Array.from({length:this.generation_config.num_beams},()=>{const l=this.randomSelect(o);return[s.data[l],Math.log(o[l])]})}},$F=class extends nh{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));const[r,s]=await Ol(e,t),o=wn(r.data);return Array.from({length:this.generation_config.num_beams},(l,u)=>[s.data[u],Math.log(o[u])])}},QF=class{constructor(e){if(e)for(const t in e){if(t in this)throw new TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);const r=e[t];if(!(r instanceof me))throw new TypeError(`Expected a Tensor for key "${t}", got ${typeof r}`);this[t]=r}}get_seq_length(){const e=this;for(const t in e)if(t.startsWith("past_key_values."))return e[t].dims.at(-2);throw new Error("Unable to determine sequence length from the cache.")}async dispose(){const e=[];for(const t of Object.values(this))t.location==="gpu-buffer"&&e.push(t.dispose());await Promise.all(e)}},Wx=QF,yl=null;function WF(e){yl=e}function b_(e){if(e instanceof me)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new me("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new me("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function Yx(e){return new me("bool",[e],[1])}var ve={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,MultimodalLanguageModelOnly:16,VoxtralRealtime:17},vl={[ve.DecoderOnly]:{can_generate:!0,forward:as,prepare_inputs:yu,sessions:(e,t)=>({model:t.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.DecoderOnlyWithoutHead]:{can_generate:!1,forward:as,prepare_inputs:yu,sessions:(e,t)=>({model:t.model_file_name??"model"})},[ve.Seq2Seq]:{can_generate:!0,forward:Tf,prepare_inputs:jf,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.Vision2Seq]:{can_generate:!0,forward:Tf,prepare_inputs:jf,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.Musicgen]:{can_generate:!0,forward:Tf,sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.EncoderDecoder]:{can_generate:!1,forward:Tf,sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[ve.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[ve.ImageTextToText]:{can_generate:!0,forward:f1,prepare_inputs:fu,sessions:e=>{const t={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};return e.is_encoder_decoder&&(t.model="encoder_model"),t},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.AudioTextToText]:{can_generate:!0,forward:ZF,prepare_inputs:fu,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:fu,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"}),optional_configs:{generation_config:"generation_config.json"}},[ve.Phi3V]:{can_generate:!0,prepare_inputs:fu,sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.MultiModality]:{can_generate:!0,sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.AutoEncoder]:{can_generate:!1,forward:XF,sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[ve.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[ve.Chatterbox]:{can_generate:!0,forward:Js,sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.MultimodalLanguageModelOnly]:{can_generate:!0,forward:f1,prepare_inputs:fu,sessions:()=>({embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[ve.VoxtralRealtime]:{can_generate:!0,prepare_inputs:yu,sessions:()=>({embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{can_generate:!1,forward:Js,sessions:(e,t)=>({model:t.model_file_name??"model"})}};function YF(e,t,r={}){const s=vl[e]??vl.default;return{sessions:s.sessions(t,r),cache_sessions:s.cache_sessions,optional_configs:s.optional_configs}}var ns=new Map,sg=new Map,Tl=new Map,H=class extends Oa{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(e,t,r){super(),this.config=e,this.sessions=t,this.configs=r;const s=Tl.get(this.constructor),o=ns.get(s),l=vl[o]??vl.default;this.can_generate=l.can_generate,this._forward=l.forward,this._prepare_inputs_for_generation=l.prepare_inputs,this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const e=[];for(const t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:r=null,cache_dir:s=null,local_files_only:o=!1,revision:l="main",model_file_name:u=null,subfolder:d="onnx",device:f=null,dtype:p=null,use_external_data_format:g=null,session_options:y={}}={}){const w={progress_callback:t,config:r,cache_dir:s,local_files_only:o,revision:l,model_file_name:u,subfolder:d,device:f,dtype:p,use_external_data_format:g,session_options:y},b=Tl.get(this),S=ns.get(b);r=w.config=await xu.from_pretrained(e,w);const E=vl[S]??vl.default;if(S===void 0){const R=b??r?.model_type;R!=="custom"&&Re.warn(`Model type for '${R}' not found, assuming encoder-only architecture. Please report this at ${Kf}.`)}const z=E.sessions(r,w),k=[CF(e,z,w,E.cache_sessions)];E.optional_configs&&k.push(JF(e,E.optional_configs,w));const L=await Promise.all(k);return new this(r,...L)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,r=null){const s=new w_;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&s.push(new RF(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&s.push(new DF(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&s.push(new IF(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&s.push(new BF(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&s.push(new PF(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&s.push(new LF(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&s.push(new FF(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){const o=t>1||e.forced_bos_token_id===null?t:t+1;s.push(new qx(e.begin_suppress_tokens,o))}return e.guidance_scale!==null&&e.guidance_scale>1&&s.push(new UF(e.guidance_scale)),e.temperature===0&&e.do_sample&&(Re.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&s.push(new GF(e.temperature)),r!==null&&s.extend(r),s}_prepare_generation_config(e,t,r=Hx){const s={...this.config};for(const l of["decoder","generator","text_config"])l in s&&Object.assign(s,s[l]);const o=new r(s);return Object.assign(o,this.generation_config??{}),e&&Object.assign(o,e),t&&Object.assign(o,yn(t,Object.getOwnPropertyNames(o))),o}_get_stopping_criteria(e,t=null){const r=new $x;return e.max_length!==null&&r.push(new jF(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&r.push(new VF(e.eos_token_id)),t&&r.extend(t),r}_validate_model_class(){if(!this.can_generate){const e=[yl.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,yl.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,yl.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,yl.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Tl.get(this.constructor),r=new Set,s=this.config.model_type;for(const l of e){const u=l?.get(s);u&&r.add(u)}let o=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw r.size>0&&(o+=` Please use the following class instead: ${[...r].join(", ")}`),Error(o)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw new Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:r,is_encoder_decoder:s}){return r.past_key_values=this.getPastKeyValues(t,r.past_key_values),r.input_ids=new me("int64",e.flat(),[e.length,1]),s||(r.attention_mask=zt([r.attention_mask,ha([r.attention_mask.dims[0],1])],1)),r.position_ids=null,r}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:r}){const s=yn(r,this.forward_params),o=this.main_input_name;if(o in s){if(e)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else s[o]=e;return{inputs_tensor:s[o],model_inputs:s,model_input_name:o}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:r,generation_config:s}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!t.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:l,pixel_values:u,attention_mask:d,...f}=t,p=await this._prepare_inputs_embeds(t);t={...f,...yn(p,["inputs_embeds","attention_mask"])}}let{last_hidden_state:o}=await Js(this,t);if(s.guidance_scale!==null&&s.guidance_scale>1)o=zt([o,m_(o,0)],0),"attention_mask"in t&&(t.attention_mask=zt([t.attention_mask,rx(t.attention_mask)],0));else if(t.decoder_input_ids){const l=b_(t.decoder_input_ids).dims[0];if(l!==o.dims[0]){if(o.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${o.dims[0]}) than the decoder inputs (${l}).`);o=zt(Array.from({length:l},()=>o),0)}}return t.encoder_outputs=o,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:r,decoder_start_token_id:s,bos_token_id:o,generation_config:l}){let{decoder_input_ids:u,...d}=r;if(!(u instanceof me)){if(u)Array.isArray(u[0])||(u=Array.from({length:e},()=>u));else if(s??=o,this.config.model_type==="musicgen")u=Array.from({length:e*this.config.decoder.num_codebooks},()=>[s]);else if(Array.isArray(s)){if(s.length!==e)throw new Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${s.length}`);u=s}else u=Array.from({length:e},()=>[s]);u=b_(u)}return r.decoder_attention_mask=nx(u),{input_ids:u,model_inputs:d}}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:s=null,streamer:o=null,...l}){this._validate_model_class(),t=this._prepare_generation_config(t,l);let{inputs_tensor:u,model_inputs:d,model_input_name:f}=this._prepare_model_inputs({inputs:e,model_kwargs:l});const p=this.config.is_encoder_decoder;p&&("encoder_outputs"in d||(d=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:u,model_inputs:d,model_input_name:f,generation_config:t})));let g;p?{input_ids:g,model_inputs:d}=this._prepare_decoder_input_ids_for_generation({batch_size:d[f].dims.at(0),model_input_name:f,model_kwargs:d,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):g=d[f];let y=g.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=y+t.max_new_tokens);const w=this._get_logits_processor(t,y,r),b=this._get_stopping_criteria(t,s),S=d[f].dims.at(0),E=nh.getSampler(t),z=new Array(S).fill(0),k=g.tolist();o&&o.put(k);let L,R={},N={};for(;;){if(d=this.prepare_inputs_for_generation(k,d,t),L=await this.forward(d),t.return_dict_in_generate)if(t.output_attentions){const _e=this.getAttentions(L);for(const de in _e)de in R||(R[de]=[]),R[de].push(_e[de])}else this._return_dict_in_generate_keys&&Object.assign(N,yn(L,this._return_dict_in_generate_keys));const C=L.logits.slice(null,-1,null).to("float32"),ue=w(k,C),oe=[];for(let _e=0;_e_e))break;d=this._update_model_kwargs_for_generation({generated_input_ids:oe,outputs:L,model_inputs:d,is_encoder_decoder:p})}o&&o.end();const B=this.getPastKeyValues(L,d.past_key_values,!0),j=new me("int64",k.flat(),[k.length,k[0].length]);if(t.return_dict_in_generate)return{sequences:j,past_key_values:B,...R,...N};for(const C of Object.values(L))C.location==="gpu-buffer"&&C.dispose();return j}getPastKeyValues(e,t,r=!1){const s=Object.create(null);for(const o in e)if(o.startsWith("present")){const l=o.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values"),u=o.includes("encoder");if(u&&t?s[l]=t[l]:s[l]=e[o],t&&(!u||r)){const d=t[l];d.location==="gpu-buffer"&&d.dispose()}}return new Wx(s)}getAttentions(e){const t={};for(const r of["cross_attentions","encoder_attentions","decoder_attentions"])for(const s in e)s.startsWith(r)&&(r in t||(t[r]=[]),t[r].push(e[s]));return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{const r=this.sessions.decoder_model_merged??this.sessions.model,s=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,o=r?.config?.kv_cache_dtype??"float32",l=o==="float16"?Sl.float16:Sl.float32,u=eh(this.config,{batch_size:s});for(const d in u){const f=u[d].reduce((p,g)=>p*g,1);e[d]=new me(o,new l(f),u[d])}}}async _encode_input(e,t,r){if(!Object.hasOwn(this.sessions,e))throw new Error(`Model does not have a ${e} session.`);const s=this.sessions[e];return(await st(s,yn(t,s.inputNames)))[r]}async encode_image(e){return this._encode_input("vision_encoder",e,"image_features")}async encode_text(e){return this._encode_input("embed_tokens",e,"inputs_embeds")}async encode_audio(e){return this._encode_input("audio_encoder",e,"audio_features")}};async function Tf(e,t){let{encoder_outputs:r,input_ids:s,decoder_input_ids:o,...l}=t;if(!r){const u=yn(t,e.sessions.model.inputNames);r=(await Js(e,u)).last_hidden_state}return l.input_ids=o,l.encoder_hidden_states=r,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(l.encoder_attention_mask=t.attention_mask),await as(e,l,!0)}async function Js(e,t){const r=e.sessions.model,s=yn(t,r.inputNames);if(r.inputNames.includes("inputs_embeds")&&!s.inputs_embeds){if(!t.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:t.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=rx(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=ha([o[0],o[2],o[3]])}return await st(r,s)}async function XF(e,t){const r=await e.encode(t);return await e.decode(r)}async function as(e,t,r=!1){const s=e.sessions[r?"decoder_model_merged":"model"],{past_key_values:o,...l}=t;if(s.inputNames.includes("use_cache_branch")&&(l.use_cache_branch=Yx(!!o)),s.inputNames.includes("position_ids")&&l.attention_mask&&!l.position_ids){const d=["paligemma","gemma3_text","gemma3"].includes(e.config.model_type)?1:0;l.position_ids=KF(l,o,d)}s.inputNames.includes("num_logits_to_keep")&&!l.num_logits_to_keep&&(l.num_logits_to_keep=new me("int64",[0n],[])),e.addPastKeyValues(l,o);const u=yn(l,s.inputNames);return await st(s,u)}async function Xx(e,{encode_function:t,merge_function:r,modality_input_names:s,modality_output_name:o,input_ids:l=null,attention_mask:u=null,position_ids:d=null,inputs_embeds:f=null,past_key_values:p=null,generation_config:g=null,logits_processor:y=null,...w}){if(!f){f=await e.encode_text({input_ids:l,...w});const S=yn(w,s);if(Object.keys(S).length>0){if(l.dims[1]!==1){const E=await t({...S,...w});({inputs_embeds:f,attention_mask:u}=r({[o]:E,inputs_embeds:f,input_ids:l,attention_mask:u}))}else if(p&&l.dims[1]===1){const E=l.dims[1],z=p.get_seq_length();u=zt([ha([l.dims[0],z]),u.slice(null,[u.dims[1]-E,u.dims[1]])],1)}}}if(!d&&["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text"].includes(e.config.model_type)){const{image_grid_thw:S,video_grid_thw:E}=w;[d]=e.get_rope_index(l,S,E,u)}return await as(e,{inputs_embeds:f,past_key_values:p,attention_mask:u,position_ids:d,generation_config:g,logits_processor:y},!0)}async function ZF(e,t){return await Xx(e,{...t,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function f1(e,t){return await Xx(e,{...t,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function Zx(e,t=0){const[r,s]=e.dims,o=e.data,l=new BigInt64Array(o.length);for(let u=0;uu.dims[1]||o[o.at(-1)])),{...r,decoder_input_ids:b_(t)}}function fu(e,...t){return e.config.is_encoder_decoder?jf(e,...t):yu(e,...t)}function Kx({modality_token_id:e,inputs_embeds:t,modality_features:r,input_ids:s,attention_mask:o}){const l=s.tolist().map(p=>p.reduce((g,y,w)=>(y==e&&g.push(w),g),[])),u=l.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 f=0;for(let p=0;p{const o=await ss(e,t[s],!1,r);return[s,o]})))}var og={};Al(og,{ASTForAudioClassification:()=>dN,ASTModel:()=>uN,ASTPreTrainedModel:()=>dg,AfmoeForCausalLM:()=>oN,AfmoeModel:()=>iN,AfmoePreTrainedModel:()=>cg,AlbertForMaskedLM:()=>aN,AlbertForQuestionAnswering:()=>nN,AlbertForSequenceClassification:()=>tN,AlbertModel:()=>eN,AlbertPreTrainedModel:()=>Au,ApertusForCausalLM:()=>sN,ApertusModel:()=>rN,ApertusPreTrainedModel:()=>lg,ArceeForCausalLM:()=>cN,ArceeModel:()=>lN,ArceePreTrainedModel:()=>ug,BartForConditionalGeneration:()=>hN,BartForSequenceClassification:()=>pN,BartModel:()=>fN,BartPretrainedModel:()=>ah,BeitForImageClassification:()=>_N,BeitModel:()=>mN,BeitPreTrainedModel:()=>fg,BertForMaskedLM:()=>yN,BertForQuestionAnswering:()=>bN,BertForSequenceClassification:()=>vN,BertForTokenClassification:()=>wN,BertModel:()=>gN,BertPreTrainedModel:()=>zl,BlenderbotForConditionalGeneration:()=>xN,BlenderbotModel:()=>MN,BlenderbotPreTrainedModel:()=>hg,BlenderbotSmallForConditionalGeneration:()=>SN,BlenderbotSmallModel:()=>TN,BlenderbotSmallPreTrainedModel:()=>pg,BloomForCausalLM:()=>AN,BloomModel:()=>EN,BloomPreTrainedModel:()=>mg,CLIPModel:()=>RN,CLIPPreTrainedModel:()=>to,CLIPSegForImageSegmentation:()=>GN,CLIPSegModel:()=>UN,CLIPSegPreTrainedModel:()=>_g,CLIPTextModel:()=>BN,CLIPTextModelWithProjection:()=>s2,CLIPVisionModel:()=>PN,CLIPVisionModelWithProjection:()=>IN,CamembertForMaskedLM:()=>kN,CamembertForQuestionAnswering:()=>LN,CamembertForSequenceClassification:()=>ON,CamembertForTokenClassification:()=>zN,CamembertModel:()=>CN,CamembertPreTrainedModel:()=>Ll,ChatterboxModel:()=>t2,ChatterboxPreTrainedModel:()=>e2,ChineseCLIPModel:()=>NN,ChineseCLIPPreTrainedModel:()=>n2,ClapAudioModelWithProjection:()=>r2,ClapModel:()=>DN,ClapPreTrainedModel:()=>rh,ClapTextModelWithProjection:()=>a2,CodeGenForCausalLM:()=>VN,CodeGenModel:()=>jN,CodeGenPreTrainedModel:()=>gg,Cohere2ForCausalLM:()=>QN,Cohere2Model:()=>$N,Cohere2PreTrainedModel:()=>vg,CohereForCausalLM:()=>HN,CohereModel:()=>qN,CoherePreTrainedModel:()=>yg,ConvBertForMaskedLM:()=>YN,ConvBertForQuestionAnswering:()=>KN,ConvBertForSequenceClassification:()=>XN,ConvBertForTokenClassification:()=>ZN,ConvBertModel:()=>WN,ConvBertPreTrainedModel:()=>Fl,ConvNextForImageClassification:()=>e4,ConvNextModel:()=>JN,ConvNextPreTrainedModel:()=>wg,ConvNextV2ForImageClassification:()=>n4,ConvNextV2Model:()=>t4,ConvNextV2PreTrainedModel:()=>bg,DFineForObjectDetection:()=>i4,DFineModel:()=>s4,DFinePreTrainedModel:()=>xg,DINOv3ConvNextModel:()=>O4,DINOv3ConvNextPreTrainedModel:()=>p2,DINOv3ViTModel:()=>z4,DINOv3ViTPreTrainedModel:()=>m2,DPTForDepthEstimation:()=>I4,DPTModel:()=>P4,DPTPreTrainedModel:()=>Cg,DacDecoderModel:()=>c2,DacDecoderOutput:()=>o2,DacEncoderModel:()=>l2,DacEncoderOutput:()=>i2,DacModel:()=>o4,DacPreTrainedModel:()=>sh,DebertaForMaskedLM:()=>c4,DebertaForQuestionAnswering:()=>f4,DebertaForSequenceClassification:()=>u4,DebertaForTokenClassification:()=>d4,DebertaModel:()=>l4,DebertaPreTrainedModel:()=>Nl,DebertaV2ForMaskedLM:()=>p4,DebertaV2ForQuestionAnswering:()=>g4,DebertaV2ForSequenceClassification:()=>m4,DebertaV2ForTokenClassification:()=>_4,DebertaV2Model:()=>h4,DebertaV2PreTrainedModel:()=>Dl,DecisionTransformerModel:()=>y4,DecisionTransformerPreTrainedModel:()=>u2,DeiTForImageClassification:()=>w4,DeiTModel:()=>v4,DeiTPreTrainedModel:()=>Tg,DepthAnythingForDepthEstimation:()=>b4,DepthAnythingPreTrainedModel:()=>d2,DepthProForDepthEstimation:()=>M4,DepthProPreTrainedModel:()=>f2,DetrForObjectDetection:()=>T4,DetrForSegmentation:()=>S4,DetrModel:()=>x4,DetrObjectDetectionOutput:()=>Sg,DetrPreTrainedModel:()=>ih,DetrSegmentationOutput:()=>h2,Dinov2ForImageClassification:()=>A4,Dinov2Model:()=>E4,Dinov2PreTrainedModel:()=>Eg,Dinov2WithRegistersForImageClassification:()=>k4,Dinov2WithRegistersModel:()=>C4,Dinov2WithRegistersPreTrainedModel:()=>Ag,DistilBertForMaskedLM:()=>R4,DistilBertForQuestionAnswering:()=>D4,DistilBertForSequenceClassification:()=>F4,DistilBertForTokenClassification:()=>N4,DistilBertModel:()=>L4,DistilBertPreTrainedModel:()=>Rl,DonutSwinModel:()=>B4,DonutSwinPreTrainedModel:()=>_2,EdgeTamModel:()=>FB,EfficientNetForImageClassification:()=>G4,EfficientNetModel:()=>U4,EfficientNetPreTrainedModel:()=>kg,ElectraForMaskedLM:()=>V4,ElectraForQuestionAnswering:()=>$4,ElectraForSequenceClassification:()=>q4,ElectraForTokenClassification:()=>H4,ElectraModel:()=>j4,ElectraPreTrainedModel:()=>Bl,Ernie4_5ForCausalLM:()=>W4,Ernie4_5Model:()=>Q4,Ernie4_5PretrainedModel:()=>Og,EsmForMaskedLM:()=>X4,EsmForSequenceClassification:()=>Z4,EsmForTokenClassification:()=>K4,EsmModel:()=>Y4,EsmPreTrainedModel:()=>ku,ExaoneForCausalLM:()=>eD,ExaoneModel:()=>J4,ExaonePreTrainedModel:()=>zg,FalconForCausalLM:()=>nD,FalconH1ForCausalLM:()=>rD,FalconH1Model:()=>aD,FalconH1PreTrainedModel:()=>Fg,FalconModel:()=>tD,FalconPreTrainedModel:()=>Lg,FastViTForImageClassification:()=>iD,FastViTModel:()=>sD,FastViTPreTrainedModel:()=>Ng,Florence2ForConditionalGeneration:()=>oD,Florence2PreTrainedModel:()=>g2,GLPNForDepthEstimation:()=>gD,GLPNModel:()=>_D,GLPNPreTrainedModel:()=>Ug,GPT2LMHeadModel:()=>AD,GPT2Model:()=>ED,GPT2PreTrainedModel:()=>Hg,GPTBigCodeForCausalLM:()=>vD,GPTBigCodeModel:()=>yD,GPTBigCodePreTrainedModel:()=>Gg,GPTJForCausalLM:()=>kD,GPTJModel:()=>CD,GPTJPreTrainedModel:()=>$g,GPTNeoForCausalLM:()=>bD,GPTNeoModel:()=>wD,GPTNeoPreTrainedModel:()=>jg,GPTNeoXForCausalLM:()=>xD,GPTNeoXModel:()=>MD,GPTNeoXPreTrainedModel:()=>Vg,Gemma2ForCausalLM:()=>dD,Gemma2Model:()=>uD,Gemma2PreTrainedModel:()=>Rg,Gemma3ForCausalLM:()=>hD,Gemma3Model:()=>fD,Gemma3PreTrainedModel:()=>Bg,Gemma3nForCausalLM:()=>v2,Gemma3nForConditionalGeneration:()=>Pg,Gemma3nPreTrainedModel:()=>y2,GemmaForCausalLM:()=>cD,GemmaModel:()=>lD,GemmaPreTrainedModel:()=>Dg,GlmForCausalLM:()=>mD,GlmModel:()=>pD,GlmPreTrainedModel:()=>Ig,GptOssForCausalLM:()=>SD,GptOssModel:()=>TD,GptOssPreTrainedModel:()=>qg,GraniteForCausalLM:()=>zD,GraniteModel:()=>OD,GraniteMoeHybridForCausalLM:()=>FD,GraniteMoeHybridModel:()=>LD,GraniteMoeHybridPreTrainedModel:()=>Wg,GranitePreTrainedModel:()=>Qg,GraniteSpeechForConditionalGeneration:()=>ND,GroundingDinoForObjectDetection:()=>DD,GroundingDinoPreTrainedModel:()=>b2,GroupViTModel:()=>RD,GroupViTPreTrainedModel:()=>M2,HeliumForCausalLM:()=>PD,HeliumModel:()=>BD,HeliumPreTrainedModel:()=>Xg,HieraForImageClassification:()=>UD,HieraModel:()=>ID,HieraPreTrainedModel:()=>Zg,HubertForCTC:()=>QD,HubertForSequenceClassification:()=>WD,HubertModel:()=>$D,HubertPreTrainedModel:()=>HD,HunYuanDenseV1ForCausalLM:()=>XD,HunYuanDenseV1Model:()=>YD,HunYuanDenseV1PreTrainedModel:()=>Kg,IJepaForImageClassification:()=>t6,IJepaModel:()=>e6,IJepaPreTrainedModel:()=>Jg,Idefics3ForConditionalGeneration:()=>JD,JAISLMHeadModel:()=>a6,JAISModel:()=>n6,JAISPreTrainedModel:()=>ey,JinaCLIPModel:()=>r6,JinaCLIPPreTrainedModel:()=>oh,JinaCLIPTextModel:()=>T2,JinaCLIPVisionModel:()=>s6,Lfm2ForCausalLM:()=>o6,Lfm2Model:()=>i6,Lfm2MoeForCausalLM:()=>c6,Lfm2MoeModel:()=>l6,Lfm2MoePreTrainedModel:()=>ny,Lfm2PreTrainedModel:()=>ty,Lfm2VlForConditionalGeneration:()=>u6,LiteWhisperForConditionalGeneration:()=>Z8,Llama4ForCausalLM:()=>h6,Llama4PreTrainedModel:()=>S2,LlamaForCausalLM:()=>f6,LlamaModel:()=>d6,LlamaPreTrainedModel:()=>ay,LlavaForConditionalGeneration:()=>Xi,LlavaOnevisionForConditionalGeneration:()=>Xi,LlavaPreTrainedModel:()=>x2,LlavaQwen2ForCausalLM:()=>KD,LongT5ForConditionalGeneration:()=>m6,LongT5Model:()=>p6,LongT5PreTrainedModel:()=>ry,M2M100ForConditionalGeneration:()=>g6,M2M100Model:()=>_6,M2M100PreTrainedModel:()=>sy,MBartForCausalLM:()=>S6,MBartForConditionalGeneration:()=>x6,MBartForSequenceClassification:()=>T6,MBartModel:()=>M6,MBartPreTrainedModel:()=>Ou,MPNetForMaskedLM:()=>cR,MPNetForQuestionAnswering:()=>fR,MPNetForSequenceClassification:()=>uR,MPNetForTokenClassification:()=>dR,MPNetModel:()=>lR,MPNetPreTrainedModel:()=>Pl,MT5ForConditionalGeneration:()=>_R,MT5Model:()=>mR,MT5PreTrainedModel:()=>my,MarianMTModel:()=>v6,MarianModel:()=>y6,MarianPreTrainedModel:()=>iy,MaskFormerForInstanceSegmentation:()=>b6,MaskFormerModel:()=>w6,MaskFormerPreTrainedModel:()=>oy,Metric3DForDepthEstimation:()=>E6,Metric3DPreTrainedModel:()=>E2,Metric3Dv2ForDepthEstimation:()=>A6,Metric3Dv2PreTrainedModel:()=>A2,MgpstrForSceneTextRecognition:()=>C6,MgpstrModelOutput:()=>C2,MgpstrPreTrainedModel:()=>k2,MimiDecoderModel:()=>F2,MimiDecoderOutput:()=>z2,MimiEncoderModel:()=>L2,MimiEncoderOutput:()=>O2,MimiModel:()=>k6,MimiPreTrainedModel:()=>lh,MistralForCausalLM:()=>z6,MistralModel:()=>O6,MistralPreTrainedModel:()=>ly,MobileBertForMaskedLM:()=>F6,MobileBertForQuestionAnswering:()=>D6,MobileBertForSequenceClassification:()=>N6,MobileBertModel:()=>L6,MobileBertPreTrainedModel:()=>zu,MobileLLMForCausalLM:()=>B6,MobileLLMModel:()=>R6,MobileLLMPreTrainedModel:()=>cy,MobileNetV1ForImageClassification:()=>I6,MobileNetV1ForSemanticSegmentation:()=>U6,MobileNetV1Model:()=>P6,MobileNetV1PreTrainedModel:()=>ch,MobileNetV2ForImageClassification:()=>j6,MobileNetV2ForSemanticSegmentation:()=>V6,MobileNetV2Model:()=>G6,MobileNetV2PreTrainedModel:()=>uh,MobileNetV3ForImageClassification:()=>H6,MobileNetV3ForSemanticSegmentation:()=>$6,MobileNetV3Model:()=>q6,MobileNetV3PreTrainedModel:()=>dh,MobileNetV4ForImageClassification:()=>W6,MobileNetV4ForSemanticSegmentation:()=>Y6,MobileNetV4Model:()=>Q6,MobileNetV4PreTrainedModel:()=>fh,MobileViTForImageClassification:()=>Z6,MobileViTModel:()=>X6,MobileViTPreTrainedModel:()=>uy,MobileViTV2ForImageClassification:()=>J6,MobileViTV2Model:()=>K6,MobileViTV2PreTrainedModel:()=>dy,ModernBertDecoderForCausalLM:()=>sR,ModernBertDecoderModel:()=>rR,ModernBertDecoderPreTrainedModel:()=>fy,ModernBertForMaskedLM:()=>tR,ModernBertForSequenceClassification:()=>nR,ModernBertForTokenClassification:()=>aR,ModernBertModel:()=>eR,ModernBertPreTrainedModel:()=>Lu,Moondream1ForConditionalGeneration:()=>ZD,MoonshineForConditionalGeneration:()=>oR,MoonshineModel:()=>iR,MoonshinePreTrainedModel:()=>hy,MptForCausalLM:()=>pR,MptModel:()=>hR,MptPreTrainedModel:()=>py,MultiModalityCausalLM:()=>gR,MultiModalityPreTrainedModel:()=>N2,MusicgenForCausalLM:()=>vR,MusicgenForConditionalGeneration:()=>D2,MusicgenModel:()=>yR,MusicgenPreTrainedModel:()=>_y,NanoChatForCausalLM:()=>bR,NanoChatModel:()=>wR,NanoChatPreTrainedModel:()=>gy,NeoBertForMaskedLM:()=>xR,NeoBertForQuestionAnswering:()=>ER,NeoBertForSequenceClassification:()=>TR,NeoBertForTokenClassification:()=>SR,NeoBertModel:()=>MR,NeoBertPreTrainedModel:()=>Il,NomicBertModel:()=>AR,NomicBertPreTrainedModel:()=>R2,OPTForCausalLM:()=>IR,OPTModel:()=>PR,OPTPreTrainedModel:()=>xy,Olmo2ForCausalLM:()=>zR,Olmo2Model:()=>OR,Olmo2PreTrainedModel:()=>vy,Olmo3ForCausalLM:()=>FR,Olmo3Model:()=>LR,Olmo3PreTrainedModel:()=>wy,OlmoForCausalLM:()=>kR,OlmoHybridForCausalLM:()=>DR,OlmoHybridModel:()=>NR,OlmoHybridPreTrainedModel:()=>by,OlmoModel:()=>CR,OlmoPreTrainedModel:()=>yy,OpenELMForCausalLM:()=>BR,OpenELMModel:()=>RR,OpenELMPreTrainedModel:()=>My,OwlViTForObjectDetection:()=>VR,OwlViTModel:()=>jR,OwlViTPreTrainedModel:()=>Sy,Owlv2ForObjectDetection:()=>GR,Owlv2Model:()=>UR,Owlv2PreTrainedModel:()=>Ty,PaliGemmaForConditionalGeneration:()=>qR,ParakeetForCTC:()=>HR,ParakeetPreTrainedModel:()=>B2,PatchTSMixerForPrediction:()=>QR,PatchTSMixerModel:()=>$R,PatchTSMixerPreTrainedModel:()=>Ey,PatchTSTForPrediction:()=>YR,PatchTSTModel:()=>WR,PatchTSTPreTrainedModel:()=>Ay,Phi3ForCausalLM:()=>JR,Phi3Model:()=>KR,Phi3PreTrainedModel:()=>ky,Phi3VForCausalLM:()=>I2,Phi3VPreTrainedModel:()=>P2,PhiForCausalLM:()=>ZR,PhiModel:()=>XR,PhiPreTrainedModel:()=>Cy,PreTrainedModel:()=>H,PvtForImageClassification:()=>tB,PvtModel:()=>eB,PvtPreTrainedModel:()=>Oy,PyAnnoteForAudioFrameClassification:()=>aB,PyAnnoteModel:()=>nB,PyAnnotePreTrainedModel:()=>zy,Qwen2ForCausalLM:()=>sB,Qwen2Model:()=>rB,Qwen2MoeForCausalLM:()=>oB,Qwen2MoeModel:()=>iB,Qwen2MoePreTrainedModel:()=>Fy,Qwen2PreTrainedModel:()=>Ly,Qwen2VLForCausalLM:()=>Dy,Qwen2VLForConditionalGeneration:()=>Ny,Qwen2VLPreTrainedModel:()=>U2,Qwen2_5_VLForCausalLM:()=>Ry,Qwen2_5_VLForConditionalGeneration:()=>G2,Qwen3ForCausalLM:()=>cB,Qwen3Model:()=>lB,Qwen3MoeForCausalLM:()=>dB,Qwen3MoeModel:()=>uB,Qwen3MoePreTrainedModel:()=>Py,Qwen3NextForCausalLM:()=>hB,Qwen3NextModel:()=>fB,Qwen3NextPreTrainedModel:()=>Iy,Qwen3PreTrainedModel:()=>By,Qwen3VLForCausalLM:()=>Gy,Qwen3VLForConditionalGeneration:()=>Uy,Qwen3VLMoeForCausalLM:()=>j2,Qwen3VLMoeForConditionalGeneration:()=>pB,Qwen3_5ForCausalLM:()=>Vy,Qwen3_5ForConditionalGeneration:()=>jy,Qwen3_5MoeForCausalLM:()=>V2,Qwen3_5MoeForConditionalGeneration:()=>mB,RFDetrForObjectDetection:()=>vB,RFDetrModel:()=>yB,RFDetrObjectDetectionOutput:()=>q2,RFDetrPreTrainedModel:()=>Hy,RTDetrForObjectDetection:()=>r4,RTDetrModel:()=>a4,RTDetrObjectDetectionOutput:()=>Cu,RTDetrPreTrainedModel:()=>Mg,RTDetrV2ForObjectDetection:()=>zB,RTDetrV2Model:()=>OB,RTDetrV2ObjectDetectionOutput:()=>H2,RTDetrV2PreTrainedModel:()=>$y,ResNetForImageClassification:()=>gB,ResNetModel:()=>_B,ResNetPreTrainedModel:()=>qy,RoFormerForMaskedLM:()=>EB,RoFormerForQuestionAnswering:()=>kB,RoFormerForSequenceClassification:()=>AB,RoFormerForTokenClassification:()=>CB,RoFormerModel:()=>SB,RoFormerPreTrainedModel:()=>Gl,RobertaForMaskedLM:()=>bB,RobertaForQuestionAnswering:()=>TB,RobertaForSequenceClassification:()=>MB,RobertaForTokenClassification:()=>xB,RobertaModel:()=>wB,RobertaPreTrainedModel:()=>Ul,Sam2ImageSegmentationOutput:()=>W2,Sam2Model:()=>Qy,Sam2PreTrainedModel:()=>Y2,Sam3TrackerModel:()=>NB,SamImageSegmentationOutput:()=>$2,SamModel:()=>LB,SamPreTrainedModel:()=>Q2,SapiensForDepthEstimation:()=>RB,SapiensForNormalEstimation:()=>BB,SapiensForSemanticSegmentation:()=>DB,SapiensPreTrainedModel:()=>hh,SegformerForImageClassification:()=>IB,SegformerForSemanticSegmentation:()=>UB,SegformerModel:()=>PB,SegformerPreTrainedModel:()=>ph,SiglipModel:()=>GB,SiglipPreTrainedModel:()=>Wy,SiglipTextModel:()=>X2,SiglipVisionModel:()=>jB,SmolLM3ForCausalLM:()=>qB,SmolLM3Model:()=>VB,SmolLM3PreTrainedModel:()=>Yy,SnacDecoderModel:()=>K2,SnacEncoderModel:()=>Z2,SnacModel:()=>HB,SnacPreTrainedModel:()=>mh,SpeechT5ForSpeechToText:()=>QB,SpeechT5ForTextToSpeech:()=>WB,SpeechT5HifiGan:()=>YB,SpeechT5Model:()=>$B,SpeechT5PreTrainedModel:()=>_h,SqueezeBertForMaskedLM:()=>ZB,SqueezeBertForQuestionAnswering:()=>JB,SqueezeBertForSequenceClassification:()=>KB,SqueezeBertModel:()=>XB,SqueezeBertPreTrainedModel:()=>Fu,StableLmForCausalLM:()=>t8,StableLmModel:()=>e8,StableLmPreTrainedModel:()=>Xy,Starcoder2ForCausalLM:()=>a8,Starcoder2Model:()=>n8,Starcoder2PreTrainedModel:()=>Zy,StyleTextToSpeech2Model:()=>r8,StyleTextToSpeech2PreTrainedModel:()=>J2,SupertonicForConditionalGeneration:()=>tT,SupertonicPreTrainedModel:()=>eT,Swin2SRForImageSuperResolution:()=>c8,Swin2SRModel:()=>l8,Swin2SRPreTrainedModel:()=>Ky,SwinForImageClassification:()=>i8,SwinForSemanticSegmentation:()=>o8,SwinModel:()=>s8,SwinPreTrainedModel:()=>gh,T5ForConditionalGeneration:()=>d8,T5Model:()=>u8,T5PreTrainedModel:()=>Jy,TableTransformerForObjectDetection:()=>h8,TableTransformerModel:()=>f8,TableTransformerObjectDetectionOutput:()=>nT,TableTransformerPreTrainedModel:()=>ev,TrOCRForCausalLM:()=>p8,TrOCRPreTrainedModel:()=>aT,UltravoxModel:()=>Yg,UltravoxPreTrainedModel:()=>w2,UniSpeechForCTC:()=>_8,UniSpeechForSequenceClassification:()=>g8,UniSpeechModel:()=>m8,UniSpeechPreTrainedModel:()=>yh,UniSpeechSatForAudioFrameClassification:()=>b8,UniSpeechSatForCTC:()=>v8,UniSpeechSatForSequenceClassification:()=>w8,UniSpeechSatModel:()=>y8,UniSpeechSatPreTrainedModel:()=>Nu,VaultGemmaForCausalLM:()=>x8,VaultGemmaModel:()=>M8,VaultGemmaPreTrainedModel:()=>tv,ViTForImageClassification:()=>E8,ViTMAEModel:()=>A8,ViTMAEPreTrainedModel:()=>rT,ViTMSNForImageClassification:()=>k8,ViTMSNModel:()=>C8,ViTMSNPreTrainedModel:()=>av,ViTModel:()=>S8,ViTPreTrainedModel:()=>nv,VisionEncoderDecoderModel:()=>T8,VitMatteForImageMatting:()=>O8,VitMattePreTrainedModel:()=>sT,VitPoseForPoseEstimation:()=>z8,VitPosePreTrainedModel:()=>iT,VitsModel:()=>L8,VitsModelOutput:()=>oT,VitsPreTrainedModel:()=>lT,VoxtralForConditionalGeneration:()=>F8,VoxtralRealtimeForConditionalGeneration:()=>uT,VoxtralRealtimePreTrainedModel:()=>cT,Wav2Vec2BertForCTC:()=>G8,Wav2Vec2BertForSequenceClassification:()=>j8,Wav2Vec2BertModel:()=>U8,Wav2Vec2BertPreTrainedModel:()=>vh,Wav2Vec2ForAudioFrameClassification:()=>qD,Wav2Vec2ForCTC:()=>jD,Wav2Vec2ForSequenceClassification:()=>VD,Wav2Vec2Model:()=>GD,Wav2Vec2PreTrainedModel:()=>ei,WavLMForAudioFrameClassification:()=>Q8,WavLMForCTC:()=>q8,WavLMForSequenceClassification:()=>H8,WavLMForXVector:()=>$8,WavLMModel:()=>V8,WavLMPreTrainedModel:()=>jl,WeSpeakerResNetModel:()=>W8,WeSpeakerResNetPreTrainedModel:()=>fT,WhisperForConditionalGeneration:()=>hT,WhisperModel:()=>X8,WhisperPreTrainedModel:()=>rv,XLMForQuestionAnswering:()=>nP,XLMForSequenceClassification:()=>eP,XLMForTokenClassification:()=>tP,XLMModel:()=>K8,XLMPreTrainedModel:()=>Vl,XLMRobertaForMaskedLM:()=>rP,XLMRobertaForQuestionAnswering:()=>oP,XLMRobertaForSequenceClassification:()=>sP,XLMRobertaForTokenClassification:()=>iP,XLMRobertaModel:()=>aP,XLMRobertaPreTrainedModel:()=>ql,XLMWithLMHeadModel:()=>J8,XVectorOutput:()=>dT,YolosForObjectDetection:()=>cP,YolosModel:()=>lP,YolosObjectDetectionOutput:()=>pT,YolosPreTrainedModel:()=>sv,YoutuForCausalLM:()=>dP,YoutuModel:()=>uP,YoutuPreTrainedModel:()=>iv});var Au=class extends H{},eN=class extends Au{},tN=class extends Au{async _call(e){return new Ne(await super._call(e))}},nN=class extends Au{async _call(e){return new Ln(await super._call(e))}},aN=class extends Au{async _call(e){return new dn(await super._call(e))}},lg=class extends H{},rN=class extends lg{},sN=class extends lg{},cg=class extends H{},iN=class extends cg{},oN=class extends cg{},ug=class extends H{},lN=class extends ug{},cN=class extends ug{},dg=class extends H{},uN=class extends dg{},dN=class extends dg{},ah=class extends H{},fN=class extends ah{},hN=class extends ah{},pN=class extends ah{async _call(e){return new Ne(await super._call(e))}},fg=class extends H{},mN=class extends fg{},_N=class extends fg{async _call(e){return new Ne(await super._call(e))}},zl=class extends H{},gN=class extends zl{},yN=class extends zl{async _call(e){return new dn(await super._call(e))}},vN=class extends zl{async _call(e){return new Ne(await super._call(e))}},wN=class extends zl{async _call(e){return new nn(await super._call(e))}},bN=class extends zl{async _call(e){return new Ln(await super._call(e))}},hg=class extends H{},MN=class extends hg{},xN=class extends hg{},pg=class extends H{},TN=class extends pg{},SN=class extends pg{},mg=class extends H{},EN=class extends mg{},AN=class extends mg{},Ll=class extends H{},CN=class extends Ll{},kN=class extends Ll{async _call(e){return new dn(await super._call(e))}},ON=class extends Ll{async _call(e){return new Ne(await super._call(e))}},zN=class extends Ll{async _call(e){return new nn(await super._call(e))}},LN=class extends Ll{async _call(e){return new Ln(await super._call(e))}},FN=4299n,h1=6561n,e2=class extends H{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},t2=class extends e2{async encode_speech(e){return st(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:r=null,exaggeration:s=null,position_ids:o=null,inputs_embeds:l=null,past_key_values:u=null,generation_config:d=null,logits_processor:f=null,audio_features:p=null,audio_tokens:g=null,speaker_embeddings:y=null,speaker_features:w=null,...b}){let S;if(!l){const z=this.sessions.embed_tokens.inputNames,k={input_ids:e};if(z.includes("exaggeration")){if(!(s instanceof me)){const L=e.dims[0];if(s==null)s=On([L],.5);else if(typeof s=="number")s=On([L],s);else if(Array.isArray(s))s=new me("float32",s,[L]);else throw new Error("Unsupported type for `exaggeration` input")}k.exaggeration=s}if(z.includes("position_ids")&&(k.position_ids=o),{inputs_embeds:l}=await st(this.sessions.embed_tokens,k),p&&g&&y&&w&&(S={audio_features:p,audio_tokens:g,speaker_embeddings:y,speaker_features:w}),S||r)S??=await this.encode_speech(r),l=zt([S.audio_features,l],1),t=ha([l.dims[0],l.dims[1]]);else{const L=l.dims[1];if(!u||L!==1)throw new Error("Incorrect state encountered during generation.");const R=u.get_seq_length();t=ha([l.dims[0],R+L])}}return{...await as(this,{inputs_embeds:l,past_key_values:u,attention_mask:t,generation_config:d,logits_processor:f},!1),...S}}prepare_inputs_for_generation(e,t,r){if(!t.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(t.input_ids.dims[1]===1){const s=Array.from({length:e.length},(o,l)=>e[l].length-e[l].findLastIndex(u=>u==h1)-1);t.position_ids=new me("int64",s,[e.length,1])}else{const o=t.input_ids.tolist().map(l=>{let u=0;return l.map(d=>d>=h1?0:u++)});t.position_ids=new me("int64",o.flat(),t.input_ids.dims)}return t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),yu(this,e,t)}async generate(e){const{sequences:t,audio_tokens:r,speaker_embeddings:s,speaker_features:o}=await super.generate({...e,return_dict_in_generate:!0}),l=t.slice(null,[e.input_ids.dims[1],-1]),u=On([l.dims[0],3],FN),d=zt([r,l,u],1),{waveform:f}=await st(this.sessions.conditional_decoder,{speech_tokens:d,speaker_features:o,speaker_embeddings:s});return f}},n2=class extends H{},NN=class extends n2{},rh=class extends H{},DN=class extends rh{},a2=class extends rh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},r2=class extends rh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"audio_model"})}},to=class extends H{},RN=class extends to{},BN=class extends to{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},s2=class extends to{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},PN=class extends to{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},IN=class extends to{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},_g=class extends H{},UN=class extends _g{},GN=class extends _g{},gg=class extends H{},jN=class extends gg{},VN=class extends gg{},yg=class extends H{},qN=class extends yg{},HN=class extends yg{},vg=class extends H{},$N=class extends vg{},QN=class extends vg{},Fl=class extends H{},WN=class extends Fl{},YN=class extends Fl{async _call(e){return new dn(await super._call(e))}},XN=class extends Fl{async _call(e){return new Ne(await super._call(e))}},ZN=class extends Fl{async _call(e){return new nn(await super._call(e))}},KN=class extends Fl{async _call(e){return new Ln(await super._call(e))}},wg=class extends H{},JN=class extends wg{},e4=class extends wg{async _call(e){return new Ne(await super._call(e))}},bg=class extends H{},t4=class extends bg{},n4=class extends bg{async _call(e){return new Ne(await super._call(e))}},Mg=class extends H{},a4=class extends Mg{},r4=class extends Mg{async _call(e){return new Cu(await super._call(e))}},Cu=class extends tn{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},xg=class extends H{},s4=class extends xg{},i4=class extends xg{async _call(e){return new Cu(await super._call(e))}},i2=class extends tn{constructor({audio_codes:e}){super(),this.audio_codes=e}},o2=class extends tn{constructor({audio_values:e}){super(),this.audio_values=e}},sh=class extends H{main_input_name="input_values";forward_params=["input_values"]},o4=class extends sh{async encode(e){return new i2(await st(this.sessions.encoder_model,e))}async decode(e){return new o2(await st(this.sessions.decoder_model,e))}},l2=class extends sh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},c2=class extends sh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},Nl=class extends H{},l4=class extends Nl{},c4=class extends Nl{async _call(e){return new dn(await super._call(e))}},u4=class extends Nl{async _call(e){return new Ne(await super._call(e))}},d4=class extends Nl{async _call(e){return new nn(await super._call(e))}},f4=class extends Nl{async _call(e){return new Ln(await super._call(e))}},Dl=class extends H{},h4=class extends Dl{},p4=class extends Dl{async _call(e){return new dn(await super._call(e))}},m4=class extends Dl{async _call(e){return new Ne(await super._call(e))}},_4=class extends Dl{async _call(e){return new nn(await super._call(e))}},g4=class extends Dl{async _call(e){return new Ln(await super._call(e))}},u2=class extends H{},y4=class extends u2{},Tg=class extends H{},v4=class extends Tg{},w4=class extends Tg{async _call(e){return new Ne(await super._call(e))}},d2=class extends H{},b4=class extends d2{},f2=class extends H{},M4=class extends f2{},ih=class extends H{},x4=class extends ih{},T4=class extends ih{async _call(e){return new Sg(await super._call(e))}},S4=class extends ih{async _call(e){return new h2(await super._call(e))}},Sg=class extends tn{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},h2=class extends tn{constructor({logits:e,pred_boxes:t,pred_masks:r}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=r}},Eg=class extends H{},E4=class extends Eg{},A4=class extends Eg{async _call(e){return new Ne(await super._call(e))}},Ag=class extends H{},C4=class extends Ag{},k4=class extends Ag{async _call(e){return new Ne(await super._call(e))}},p2=class extends H{},O4=class extends p2{},m2=class extends H{},z4=class extends m2{},Rl=class extends H{},L4=class extends Rl{},F4=class extends Rl{async _call(e){return new Ne(await super._call(e))}},N4=class extends Rl{async _call(e){return new nn(await super._call(e))}},D4=class extends Rl{async _call(e){return new Ln(await super._call(e))}},R4=class extends Rl{async _call(e){return new dn(await super._call(e))}},_2=class extends H{},B4=class extends _2{},Cg=class extends H{},P4=class extends Cg{},I4=class extends Cg{},kg=class extends H{},U4=class extends kg{},G4=class extends kg{async _call(e){return new Ne(await super._call(e))}},Bl=class extends H{},j4=class extends Bl{},V4=class extends Bl{async _call(e){return new dn(await super._call(e))}},q4=class extends Bl{async _call(e){return new Ne(await super._call(e))}},H4=class extends Bl{async _call(e){return new nn(await super._call(e))}},$4=class extends Bl{async _call(e){return new Ln(await super._call(e))}},Og=class extends H{},Q4=class extends Og{},W4=class extends Og{},ku=class extends H{},Y4=class extends ku{},X4=class extends ku{async _call(e){return new dn(await super._call(e))}},Z4=class extends ku{async _call(e){return new Ne(await super._call(e))}},K4=class extends ku{async _call(e){return new nn(await super._call(e))}},zg=class extends H{},J4=class extends zg{},eD=class extends zg{},Lg=class extends H{},tD=class extends Lg{},nD=class extends Lg{},Fg=class extends H{},aD=class extends Fg{},rD=class extends Fg{},Ng=class extends H{},sD=class extends Ng{},iD=class extends Ng{async _call(e){return new Ne(await super._call(e))}},g2=class extends H{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},oD=class extends g2{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:r,attention_mask:s}){return{inputs_embeds:zt([t,e],1),attention_mask:zt([ha(t.dims.slice(0,2)),s],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:r,attention_mask:s}){if(!e&&!t)throw new Error("Either `input_ids` or `pixel_values` should be provided.");let o,l;return e&&(o=await this.encode_text({input_ids:e})),t&&(l=await this.encode_image({pixel_values:t})),o&&l?{inputs_embeds:r,attention_mask:s}=this._merge_input_ids_with_image_features({inputs_embeds:o,image_features:l,input_ids:e,attention_mask:s}):r=o||l,{inputs_embeds:r,attention_mask:s}}async forward({input_ids:e,pixel_values:t,attention_mask:r,decoder_input_ids:s,decoder_attention_mask:o,encoder_outputs:l,past_key_values:u,inputs_embeds:d,decoder_inputs_embeds:f}){if(d||({inputs_embeds:d,attention_mask:r}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:d,attention_mask:r})),!l){let{last_hidden_state:g}=await Js(this,{inputs_embeds:d,attention_mask:r});l=g}if(!f){if(!s)throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");f=await this.encode_text({input_ids:s})}return await as(this,{inputs_embeds:f,attention_mask:o,encoder_attention_mask:r,encoder_hidden_states:l,past_key_values:u},!0)}},Dg=class extends H{},lD=class extends Dg{},cD=class extends Dg{},Rg=class extends H{},uD=class extends Rg{},dD=class extends Rg{},Bg=class extends H{},fD=class extends Bg{},hD=class extends Bg{},y2=class extends H{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},Pg=class extends y2{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,input_features:s=null,input_features_mask:o=null,position_ids:l=null,inputs_embeds:u=null,per_layer_inputs:d=null,past_key_values:f=null,generation_config:p=null,logits_processor:g=null,...y}){if((!u||!d)&&({inputs_embeds:u,per_layer_inputs:d}=await st(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(r){const{image_features:b}=await st(this.sessions.vision_encoder,{pixel_values:r});({inputs_embeds:u,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:b,inputs_embeds:u,input_ids:e,attention_mask:t}))}if(s){const{audio_features:b}=await st(this.sessions.audio_encoder,{input_features:s,input_features_mask:o});({inputs_embeds:u,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:b,inputs_embeds:u,input_ids:e,attention_mask:t}))}}return await as(this,{inputs_embeds:u,per_layer_inputs:d,past_key_values:f,attention_mask:t,position_ids:l,generation_config:p,logits_processor:g},!0)}_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return ig({image_token_id:this.config.image_token_id,...e,image_features:r})}_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return Jx({audio_token_id:this.config.audio_token_id,...e,audio_features:r})}},v2=class extends Pg{},Ig=class extends H{},pD=class extends Ig{},mD=class extends Ig{},Ug=class extends H{},_D=class extends Ug{},gD=class extends Ug{},Gg=class extends H{},yD=class extends Gg{},vD=class extends Gg{},jg=class extends H{},wD=class extends jg{},bD=class extends jg{},Vg=class extends H{},MD=class extends Vg{},xD=class extends Vg{},qg=class extends H{},TD=class extends qg{},SD=class extends qg{},Hg=class extends H{},ED=class extends Hg{},AD=class extends Hg{},$g=class extends H{},CD=class extends $g{},kD=class extends $g{},Qg=class extends H{},OD=class extends Qg{},zD=class extends Qg{},Wg=class extends H{},LD=class extends Wg{},FD=class extends Wg{},w2=class extends H{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},Yg=class extends w2{_merge_input_ids_with_audio_features(e){const t=e.audio_features.dims.at(-1),r=e.audio_features.view(-1,t);return Jx({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:r})}},ND=class extends Yg{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},b2=class extends H{},DD=class extends b2{},M2=class extends H{},RD=class extends M2{},Xg=class extends H{},BD=class extends Xg{},PD=class extends Xg{},Zg=class extends H{},ID=class extends Zg{},UD=class extends Zg{async _call(e){return new Ne(await super._call(e))}},ei=class extends H{},GD=class extends ei{},jD=class extends ei{async _call(e){return new eo(await super._call(e))}},VD=class extends ei{async _call(e){return new Ne(await super._call(e))}},qD=class extends ei{async _call(e){return new nn(await super._call(e))}},HD=class extends H{},$D=class extends ei{},QD=class extends ei{async _call(e){return new eo(await super._call(e))}},WD=class extends ei{async _call(e){return new Ne(await super._call(e))}},Kg=class extends H{},YD=class extends Kg{},XD=class extends Kg{},x2=class extends H{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},Xi=class extends x2{_merge_input_ids_with_image_features(e){const t=e.image_features.dims.at(-1),r=e.image_features.view(-1,t);return ig({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:r})}},ZD=class extends Xi{},KD=class extends Xi{},JD=class extends Xi{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},Jg=class extends H{},e6=class extends Jg{},t6=class extends Jg{async _call(e){return new Ne(await super._call(e))}},ey=class extends H{},n6=class extends ey{},a6=class extends ey{},oh=class extends H{},r6=class extends oh{async forward(e){const t=!e.input_ids,r=!e.pixel_values;if(t&&r)throw new Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=ha([e.pixel_values.dims[0],1])),r){const{image_size:f}=this.config.vision_config;e.pixel_values=On([0,3,f,f],0)}const{text_embeddings:s,image_embeddings:o,l2norm_text_embeddings:l,l2norm_image_embeddings:u}=await super.forward(e),d={};return t||(d.text_embeddings=s,d.l2norm_text_embeddings=l),r||(d.image_embeddings=o,d.l2norm_image_embeddings=u),d}},T2=class extends oh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},s6=class extends oh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},ty=class extends H{},i6=class extends ty{},o6=class extends ty{},ny=class extends H{},l6=class extends ny{},c6=class extends ny{},u6=class extends Xi{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},ay=class extends H{},d6=class extends ay{},f6=class extends ay{},S2=class extends H{},h6=class extends S2{},ry=class extends H{},p6=class extends ry{},m6=class extends ry{},sy=class extends H{},_6=class extends sy{},g6=class extends sy{},iy=class extends H{},y6=class extends iy{},v6=class extends iy{},oy=class extends H{},w6=class extends oy{},b6=class extends oy{},Ou=class extends H{},M6=class extends Ou{},x6=class extends Ou{},T6=class extends Ou{async _call(e){return new Ne(await super._call(e))}},S6=class extends Ou{},E2=class extends H{},E6=class extends E2{},A2=class extends H{},A6=class extends A2{},C2=class extends tn{constructor({char_logits:e,bpe_logits:t,wp_logits:r}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=r}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},k2=class extends H{},C6=class extends k2{async _call(e){return new C2(await super._call(e))}},O2=class extends tn{constructor({audio_codes:e}){super(),this.audio_codes=e}},z2=class extends tn{constructor({audio_values:e}){super(),this.audio_values=e}},lh=class extends H{main_input_name="input_values";forward_params=["input_values"]},k6=class extends lh{async encode(e){return new O2(await st(this.sessions.encoder_model,e))}async decode(e){return new z2(await st(this.sessions.decoder_model,e))}},L2=class extends lh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},F2=class extends lh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},ly=class extends H{},O6=class extends ly{},z6=class extends ly{},zu=class extends H{},L6=class extends zu{},F6=class extends zu{async _call(e){return new dn(await super._call(e))}},N6=class extends zu{async _call(e){return new Ne(await super._call(e))}},D6=class extends zu{async _call(e){return new Ln(await super._call(e))}},cy=class extends H{},R6=class extends cy{},B6=class extends cy{},ch=class extends H{},P6=class extends ch{},I6=class extends ch{async _call(e){return new Ne(await super._call(e))}},U6=class extends ch{},uh=class extends H{},G6=class extends uh{},j6=class extends uh{async _call(e){return new Ne(await super._call(e))}},V6=class extends uh{},dh=class extends H{},q6=class extends dh{},H6=class extends dh{async _call(e){return new Ne(await super._call(e))}},$6=class extends dh{},fh=class extends H{},Q6=class extends fh{},W6=class extends fh{async _call(e){return new Ne(await super._call(e))}},Y6=class extends fh{},uy=class extends H{},X6=class extends uy{},Z6=class extends uy{async _call(e){return new Ne(await super._call(e))}},dy=class extends H{},K6=class extends dy{},J6=class extends dy{async _call(e){return new Ne(await super._call(e))}},Lu=class extends H{},eR=class extends Lu{},tR=class extends Lu{async _call(e){return new dn(await super._call(e))}},nR=class extends Lu{async _call(e){return new Ne(await super._call(e))}},aR=class extends Lu{async _call(e){return new nn(await super._call(e))}},fy=class extends H{},rR=class extends fy{},sR=class extends fy{},hy=class extends H{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},iR=class extends hy{},oR=class extends hy{},Pl=class extends H{},lR=class extends Pl{},cR=class extends Pl{async _call(e){return new dn(await super._call(e))}},uR=class extends Pl{async _call(e){return new Ne(await super._call(e))}},dR=class extends Pl{async _call(e){return new nn(await super._call(e))}},fR=class extends Pl{async _call(e){return new Ln(await super._call(e))}},py=class extends H{},hR=class extends py{},pR=class extends py{},my=class extends H{},mR=class extends my{},_R=class extends my{},N2=class extends H{},gR=class extends N2{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...e){super(...e),this._generation_mode="text"}async forward(e){const t=this._generation_mode??"text";let r;if(t==="text"||!e.past_key_values){const d=this.sessions.prepare_inputs_embeds,f=yn(e,d.inputNames);r=await st(d,f)}else{const d=this.sessions.gen_img_embeds,f=yn({image_ids:e.input_ids},d.inputNames);r=await st(d,f)}const s={...e,...r},o=await as(this,s),l=this.sessions[t==="text"?"lm_head":"gen_head"];if(!l)throw new Error(`Unable to find "${l}" generation head`);const u=await st(l,yn(o,l.inputNames));return{...r,...o,...u}}prepare_inputs_for_generation(e,t,r){const s=!!t.past_key_values;return r.guidance_scale!==null&&r.guidance_scale>1&&(s?t.input_ids=zt([t.input_ids,t.input_ids],0):(t.input_ids=zt([t.input_ids,m_(t.input_ids,BigInt(r.pad_token_id))],0),t.attention_mask=zt([t.attention_mask,m_(t.attention_mask,0n)],0))),(s||!t.pixel_values)&&(t.pixel_values=On([0,0,3,384,384],1)),s&&(t.images_seq_mask=new me("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new me("bool",new Array(0).fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode="text",super.generate(e)}async generate_images(e){this._generation_mode="image";const t=(e.inputs??e[this.main_input_name]).dims[1],s=(await super.generate(e)).slice(null,[t,null]),o=this.sessions.image_decode,{decoded_image:l}=await st(o,{generated_tokens:s}),u=l.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),d=[];for(const f of u){const p=Xa.fromTensor(f);d.push(p)}return d}},_y=class extends H{},yR=class extends _y{},vR=class extends _y{},D2=class extends H{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(e){const[t,r]=e.dims,s=this.config.decoder.num_codebooks,o=r-s;let l=0;for(let f=0;f0&&y<=o&&(e.data[l++]=e.data[f])}const u=Math.floor(t/s),d=l/(u*s);return new me(e.type,e.data.slice(0,l),[u,s,d])}prepare_inputs_for_generation(e,t,r){const s=BigInt(this.config.decoder.pad_token_id);let o=structuredClone(e);for(let l=0;l=u&&(o[l][u]=s);return r.guidance_scale!==null&&r.guidance_scale>1&&(o=o.concat(o)),jf(this,o,t)}async generate(e){const t=await super.generate(e),r=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:s}=await st(this.sessions.encodec_decode,{audio_codes:r});return s}},gy=class extends H{},wR=class extends gy{},bR=class extends gy{},Il=class extends H{},MR=class extends Il{},xR=class extends Il{async _call(e){return new dn(await super._call(e))}},TR=class extends Il{async _call(e){return new Ne(await super._call(e))}},SR=class extends Il{async _call(e){return new nn(await super._call(e))}},ER=class extends Il{async _call(e){return new Ln(await super._call(e))}},R2=class extends H{},AR=class extends R2{},yy=class extends H{},CR=class extends yy{},kR=class extends yy{},vy=class extends H{},OR=class extends vy{},zR=class extends vy{},wy=class extends H{},LR=class extends wy{},FR=class extends wy{},by=class extends H{},NR=class extends by{},DR=class extends by{},My=class extends H{},RR=class extends My{},BR=class extends My{},xy=class extends H{},PR=class extends xy{},IR=class extends xy{},Ty=class extends H{},UR=class extends Ty{},GR=class extends Ty{},Sy=class extends H{},jR=class extends Sy{},VR=class extends Sy{},qR=class extends Xi{},B2=class extends H{},HR=class extends B2{async _call(e){return new eo(await super._call(e))}},Ey=class extends H{},$R=class extends Ey{},QR=class extends Ey{},Ay=class extends H{},WR=class extends Ay{},YR=class extends Ay{},Cy=class extends H{},XR=class extends Cy{},ZR=class extends Cy{},ky=class extends H{},KR=class extends ky{},JR=class extends ky{},P2=class extends H{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},I2=class extends P2{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:r=null,image_sizes:s=null,position_ids:o=null,inputs_embeds:l=null,past_key_values:u=null,generation_config:d=null,logits_processor:f=null,...p}){if(!l){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 st(this.sessions.vision_encoder,{pixel_values:r,image_sizes:s}))}else{const w=this.config.normalized_config.hidden_size;y=new me("float32",[],[0,w])}({inputs_embeds:l}=await st(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:y}))}return await as(this,{inputs_embeds:l,past_key_values:u,attention_mask:t,position_ids:o,generation_config:d,logits_processor:f},!1)}},Oy=class extends H{},eB=class extends Oy{},tB=class extends Oy{async _call(e){return new Ne(await super._call(e))}},zy=class extends H{},nB=class extends zy{},aB=class extends zy{async _call(e){return new nn(await super._call(e))}},Ly=class extends H{},rB=class extends Ly{},sB=class extends Ly{},Fy=class extends H{},iB=class extends Fy{},oB=class extends Fy{},U2=class extends H{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},Ny=class extends U2{image_grid_thw_name="grid_thw";get_rope_index(e,t,r,s){const{vision_config:o,image_token_id:l,video_token_id:u,vision_start_token_id:d}=this.config,f=o.spatial_merge_size??2,p=[];if(t||r){let g=e.tolist();s||(s=nx(e));const y=s.tolist(),w=Array.from({length:3},k=>Array.from({length:e.dims[0]},L=>Array.from({length:e.dims[1]},R=>1))),b=t?t.tolist():[],S=r?r.tolist():[];let E=0,z=0;for(let k=0;ky[k][I]==1),N=L.reduce((ee,I,$)=>(I==d&&ee.push($),ee),[]).map(ee=>L[ee+1]),B=N.filter(ee=>ee==l).length,j=N.filter(ee=>ee==u).length;let C=[],ue=0,oe=B,he=j;for(let ee=0;eeDt>ue&&an==l),$=L.findIndex((an,Dt)=>Dt>ue&&an==u),J=oe>0&&I!==-1?I:L.length+1,D=he>0&&$!==-1?$:L.length+1;let te,ae,ge,Me;J0?Ht(C.at(-1))[0]+1:0;C.push(Array.from({length:3*ke},(an,Dt)=>Ue+Dt%ke));const xt=ke+Ue,He=Ee*ze*et,Ye=Array.from({length:He},(an,Dt)=>xt+Math.floor(Dt/(ze*et))),bn=Array.from({length:He},(an,Dt)=>xt+Math.floor(Dt/et)%ze),za=Array.from({length:He},(an,Dt)=>xt+Dt%et);C.push([Ye,bn,za].flat()),ue=te+He}if(ue0?Ht(C.at(-1))[0]+1:0,I=L.length-ue;C.push(Array.from({length:3*I},($,J)=>ee+J%I))}const _e=C.reduce((ee,I)=>ee+I.length,0),de=new Array(_e);let re=0;for(let ee=0;ee<3;++ee)for(let I=0;Ig[E%g.length]),b=Array.from({length:y[0]},(S,E)=>Ht(g.subarray(y[1]*E,y[1]*(E+1)))[0]+1n+BigInt(y[1]));return[new me("int64",w,[3,...y]),new me("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 me("int64",w,[3,...e.dims]),ax([g,1])]}}async encode_image({pixel_values:e,image_grid_thw:t}){return(await st(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return ig({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,r){if(t.attention_mask&&!t.position_ids)if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;const s=t.past_key_values.get_seq_length();if(so+u);t.position_ids=Ji([l,l,l],0)}}return t}},Dy=class extends Ny{},G2=class extends Ny{image_grid_thw_name="image_grid_thw"},Ry=class extends Dy{image_grid_thw_name="image_grid_thw"},By=class extends H{},lB=class extends By{},cB=class extends By{},Py=class extends H{},uB=class extends Py{},dB=class extends Py{},Iy=class extends H{},fB=class extends Iy{},hB=class extends Iy{},Uy=class extends G2{},Gy=class extends Ry{},pB=class extends Uy{},j2=class extends Gy{},jy=class extends Uy{},Vy=class extends jy{},mB=class extends jy{},V2=class extends Vy{},qy=class extends H{},_B=class extends qy{},gB=class extends qy{async _call(e){return new Ne(await super._call(e))}},Hy=class extends H{},yB=class extends Hy{},vB=class extends Hy{async _call(e){return new q2(await super._call(e))}},q2=class extends Cu{},Ul=class extends H{},wB=class extends Ul{},bB=class extends Ul{async _call(e){return new dn(await super._call(e))}},MB=class extends Ul{async _call(e){return new Ne(await super._call(e))}},xB=class extends Ul{async _call(e){return new nn(await super._call(e))}},TB=class extends Ul{async _call(e){return new Ln(await super._call(e))}},Gl=class extends H{},SB=class extends Gl{},EB=class extends Gl{async _call(e){return new dn(await super._call(e))}},AB=class extends Gl{async _call(e){return new Ne(await super._call(e))}},CB=class extends Gl{async _call(e){return new nn(await super._call(e))}},kB=class extends Gl{async _call(e){return new Ln(await super._call(e))}},$y=class extends H{},OB=class extends $y{},zB=class extends $y{async _call(e){return new H2(await super._call(e))}},H2=class extends Cu{},$2=class extends tn{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},Q2=class extends H{},LB=class extends Q2{async get_image_embeddings({pixel_values:e}){return await Js(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??=ha(e.input_points.dims.slice(0,-1));const t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await st(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new $2(await super._call(e))}},W2=class extends tn{constructor({iou_scores:e,pred_masks:t,object_score_logits:r}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=r}},Y2=class extends H{},Qy=class extends Y2{async get_image_embeddings({pixel_values:e}){return await Js(this,{pixel_values:e})}async forward(e){const{num_feature_levels:t}=this.config.vision_config;if(Array.from({length:t},(l,u)=>`image_embeddings.${u}`).some(l=>!e[l])?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 l=e.input_points.dims;e.input_labels??=ha(l.slice(0,-1)),e.input_boxes??=On([l[0],0,4],0)}else if(e.input_boxes){const l=e.input_boxes.dims;e.input_labels=On([l[0],l[1],0],-1n),e.input_points=On([l[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=yn(e,s.inputNames);return await st(s,o)}async _call(e){return new W2(await super._call(e))}},FB=class extends Qy{},NB=class extends Qy{},hh=class extends H{},DB=class extends hh{},RB=class extends hh{},BB=class extends hh{},ph=class extends H{},PB=class extends ph{},IB=class extends ph{},UB=class extends ph{},Wy=class extends H{},GB=class extends Wy{},X2=class extends Wy{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"text_model"})}},jB=class extends to{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"vision_model"})}},Yy=class extends H{},VB=class extends Yy{},qB=class extends Yy{},mh=class extends H{main_input_name="input_values";forward_params=["input_values"]},HB=class extends mh{async encode(e){return await st(this.sessions.encoder_model,e)}async decode(e){return await st(this.sessions.decoder_model,e)}},Z2=class extends mh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"encoder_model"})}},K2=class extends mh{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??"decoder_model"})}},_h=class extends H{},$B=class extends _h{},QB=class extends _h{},WB=class extends _h{async generate_speech(e,t,{threshold:r=.5,minlenratio:s=0,maxlenratio:o=20,vocoder:l=null}={}){const u={input_ids:e},{encoder_outputs:d,encoder_attention_mask:f}=await Js(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,z=0;for(;;){++z;const R=Yx(!!E);let N;E?N=E.output_sequence_out:N=new me("float32",new Float32Array(w),[1,1,w]);let B={use_cache_branch:R,output_sequence:N,encoder_attention_mask:f,speaker_embeddings:t,encoder_hidden_states:d};this.addPastKeyValues(B,S),E=await st(this.sessions.decoder_model_merged,B),S=this.getPastKeyValues(E,S);const{prob:j,spectrum:C}=E;if(b.push(C),z>=y&&(Array.from(j.data).filter(ue=>ue>=r).length>0||z>=g))break}const k=zt(b),{waveform:L}=await st(l.sessions.model,{spectrogram:k});return{spectrogram:k,waveform:L}}},YB=class extends H{main_input_name="spectrogram"},Fu=class extends H{},XB=class extends Fu{},ZB=class extends Fu{async _call(e){return new dn(await super._call(e))}},KB=class extends Fu{async _call(e){return new Ne(await super._call(e))}},JB=class extends Fu{async _call(e){return new Ln(await super._call(e))}},Xy=class extends H{},e8=class extends Xy{},t8=class extends Xy{},Zy=class extends H{},n8=class extends Zy{},a8=class extends Zy{},J2=class extends H{},r8=class extends J2{},eT=class extends H{},tT=class extends eT{async generate_speech({input_ids:e,attention_mask:t,style:r,num_inference_steps:s=5,speed:o=1.05}){const{sampling_rate:l,chunk_compress_factor:u,base_chunk_size:d,latent_dim:f}=this.config,{last_hidden_state:p,durations:g}=await st(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:r}),y=g.div(o).mul_(l),w=d*u,b=y.data,S=Int32Array.from(b,oe=>Math.ceil(oe/w)),E=Math.max(...S),z=e.dims[0],k=new BigInt64Array(z*E);for(let oe=0;oez*k,1);f[S]=new me(p,new g(E),y[S])}const w=new me(p,new g(d*p1),[1,d,p1]),b=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!b)throw new Error("input_features must be iterable or async iterable");return{encoder_session:o,enc_kv_cache:f,enc_padding_cache:w,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:b,text_hidden_size:r.hidden_size}}async function R8(e,t){const r=t.dims[2],s=Math.floor((N8+r-3)/2)+1,o=new me("int64",BigInt64Array.from({length:s},(g,y)=>BigInt(e.enc_past_seq_len+y)),[1,s]),l=e.enc_past_seq_len+s,u=ha([1,l]),{audio_embeds:d,present_padding_cache:f,...p}=await st(e.encoder_session,{input_features:t,attention_mask:u,position_ids:o,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location==="gpu-buffer"&&e.enc_padding_cache.dispose(),e.enc_padding_cache=f;for(const g in p)if(g.startsWith("present.")){const y=g.replace("present","past_key_values"),w=e.enc_kv_cache[y];w?.location==="gpu-buffer"&&w.dispose(),e.enc_kv_cache[y]=p[g]}return e.enc_past_seq_len=l,d}async function B8(e,t){for(;e.audio_embed_total_tokens0&&e.audio_embed_queue.length>0;){const u=e.audio_embed_queue[0],d=u.tokens-e.audio_queue_offset,f=Math.min(l,d),p=e.audio_queue_offset*e.text_hidden_size;for(let g=0;g=u.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=r-l}var I8=class extends th{constructor(e){super(),this._s=e}_call(e){const t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},cT=class extends H{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},uT=class extends cT{async forward({input_ids:e,past_key_values:t,...r}){const s=e.dims[1],o=t_.get(this);o&&await B8(o,o.audio_consumed+s);const{inputs_embeds:l}=await st(this.sessions.embed_tokens,{input_ids:e});o&&P8(o,l,s);const u={inputs_embeds:l,...r};this.addPastKeyValues(u,t);const d=this.sessions.decoder_model_merged,f=yn(u,d.inputNames);return await st(d,f)}async generate({input_features:e,stopping_criteria:t,...r}){if(!e)throw new Error("input_features (generator/iterable) must be provided");const s=D8(this,e);t_.set(this,s);const o=new $x;o.push(new I8(s)),t&&o.extend(t);try{return await super.generate({...r,stopping_criteria:o})}finally{s.enc_kv_cache.dispose(),t_.delete(this)}}},vh=class extends H{},U8=class extends vh{},G8=class extends vh{async _call(e){return new eo(await super._call(e))}},j8=class extends vh{async _call(e){return new Ne(await super._call(e))}},dT=class extends tn{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},jl=class extends H{},V8=class extends jl{},q8=class extends jl{async _call(e){return new eo(await super._call(e))}},H8=class extends jl{async _call(e){return new Ne(await super._call(e))}},$8=class extends jl{async _call(e){return new dT(await super._call(e))}},Q8=class extends jl{async _call(e){return new nn(await super._call(e))}},fT=class extends H{},W8=class extends fT{},Y8=class extends Hx{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},rv=class extends H{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},X8=class extends rv{},hT=class extends rv{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,Y8)}_retrieve_init_tokens(e){const t=[e.decoder_start_token_id];let r=e.language;const s=e.task;if(e.is_multilingual){r||(Re.warn("No language specified - defaulting to English (en)."),r="en");const l=`<|${cz(r)}|>`;t.push(e.lang_to_id[l]),t.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&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(Re.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(o=>o!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:r=null,stopping_criteria:s=null,...o}){t=this._prepare_generation_config(t,o);const l=o.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(r??=new w_,r.push(new NF(t,l))),t.begin_suppress_tokens&&(r??=new w_,r.push(new qx(t.begin_suppress_tokens,l.length))),t.return_token_timestamps){if(!t.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.");t.task==="translate"&&Re.warn("Token-level timestamps may not be reliable for task 'translate'."),t.output_attentions=!0,t.return_dict_in_generate=!0}const u=await super.generate({inputs:e,generation_config:t,logits_processor:r,decoder_input_ids:l,...o});return t.return_token_timestamps&&(u.token_timestamps=this._extract_token_timestamps(u,t.alignment_heads,t.num_frames)),u}_extract_token_timestamps(e,t,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&&Re.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&&(Re.warn("Model config has no `median_filter_width`, using default value of 7."),o=7);const l=e.cross_attentions,u=Array.from({length:this.config.decoder_layers},(S,E)=>zt(l.map(z=>z[E]),2)),d=Ji(t.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),[f,p]=pO(d,-2,0,!0),g=d.clone();for(let S=0;Sz[j+1]-z[j]),R=Sr([1],L).map(B=>!!B),N=[];for(let B=0;Be[0]);static BASE_IF_FAIL=!0},m1=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},bP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},n_=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},MP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},xP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},TP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},HT=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},SP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},EP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},AP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},CP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},_1=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},g1=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},y1=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},kP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},OP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var zP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_CTC_MAPPING_NAMES]},LP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]});(class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]});var FP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var NP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},DP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]});(class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]});var RP=class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]});(class extends ft{static MODEL_CLASS_MAPPINGS=[dt.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]});async function tr(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(t=>Xa.read(t)))}async function vu(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(r=>typeof r=="string"||r instanceof URL?yz(r,t):r instanceof Float64Array?new Float32Array(r):r))}function M_(e,t){t&&(e=e.map(u=>u|0));const[r,s,o,l]=e;return{xmin:r,ymin:s,xmax:o,ymax:l}}var Vt=class extends Oa{constructor({task:e,model:t,tokenizer:r=null,processor:s=null}){super(),this.task=e,this.model=t,this.tokenizer=r,this.processor=s}async dispose(){await this.model.dispose()}},BP=class extends Vt{async _call(e,{top_k:t=1}={}){const r=this.tokenizer(e,{padding:!0,truncation:!0}),s=await this.model(r),{problem_type:o,id2label:l}=this.model.config,u=o==="multi_label_classification"?f=>f.sigmoid():f=>new me("float32",wn(f.data),f.dims),d=[];for(const f of s.logits){const p=u(f),g=await Ol(p,t),y=g[0].tolist(),b=g[1].tolist().map((S,E)=>({label:l?l[S]:`LABEL_${S}`,score:y[E]}));t===1?d.push(...b):d.push(b)}return Array.isArray(e)||t===1?d:d[0]}},PP=class extends Vt{async _call(e,{ignore_labels:t=["O"]}={}){const r=Array.isArray(e),s=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),l=(await this.model(s)).logits,u=this.model.config.id2label,d=[];for(let f=0;fB==g),E=l[w].tolist(),z=u[w].tolist();for(let B=1;Bj==b[B])!==-1)&&(E[B]=-1/0,z[B]=-1/0);const k=wn(E).map((B,j)=>[B,j]),L=wn(z).map((B,j)=>[B,j]);k[0][0]=0,L[0][0]=0;const R=bA(k,L).filter(B=>B[0][1]<=B[1][1]).map(B=>[B[0][1],B[1][1],B[0][0]*B[1][0]]).sort((B,j)=>j[2]-B[2]),N=[];for(let B=0;BE==r);if(g===-1)throw Error(`Mask token (${s}) not found in text.`);const y=l[f][g],w=await Ol(new me("float32",wn(y.data),y.dims),t),b=w[0].tolist(),S=w[1].tolist();u.push(S.map((E,z)=>{const k=p.slice();return k[g]=E,{score:b[z],token:Number(E),token_str:this.tokenizer.decode([E]),sequence:this.tokenizer.decode(k,{skip_special_tokens:!0})}}))}return Array.isArray(e)?u:u[0]}},ov=class extends Vt{_key="generated_text";async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(d=>this.model.config.prefix+d));const r=this.model.config.task_specific_params;r&&r[this.task]&&r[this.task].prefix&&(e=e.map(d=>r[this.task].prefix+d));const s=this.tokenizer,o={padding:!0,truncation:!0};let l;this.task==="translation"&&"_build_translation_inputs"in s?l=s._build_translation_inputs(e,o,t):l=s(e,o);const u=await this.model.generate({...l,...t});return s.batch_decode(u,{skip_special_tokens:!0}).map(d=>({[this._key]:d}))}},GP=class extends ov{_key="summary_text"},jP=class extends ov{_key="translation_text"};function v1(e){return Array.isArray(e)&&e.every(t=>"role"in t&&"content"in t)}var VP=class extends Vt{async _call(e,t={}){let r=!1,s=!1,o=t.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,l=t.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(v1(e))e=[e];else if(Array.isArray(e)&&e.every(v1))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,...l})),o=!1,l=void 0}const d=s?!1:t.return_full_text??!0;this.tokenizer.padding_side="left";const f=this.tokenizer(u,{add_special_tokens:o,padding:!0,truncation:!0,...l}),p=await this.model.generate({...f,...t}),g=this.tokenizer.batch_decode(p,{skip_special_tokens:!0});let y;!d&&f.input_ids.dims.at(-1)>0&&(y=this.tokenizer.batch_decode(f.input_ids,{skip_special_tokens:!0}).map(b=>b.length));const w=Array.from({length:e.length},b=>[]);for(let b=0;b[t.toLowerCase(),r])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(Re.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&&(Re.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:r="This example is {}.",multi_label:s=!1}={}){const o=Array.isArray(e);o||(e=[e]),Array.isArray(t)||(t=[t]);const l=t.map(f=>r.replace("{}",f)),u=s||t.length===1,d=[];for(const f of e){const p=[];for(const w of l){const b=this.tokenizer(f,{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=>wn(w)[1]):wn(p)).map((w,b)=>[w,b]).sort((w,b)=>b[0]-w[0]);d.push({sequence:f,labels:y.map(w=>t[w[1]]),scores:y.map(w=>w[0])})}return o?d:d[0]}},HP=class extends Vt{async _call(e,{top_k:t=5}={}){const r=this.processor.feature_extractor.config.sampling_rate,s=await vu(e,r),o=this.model.config.id2label,l=[];for(const u of s){const d=await this.processor(u),p=(await this.model(d)).logits[0],g=await Ol(new me("float32",wn(p.data),p.dims),t),y=g[0].tolist(),b=g[1].tolist().map((S,E)=>({label:o?o[S]:`LABEL_${S}`,score:y[E]}));l.push(b)}return Array.isArray(e)?l:l[0]}},$P=class extends Vt{async _call(e,t,{hypothesis_template:r="This is a sound of {}."}={}){const s=!Array.isArray(e);s&&(e=[e]);const o=t.map(p=>r.replace("{}",p)),l=this.tokenizer(o,{padding:!0,truncation:!0}),u=this.processor.feature_extractor.config.sampling_rate,d=await vu(e,u),f=[];for(const p of d){const g=await this.processor(p),y=await this.model({...l,...g}),w=wn(y.logits_per_audio.data);f.push([...w].map((b,S)=>({score:b,label:t[S]})))}return s?f[0]:f}},QP=class extends Vt{async _call(e,t={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(e,t);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(e,t);case"moonshine":return this._call_moonshine(e,t);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&Re.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&Re.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,l=await vu(s,o),u=[];for(const d of l){const f=await this.processor(d),g=(await this.model(f)).logits[0],y=[];for(const b of g)y.push(Ht(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,t){const r=t.return_timestamps??!1,s=t.chunk_length_s??0,o=t.force_full_sequences??!1;let l=t.stride_length_s??null;const u={...t};r==="word"&&(u.return_token_timestamps=!0,u.return_timestamps=!1);const d=!Array.isArray(e),f=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 vu(f,w),S=[];for(const E of b){let z=[];if(s>0){if(l===null)l=s/6;else if(s<=l)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const R=w*s,N=w*l,B=R-2*N;let j=0;for(;;){const C=j+R,ue=E.subarray(j,C),oe=await this.processor(ue),he=j===0,_e=C>=E.length;if(z.push({stride:[ue.length,he?0:N,_e?0:N],input_features:oe.input_features,is_last:_e}),_e)break;j+=B}}else z=[{stride:[E.length,0,0],input_features:(await this.processor(E)).input_features,is_last:!0}];for(const R of z){u.num_frames=Math.floor(R.stride[0]/y);const N=await this.model.generate({inputs:R.input_features,...u});r==="word"?(R.tokens=N.sequences.tolist()[0],R.token_timestamps=N.token_timestamps.tolist()[0].map(B=>mu(B,2))):R.tokens=N[0].tolist(),R.stride=R.stride.map(B=>B/w)}const[k,L]=this.tokenizer._decode_asr(z,{time_precision:g,return_timestamps:r,force_full_sequences:o});S.push({text:k,...L})}return d?S[0]:S}async _call_moonshine(e,t){const r=!Array.isArray(e),s=r?[e]:e,o=this.processor.feature_extractor.config.sampling_rate,l=await vu(s,o),u=[];for(const d of l){const f=await this.processor(d),p=Math.floor(d.length/o)*6,g=await this.model.generate({max_new_tokens:p,...t,...f}),y=this.processor.batch_decode(g,{skip_special_tokens:!0})[0];u.push({text:y})}return r?u[0]:u}},WP=class extends Vt{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e=="string"||e instanceof URL)&&(e=new Float32Array(await(await rt.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new me("float32",e,[e.length]);else if(!(e instanceof me))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw new Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,r,s=null){const o=t.data,[l,u]=t.dims,d=s?s.data:null,f=[];for(let p=0;p({generated_text:p.trim()}));l.push(f)}return r?l:l[0]}},XP=class extends Vt{async _call(e,{top_k:t=5}={}){const r=await tr(e),{pixel_values:s}=await this.processor(r),o=await this.model({pixel_values:s}),{id2label:l}=this.model.config,u=[];for(const d of o.logits){const f=await Ol(new me("float32",wn(d.data),d.dims),t),p=f[0].tolist(),y=f[1].tolist().map((w,b)=>({label:l?l[w]:`LABEL_${w}`,score:p[b]}));u.push(y)}return Array.isArray(e)?u:u[0]}},w1={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},$T=class extends Vt{async _call(e,{threshold:t=.5,mask_threshold:r=.5,overlap_mask_area_threshold:s=.8,label_ids_to_fuse:o=null,target_sizes:l=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 f=await tr(e),p=f.map(k=>[k.height,k.width]),g=await this.processor(f),{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 k=y[0];if(k in g)throw Error(`Input name ${k} already exists in the inputs.`);g[k]=g.pixel_values}const b=await this.model(g);let S=null;if(u!==null)S=w1[u];else if(this.processor.image_processor){for(const[k,L]of Object.entries(w1))if(L in this.processor.image_processor){S=this.processor.image_processor[L].bind(this.processor.image_processor),u=k;break}}const E=this.model.config.id2label,z=[];if(u)if(u==="panoptic"||u==="instance"){const k=S(b,t,r,s,o,l??p)[0],L=k.segmentation;for(const R of k.segments_info){const N=new Uint8ClampedArray(L.data.length);for(let j=0;jC<-1e-5||C>1+1e-5)&&B.sigmoid_();const j=await Xa.fromTensor(B.mul_(255).to("uint8")).resize(N[1],N[0]);z.push({label:null,score:null,mask:j})}}return z}},ZP=class extends $T{async _call(e,t={}){const r=await tr(e),s=await super._call(e,t),o=r.map((l,u)=>{const d=l.clone();return d.putAlpha(s[u].mask),d});return Array.isArray(e)?o:o[0]}},KP=class extends Vt{async _call(e,t,{hypothesis_template:r="This is a photo of {}"}={}){const s=Array.isArray(e),o=await tr(e),l=t.map(y=>r.replace("{}",y)),u=this.tokenizer(l,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:d}=await this.processor(o),f=await this.model({...u,pixel_values:d}),p=this.model.config.model_type==="siglip"?y=>y.sigmoid().data:y=>wn(y.data),g=[];for(const y of f.logits_per_image){const b=[...p(y)].map((S,E)=>({score:S,label:t[E]}));b.sort((S,E)=>E.score-S.score),g.push(b)}return s?g:g[0]}},JP=class extends Vt{async _call(e,{threshold:t=.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 tr(e),l=r?null:o.map(w=>[w.height,w.width]),{pixel_values:u,pixel_mask:d}=await this.processor(o),f=await this.model({pixel_values:u,pixel_mask:d}),p=this.processor.image_processor.post_process_object_detection(f,t,l),{id2label:g}=this.model.config,y=p.map(w=>w.boxes.map((b,S)=>({score:w.scores[S],label:g[w.classes[S]],box:M_(b,!r)})));return s?y:y[0]}},e5=class extends Vt{async _call(e,t,{threshold:r=.1,top_k:s=null,percentage:o=!1}={}){const l=Array.isArray(e),u=await tr(e),d=this.tokenizer(t,{padding:!0,truncation:!0}),f=await this.processor(u),p=[];for(let g=0;g({score:z.scores[L],label:z.labels[L],box:M_(k,!o)}))}else{const z=this.processor.image_processor.post_process_object_detection(S,r,w,!0)[0];E=z.boxes.map((k,L)=>({score:z.scores[L],label:t[z.classes[L]],box:M_(k,!o)}))}E.sort((z,k)=>k.score-z.score),s!==null&&(E=E.slice(0,s)),p.push(E)}return l?p:p[0]}},t5=class extends Vt{async _call(e,t,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 tr(e))[0],{pixel_values:o}=await this.processor(s),l=`${t}`,u=this.tokenizer(l,{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}]}},n5=class extends Vt{async _call(e){const t=await tr(e),r=await this.processor(t),s=await this.model(r),o=[];for(const l of s.reconstruction){const u=l.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");o.push(Xa.fromTensor(u))}return Array.isArray(e)?o:o[0]}},a5=class extends Vt{async _call(e){const t=await tr(e),r=await this.processor(t),{predicted_depth:s}=await this.model(r),o=[];for(let l=0;lxu.from_pretrained(e,{config:t,cache_dir:r,local_files_only:s,revision:o}))}async function o5(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:o=null}={}){t=await i5(e,{config:t});const l=["config.json"],u=t["transformers.js_config"]??{},d=u.use_external_data_format,f="onnx",p=s??u.device;let g=r??u.dtype,y;const w=t.architectures||[];let b=!1;for(const k of w){const L=ns.get(k);if(L!==void 0){y=L,b=!0;break}}if(!b&&t.model_type){const k=ns.get(t.model_type);if(k!==void 0&&(y=k,b=!0),!b){for(const L of Object.values(yl))if(L.has(t.model_type)){y=ns.get(L.get(t.model_type)),b=!0;break}}}if(!b){const k=w.length>0?w.join(", "):"(none)";Re.warn(`[get_model_files] Architecture(s) not found in MODEL_TYPE_MAPPING: [${k}] for model type '${t.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Kf}`),y=ve.EncoderOnly}const S=(k,L=null)=>{L=L??k;const R=KM(p,k),N=JM(g,k,R),B=p_[N]??"",j=`${L}${B}.onnx`,C=`${f}/${j}`;l.push(C);const ue=Gx(d,j,k);for(const oe of jx(j,ue)){const he=`${f}/${oe}`;l.push(he)}},{sessions:E,optional_configs:z}=YF(y,t,{model_file_name:o});for(const[k,L]of Object.entries(E))S(k,L);if(z)for(const k of Object.values(z))l.push(k);return l}async function l5(e){if(!e)throw new Error("modelId is required");return(await Zf(e,Mu,{})).exists?[Mu]:[]}async function c5(e,{config:t=null,dtype:r=null,device:s=null,model_file_name:o=null,include_tokenizer:l=!0,include_processor:u=!0}={}){const d=await o5(e,{config:t,dtype:r,device:s,model_file_name:o});if(l){const f=await sx(e);d.push(...f)}if(u){const f=await l5(e);d.push(...f)}return d}async function u5(e,t,r={}){e=QT[e]??e;const s=Vf[e];if(!s)throw new Error(`Unsupported pipeline task: ${e}. Must be one of [${Object.keys(Vf).join(", ")}]`);const{type:o}=s;return c5(t,{...r,include_tokenizer:o!=="audio"&&o!=="image",include_processor:o!=="text"})}async function WT(e,t=null,{progress_callback:r=null,config:s=null,cache_dir:o=null,local_files_only:l=!1,revision:u="main",device:d=null,dtype:f=null,subfolder:p="onnx",use_external_data_format:g=null,model_file_name:y=null,session_options:w={}}={}){e=QT[e]??e;const b=Vf[e.split("_",1)[0]];if(!b)throw Error(`Unsupported pipeline: ${e}. Must be one of [${Object.keys(Vf)}]`);t||(t=b.default.model,Re.info(`No model specified. Using default model: "${t}".`),!f&&b.default.dtype&&(f=b.default.dtype));const S=await u5(e,t,{device:d,dtype:f});let E={};r&&(await Promise.all(S.map(async _e=>Zf(t,_e)))).forEach((_e,de)=>{_e.exists&&(E[S[de]]={loaded:0,total:_e.size??0})});const z={progress_callback:r?(he=>{if(he.status==="progress"){E[he.file]={loaded:he.loaded,total:he.total};const _e=Object.values(E).reduce((W,pe)=>W+pe.loaded,0),de=Object.values(E).reduce((W,pe)=>W+pe.total,0),re=de>0?_e/de*100:0;r({status:"progress_total",name:he.name,progress:re,loaded:_e,total:de,files:structuredClone(E)})}r(he)}):void 0,config:s,cache_dir:o,local_files_only:l,revision:u,device:d,dtype:f,subfolder:p,use_external_data_format:g,model_file_name:y,session_options:w},k=S.includes("tokenizer.json"),L=S.includes("preprocessor_config.json"),R=b.model;let N;if(Array.isArray(R)){const he=s??await xu.from_pretrained(t,z),{model_type:_e}=he,de=R.find(re=>re.supports(_e));if(!de)throw Error(`Unsupported model type "${_e}" for task "${e}". None of the candidate model classes support this type.`);N=de.from_pretrained(t,{...z,config:he})}else N=R.from_pretrained(t,z);const[B,j,C]=await Promise.all([k?yt.from_pretrained(t,z):null,L?MF.from_pretrained(t,z):null,N]),ue={task:e,model:C};B&&(ue.tokenizer=B),j&&(ue.processor=j),$i(r,{status:"ready",task:e,model:t});const oe=b.pipeline;return new oe(ue)}We.IS_PROCESS_AVAILABLE;const d5=3600,f5=540,h5=60,p5=2,m5=1,_5=.05,g5=.02,y5=.75,v5=.6,w5=.4,b1=1.2,M1=.75,b5=40,M5=e=>`task: search result | query: ${e}`,x5=(e,t)=>`title: ${e} | text: ${t}`,T5="shreyask/embeddinggemma-300m-ONNX",x1="onnx-community/Qwen3-Reranker-0.6B-ONNX",S5="shreyask/qmd-query-expansion-1.7B-ONNX",E5=["API versioning best practices","distributed consensus algorithms","gradient descent optimization"];let qf=null,Hf=null,$f=null,kf=null,YT=-1,XT=-1;async function A5(){if(!navigator.gpu)return!1;try{return await navigator.gpu.requestAdapter()!==null}catch{return!1}}function lv(e,t){if(!t)return;let r=-1,s=null;return o=>{switch(o.status){case"initiate":r<0&&(r=0,t({name:e,status:"downloading",progress:0}));break;case"download":break;case"progress":{const l=o.progress/100;(l-r>=.02||l>=1)&&(r=l,s&&clearTimeout(s),s=setTimeout(()=>{t({name:e,status:"downloading",progress:l})},50));break}case"done":s&&clearTimeout(s),t({name:e,status:"loading",progress:1});break;case"ready":s&&clearTimeout(s),r=1,t({name:e,status:"ready",progress:1});break}}}async function C5(e){if(qf)return;const t="embedding";e?.({name:t,status:"pending",progress:0});try{qf=await WT("feature-extraction",T5,{dtype:"q4",device:"webgpu",progress_callback:lv(t,e)}),e?.({name:t,status:"ready",progress:1})}catch(r){throw e?.({name:t,status:"error",progress:0,error:r instanceof Error?r.message:String(r)}),r}}async function k5(e){if($f)return;const t="reranker";e?.({name:t,status:"pending",progress:0});try{const r=lv(t,e);kf=await yt.from_pretrained(x1,{progress_callback:r});const s=kf("yes",{add_special_tokens:!1}).input_ids.data,o=kf("no",{add_special_tokens:!1}).input_ids.data;YT=Number(s[s.length-1]),XT=Number(o[o.length-1]),$f=await HT.from_pretrained(x1,{dtype:"q4",device:"webgpu",progress_callback:r}),e?.({name:t,status:"ready",progress:1})}catch(r){throw e?.({name:t,status:"error",progress:0,error:r instanceof Error?r.message:String(r)}),r}}async function O5(e){if(Hf)return;const t="expansion";e?.({name:t,status:"pending",progress:0});try{Hf=await WT("text-generation",S5,{dtype:"q4",device:"webgpu",progress_callback:lv(t,e)}),e?.({name:t,status:"ready",progress:1})}catch(r){throw e?.({name:t,status:"error",progress:0,error:r instanceof Error?r.message:String(r)}),r}}async function z5(e){if(!await A5()){const r="WebGPU is not available in this browser";for(const s of["embedding","reranker","expansion"])e?.({name:s,status:"error",progress:0,error:r});throw new Error(r)}await k5(e),await C5(e),await O5(e).catch(()=>{})}function ZT(){return qf}function L5(){return $f}function F5(){return kf}function N5(){return{yes:YT,no:XT}}function D5(){return Hf}function R5(){return qf!==null&&$f!==null}function B5(){return Hf!==null}const KT=800,P5=[[/\n#{1}(?!#)/g,100,"h1"],[/\n#{2}(?!#)/g,90,"h2"],[/\n#{3}(?!#)/g,80,"h3"],[/\n#{4}(?!#)/g,70,"h4"],[/\n#{5}(?!#)/g,60,"h5"],[/\n#{6}(?!#)/g,50,"h6"],[/\n```/g,80,"codeblock"],[/\n(?:---|\*\*\*|___)\s*\n/g,60,"hr"],[/\n\n+/g,20,"blank"],[/\n[-*]\s/g,5,"list"],[/\n\d+\.\s/g,5,"numlist"],[/\n/g,1,"newline"]];function I5(e){const t=new Map;for(const[r,s,o]of P5)for(const l of e.matchAll(r)){const u=l.index,d=t.get(u);(!d||s>d.score)&&t.set(u,{pos:u,score:s,type:o})}return[...t.values()].sort((r,s)=>r.pos-s.pos)}function U5(e){const t=[],r=/\n```/g;let s=!1,o=0;for(const l of e.matchAll(r))s?(t.push({start:o,end:l.index+l[0].length}),s=!1):(o=l.index,s=!0);return s&&t.push({start:o,end:e.length}),t}function G5(e,t){return t.some(r=>e>r.start&&et)break;if(G5(f.pos,o))continue;const g=(t-f.pos)/r,y=1-g*g*s,w=f.score*y;w>u&&(u=w,d=f.pos)}return d}function V5(e,t=d5,r=f5,s=KT){if(e.length<=t)return[{text:e,pos:0}];const o=I5(e),l=U5(e),u=[];let d=0;for(;dd&&y<=f&&(p=y)}if(p<=d&&(p=Math.min(d+t,e.length)),u.push({text:e.slice(d,p),pos:d}),p>=e.length)break;d=p-r;const g=u.at(-1).pos;d<=g&&(d=p)}return u}function a_(e,t){const r=e.match(/^#\s+(.+)$/m);if(r)return r[1].trim();const s=t.lastIndexOf(".");return s>0?t.slice(0,s):t}function q5(e){return V5(e.body).map((r,s)=>({docId:e.id,chunkIndex:s,text:r.text,startChar:r.pos,title:e.title}))}async function T1(e){const t=ZT();if(!t)throw new Error("Embedding model not loaded");const r=M5(e),s=await t(r,{pooling:"mean",normalize:!0});return new Float32Array(s.tolist()[0])}async function H5(e,t){const r=ZT();if(!r)throw new Error("Embedding model not loaded");const s=x5(e,t),o=await r(s,{pooling:"mean",normalize:!0});return new Float32Array(o.tolist()[0])}function S1(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2)}class $5{chunks;avgDocLength;docLengths;termFreqs;docFreqs;N;constructor(t){this.chunks=t,this.N=t.length,this.docLengths=[],this.termFreqs=new Map,this.docFreqs=new Map;let r=0;for(let s=0;s0?r/this.N:0}search(t,r=20){const s=S1(t);if(s.length===0||this.N===0)return[];const o=new Float64Array(this.N);for(const u of s){const d=this.docFreqs.get(u);if(d===void 0)continue;const f=this.termFreqs.get(u),p=Math.log((this.N-d+.5)/(d+.5)+1);for(let g=0;g0&&l.push({chunk:this.chunks[u],score:o[u],source:"bm25"});return l.sort((u,d)=>d.score-u.score),l.slice(0,r)}}const Q5=e=>`/no_think Expand this search query: ${e}`;function W5(e){const t=e.trim().split(` +`);let r="";const s=[];let o="";for(const l of t){const u=l.trim();u.toLowerCase().startsWith("lex:")?r=u.slice(4).trim():u.toLowerCase().startsWith("vec:")?s.push(u.slice(4).trim()):u.toLowerCase().startsWith("hyde:")&&(o=u.slice(5).trim())}return!r&&s.length===0&&!o?{lex:e,vec:[e],hyde:e}:{lex:r||e,vec:s.length>0?s:[e],hyde:o||e}}async function Y5(e){const t=D5();if(!t)throw new Error("Expansion model not loaded");const r=Q5(e),o=(await t(r,{max_new_tokens:256,do_sample:!1}))[0].generated_text,l=typeof o=="string"?o.slice(r.length):o;return W5(String(l))}function X5(e,t){let r=0,s=0,o=0;for(let l=0;l({chunk:o,score:X5(e,o.embedding),source:"vector"}));return s.sort((o,l)=>l.score-o.score),s.slice(0,r)}function Z5(e,t=b5){const r=new Map;e.forEach((o,l)=>{const u=l<2?p5:m5;o.results.forEach((d,f)=>{const p=f+1,g=u/(h5+p),y=r.get(d.chunk.docId);y?(y.totalScore+=g,y.topRank=Math.min(y.topRank,p),y.contributions.push({source:d.source,queryType:o.queryType,query:o.query,rank:p,weight:u,rrfContribution:g}),d.score>y.bestChunkScore&&(y.bestChunk=d.chunk.text,y.bestChunkScore=d.score)):r.set(d.chunk.docId,{docId:d.chunk.docId,filepath:d.chunk.docId,title:d.chunk.title,bestChunk:d.chunk.text,bestChunkScore:d.score,totalScore:g,topRank:p,contributions:[{source:d.source,queryType:o.queryType,query:o.query,rank:p,weight:u,rrfContribution:g}]})})});for(const o of r.values())o.topRank===1&&(o.totalScore+=_5),o.topRank<=2&&(o.totalScore+=g5);return Array.from(r.values()).sort((o,l)=>l.totalScore-o.totalScore).slice(0,t).map(o=>({docId:o.docId,filepath:o.filepath,title:o.title,bestChunk:o.bestChunk,score:o.totalScore,contributions:o.contributions}))}const K5='Judge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be "yes" or "no".',J5="Given a web search query, retrieve relevant passages that answer the query";function eI(e,t,r){return`<|im_start|>system +${K5}<|im_end|> +<|im_start|>user +: ${J5} + +: ${e} + +: ${t}<|im_end|> +<|im_start|>assistant + + + +`}async function tI(e,t){const r=L5(),s=F5(),o=N5();if(!r||!s)throw new Error("Reranker model not loaded");const l=eI(e,t),u=s(l,{truncation:!0,max_length:2048}),d=await r(u),[,f,p]=d.logits.dims.map(Number),g=(f-1)*p,y=d.logits.data,w=y[g+o.yes],b=y[g+o.no],S=Math.max(w,b),E=Math.exp(w-S),z=Math.exp(b-S);return E/(E+z)}function nI(e,t){const r=e.map((l,u)=>{const d=u+1,f=t.get(l.docId)??0;let p;d<=3?p=y5:d<=10?p=v5:p=w5;const g=p*l.score+(1-p)*f;return{...l,rerankScore:f,blendedScore:g}});r.sort((l,u)=>u.blendedScore-l.blendedScore);const s=new Set,o=[];for(const l of r)s.has(l.docId)||(s.add(l.docId),o.push({filepath:l.filepath,title:l.title,bestChunk:l.bestChunk,score:l.blendedScore,docId:l.docId}));return o}async function*aI(e){const{query:t,embeddedChunks:r,bm25Index:s}=e;let o;if(B5()){yield{stage:"expansion",status:"running"};try{o=await Y5(t),yield{stage:"expansion",status:"done",data:o}}catch(R){o={lex:t,vec:[t],hyde:t},yield{stage:"expansion",status:"error",error:String(R)}}}else o={lex:t,vec:[t],hyde:t},yield{stage:"expansion",status:"error",error:"Expansion model not loaded — using original query"};yield{stage:"search",status:"running"};const l=s.search(t,20),u=s.search(o.lex,20),d=o.vec.flatMap(R=>s.search(R,20)),f=await T1(o.hyde),p=await Promise.all(o.vec.map(R=>T1(R))),g=E1(f,r,20),y=p.flatMap(R=>E1(R,r,20)),w=[...l,...u,...d],b=[...g,...y];yield{stage:"search",status:"done",data:{bm25Hits:w,vectorHits:b}};const S=[{results:l,queryType:"original",query:t},{results:g,queryType:"hyde",query:o.hyde},{results:u,queryType:"lex",query:o.lex},...o.vec.map((R,N)=>({results:y.slice(N*20,(N+1)*20),queryType:"vec",query:R})),...o.vec.map((R,N)=>({results:d.slice(N*20,(N+1)*20),queryType:"vec",query:R}))],E=Z5(S);yield{stage:"rrf",status:"done",data:{merged:E}},yield{stage:"rerank",status:"running"};const z=new Map;for(const R of E){const N=await tI(t,R.bestChunk);z.set(R.docId,N)}const k=E.map(R=>({...R,rerankScore:z.get(R.docId)??0,blendedScore:0}));yield{stage:"rerank",status:"done",data:{before:E,after:k}},yield{stage:"blend",status:"done",data:{finalResults:nI(E,z)}}}function rI({onSearch:e,disabled:t}){const[r,s]=jt.useState("");function o(u){u.preventDefault();const d=r.trim();d&&e(d)}function l(u){s(u),e(u)}return Z.jsxs("div",{style:{marginBottom:"1.5rem"},children:[Z.jsxs("form",{onSubmit:o,style:{display:"flex",gap:"0.5rem"},children:[Z.jsx("input",{type:"text",value:r,onChange:u=>s(u.target.value),disabled:t,placeholder:t?"Loading models…":"Enter a search query…",style:{flex:1,padding:"0.6rem 0.9rem",fontSize:"1rem",fontFamily:"system-ui, -apple-system, sans-serif",border:"1px solid #ccc",borderRadius:"6px",background:t?"#f5f5f5":"#fff",color:t?"#999":"#111",outline:"none",transition:"border-color 0.15s"},onFocus:u=>{t||(u.target.style.borderColor="#4285F4")},onBlur:u=>{u.target.style.borderColor="#ccc"}}),Z.jsx("button",{type:"submit",disabled:t||!r.trim(),style:{padding:"0.6rem 1.2rem",fontSize:"1rem",fontFamily:"system-ui, -apple-system, sans-serif",background:t||!r.trim()?"#ccc":"#4285F4",color:"#fff",border:"none",borderRadius:"6px",cursor:t||!r.trim()?"not-allowed":"pointer",transition:"background 0.15s",fontWeight:600},children:"Search"})]}),Z.jsxs("div",{style:{marginTop:"0.6rem",display:"flex",gap:"0.4rem",flexWrap:"wrap",alignItems:"center"},children:[Z.jsx("span",{style:{fontSize:"0.8rem",color:"#666",fontFamily:"system-ui, -apple-system, sans-serif"},children:"Examples:"}),E5.map(u=>Z.jsx("button",{onClick:()=>l(u),disabled:t,style:{padding:"0.25rem 0.6rem",fontSize:"0.8rem",fontFamily:"system-ui, -apple-system, sans-serif",background:"#f0f4ff",color:t?"#aaa":"#4285F4",border:"1px solid #c5d5ff",borderRadius:"4px",cursor:t?"not-allowed":"pointer"},children:u},u))]})]})}const sI={pending:"#9e9e9e",downloading:"#1976d2",loading:"#f9a825",ready:"#388e3c",error:"#d32f2f"},iI={pending:"Pending",downloading:"Downloading",loading:"Loading",ready:"Ready",error:"Error"};function oI({progress:e,color:t}){return Z.jsx("div",{style:{height:"4px",background:"#e0e0e0",borderRadius:"2px",overflow:"hidden",marginTop:"4px"},children:Z.jsx("div",{style:{height:"100%",width:`${Math.round(e*100)}%`,background:t,borderRadius:"2px",transition:"width 0.3s ease"}})})}function lI({model:e}){const t=sI[e.status],r=e.status==="downloading"||e.status==="loading";return Z.jsxs("div",{style:{padding:"0.5rem 0.75rem",background:"#fff",border:"1px solid #e0e0e0",borderRadius:"6px",marginBottom:"0.4rem"},children:[Z.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[Z.jsx("span",{style:{fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.78rem",color:"#333"},children:e.name}),Z.jsxs("span",{style:{fontSize:"0.72rem",fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:600,color:t,display:"flex",alignItems:"center",gap:"0.3rem"},children:[e.status==="ready"&&Z.jsx("span",{style:{fontSize:"0.85rem"},children:"✓"}),e.status==="error"&&Z.jsx("span",{style:{fontSize:"0.85rem"},children:"✗"}),iI[e.status],r&&Z.jsxs("span",{style:{color:"#888",fontWeight:400},children:[Math.round(e.progress*100),"%"]})]})]}),r&&Z.jsx(oI,{progress:e.progress,color:t}),e.status==="error"&&e.error&&Z.jsx("div",{style:{marginTop:"4px",fontSize:"0.72rem",color:"#d32f2f",fontFamily:"system-ui, -apple-system, sans-serif"},children:e.error})]})}function cI({models:e}){const t=e.length>0&&e.every(r=>r.status==="ready");return Z.jsxs("div",{style:{padding:"1rem",background:"#f8f8f8",border:"1px solid #e0e0e0",borderRadius:"8px",marginBottom:"1.5rem"},children:[Z.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"0.6rem"},children:[Z.jsx("h3",{style:{margin:0,fontSize:"0.85rem",fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:600,color:"#444",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Models"}),t&&Z.jsx("span",{style:{fontSize:"0.75rem",fontFamily:"system-ui, -apple-system, sans-serif",color:"#388e3c",fontWeight:600},children:"All ready"})]}),e.map(r=>Z.jsx(lI,{model:r},r.name)),e.length===0&&Z.jsx("div",{style:{color:"#999",fontSize:"0.85rem",fontFamily:"system-ui, -apple-system, sans-serif"},children:"No models configured."})]})}function uI(){return Z.jsx("span",{style:{display:"inline-block",width:"16px",height:"16px",border:"2px solid #ddd",borderTopColor:"#f9a825",borderRadius:"50%",animation:"spin 0.7s linear infinite"}})}function r_({label:e,content:t}){const r=Array.isArray(t)?t.join(` +`):t;return Z.jsxs("div",{style:{background:"#fff",border:"1px solid #e0e0e0",borderRadius:"6px",padding:"0.65rem 0.85rem",marginBottom:"0.5rem"},children:[Z.jsx("div",{style:{fontSize:"0.72rem",fontWeight:700,fontFamily:"system-ui, -apple-system, sans-serif",color:"#f57f17",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"0.4rem"},children:e}),Z.jsx("div",{style:{fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.72rem",color:"#333",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:r})]})}function dI({state:e}){const t=e.status==="idle",r=e.status==="running",s=e.status==="done",o=e.status==="error";return Z.jsxs("div",{style:{opacity:t?.45:1,transition:"opacity 0.3s"},children:[Z.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem"},children:[Z.jsx("h3",{style:{margin:0,fontSize:"0.8rem",fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:700,color:"#5d4037",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Query Expansion"}),r&&Z.jsx(uI,{})]}),t&&Z.jsx("p",{style:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.8rem",color:"#999",margin:0},children:"Awaiting query…"}),r&&Z.jsx("p",{style:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.8rem",color:"#888",margin:0,fontStyle:"italic"},children:"Generating expanded queries…"}),o&&Z.jsxs("div",{style:{padding:"0.65rem",background:"#fce4ec",border:"1px solid #ef9a9a",borderRadius:"6px",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.8rem",color:"#c62828"},children:["Error: ",e.error]}),s&&e.data&&Z.jsxs(Z.Fragment,{children:[Z.jsx(r_,{label:"HyDE (Hypothetical Document)",content:e.data.hyde}),Z.jsx(r_,{label:"Vec Sentences",content:e.data.vec}),Z.jsx(r_,{label:"Lex Keywords",content:e.data.lex})]})]})}function fI(){return Z.jsx("span",{style:{display:"inline-block",width:"16px",height:"16px",border:"2px solid #ddd",borderTopColor:"#00897b",borderRadius:"50%",animation:"spin 0.7s linear infinite"}})}function hI({score:e,source:t}){const r=t==="bm25"?e.toFixed(2):(e*100).toFixed(1)+"%",s=t==="vector"?"#e0f2f1":"#e8eaf6",o=t==="vector"?"#00695c":"#283593";return Z.jsx("span",{style:{padding:"0.1rem 0.35rem",borderRadius:"4px",background:s,color:o,fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.68rem",fontWeight:700,flexShrink:0},children:r})}function pI({hit:e}){const[t,r]=jt.useState(!1);return Z.jsxs("div",{onClick:()=>r(s=>!s),style:{padding:"0.45rem 0.65rem",background:"#fff",border:"1px solid #e0e0e0",borderRadius:"5px",marginBottom:"0.3rem",cursor:"pointer",fontSize:"0.78rem"},onMouseEnter:s=>{s.currentTarget.style.boxShadow="0 1px 5px rgba(0,0,0,0.08)"},onMouseLeave:s=>{s.currentTarget.style.boxShadow="none"},children:[Z.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.4rem"},children:[Z.jsx("span",{style:{flex:1,fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:600,color:"#1a1a1a",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.chunk.title}),Z.jsx(hI,{score:e.score,source:e.source}),Z.jsx("span",{style:{color:"#bbb",fontSize:"0.65rem"},children:t?"▲":"▼"})]}),t&&Z.jsx("div",{style:{marginTop:"0.4rem",fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.68rem",color:"#555",lineHeight:1.55,whiteSpace:"pre-wrap",wordBreak:"break-word",borderTop:"1px solid #f0f0f0",paddingTop:"0.4rem"},children:e.chunk.text})]})}function A1({label:e,hits:t,color:r}){const s=t.slice(0,5);return Z.jsxs("div",{style:{marginBottom:"0.85rem"},children:[Z.jsxs("div",{style:{fontSize:"0.72rem",fontWeight:700,fontFamily:"system-ui, -apple-system, sans-serif",color:r,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"0.4rem"},children:[e," ",Z.jsxs("span",{style:{color:"#999",fontWeight:400},children:["(",t.length," hits)"]})]}),s.map((o,l)=>Z.jsx(pI,{hit:o},`${o.chunk.docId}-${o.chunk.chunkIndex}-${l}`)),t.length>5&&Z.jsxs("div",{style:{fontSize:"0.72rem",color:"#999",fontFamily:"system-ui, -apple-system, sans-serif",paddingLeft:"0.25rem"},children:["+",t.length-5," more"]})]})}function mI({state:e}){const t=e.status==="idle",r=e.status==="running",s=e.status==="done";return Z.jsxs("div",{style:{opacity:t?.45:1,transition:"opacity 0.3s"},children:[Z.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem"},children:[Z.jsx("h3",{style:{margin:0,fontSize:"0.8rem",fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:700,color:"#004d40",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Parallel Search"}),r&&Z.jsx(fI,{})]}),t&&Z.jsx("p",{style:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.8rem",color:"#999",margin:0},children:"Awaiting expansion…"}),r&&Z.jsx("p",{style:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.8rem",color:"#888",margin:0,fontStyle:"italic"},children:"Running vector + BM25 search…"}),s&&e.data&&Z.jsxs(Z.Fragment,{children:[Z.jsx(A1,{label:"Vector Search",hits:e.data.vectorHits,color:"#00695c"}),Z.jsx(A1,{label:"BM25 Search",hits:e.data.bm25Hits,color:"#283593"})]})]})}function _I({score:e}){const t=Math.round(e*100),r=t>=80?"#e8f5e9":t>=50?"#fff8e1":"#fce4ec",s=t>=80?"#2e7d32":t>=50?"#f57f17":"#c62828";return Z.jsxs("span",{style:{display:"inline-block",padding:"0.15rem 0.45rem",borderRadius:"4px",background:r,color:s,fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.72rem",fontWeight:700},children:[t,"%"]})}function gI({title:e,score:t,snippet:r,expanded:s,onToggle:o}){const[l,u]=jt.useState(!1),d=s!==void 0,f=d?s:l;function p(){d?o?.():u(y=>!y)}const g=r.length>200?r.slice(0,200)+"…":r;return Z.jsxs("div",{onClick:p,style:{padding:"0.65rem 0.85rem",background:"#fff",border:"1px solid #e0e0e0",borderRadius:"6px",marginBottom:"0.4rem",cursor:"pointer",transition:"box-shadow 0.15s"},onMouseEnter:y=>{y.currentTarget.style.boxShadow="0 2px 8px rgba(0,0,0,0.1)"},onMouseLeave:y=>{y.currentTarget.style.boxShadow="none"},children:[Z.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"0.5rem"},children:[Z.jsx("span",{style:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.85rem",fontWeight:600,color:"#1a1a1a",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:e}),Z.jsx(_I,{score:t}),Z.jsx("span",{style:{color:"#999",fontSize:"0.75rem",flexShrink:0},children:f?"▲":"▼"})]}),Z.jsx("div",{style:{marginTop:"0.4rem",fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.72rem",color:"#555",lineHeight:1.5,whiteSpace:f?"pre-wrap":"nowrap",overflow:"hidden",textOverflow:f?"unset":"ellipsis"},children:f?r:g})]})}function yI(){return Z.jsx("span",{style:{display:"inline-block",width:"16px",height:"16px",border:"2px solid #ddd",borderTopColor:"#43a047",borderRadius:"50%",animation:"spin 0.7s linear infinite"}})}function s_({label:e,color:t,badge:r}){return Z.jsxs("div",{style:{fontSize:"0.72rem",fontWeight:700,fontFamily:"system-ui, -apple-system, sans-serif",color:t,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"0.4rem",display:"flex",alignItems:"center",gap:"0.4rem"},children:[e,r&&Z.jsx("span",{style:{color:"#999",fontWeight:400,fontSize:"0.68rem"},children:r})]})}function vI({result:e,rank:t}){return Z.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",padding:"0.35rem 0.55rem",background:"#fff",border:"1px solid #e0e0e0",borderRadius:"5px",marginBottom:"0.25rem",fontSize:"0.75rem"},children:[Z.jsxs("span",{style:{fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",color:"#aaa",fontSize:"0.68rem",minWidth:"18px"},children:["#",t]}),Z.jsx("span",{style:{flex:1,fontFamily:"system-ui, -apple-system, sans-serif",color:"#1a1a1a",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),Z.jsx("span",{style:{fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.68rem",color:"#2e7d32",fontWeight:700,flexShrink:0},children:e.score.toFixed(4)})]})}function wI({before:e,after:t}){const r=e.slice(0,5),s=[...t].sort((o,l)=>l.blendedScore-o.blendedScore).slice(0,5);return Z.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0.5rem"},children:[Z.jsxs("div",{children:[Z.jsx("div",{style:{fontSize:"0.68rem",fontWeight:600,fontFamily:"system-ui, -apple-system, sans-serif",color:"#888",marginBottom:"0.3rem",textAlign:"center"},children:"Before"}),r.map((o,l)=>Z.jsxs("div",{style:{padding:"0.3rem 0.4rem",background:"#fff",border:"1px solid #e0e0e0",borderRadius:"4px",marginBottom:"0.2rem",fontSize:"0.68rem",display:"flex",gap:"0.3rem"},children:[Z.jsxs("span",{style:{fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",color:"#bbb"},children:[l+1,"."]}),Z.jsx("span",{style:{fontFamily:"system-ui, -apple-system, sans-serif",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#333"},children:o.title})]},o.docId))]}),Z.jsxs("div",{children:[Z.jsx("div",{style:{fontSize:"0.68rem",fontWeight:600,fontFamily:"system-ui, -apple-system, sans-serif",color:"#388e3c",marginBottom:"0.3rem",textAlign:"center"},children:"After Rerank"}),s.map((o,l)=>Z.jsxs("div",{style:{padding:"0.3rem 0.4rem",background:"#f1f8e9",border:"1px solid #c8e6c9",borderRadius:"4px",marginBottom:"0.2rem",fontSize:"0.68rem",display:"flex",gap:"0.3rem"},children:[Z.jsxs("span",{style:{fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",color:"#81c784"},children:[l+1,"."]}),Z.jsx("span",{style:{fontFamily:"system-ui, -apple-system, sans-serif",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#2e7d32",fontWeight:500},children:o.title})]},o.docId))]})]})}function bI({state:e}){const t=e.rrf.status==="done",r=e.rerank.status==="running",s=e.rerank.status==="done",o=e.blend.status==="done",l=!t&&!r&&!s&&!o;return Z.jsxs("div",{style:{opacity:l?.45:1,transition:"opacity 0.3s"},children:[Z.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem"},children:[Z.jsx("h3",{style:{margin:0,fontSize:"0.8rem",fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:700,color:"#1b5e20",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Fusion & Reranking"}),r&&Z.jsx(yI,{})]}),l&&Z.jsx("p",{style:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.8rem",color:"#999",margin:0},children:"Awaiting search…"}),t&&e.rrf.data&&Z.jsxs("div",{style:{marginBottom:"0.85rem"},children:[Z.jsx(s_,{label:"RRF Fusion",color:"#558b2f",badge:`(${e.rrf.data.merged.length} docs)`}),e.rrf.data.merged.slice(0,5).map((u,d)=>Z.jsx(vI,{result:u,rank:d+1},u.docId)),e.rrf.data.merged.length>5&&Z.jsxs("div",{style:{fontSize:"0.72rem",color:"#999",fontFamily:"system-ui, -apple-system, sans-serif",paddingLeft:"0.25rem"},children:["+",e.rrf.data.merged.length-5," more"]})]}),r&&!s&&Z.jsx("p",{style:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.8rem",color:"#888",margin:"0 0 0.75rem 0",fontStyle:"italic"},children:"Reranking with cross-encoder…"}),s&&e.rerank.data&&Z.jsxs("div",{style:{marginBottom:"0.85rem"},children:[Z.jsx(s_,{label:"Reranking",color:"#33691e"}),Z.jsx(wI,{before:e.rerank.data.before,after:e.rerank.data.after})]}),o&&e.blend.data&&Z.jsxs("div",{children:[Z.jsx(s_,{label:"Final Results",color:"#1b5e20",badge:`(${e.blend.data.finalResults.length} docs)`}),e.blend.data.finalResults.slice(0,5).map(u=>Z.jsx(gI,{title:u.title,score:u.score,snippet:u.bestChunk},u.docId))]})]})}const C1=[{label:"User Query",bg:"#E8F0FE",headerColor:"#1a237e"},{label:"Query Expansion",bg:"#FFF8E1",headerColor:"#5d4037"},{label:"Parallel Search",bg:"#E0F2F1",headerColor:"#004d40"},{label:"Result Fusion & Reranking",bg:"#E8F5E9",headerColor:"#1b5e20"}];function MI({query:e}){return Z.jsxs("div",{children:[Z.jsx("h3",{style:{margin:"0 0 0.75rem 0",fontSize:"0.8rem",fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:700,color:"#1a237e",textTransform:"uppercase",letterSpacing:"0.05em"},children:"User Query"}),e?Z.jsx("div",{style:{padding:"0.65rem 0.85rem",background:"#fff",border:"1px solid #c5cae9",borderRadius:"6px",fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.85rem",color:"#1a237e",wordBreak:"break-word",lineHeight:1.5},children:e}):Z.jsx("p",{style:{fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"0.8rem",color:"#999",margin:0},children:"No query yet."})]})}function xI({state:e,query:t}){return Z.jsxs(Z.Fragment,{children:[Z.jsx("style",{children:` + @keyframes spin { + to { transform: rotate(360deg); } + } + `}),Z.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"0",borderRadius:"10px",overflow:"hidden",border:"1px solid #d0d0d0",boxShadow:"0 2px 12px rgba(0,0,0,0.07)"},children:C1.map((r,s)=>Z.jsxs("div",{style:{background:r.bg,padding:"1rem",borderRight:s{d.target===d.currentTarget&&e()},children:Z.jsxs("div",{style:{background:"#fff",borderRadius:"10px",padding:"1.5rem",width:"90%",maxWidth:"560px",boxShadow:"0 8px 32px rgba(0,0,0,0.2)",fontFamily:"system-ui, -apple-system, sans-serif"},children:[Z.jsx("h3",{style:{margin:"0 0 1rem 0",fontSize:"1rem",color:"#1a1a1a"},children:"Paste Document"}),Z.jsxs("div",{style:{marginBottom:"0.75rem"},children:[Z.jsx("label",{style:{fontSize:"0.8rem",color:"#555",display:"block",marginBottom:"0.3rem"},children:"Filename"}),Z.jsx("input",{type:"text",value:o,onChange:d=>l(d.target.value),style:{width:"100%",padding:"0.45rem 0.65rem",fontSize:"0.85rem",fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",border:"1px solid #ccc",borderRadius:"5px",boxSizing:"border-box"}})]}),Z.jsxs("div",{style:{marginBottom:"1rem"},children:[Z.jsx("label",{style:{fontSize:"0.8rem",color:"#555",display:"block",marginBottom:"0.3rem"},children:"Content (Markdown or plain text)"}),Z.jsx("textarea",{value:r,onChange:d=>s(d.target.value),rows:12,placeholder:"Paste your document content here…",style:{width:"100%",padding:"0.5rem 0.65rem",fontSize:"0.8rem",fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",border:"1px solid #ccc",borderRadius:"5px",resize:"vertical",boxSizing:"border-box",lineHeight:1.5}})]}),Z.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"0.5rem"},children:[Z.jsx("button",{onClick:e,style:{padding:"0.5rem 1rem",fontSize:"0.85rem",fontFamily:"system-ui, -apple-system, sans-serif",background:"#f5f5f5",color:"#555",border:"1px solid #ddd",borderRadius:"5px",cursor:"pointer"},children:"Cancel"}),Z.jsx("button",{onClick:u,disabled:!r.trim(),style:{padding:"0.5rem 1rem",fontSize:"0.85rem",fontFamily:"system-ui, -apple-system, sans-serif",background:r.trim()?"#4285F4":"#ccc",color:"#fff",border:"none",borderRadius:"5px",cursor:r.trim()?"pointer":"not-allowed",fontWeight:600},children:"Add Document"})]})]})})}function SI({documents:e,onUpload:t,onPaste:r}){const s=jt.useRef(null),[o,l]=jt.useState(!1);function u(d){const f=d.target.files;f&&f.length>0&&t(f),d.target.value=""}return Z.jsxs("div",{style:{padding:"1rem",background:"#f8f8f8",border:"1px solid #e0e0e0",borderRadius:"8px",marginBottom:"1.5rem",fontFamily:"system-ui, -apple-system, sans-serif"},children:[Z.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"0.6rem"},children:[Z.jsxs("h3",{style:{margin:0,fontSize:"0.85rem",fontWeight:600,color:"#444",textTransform:"uppercase",letterSpacing:"0.05em"},children:["Documents",Z.jsxs("span",{style:{marginLeft:"0.5rem",fontSize:"0.75rem",fontWeight:400,color:"#888"},children:["(",e.length,")"]})]}),Z.jsxs("div",{style:{display:"flex",gap:"0.4rem"},children:[Z.jsx("button",{onClick:()=>s.current?.click(),style:{padding:"0.3rem 0.7rem",fontSize:"0.78rem",background:"#fff",color:"#4285F4",border:"1px solid #4285F4",borderRadius:"5px",cursor:"pointer",fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:500},children:"Upload"}),Z.jsx("button",{onClick:()=>l(!0),style:{padding:"0.3rem 0.7rem",fontSize:"0.78rem",background:"#fff",color:"#34a853",border:"1px solid #34a853",borderRadius:"5px",cursor:"pointer",fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:500},children:"Paste"})]})]}),Z.jsx("input",{ref:s,type:"file",accept:".md,.txt",multiple:!0,style:{display:"none"},onChange:u}),e.length===0?Z.jsx("p",{style:{fontSize:"0.82rem",color:"#999",margin:0},children:"No documents loaded. Upload .md or .txt files, or paste text."}):Z.jsx("div",{style:{maxHeight:"180px",overflowY:"auto"},children:e.map(d=>Z.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"0.35rem 0.6rem",background:"#fff",border:"1px solid #e0e0e0",borderRadius:"5px",marginBottom:"0.3rem",gap:"0.5rem"},children:[Z.jsx("span",{style:{fontSize:"0.75rem",color:"#ccc",flexShrink:0},children:"▪"}),Z.jsx("span",{style:{flex:1,fontSize:"0.8rem",fontWeight:500,color:"#333",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d.title}),Z.jsx("span",{style:{fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', monospace",fontSize:"0.68rem",color:"#aaa",flexShrink:0},children:d.filepath})]},d.id))}),o&&Z.jsx(TI,{onClose:()=>l(!1),onConfirm:r})]})}const EI=["api-design-principles.md","distributed-systems-overview.md","machine-learning-primer.md"],k1={expansion:{status:"idle"},search:{status:"idle"},rrf:{status:"idle"},rerank:{status:"idle"},blend:{status:"idle"}};function AI(){const[e,t]=jt.useState([{name:"embedding",status:"pending",progress:0},{name:"reranker",status:"pending",progress:0},{name:"expansion",status:"pending",progress:0}]),[r,s]=jt.useState([]),[o,l]=jt.useState([]),[u,d]=jt.useState([]),[f,p]=jt.useState(null),[g,y]=jt.useState(k1),[w,b]=jt.useState(!1),[S,E]=jt.useState("");jt.useEffect(()=>{z5(N=>{t(B=>B.map(j=>j.name===N.name?N:j))}).catch(console.error)},[]),jt.useEffect(()=>{async function N(){const B=[];for(const j of EI){const ue=await(await fetch(`/eval-docs/${j}`)).text(),oe=a_(ue,j);B.push({id:j,title:oe,body:ue,filepath:j})}s(B)}N()},[]),jt.useEffect(()=>{if(r.length===0)return;const N=r.flatMap(j=>q5(j));l(N),p(new $5(N)),e.find(j=>j.name==="embedding")?.status==="ready"&&N.length>0&&(b(!0),(async()=>{const j=[];for(const C of N){const ue=await H5(C.title,C.text);j.push({...C,embedding:ue})}d(j),b(!1)})())},[r,e]);const z=jt.useCallback(async N=>{const B=[];for(const j of Array.from(N)){const C=await j.text(),ue=a_(C,j.name);B.push({id:j.name,title:ue,body:C,filepath:j.name})}s(j=>[...j,...B])},[]),k=jt.useCallback((N,B)=>{const j=a_(N,B);s(C=>[...C,{id:B,title:j,body:N,filepath:B}])},[]),L=jt.useCallback(async N=>{if(!f||u.length===0)return;E(N),y(k1);const B=aI({query:N,embeddedChunks:u,bm25Index:f});for await(const j of B)y(C=>({...C,[j.stage]:{status:j.status,..."data"in j?{data:j.data}:{},..."error"in j?{error:j.error}:{}}}))},[f,u,o]),R=R5()&&u.length>0&&!w;return Z.jsxs("div",{style:{fontFamily:"system-ui, -apple-system, sans-serif",maxWidth:1400,margin:"0 auto",padding:"1rem"},children:[Z.jsxs("header",{style:{marginBottom:"1.5rem"},children:[Z.jsx("h1",{style:{margin:0,fontSize:"1.5rem"},children:"QMD Web Demo"}),Z.jsx("p",{style:{margin:"0.25rem 0 0",color:"#666",fontSize:"0.9rem"},children:"In-Browser Hybrid Search Pipeline — WebGPU + Transformers.js"})]}),Z.jsx(cI,{models:e}),w&&Z.jsx("div",{style:{padding:"0.5rem 1rem",background:"#FFF3E0",borderRadius:6,marginBottom:"1rem",fontSize:"0.85rem"},children:"Indexing documents (embedding chunks)..."}),Z.jsx(rI,{onSearch:L,disabled:!R}),S&&Z.jsx(xI,{state:g,query:S}),Z.jsx(SI,{documents:r.map(N=>({id:N.id,title:N.title,filepath:N.filepath})),onUpload:z,onPaste:k})]})}gE.createRoot(document.getElementById("root")).render(Z.jsx(jt.StrictMode,{children:Z.jsx(AI,{})}));