var DP=Object.defineProperty;var zP=(e,t,n)=>t in e?DP(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ft=(e,t,n)=>zP(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function n(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(o){if(o.ep)return;o.ep=!0;const a=n(o);fetch(o.href,a)}})();var Co=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Og(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var NT={exports:{}},Dg={},jT={exports:{}},mr={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var mp=Symbol.for("react.element"),RP=Symbol.for("react.portal"),LP=Symbol.for("react.fragment"),BP=Symbol.for("react.strict_mode"),NP=Symbol.for("react.profiler"),jP=Symbol.for("react.provider"),VP=Symbol.for("react.context"),UP=Symbol.for("react.forward_ref"),WP=Symbol.for("react.suspense"),GP=Symbol.for("react.memo"),qP=Symbol.for("react.lazy"),Zb=Symbol.iterator;function HP(e){return e===null||typeof e!="object"?null:(e=Zb&&e[Zb]||e["@@iterator"],typeof e=="function"?e:null)}var VT={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},UT=Object.assign,WT={};function dd(e,t,n){this.props=e,this.context=t,this.refs=WT,this.updater=n||VT}dd.prototype.isReactComponent={};dd.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};dd.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function GT(){}GT.prototype=dd.prototype;function Q0(e,t,n){this.props=e,this.context=t,this.refs=WT,this.updater=n||VT}var Y0=Q0.prototype=new GT;Y0.constructor=Q0;UT(Y0,dd.prototype);Y0.isPureReactComponent=!0;var Jb=Array.isArray,qT=Object.prototype.hasOwnProperty,Z0={current:null},HT={key:!0,ref:!0,__self:!0,__source:!0};function KT(e,t,n){var i,o={},a=null,l=null;if(t!=null)for(i in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(a=""+t.key),t)qT.call(t,i)&&!HT.hasOwnProperty(i)&&(o[i]=t[i]);var d=arguments.length-2;if(d===1)o.children=n;else if(1>>1,xe=te[ne];if(0>>1;neo(et,Ae))cto(Et,et)?(te[ne]=Et,te[ct]=Ae,ne=ct):(te[ne]=et,te[Ye]=Ae,ne=Ye);else if(cto(Et,Ae))te[ne]=Et,te[ct]=Ae,ne=ct;else break e}}return fe}function o(te,fe){var Ae=te.sortIndex-fe.sortIndex;return Ae!==0?Ae:te.id-fe.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var l=Date,d=l.now();e.unstable_now=function(){return l.now()-d}}var c=[],p=[],v=1,_=null,T=3,M=!1,I=!1,C=!1,E=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function A(te){for(var fe=n(p);fe!==null;){if(fe.callback===null)i(p);else if(fe.startTime<=te)i(p),fe.sortIndex=fe.expirationTime,t(c,fe);else break;fe=n(p)}}function N(te){if(C=!1,A(te),!I)if(n(c)!==null)I=!0,gt(R);else{var fe=n(p);fe!==null&&Me(N,fe.startTime-te)}}function R(te,fe){I=!1,C&&(C=!1,x(j),j=-1),M=!0;var Ae=T;try{for(A(fe),_=n(c);_!==null&&(!(_.expirationTime>fe)||te&&!Ne());){var ne=_.callback;if(typeof ne=="function"){_.callback=null,T=_.priorityLevel;var xe=ne(_.expirationTime<=fe);fe=e.unstable_now(),typeof xe=="function"?_.callback=xe:_===n(c)&&i(c),A(fe)}else i(c);_=n(c)}if(_!==null)var pt=!0;else{var Ye=n(p);Ye!==null&&Me(N,Ye.startTime-fe),pt=!1}return pt}finally{_=null,T=Ae,M=!1}}var B=!1,W=null,j=-1,ae=5,ve=-1;function Ne(){return!(e.unstable_now()-vete||125ne?(te.sortIndex=Ae,t(p,te),n(c)===null&&te===n(p)&&(C?(x(j),j=-1):C=!0,Me(N,Ae-ne))):(te.sortIndex=xe,t(c,te),I||M||(I=!0,gt(R))),te},e.unstable_shouldYield=Ne,e.unstable_wrapCallback=function(te){var fe=T;return function(){var Ae=T;T=fe;try{return te.apply(this,arguments)}finally{T=Ae}}}})(JT);ZT.exports=JT;var iA=ZT.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var sA=en,Gs=iA;function tn(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Oy=Object.prototype.hasOwnProperty,oA=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,tx={},nx={};function aA(e){return Oy.call(nx,e)?!0:Oy.call(tx,e)?!1:oA.test(e)?nx[e]=!0:(tx[e]=!0,!1)}function lA(e,t,n,i){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return i?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function uA(e,t,n,i){if(t===null||typeof t>"u"||lA(e,t,n,i))return!0;if(i)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function bs(e,t,n,i,o,a,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=i,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=l}var Zi={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Zi[e]=new bs(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Zi[t]=new bs(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Zi[e]=new bs(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Zi[e]=new bs(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Zi[e]=new bs(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Zi[e]=new bs(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Zi[e]=new bs(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Zi[e]=new bs(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Zi[e]=new bs(e,5,!1,e.toLowerCase(),null,!1,!1)});var ev=/[\-:]([a-z])/g;function tv(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(ev,tv);Zi[t]=new bs(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ev,tv);Zi[t]=new bs(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ev,tv);Zi[t]=new bs(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Zi[e]=new bs(e,1,!1,e.toLowerCase(),null,!1,!1)});Zi.xlinkHref=new bs("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Zi[e]=new bs(e,1,!1,e.toLowerCase(),null,!0,!0)});function nv(e,t,n,i){var o=Zi.hasOwnProperty(t)?Zi[t]:null;(o!==null?o.type!==0:i||!(2d||o[l]!==a[d]){var c=` `+o[l].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=l&&0<=d);break}}}finally{H_=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Sh(e):""}function cA(e){switch(e.tag){case 5:return Sh(e.type);case 16:return Sh("Lazy");case 13:return Sh("Suspense");case 19:return Sh("SuspenseList");case 0:case 2:case 15:return e=K_(e.type,!1),e;case 11:return e=K_(e.type.render,!1),e;case 1:return e=K_(e.type,!0),e;default:return""}}function Ly(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Oc:return"Fragment";case Fc:return"Portal";case Dy:return"Profiler";case rv:return"StrictMode";case zy:return"Suspense";case Ry:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case nM:return(e.displayName||"Context")+".Consumer";case tM:return(e._context.displayName||"Context")+".Provider";case iv:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case sv:return t=e.displayName||null,t!==null?t:Ly(e.type)||"Memo";case gl:t=e._payload,e=e._init;try{return Ly(e(t))}catch{}}return null}function dA(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ly(t);case 8:return t===rv?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Al(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function iM(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function fA(e){var t=iM(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),i=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(l){i=""+l,a.call(this,l)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return i},setValue:function(l){i=""+l},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function gm(e){e._valueTracker||(e._valueTracker=fA(e))}function sM(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),i="";return e&&(i=iM(e)?e.checked?"true":"false":e.value),e=i,e!==n?(t.setValue(e),!0):!1}function Zm(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function By(e,t){var n=t.checked;return ni({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function ix(e,t){var n=t.defaultValue==null?"":t.defaultValue,i=t.checked!=null?t.checked:t.defaultChecked;n=Al(t.value!=null?t.value:n),e._wrapperState={initialChecked:i,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function oM(e,t){t=t.checked,t!=null&&nv(e,"checked",t,!1)}function Ny(e,t){oM(e,t);var n=Al(t.value),i=t.type;if(n!=null)i==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(i==="submit"||i==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?jy(e,t.type,n):t.hasOwnProperty("defaultValue")&&jy(e,t.type,Al(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function sx(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var i=t.type;if(!(i!=="submit"&&i!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function jy(e,t,n){(t!=="number"||Zm(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Eh=Array.isArray;function Qc(e,t,n,i){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=_m.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Hh(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Fh={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},hA=["Webkit","ms","Moz","O"];Object.keys(Fh).forEach(function(e){hA.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Fh[t]=Fh[e]})});function cM(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Fh.hasOwnProperty(e)&&Fh[e]?(""+t).trim():t+"px"}function dM(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var i=n.indexOf("--")===0,o=cM(n,t[n],i);n==="float"&&(n="cssFloat"),i?e.setProperty(n,o):e[n]=o}}var pA=ni({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Wy(e,t){if(t){if(pA[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(tn(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(tn(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(tn(61))}if(t.style!=null&&typeof t.style!="object")throw Error(tn(62))}}function Gy(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var qy=null;function ov(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Hy=null,Yc=null,Zc=null;function lx(e){if(e=yp(e)){if(typeof Hy!="function")throw Error(tn(280));var t=e.stateNode;t&&(t=Ng(t),Hy(e.stateNode,e.type,t))}}function fM(e){Yc?Zc?Zc.push(e):Zc=[e]:Yc=e}function hM(){if(Yc){var e=Yc,t=Zc;if(Zc=Yc=null,lx(e),t)for(e=0;e>>=0,e===0?32:31-(kA(e)/SA|0)|0}var ym=64,vm=4194304;function Ch(e){switch(e&-e){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: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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ng(e,t){var n=e.pendingLanes;if(n===0)return 0;var i=0,o=e.suspendedLanes,a=e.pingedLanes,l=n&268435455;if(l!==0){var d=l&~o;d!==0?i=Ch(d):(a&=l,a!==0&&(i=Ch(a)))}else l=n&~o,l!==0?i=Ch(l):a!==0&&(i=Ch(a));if(i===0)return 0;if(t!==0&&t!==i&&!(t&o)&&(o=i&-i,a=t&-t,o>=a||o===16&&(a&4194240)!==0))return t;if(i&4&&(i|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=i;0n;n++)t.push(e);return t}function gp(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Po(t),e[t]=n}function AA(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var i=e.eventTimes;for(e=e.expirationTimes;0=Dh),_x=" ",yx=!1;function FM(e,t){switch(e){case"keyup":return i$.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function OM(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Dc=!1;function o$(e,t){switch(e){case"compositionend":return OM(t);case"keypress":return t.which!==32?null:(yx=!0,_x);case"textInput":return e=t.data,e===_x&&yx?null:e;default:return null}}function a$(e,t){if(Dc)return e==="compositionend"||!pv&&FM(e,t)?(e=$M(),Bm=dv=wl=null,Dc=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=i}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=xx(n)}}function LM(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?LM(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function BM(){for(var e=window,t=Zm();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Zm(e.document)}return t}function mv(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function g$(e){var t=BM(),n=e.focusedElem,i=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&LM(n.ownerDocument.documentElement,n)){if(i!==null&&mv(n)){if(t=i.start,e=i.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,a=Math.min(i.start,o);i=i.end===void 0?a:Math.min(i.end,o),!e.extend&&a>i&&(o=i,i=a,a=o),o=Tx(n,a);var l=Tx(n,i);o&&l&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==l.node||e.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),a>i?(e.addRange(t),e.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,zc=null,Jy=null,Rh=null,e0=!1;function Mx(e,t,n){var i=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;e0||zc==null||zc!==Zm(i)||(i=zc,"selectionStart"in i&&mv(i)?i={start:i.selectionStart,end:i.selectionEnd}:(i=(i.ownerDocument&&i.ownerDocument.defaultView||window).getSelection(),i={anchorNode:i.anchorNode,anchorOffset:i.anchorOffset,focusNode:i.focusNode,focusOffset:i.focusOffset}),Rh&&Jh(Rh,i)||(Rh=i,i=sg(Jy,"onSelect"),0Bc||(e.current=o0[Bc],o0[Bc]=null,Bc--)}function Wr(e,t){Bc++,o0[Bc]=e.current,e.current=t}var $l={},cs=Dl($l),Is=Dl(!1),wu=$l;function rd(e,t){var n=e.type.contextTypes;if(!n)return $l;var i=e.stateNode;if(i&&i.__reactInternalMemoizedUnmaskedChildContext===t)return i.__reactInternalMemoizedMaskedChildContext;var o={},a;for(a in n)o[a]=t[a];return i&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function Fs(e){return e=e.childContextTypes,e!=null}function ag(){Hr(Is),Hr(cs)}function $x(e,t,n){if(cs.current!==$l)throw Error(tn(168));Wr(cs,t),Wr(Is,n)}function KM(e,t,n){var i=e.stateNode;if(t=t.childContextTypes,typeof i.getChildContext!="function")return n;i=i.getChildContext();for(var o in i)if(!(o in t))throw Error(tn(108,dA(e)||"Unknown",o));return ni({},n,i)}function lg(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||$l,wu=cs.current,Wr(cs,e),Wr(Is,Is.current),!0}function Ix(e,t,n){var i=e.stateNode;if(!i)throw Error(tn(169));n?(e=KM(e,t,wu),i.__reactInternalMemoizedMergedChildContext=e,Hr(Is),Hr(cs),Wr(cs,e)):Hr(Is),Wr(Is,n)}var Pa=null,jg=!1,ly=!1;function XM(e){Pa===null?Pa=[e]:Pa.push(e)}function C$(e){jg=!0,XM(e)}function zl(){if(!ly&&Pa!==null){ly=!0;var e=0,t=zr;try{var n=Pa;for(zr=1;e>=l,o-=l,Aa=1<<32-Po(t)+o|n<j?(ae=W,W=null):ae=W.sibling;var ve=T(x,W,A[j],N);if(ve===null){W===null&&(W=ae);break}e&&W&&ve.alternate===null&&t(x,W),k=a(ve,k,j),B===null?R=ve:B.sibling=ve,B=ve,W=ae}if(j===A.length)return n(x,W),Xr&&lu(x,j),R;if(W===null){for(;jj?(ae=W,W=null):ae=W.sibling;var Ne=T(x,W,ve.value,N);if(Ne===null){W===null&&(W=ae);break}e&&W&&Ne.alternate===null&&t(x,W),k=a(Ne,k,j),B===null?R=Ne:B.sibling=Ne,B=Ne,W=ae}if(ve.done)return n(x,W),Xr&&lu(x,j),R;if(W===null){for(;!ve.done;j++,ve=A.next())ve=_(x,ve.value,N),ve!==null&&(k=a(ve,k,j),B===null?R=ve:B.sibling=ve,B=ve);return Xr&&lu(x,j),R}for(W=i(x,W);!ve.done;j++,ve=A.next())ve=M(W,x,j,ve.value,N),ve!==null&&(e&&ve.alternate!==null&&W.delete(ve.key===null?j:ve.key),k=a(ve,k,j),B===null?R=ve:B.sibling=ve,B=ve);return e&&W.forEach(function(oe){return t(x,oe)}),Xr&&lu(x,j),R}function E(x,k,A,N){if(typeof A=="object"&&A!==null&&A.type===Oc&&A.key===null&&(A=A.props.children),typeof A=="object"&&A!==null){switch(A.$$typeof){case mm:e:{for(var R=A.key,B=k;B!==null;){if(B.key===R){if(R=A.type,R===Oc){if(B.tag===7){n(x,B.sibling),k=o(B,A.props.children),k.return=x,x=k;break e}}else if(B.elementType===R||typeof R=="object"&&R!==null&&R.$$typeof===gl&&Dx(R)===B.type){n(x,B.sibling),k=o(B,A.props),k.ref=bh(x,B,A),k.return=x,x=k;break e}n(x,B);break}else t(x,B);B=B.sibling}A.type===Oc?(k=yu(A.props.children,x.mode,N,A.key),k.return=x,x=k):(N=Hm(A.type,A.key,A.props,null,x.mode,N),N.ref=bh(x,k,A),N.return=x,x=N)}return l(x);case Fc:e:{for(B=A.key;k!==null;){if(k.key===B)if(k.tag===4&&k.stateNode.containerInfo===A.containerInfo&&k.stateNode.implementation===A.implementation){n(x,k.sibling),k=o(k,A.children||[]),k.return=x,x=k;break e}else{n(x,k);break}else t(x,k);k=k.sibling}k=gy(A,x.mode,N),k.return=x,x=k}return l(x);case gl:return B=A._init,E(x,k,B(A._payload),N)}if(Eh(A))return I(x,k,A,N);if(gh(A))return C(x,k,A,N);Sm(x,A)}return typeof A=="string"&&A!==""||typeof A=="number"?(A=""+A,k!==null&&k.tag===6?(n(x,k.sibling),k=o(k,A),k.return=x,x=k):(n(x,k),k=my(A,x.mode,N),k.return=x,x=k),l(x)):n(x,k)}return E}var sd=JM(!0),ek=JM(!1),dg=Dl(null),fg=null,Vc=null,vv=null;function wv(){vv=Vc=fg=null}function bv(e){var t=dg.current;Hr(dg),e._currentValue=t}function u0(e,t,n){for(;e!==null;){var i=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,i!==null&&(i.childLanes|=t)):i!==null&&(i.childLanes&t)!==t&&(i.childLanes|=t),e===n)break;e=e.return}}function ed(e,t){fg=e,vv=Vc=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&($s=!0),e.firstContext=null)}function uo(e){var t=e._currentValue;if(vv!==e)if(e={context:e,memoizedValue:t,next:null},Vc===null){if(fg===null)throw Error(tn(308));Vc=e,fg.dependencies={lanes:0,firstContext:e}}else Vc=Vc.next=e;return t}var pu=null;function xv(e){pu===null?pu=[e]:pu.push(e)}function tk(e,t,n,i){var o=t.interleaved;return o===null?(n.next=n,xv(t)):(n.next=o.next,o.next=n),t.interleaved=n,Va(e,i)}function Va(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var _l=!1;function Tv(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function nk(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Fa(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Sl(e,t,n){var i=e.updateQueue;if(i===null)return null;if(i=i.shared,Mr&2){var o=i.pending;return o===null?t.next=t:(t.next=o.next,o.next=t),i.pending=t,Va(e,n)}return o=i.interleaved,o===null?(t.next=t,xv(i)):(t.next=o.next,o.next=t),i.interleaved=t,Va(e,n)}function jm(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var i=t.lanes;i&=e.pendingLanes,n|=i,t.lanes=n,lv(e,n)}}function zx(e,t){var n=e.updateQueue,i=e.alternate;if(i!==null&&(i=i.updateQueue,n===i)){var o=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};a===null?o=a=l:a=a.next=l,n=n.next}while(n!==null);a===null?o=a=t:a=a.next=t}else o=a=t;n={baseState:i.baseState,firstBaseUpdate:o,lastBaseUpdate:a,shared:i.shared,effects:i.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function hg(e,t,n,i){var o=e.updateQueue;_l=!1;var a=o.firstBaseUpdate,l=o.lastBaseUpdate,d=o.shared.pending;if(d!==null){o.shared.pending=null;var c=d,p=c.next;c.next=null,l===null?a=p:l.next=p,l=c;var v=e.alternate;v!==null&&(v=v.updateQueue,d=v.lastBaseUpdate,d!==l&&(d===null?v.firstBaseUpdate=p:d.next=p,v.lastBaseUpdate=c))}if(a!==null){var _=o.baseState;l=0,v=p=c=null,d=a;do{var T=d.lane,M=d.eventTime;if((i&T)===T){v!==null&&(v=v.next={eventTime:M,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var I=e,C=d;switch(T=t,M=n,C.tag){case 1:if(I=C.payload,typeof I=="function"){_=I.call(M,_,T);break e}_=I;break e;case 3:I.flags=I.flags&-65537|128;case 0:if(I=C.payload,T=typeof I=="function"?I.call(M,_,T):I,T==null)break e;_=ni({},_,T);break e;case 2:_l=!0}}d.callback!==null&&d.lane!==0&&(e.flags|=64,T=o.effects,T===null?o.effects=[d]:T.push(d))}else M={eventTime:M,lane:T,tag:d.tag,payload:d.payload,callback:d.callback,next:null},v===null?(p=v=M,c=_):v=v.next=M,l|=T;if(d=d.next,d===null){if(d=o.shared.pending,d===null)break;T=d,d=T.next,T.next=null,o.lastBaseUpdate=T,o.shared.pending=null}}while(!0);if(v===null&&(c=_),o.baseState=c,o.firstBaseUpdate=p,o.lastBaseUpdate=v,t=o.shared.interleaved,t!==null){o=t;do l|=o.lane,o=o.next;while(o!==t)}else a===null&&(o.shared.lanes=0);Tu|=l,e.lanes=l,e.memoizedState=_}}function Rx(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var i=cy.transition;cy.transition={};try{e(!1),t()}finally{zr=n,cy.transition=i}}function vk(){return co().memoizedState}function I$(e,t,n){var i=Cl(e);if(n={lane:i,action:n,hasEagerState:!1,eagerState:null,next:null},wk(e))bk(t,n);else if(n=tk(e,t,n,i),n!==null){var o=vs();Ao(n,e,i,o),xk(n,t,i)}}function F$(e,t,n){var i=Cl(e),o={lane:i,action:n,hasEagerState:!1,eagerState:null,next:null};if(wk(e))bk(t,o);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var l=t.lastRenderedState,d=a(l,n);if(o.hasEagerState=!0,o.eagerState=d,$o(d,l)){var c=t.interleaved;c===null?(o.next=o,xv(t)):(o.next=c.next,c.next=o),t.interleaved=o;return}}catch{}finally{}n=tk(e,t,o,i),n!==null&&(o=vs(),Ao(n,e,i,o),xk(n,t,i))}}function wk(e){var t=e.alternate;return e===ti||t!==null&&t===ti}function bk(e,t){Lh=mg=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function xk(e,t,n){if(n&4194240){var i=t.lanes;i&=e.pendingLanes,n|=i,t.lanes=n,lv(e,n)}}var gg={readContext:uo,useCallback:is,useContext:is,useEffect:is,useImperativeHandle:is,useInsertionEffect:is,useLayoutEffect:is,useMemo:is,useReducer:is,useRef:is,useState:is,useDebugValue:is,useDeferredValue:is,useTransition:is,useMutableSource:is,useSyncExternalStore:is,useId:is,unstable_isNewReconciler:!1},O$={readContext:uo,useCallback:function(e,t){return ra().memoizedState=[e,t===void 0?null:t],e},useContext:uo,useEffect:Bx,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Um(4194308,4,pk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Um(4194308,4,e,t)},useInsertionEffect:function(e,t){return Um(4,2,e,t)},useMemo:function(e,t){var n=ra();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var i=ra();return t=n!==void 0?n(t):t,i.memoizedState=i.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},i.queue=e,e=e.dispatch=I$.bind(null,ti,e),[i.memoizedState,e]},useRef:function(e){var t=ra();return e={current:e},t.memoizedState=e},useState:Lx,useDebugValue:$v,useDeferredValue:function(e){return ra().memoizedState=e},useTransition:function(){var e=Lx(!1),t=e[0];return e=$$.bind(null,e[1]),ra().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var i=ti,o=ra();if(Xr){if(n===void 0)throw Error(tn(407));n=n()}else{if(n=t(),ji===null)throw Error(tn(349));xu&30||ok(i,t,n)}o.memoizedState=n;var a={value:n,getSnapshot:t};return o.queue=a,Bx(lk.bind(null,i,a,e),[e]),i.flags|=2048,ap(9,ak.bind(null,i,a,n,t),void 0,null),n},useId:function(){var e=ra(),t=ji.identifierPrefix;if(Xr){var n=$a,i=Aa;n=(i&~(1<<32-Po(i)-1)).toString(32)+n,t=":"+t+"R"+n,n=sp++,0<\/script>",e=e.removeChild(e.firstChild)):typeof i.is=="string"?e=l.createElement(n,{is:i.is}):(e=l.createElement(n),n==="select"&&(l=e,i.multiple?l.multiple=!0:i.size&&(l.size=i.size))):e=l.createElementNS(e,n),e[ia]=t,e[np]=i,Ik(e,t,!1,!1),t.stateNode=e;e:{switch(l=Gy(n,i),n){case"dialog":qr("cancel",e),qr("close",e),o=i;break;case"iframe":case"object":case"embed":qr("load",e),o=i;break;case"video":case"audio":for(o=0;old&&(t.flags|=128,i=!0,xh(a,!1),t.lanes=4194304)}else{if(!i)if(e=pg(l),e!==null){if(t.flags|=128,i=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),xh(a,!0),a.tail===null&&a.tailMode==="hidden"&&!l.alternate&&!Xr)return ss(t),null}else 2*mi()-a.renderingStartTime>ld&&n!==1073741824&&(t.flags|=128,i=!0,xh(a,!1),t.lanes=4194304);a.isBackwards?(l.sibling=t.child,t.child=l):(n=a.last,n!==null?n.sibling=l:t.child=l,a.last=l)}return a.tail!==null?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=mi(),t.sibling=null,n=Jr.current,Wr(Jr,i?n&1|2:n&1),t):(ss(t),null);case 22:case 23:return Rv(),i=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==i&&(t.flags|=8192),i&&t.mode&1?js&1073741824&&(ss(t),t.subtreeFlags&6&&(t.flags|=8192)):ss(t),null;case 24:return null;case 25:return null}throw Error(tn(156,t.tag))}function V$(e,t){switch(_v(t),t.tag){case 1:return Fs(t.type)&&ag(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return od(),Hr(Is),Hr(cs),Sv(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return kv(t),null;case 13:if(Hr(Jr),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(tn(340));id()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Hr(Jr),null;case 4:return od(),null;case 10:return bv(t.type._context),null;case 22:case 23:return Rv(),null;case 24:return null;default:return null}}var Cm=!1,as=!1,U$=typeof WeakSet=="function"?WeakSet:Set,xn=null;function Uc(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(i){li(e,t,i)}else n.current=null}function y0(e,t,n){try{n()}catch(i){li(e,t,i)}}var Qx=!1;function W$(e,t){if(t0=rg,e=BM(),mv(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var i=n.getSelection&&n.getSelection();if(i&&i.rangeCount!==0){n=i.anchorNode;var o=i.anchorOffset,a=i.focusNode;i=i.focusOffset;try{n.nodeType,a.nodeType}catch{n=null;break e}var l=0,d=-1,c=-1,p=0,v=0,_=e,T=null;t:for(;;){for(var M;_!==n||o!==0&&_.nodeType!==3||(d=l+o),_!==a||i!==0&&_.nodeType!==3||(c=l+i),_.nodeType===3&&(l+=_.nodeValue.length),(M=_.firstChild)!==null;)T=_,_=M;for(;;){if(_===e)break t;if(T===n&&++p===o&&(d=l),T===a&&++v===i&&(c=l),(M=_.nextSibling)!==null)break;_=T,T=_.parentNode}_=M}n=d===-1||c===-1?null:{start:d,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(n0={focusedElem:e,selectionRange:n},rg=!1,xn=t;xn!==null;)if(t=xn,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,xn=e;else for(;xn!==null;){t=xn;try{var I=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(I!==null){var C=I.memoizedProps,E=I.memoizedState,x=t.stateNode,k=x.getSnapshotBeforeUpdate(t.elementType===t.type?C:ko(t.type,C),E);x.__reactInternalSnapshotBeforeUpdate=k}break;case 3:var A=t.stateNode.containerInfo;A.nodeType===1?A.textContent="":A.nodeType===9&&A.documentElement&&A.removeChild(A.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(tn(163))}}catch(N){li(t,t.return,N)}if(e=t.sibling,e!==null){e.return=t.return,xn=e;break}xn=t.return}return I=Qx,Qx=!1,I}function Bh(e,t,n){var i=t.updateQueue;if(i=i!==null?i.lastEffect:null,i!==null){var o=i=i.next;do{if((o.tag&e)===e){var a=o.destroy;o.destroy=void 0,a!==void 0&&y0(t,n,a)}o=o.next}while(o!==i)}}function Wg(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var i=n.create;n.destroy=i()}n=n.next}while(n!==t)}}function v0(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Dk(e){var t=e.alternate;t!==null&&(e.alternate=null,Dk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[ia],delete t[np],delete t[s0],delete t[S$],delete t[E$])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function zk(e){return e.tag===5||e.tag===3||e.tag===4}function Yx(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||zk(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function w0(e,t,n){var i=e.tag;if(i===5||i===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=og));else if(i!==4&&(e=e.child,e!==null))for(w0(e,t,n),e=e.sibling;e!==null;)w0(e,t,n),e=e.sibling}function b0(e,t,n){var i=e.tag;if(i===5||i===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(i!==4&&(e=e.child,e!==null))for(b0(e,t,n),e=e.sibling;e!==null;)b0(e,t,n),e=e.sibling}var Xi=null,So=!1;function pl(e,t,n){for(n=n.child;n!==null;)Rk(e,t,n),n=n.sibling}function Rk(e,t,n){if(sa&&typeof sa.onCommitFiberUnmount=="function")try{sa.onCommitFiberUnmount(zg,n)}catch{}switch(n.tag){case 5:as||Uc(n,t);case 6:var i=Xi,o=So;Xi=null,pl(e,t,n),Xi=i,So=o,Xi!==null&&(So?(e=Xi,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Xi.removeChild(n.stateNode));break;case 18:Xi!==null&&(So?(e=Xi,n=n.stateNode,e.nodeType===8?ay(e.parentNode,n):e.nodeType===1&&ay(e,n),Yh(e)):ay(Xi,n.stateNode));break;case 4:i=Xi,o=So,Xi=n.stateNode.containerInfo,So=!0,pl(e,t,n),Xi=i,So=o;break;case 0:case 11:case 14:case 15:if(!as&&(i=n.updateQueue,i!==null&&(i=i.lastEffect,i!==null))){o=i=i.next;do{var a=o,l=a.destroy;a=a.tag,l!==void 0&&(a&2||a&4)&&y0(n,t,l),o=o.next}while(o!==i)}pl(e,t,n);break;case 1:if(!as&&(Uc(n,t),i=n.stateNode,typeof i.componentWillUnmount=="function"))try{i.props=n.memoizedProps,i.state=n.memoizedState,i.componentWillUnmount()}catch(d){li(n,t,d)}pl(e,t,n);break;case 21:pl(e,t,n);break;case 22:n.mode&1?(as=(i=as)||n.memoizedState!==null,pl(e,t,n),as=i):pl(e,t,n);break;default:pl(e,t,n)}}function Zx(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new U$),t.forEach(function(i){var o=J$.bind(null,e,i);n.has(i)||(n.add(i),i.then(o,o))})}}function Mo(e,t){var n=t.deletions;if(n!==null)for(var i=0;io&&(o=l),i&=~a}if(i=o,i=mi()-i,i=(120>i?120:480>i?480:1080>i?1080:1920>i?1920:3e3>i?3e3:4320>i?4320:1960*q$(i/1960))-i,10e?16:e,bl===null)var i=!1;else{if(e=bl,bl=null,vg=0,Mr&6)throw Error(tn(331));var o=Mr;for(Mr|=4,xn=e.current;xn!==null;){var a=xn,l=a.child;if(xn.flags&16){var d=a.deletions;if(d!==null){for(var c=0;cmi()-Dv?_u(e,0):Ov|=n),Os(e,t)}function Gk(e,t){t===0&&(e.mode&1?(t=vm,vm<<=1,!(vm&130023424)&&(vm=4194304)):t=1);var n=vs();e=Va(e,t),e!==null&&(gp(e,t,n),Os(e,n))}function Z$(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Gk(e,n)}function J$(e,t){var n=0;switch(e.tag){case 13:var i=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:i=e.stateNode;break;default:throw Error(tn(314))}i!==null&&i.delete(t),Gk(e,n)}var qk;qk=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Is.current)$s=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return $s=!1,N$(e,t,n);$s=!!(e.flags&131072)}else $s=!1,Xr&&t.flags&1048576&&QM(t,cg,t.index);switch(t.lanes=0,t.tag){case 2:var i=t.type;Wm(e,t),e=t.pendingProps;var o=rd(t,cs.current);ed(t,n),o=Cv(null,t,i,e,o,n);var a=Pv();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Fs(i)?(a=!0,lg(t)):a=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tv(t),o.updater=Ug,t.stateNode=o,o._reactInternals=t,d0(t,i,e,n),t=p0(null,t,i,!0,a,n)):(t.tag=0,Xr&&a&&gv(t),ys(null,t,o,n),t=t.child),t;case 16:i=t.elementType;e:{switch(Wm(e,t),e=t.pendingProps,o=i._init,i=o(i._payload),t.type=i,o=t.tag=tI(i),e=ko(i,e),o){case 0:t=h0(null,t,i,e,n);break e;case 1:t=Hx(null,t,i,e,n);break e;case 11:t=Gx(null,t,i,e,n);break e;case 14:t=qx(null,t,i,ko(i.type,e),n);break e}throw Error(tn(306,i,""))}return t;case 0:return i=t.type,o=t.pendingProps,o=t.elementType===i?o:ko(i,o),h0(e,t,i,o,n);case 1:return i=t.type,o=t.pendingProps,o=t.elementType===i?o:ko(i,o),Hx(e,t,i,o,n);case 3:e:{if(Pk(t),e===null)throw Error(tn(387));i=t.pendingProps,a=t.memoizedState,o=a.element,nk(e,t),hg(t,i,null,n);var l=t.memoizedState;if(i=l.element,a.isDehydrated)if(a={element:i,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=a,t.memoizedState=a,t.flags&256){o=ad(Error(tn(423)),t),t=Kx(e,t,i,n,o);break e}else if(i!==o){o=ad(Error(tn(424)),t),t=Kx(e,t,i,n,o);break e}else for(Us=kl(t.stateNode.containerInfo.firstChild),Ws=t,Xr=!0,Eo=null,n=ek(t,null,i,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(id(),i===o){t=Ua(e,t,n);break e}ys(e,t,i,n)}t=t.child}return t;case 5:return rk(t),e===null&&l0(t),i=t.type,o=t.pendingProps,a=e!==null?e.memoizedProps:null,l=o.children,r0(i,o)?l=null:a!==null&&r0(i,a)&&(t.flags|=32),Ck(e,t),ys(e,t,l,n),t.child;case 6:return e===null&&l0(t),null;case 13:return Ak(e,t,n);case 4:return Mv(t,t.stateNode.containerInfo),i=t.pendingProps,e===null?t.child=sd(t,null,i,n):ys(e,t,i,n),t.child;case 11:return i=t.type,o=t.pendingProps,o=t.elementType===i?o:ko(i,o),Gx(e,t,i,o,n);case 7:return ys(e,t,t.pendingProps,n),t.child;case 8:return ys(e,t,t.pendingProps.children,n),t.child;case 12:return ys(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(i=t.type._context,o=t.pendingProps,a=t.memoizedProps,l=o.value,Wr(dg,i._currentValue),i._currentValue=l,a!==null)if($o(a.value,l)){if(a.children===o.children&&!Is.current){t=Ua(e,t,n);break e}}else for(a=t.child,a!==null&&(a.return=t);a!==null;){var d=a.dependencies;if(d!==null){l=a.child;for(var c=d.firstContext;c!==null;){if(c.context===i){if(a.tag===1){c=Fa(-1,n&-n),c.tag=2;var p=a.updateQueue;if(p!==null){p=p.shared;var v=p.pending;v===null?c.next=c:(c.next=v.next,v.next=c),p.pending=c}}a.lanes|=n,c=a.alternate,c!==null&&(c.lanes|=n),u0(a.return,n,t),d.lanes|=n;break}c=c.next}}else if(a.tag===10)l=a.type===t.type?null:a.child;else if(a.tag===18){if(l=a.return,l===null)throw Error(tn(341));l.lanes|=n,d=l.alternate,d!==null&&(d.lanes|=n),u0(l,n,t),l=a.sibling}else l=a.child;if(l!==null)l.return=a;else for(l=a;l!==null;){if(l===t){l=null;break}if(a=l.sibling,a!==null){a.return=l.return,l=a;break}l=l.return}a=l}ys(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,i=t.pendingProps.children,ed(t,n),o=uo(o),i=i(o),t.flags|=1,ys(e,t,i,n),t.child;case 14:return i=t.type,o=ko(i,t.pendingProps),o=ko(i.type,o),qx(e,t,i,o,n);case 15:return Sk(e,t,t.type,t.pendingProps,n);case 17:return i=t.type,o=t.pendingProps,o=t.elementType===i?o:ko(i,o),Wm(e,t),t.tag=1,Fs(i)?(e=!0,lg(t)):e=!1,ed(t,n),Tk(t,i,o),d0(t,i,o,n),p0(null,t,i,!0,e,n);case 19:return $k(e,t,n);case 22:return Ek(e,t,n)}throw Error(tn(156,t.tag))};function Hk(e,t){return wM(e,t)}function eI(e,t,n,i){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=i,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ao(e,t,n,i){return new eI(e,t,n,i)}function Bv(e){return e=e.prototype,!(!e||!e.isReactComponent)}function tI(e){if(typeof e=="function")return Bv(e)?1:0;if(e!=null){if(e=e.$$typeof,e===iv)return 11;if(e===sv)return 14}return 2}function Pl(e,t){var n=e.alternate;return n===null?(n=ao(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Hm(e,t,n,i,o,a){var l=2;if(i=e,typeof e=="function")Bv(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case Oc:return yu(n.children,o,a,t);case rv:l=8,o|=8;break;case Dy:return e=ao(12,n,t,o|2),e.elementType=Dy,e.lanes=a,e;case zy:return e=ao(13,n,t,o),e.elementType=zy,e.lanes=a,e;case Ry:return e=ao(19,n,t,o),e.elementType=Ry,e.lanes=a,e;case rM:return qg(n,o,a,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case tM:l=10;break e;case nM:l=9;break e;case iv:l=11;break e;case sv:l=14;break e;case gl:l=16,i=null;break e}throw Error(tn(130,e==null?e:typeof e,""))}return t=ao(l,n,t,o),t.elementType=e,t.type=i,t.lanes=a,t}function yu(e,t,n,i){return e=ao(7,e,i,t),e.lanes=n,e}function qg(e,t,n,i){return e=ao(22,e,i,t),e.elementType=rM,e.lanes=n,e.stateNode={isHidden:!1},e}function my(e,t,n){return e=ao(6,e,null,t),e.lanes=n,e}function gy(e,t,n){return t=ao(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function nI(e,t,n,i,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Q_(0),this.expirationTimes=Q_(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Q_(0),this.identifierPrefix=i,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Nv(e,t,n,i,o,a,l,d,c){return e=new nI(e,t,n,d,c),t===1?(t=1,a===!0&&(t|=8)):t=0,a=ao(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:i,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tv(a),e}function rI(e,t,n){var i=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Yk)}catch(e){console.error(e)}}Yk(),YT.exports=Hs;var lI=YT.exports,Zk,o2=lI;Zk=o2.createRoot,o2.hydrateRoot;var Jk={exports:{}},uI="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",cI=uI,dI=cI;function eS(){}function tS(){}tS.resetWarningCache=eS;var fI=function(){function e(i,o,a,l,d,c){if(c!==dI){var p=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw p.name="Invariant Violation",p}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:tS,resetWarningCache:eS};return n.PropTypes=n,n};Jk.exports=fI();var hI=Jk.exports;const Br=Og(hI);function pd(e,t,n,i){function o(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function d(v){try{p(i.next(v))}catch(_){l(_)}}function c(v){try{p(i.throw(v))}catch(_){l(_)}}function p(v){v.done?a(v.value):o(v.value).then(d,c)}p((i=i.apply(e,t||[])).next())})}function md(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,o,a,l=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return l.next=d(0),l.throw=d(1),l.return=d(2),typeof Symbol=="function"&&(l[Symbol.iterator]=function(){return this}),l;function d(p){return function(v){return c([p,v])}}function c(p){if(i)throw new TypeError("Generator is already executing.");for(;l&&(l=0,p[0]&&(n=0)),n;)try{if(i=1,o&&(a=p[0]&2?o.return:p[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,p[1])).done)return a;switch(o=0,a&&(p=[p[0]&2,a.value]),p[0]){case 0:case 1:a=p;break;case 4:return n.label++,{value:p[1],done:!1};case 5:n.label++,o=p[1],p=[0];continue;case 7:p=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(p[0]===6||p[0]===2)){n=0;continue}if(p[0]===3&&(!a||p[1]>a[0]&&p[1]0)&&!(o=i.next()).done;)a.push(o.value)}catch(d){l={error:d}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(l)throw l.error}}return a}function l2(e,t,n){if(n||arguments.length===2)for(var i=0,o=t.length,a;i0?i:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function mI(e){var t=e.name,n=t&&t.lastIndexOf(".")!==-1;if(n&&!e.type){var i=t.split(".").pop().toLowerCase(),o=pI.get(i);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var gI=[".DS_Store","Thumbs.db"];function _I(e){return pd(this,void 0,void 0,function(){return md(this,function(t){return xg(e)&&yI(e.dataTransfer)?[2,xI(e.dataTransfer,e.type)]:vI(e)?[2,wI(e)]:Array.isArray(e)&&e.every(function(n){return"getFile"in n&&typeof n.getFile=="function"})?[2,bI(e)]:[2,[]]})})}function yI(e){return xg(e)}function vI(e){return xg(e)&&xg(e.target)}function xg(e){return typeof e=="object"&&e!==null}function wI(e){return S0(e.target.files).map(function(t){return wp(t)})}function bI(e){return pd(this,void 0,void 0,function(){var t;return md(this,function(n){switch(n.label){case 0:return[4,Promise.all(e.map(function(i){return i.getFile()}))];case 1:return t=n.sent(),[2,t.map(function(i){return wp(i)})]}})})}function xI(e,t){return pd(this,void 0,void 0,function(){var n,i;return md(this,function(o){switch(o.label){case 0:return e.items?(n=S0(e.items).filter(function(a){return a.kind==="file"}),t!=="drop"?[2,n]:[4,Promise.all(n.map(TI))]):[3,2];case 1:return i=o.sent(),[2,u2(nS(i))];case 2:return[2,u2(S0(e.files).map(function(a){return wp(a)}))]}})})}function u2(e){return e.filter(function(t){return gI.indexOf(t.name)===-1})}function S0(e){if(e===null)return[];for(var t=[],n=0;ne.length)&&(t=e.length);for(var n=0,i=new Array(t);nn)return[!1,p2(n)];if(e.sizen)return[!1,p2(n)]}return[!0,null]}function fu(e){return e!=null}function BI(e){var t=e.files,n=e.accept,i=e.minSize,o=e.maxSize,a=e.multiple,l=e.maxFiles,d=e.validator;return!a&&t.length>1||a&&l>=1&&t.length>l?!1:t.every(function(c){var p=oS(c,n),v=up(p,1),_=v[0],T=aS(c,i,o),M=up(T,1),I=M[0],C=d?d(c):null;return _&&I&&!C})}function Tg(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function $m(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,function(t){return t==="Files"||t==="application/x-moz-file"}):!!e.target&&!!e.target.files}function g2(e){e.preventDefault()}function NI(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function jI(e){return e.indexOf("Edge/")!==-1}function VI(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return NI(e)||jI(e)}function ta(){for(var e=arguments.length,t=new Array(e),n=0;n1?o-1:0),l=1;le.length)&&(t=e.length);for(var n=0,i=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}function s3(e,t){if(e==null)return{};var n={},i=Object.keys(e),o,a;for(a=0;a=0)&&(n[o]=e[o]);return n}var Wv=en.forwardRef(function(e,t){var n=e.children,i=Mg(e,KI),o=fS(i),a=o.open,l=Mg(o,XI);return en.useImperativeHandle(t,function(){return{open:a}},[a]),Vs.createElement(en.Fragment,null,n(Zr(Zr({},l),{},{open:a})))});Wv.displayName="Dropzone";var dS={disabled:!1,getFilesFromEvent:_I,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};Wv.defaultProps=dS;Wv.propTypes={children:Br.func,accept:Br.objectOf(Br.arrayOf(Br.string)),multiple:Br.bool,preventDropOnDocument:Br.bool,noClick:Br.bool,noKeyboard:Br.bool,noDrag:Br.bool,noDragEventsBubbling:Br.bool,minSize:Br.number,maxSize:Br.number,maxFiles:Br.number,disabled:Br.bool,getFilesFromEvent:Br.func,onFileDialogCancel:Br.func,onFileDialogOpen:Br.func,useFsAccessApi:Br.bool,autoFocus:Br.bool,onDragEnter:Br.func,onDragLeave:Br.func,onDragOver:Br.func,onDrop:Br.func,onDropAccepted:Br.func,onDropRejected:Br.func,onError:Br.func,validator:Br.func};var A0={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function fS(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Zr(Zr({},dS),e),n=t.accept,i=t.disabled,o=t.getFilesFromEvent,a=t.maxSize,l=t.minSize,d=t.multiple,c=t.maxFiles,p=t.onDragEnter,v=t.onDragLeave,_=t.onDragOver,T=t.onDrop,M=t.onDropAccepted,I=t.onDropRejected,C=t.onFileDialogCancel,E=t.onFileDialogOpen,x=t.useFsAccessApi,k=t.autoFocus,A=t.preventDropOnDocument,N=t.noClick,R=t.noKeyboard,B=t.noDrag,W=t.noDragEventsBubbling,j=t.onError,ae=t.validator,ve=en.useMemo(function(){return GI(n)},[n]),Ne=en.useMemo(function(){return WI(n)},[n]),oe=en.useMemo(function(){return typeof E=="function"?E:y2},[E]),Se=en.useMemo(function(){return typeof C=="function"?C:y2},[C]),G=en.useRef(null),Ce=en.useRef(null),gt=en.useReducer(o3,A0),Me=_y(gt,2),te=Me[0],fe=Me[1],Ae=te.isFocused,ne=te.isFileDialogActive,xe=en.useRef(typeof window<"u"&&window.isSecureContext&&x&&UI()),pt=function(){!xe.current&&ne&&setTimeout(function(){if(Ce.current){var $e=Ce.current.files;$e.length||(fe({type:"closeDialog"}),Se())}},300)};en.useEffect(function(){return window.addEventListener("focus",pt,!1),function(){window.removeEventListener("focus",pt,!1)}},[Ce,ne,Se,xe]);var Ye=en.useRef([]),et=function($e){G.current&&G.current.contains($e.target)||($e.preventDefault(),Ye.current=[])};en.useEffect(function(){return A&&(document.addEventListener("dragover",g2,!1),document.addEventListener("drop",et,!1)),function(){A&&(document.removeEventListener("dragover",g2),document.removeEventListener("drop",et))}},[G,A]),en.useEffect(function(){return!i&&k&&G.current&&G.current.focus(),function(){}},[G,k,i]);var ct=en.useCallback(function(ge){j?j(ge):console.error(ge)},[j]),Et=en.useCallback(function(ge){ge.preventDefault(),ge.persist(),q(ge),Ye.current=[].concat(ZI(Ye.current),[ge.target]),$m(ge)&&Promise.resolve(o(ge)).then(function($e){if(!(Tg(ge)&&!W)){var Ze=$e.length,Dt=Ze>0&&BI({files:$e,accept:ve,minSize:l,maxSize:a,multiple:d,maxFiles:c,validator:ae}),Tt=Ze>0&&!Dt;fe({isDragAccept:Dt,isDragReject:Tt,isDragActive:!0,type:"setDraggedFiles"}),p&&p(ge)}}).catch(function($e){return ct($e)})},[o,p,ct,W,ve,l,a,d,c,ae]),Rt=en.useCallback(function(ge){ge.preventDefault(),ge.persist(),q(ge);var $e=$m(ge);if($e&&ge.dataTransfer)try{ge.dataTransfer.dropEffect="copy"}catch{}return $e&&_&&_(ge),!1},[_,W]),je=en.useCallback(function(ge){ge.preventDefault(),ge.persist(),q(ge);var $e=Ye.current.filter(function(Dt){return G.current&&G.current.contains(Dt)}),Ze=$e.indexOf(ge.target);Ze!==-1&&$e.splice(Ze,1),Ye.current=$e,!($e.length>0)&&(fe({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),$m(ge)&&v&&v(ge))},[G,v,W]),Ie=en.useCallback(function(ge,$e){var Ze=[],Dt=[];ge.forEach(function(Tt){var Nt=oS(Tt,ve),jt=_y(Nt,2),ht=jt[0],_e=jt[1],Be=aS(Tt,l,a),st=_y(Be,2),Je=st[0],_t=st[1],$t=ae?ae(Tt):null;if(ht&&Je&&!$t)Ze.push(Tt);else{var Wt=[_e,_t];$t&&(Wt=Wt.concat($t)),Dt.push({file:Tt,errors:Wt.filter(function(ot){return ot})})}}),(!d&&Ze.length>1||d&&c>=1&&Ze.length>c)&&(Ze.forEach(function(Tt){Dt.push({file:Tt,errors:[LI]})}),Ze.splice(0)),fe({acceptedFiles:Ze,fileRejections:Dt,type:"setFiles"}),T&&T(Ze,Dt,$e),Dt.length>0&&I&&I(Dt,$e),Ze.length>0&&M&&M(Ze,$e)},[fe,d,ve,l,a,c,T,M,I,ae]),rt=en.useCallback(function(ge){ge.preventDefault(),ge.persist(),q(ge),Ye.current=[],$m(ge)&&Promise.resolve(o(ge)).then(function($e){Tg(ge)&&!W||Ie($e,ge)}).catch(function($e){return ct($e)}),fe({type:"reset"})},[o,Ie,ct,W]),dt=en.useCallback(function(){if(xe.current){fe({type:"openDialog"}),oe();var ge={multiple:d,types:Ne};window.showOpenFilePicker(ge).then(function($e){return o($e)}).then(function($e){Ie($e,null),fe({type:"closeDialog"})}).catch(function($e){qI($e)?(Se($e),fe({type:"closeDialog"})):HI($e)?(xe.current=!1,Ce.current?(Ce.current.value=null,Ce.current.click()):ct(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no was provided."))):ct($e)});return}Ce.current&&(fe({type:"openDialog"}),oe(),Ce.current.value=null,Ce.current.click())},[fe,oe,Se,x,Ie,ct,Ne,d]),xt=en.useCallback(function(ge){!G.current||!G.current.isEqualNode(ge.target)||(ge.key===" "||ge.key==="Enter"||ge.keyCode===32||ge.keyCode===13)&&(ge.preventDefault(),dt())},[G,dt]),z=en.useCallback(function(){fe({type:"focus"})},[]),Fe=en.useCallback(function(){fe({type:"blur"})},[]),Re=en.useCallback(function(){N||(VI()?setTimeout(dt,0):dt())},[N,dt]),he=function($e){return i?null:$e},ue=function($e){return R?null:he($e)},Ee=function($e){return B?null:he($e)},q=function($e){W&&$e.stopPropagation()},re=en.useMemo(function(){return function(){var ge=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$e=ge.refKey,Ze=$e===void 0?"ref":$e,Dt=ge.role,Tt=ge.onKeyDown,Nt=ge.onFocus,jt=ge.onBlur,ht=ge.onClick,_e=ge.onDragEnter,Be=ge.onDragOver,st=ge.onDragLeave,Je=ge.onDrop,_t=Mg(ge,QI);return Zr(Zr(P0({onKeyDown:ue(ta(Tt,xt)),onFocus:ue(ta(Nt,z)),onBlur:ue(ta(jt,Fe)),onClick:he(ta(ht,Re)),onDragEnter:Ee(ta(_e,Et)),onDragOver:Ee(ta(Be,Rt)),onDragLeave:Ee(ta(st,je)),onDrop:Ee(ta(Je,rt)),role:typeof Dt=="string"&&Dt!==""?Dt:"presentation"},Ze,G),!i&&!R?{tabIndex:0}:{}),_t)}},[G,xt,z,Fe,Re,Et,Rt,je,rt,R,B,i]),V=en.useCallback(function(ge){ge.stopPropagation()},[]),me=en.useMemo(function(){return function(){var ge=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},$e=ge.refKey,Ze=$e===void 0?"ref":$e,Dt=ge.onChange,Tt=ge.onClick,Nt=Mg(ge,YI),jt=P0({accept:ve,multiple:d,type:"file",style:{display:"none"},onChange:he(ta(Dt,rt)),onClick:he(ta(Tt,V)),tabIndex:-1},Ze,Ce);return Zr(Zr({},jt),Nt)}},[Ce,n,d,rt,i]);return Zr(Zr({},te),{},{isFocused:Ae&&!i,getRootProps:re,getInputProps:me,rootRef:G,inputRef:Ce,open:he(dt)})}function o3(e,t){switch(t.type){case"focus":return Zr(Zr({},e),{},{isFocused:!0});case"blur":return Zr(Zr({},e),{},{isFocused:!1});case"openDialog":return Zr(Zr({},A0),{},{isFileDialogActive:!0});case"closeDialog":return Zr(Zr({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return Zr(Zr({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return Zr(Zr({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return Zr({},A0);default:return e}}function y2(){}var Ea={},hS={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(e,t,n)=>{e.exports=n.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,t,n)=>{n.r(t),n.d(t,{Environment:()=>Fe,Interpreter:()=>Re,Template:()=>Ee,parse:()=>Ae,tokenize:()=>_});var i=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),o=Object.freeze({set:i.Set,for:i.For,in:i.In,is:i.Is,if:i.If,else:i.Else,endif:i.EndIf,elif:i.ElseIf,endfor:i.EndFor,and:i.And,or:i.Or,not:i.Not,"not in":i.NotIn,macro:i.Macro,endmacro:i.EndMacro,true:i.BooleanLiteral,false:i.BooleanLiteral,True:i.BooleanLiteral,False:i.BooleanLiteral}),a=class{constructor(q,re){this.value=q,this.type=re}};function l(q){return/\w/.test(q)}function d(q){return/[0-9]/.test(q)}var c=[["{%",i.OpenStatement],["%}",i.CloseStatement],["{{",i.OpenExpression],["}}",i.CloseExpression],["(",i.OpenParen],[")",i.CloseParen],["{",i.OpenCurlyBracket],["}",i.CloseCurlyBracket],["[",i.OpenSquareBracket],["]",i.CloseSquareBracket],[",",i.Comma],[".",i.Dot],[":",i.Colon],["|",i.Pipe],["<=",i.ComparisonBinaryOperator],[">=",i.ComparisonBinaryOperator],["==",i.ComparisonBinaryOperator],["!=",i.ComparisonBinaryOperator],["<",i.ComparisonBinaryOperator],[">",i.ComparisonBinaryOperator],["+",i.AdditiveBinaryOperator],["-",i.AdditiveBinaryOperator],["*",i.MultiplicativeBinaryOperator],["/",i.MultiplicativeBinaryOperator],["%",i.MultiplicativeBinaryOperator],["=",i.Equals]],p=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function v(q,re={}){return q.endsWith(` `)&&(q=q.slice(0,-1)),q=q.replace(/{#.*?#}/gs,"{##}"),re.lstrip_blocks&&(q=q.replace(/^[ \t]*({[#%])/gm,"$1")),re.trim_blocks&&(q=q.replace(/([#%]})\n/g,"$1")),q.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function _(q,re={}){var Ze,Dt,Tt;const V=[],me=v(q,re);let ge=0;const $e=Nt=>{let jt="";for(;Nt(me[ge]);){if(me[ge]==="\\"){if(++ge,ge>=me.length)throw new SyntaxError("Unexpected end of input");const ht=me[ge++],_e=p.get(ht);if(_e===void 0)throw new SyntaxError(`Unexpected escaped character: ${ht}`);jt+=_e;continue}if(jt+=me[ge++],ge>=me.length)throw new SyntaxError("Unexpected end of input")}return jt};e:for(;ge0){V.push(new a(ht,i.Text));continue}}$e(ht=>/\s/.test(ht));const jt=me[ge];if(jt==="-"||jt==="+"){const ht=(Dt=V.at(-1))==null?void 0:Dt.type;if(ht===i.Text||ht===void 0)throw new SyntaxError(`Unexpected character: ${jt}`);switch(ht){case i.Identifier:case i.NumericLiteral:case i.BooleanLiteral:case i.StringLiteral:case i.CloseParen:case i.CloseSquareBracket:break;default:{++ge;const _e=$e(d);V.push(new a(`${jt}${_e}`,_e.length>0?i.NumericLiteral:i.UnaryOperator));continue}}}for(const[ht,_e]of c)if(me.slice(ge,ge+ht.length)===ht){V.push(new a(ht,_e)),ge+=ht.length;continue e}if(jt==="'"||jt==='"'){++ge;const ht=$e(_e=>_e!==jt);V.push(new a(ht,i.StringLiteral)),++ge;continue}if(d(jt)){const ht=$e(d);V.push(new a(ht,i.NumericLiteral));continue}if(l(jt)){const ht=$e(l),_e=Object.hasOwn(o,ht)?o[ht]:i.Identifier;_e===i.In&&((Tt=V.at(-1))==null?void 0:Tt.type)===i.Not?(V.pop(),V.push(new a("not in",i.NotIn))):V.push(new a(ht,_e));continue}throw new SyntaxError(`Unexpected character: ${jt}`)}return V}var T=class{constructor(){ft(this,"type","Statement")}},M=class extends T{constructor(re){super();ft(this,"type","Program");this.body=re}},I=class extends T{constructor(re,V,me){super();ft(this,"type","If");this.test=re,this.body=V,this.alternate=me}},C=class extends T{constructor(re,V,me,ge){super();ft(this,"type","For");this.loopvar=re,this.iterable=V,this.body=me,this.defaultBlock=ge}},E=class extends T{constructor(re,V){super();ft(this,"type","Set");this.assignee=re,this.value=V}},x=class extends T{constructor(re,V,me){super();ft(this,"type","Macro");this.name=re,this.args=V,this.body=me}},k=class extends T{constructor(){super(...arguments);ft(this,"type","Expression")}},A=class extends k{constructor(re,V,me){super();ft(this,"type","MemberExpression");this.object=re,this.property=V,this.computed=me}},N=class extends k{constructor(re,V){super();ft(this,"type","CallExpression");this.callee=re,this.args=V}},R=class extends k{constructor(re){super();ft(this,"type","Identifier");this.value=re}},B=class extends k{constructor(re){super();ft(this,"type","Literal");this.value=re}},W=class extends B{constructor(){super(...arguments);ft(this,"type","NumericLiteral")}},j=class extends B{constructor(){super(...arguments);ft(this,"type","StringLiteral")}},ae=class extends B{constructor(){super(...arguments);ft(this,"type","BooleanLiteral")}},ve=class extends B{constructor(){super(...arguments);ft(this,"type","ArrayLiteral")}},Ne=class extends B{constructor(){super(...arguments);ft(this,"type","TupleLiteral")}},oe=class extends B{constructor(){super(...arguments);ft(this,"type","ObjectLiteral")}},Se=class extends k{constructor(re,V,me){super();ft(this,"type","BinaryExpression");this.operator=re,this.left=V,this.right=me}},G=class extends k{constructor(re,V){super();ft(this,"type","FilterExpression");this.operand=re,this.filter=V}},Ce=class extends k{constructor(re,V){super();ft(this,"type","SelectExpression");this.iterable=re,this.test=V}},gt=class extends k{constructor(re,V,me){super();ft(this,"type","TestExpression");this.operand=re,this.negate=V,this.test=me}},Me=class extends k{constructor(re,V){super();ft(this,"type","UnaryExpression");this.operator=re,this.argument=V}},te=class extends k{constructor(re=void 0,V=void 0,me=void 0){super();ft(this,"type","SliceExpression");this.start=re,this.stop=V,this.step=me}},fe=class extends k{constructor(re,V){super();ft(this,"type","KeywordArgumentExpression");this.key=re,this.value=V}};function Ae(q){const re=new M([]);let V=0;function me(Pt,Qt){const dn=q[V++];if(!dn||dn.type!==Pt)throw new Error(`Parser Error: ${Qt}. ${dn.type} !== ${Pt}.`);return dn}function ge(){switch(q[V].type){case i.Text:return Dt();case i.OpenStatement:return Tt();case i.OpenExpression:return Nt();default:throw new SyntaxError(`Unexpected token type: ${q[V].type}`)}}function $e(...Pt){return V+Pt.length<=q.length&&Pt.some((Qt,dn)=>Qt!==q[V+dn].type)}function Ze(...Pt){return V+Pt.length<=q.length&&Pt.every((Qt,dn)=>Qt===q[V+dn].type)}function Dt(){return new j(me(i.Text,"Expected text token").value)}function Tt(){me(i.OpenStatement,"Expected opening statement token");let Pt;switch(q[V].type){case i.Set:++V,Pt=jt(),me(i.CloseStatement,"Expected closing statement token");break;case i.If:++V,Pt=ht(),me(i.OpenStatement,"Expected {% token"),me(i.EndIf,"Expected endif token"),me(i.CloseStatement,"Expected %} token");break;case i.Macro:++V,Pt=_e(),me(i.OpenStatement,"Expected {% token"),me(i.EndMacro,"Expected endmacro token"),me(i.CloseStatement,"Expected %} token");break;case i.For:++V,Pt=st(),me(i.OpenStatement,"Expected {% token"),me(i.EndFor,"Expected endfor token"),me(i.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${q[V].type}`)}return Pt}function Nt(){me(i.OpenExpression,"Expected opening expression token");const Pt=Je();return me(i.CloseExpression,"Expected closing expression token"),Pt}function jt(){const Pt=Je();if(Ze(i.Equals)){++V;const Qt=jt();return new E(Pt,Qt)}return Pt}function ht(){var Ar,Ci,xs,gr,Nr,yr,Pi,wr;const Pt=Je();me(i.CloseStatement,"Expected closing statement token");const Qt=[],dn=[];for(;!(((Ar=q[V])==null?void 0:Ar.type)===i.OpenStatement&&(((Ci=q[V+1])==null?void 0:Ci.type)===i.ElseIf||((xs=q[V+1])==null?void 0:xs.type)===i.Else||((gr=q[V+1])==null?void 0:gr.type)===i.EndIf));)Qt.push(ge());if(((Nr=q[V])==null?void 0:Nr.type)===i.OpenStatement&&((yr=q[V+1])==null?void 0:yr.type)!==i.EndIf)if(++V,Ze(i.ElseIf))me(i.ElseIf,"Expected elseif token"),dn.push(ht());else for(me(i.Else,"Expected else token"),me(i.CloseStatement,"Expected closing statement token");!(((Pi=q[V])==null?void 0:Pi.type)===i.OpenStatement&&((wr=q[V+1])==null?void 0:wr.type)===i.EndIf);)dn.push(ge());return new I(Pt,Qt,dn)}function _e(){const Pt=kn();if(Pt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Qt=hn();me(i.CloseStatement,"Expected closing statement token");const dn=[];for(;$e(i.OpenStatement,i.EndMacro);)dn.push(ge());return new x(Pt,Qt,dn)}function Be(Pt=!1){const Qt=Pt?kn:Je,dn=[Qt()],Ar=Ze(i.Comma);for(;Ar&&(++V,dn.push(Qt()),!!Ze(i.Comma)););return Ar?new Ne(dn):dn[0]}function st(){const Pt=Be(!0);if(!(Pt instanceof R||Pt instanceof Ne))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Pt.type} instead`);me(i.In,"Expected `in` keyword following loop variable");const Qt=Je();me(i.CloseStatement,"Expected closing statement token");const dn=[];for(;$e(i.OpenStatement,i.EndFor)&&$e(i.OpenStatement,i.Else);)dn.push(ge());const Ar=[];if(Ze(i.OpenStatement,i.Else))for(++V,++V,me(i.CloseStatement,"Expected closing statement token");$e(i.OpenStatement,i.EndFor);)Ar.push(ge());return new C(Pt,Qt,dn,Ar)}function Je(){return _t()}function _t(){const Pt=$t();if(Ze(i.If)){++V;const Qt=$t();if(Ze(i.Else)){++V;const dn=$t();return new I(Qt,[Pt],[dn])}else return new Ce(Pt,Qt)}return Pt}function $t(){let Pt=Wt();for(;Ze(i.Or);){const Qt=q[V];++V;const dn=Wt();Pt=new Se(Qt,Pt,dn)}return Pt}function Wt(){let Pt=ot();for(;Ze(i.And);){const Qt=q[V];++V;const dn=ot();Pt=new Se(Qt,Pt,dn)}return Pt}function ot(){let Pt;for(;Ze(i.Not);){const Qt=q[V];++V;const dn=ot();Pt=new Me(Qt,dn)}return Pt??nn()}function nn(){let Pt=Gt();for(;Ze(i.ComparisonBinaryOperator)||Ze(i.In)||Ze(i.NotIn);){const Qt=q[V];++V;const dn=Gt();Pt=new Se(Qt,Pt,dn)}return Pt}function Gt(){let Pt=En();for(;Ze(i.AdditiveBinaryOperator);){const Qt=q[V];++V;const dn=En();Pt=new Se(Qt,Pt,dn)}return Pt}function Mt(){const Pt=yn();return Ze(i.OpenParen)?mn(Pt):Pt}function mn(Pt){let Qt=new N(Pt,hn());return Ze(i.OpenParen)&&(Qt=mn(Qt)),Qt}function hn(){me(i.OpenParen,"Expected opening parenthesis for arguments list");const Pt=Sn();return me(i.CloseParen,"Expected closing parenthesis for arguments list"),Pt}function Sn(){const Pt=[];for(;!Ze(i.CloseParen);){let Qt=Je();if(Ze(i.Equals)){if(++V,!(Qt instanceof R))throw new SyntaxError("Expected identifier for keyword argument");const dn=Je();Qt=new fe(Qt,dn)}Pt.push(Qt),Ze(i.Comma)&&++V}return Pt}function Tn(){const Pt=[];let Qt=!1;for(;!Ze(i.CloseSquareBracket);)Ze(i.Colon)?(Pt.push(void 0),++V,Qt=!0):(Pt.push(Je()),Ze(i.Colon)&&(++V,Qt=!0));if(Pt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Qt){if(Pt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new te(...Pt)}return Pt[0]}function yn(){let Pt=kn();for(;Ze(i.Dot)||Ze(i.OpenSquareBracket);){const Qt=q[V];++V;let dn;const Ar=Qt.type!==i.Dot;if(Ar)dn=Tn(),me(i.CloseSquareBracket,"Expected closing square bracket");else if(dn=kn(),dn.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Pt=new A(Pt,dn,Ar)}return Pt}function En(){let Pt=$n();for(;Ze(i.MultiplicativeBinaryOperator);){const Qt=q[V];++V;const dn=$n();Pt=new Se(Qt,Pt,dn)}return Pt}function $n(){let Pt=zn();for(;Ze(i.Is);){++V;const Qt=Ze(i.Not);Qt&&++V;let dn=kn();if(dn instanceof ae&&(dn=new R(dn.value.toString())),!(dn instanceof R))throw new SyntaxError("Expected identifier for the test");Pt=new gt(Pt,Qt,dn)}return Pt}function zn(){let Pt=Mt();for(;Ze(i.Pipe);){++V;let Qt=kn();if(!(Qt instanceof R))throw new SyntaxError("Expected identifier for the filter");Ze(i.OpenParen)&&(Qt=mn(Qt)),Pt=new G(Pt,Qt)}return Pt}function kn(){const Pt=q[V];switch(Pt.type){case i.NumericLiteral:return++V,new W(Number(Pt.value));case i.StringLiteral:return++V,new j(Pt.value);case i.BooleanLiteral:return++V,new ae(Pt.value.toLowerCase()==="true");case i.Identifier:return++V,new R(Pt.value);case i.OpenParen:{++V;const Qt=Be();if(q[V].type!==i.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${q[V].type} instead`);return++V,Qt}case i.OpenSquareBracket:{++V;const Qt=[];for(;!Ze(i.CloseSquareBracket);)Qt.push(Je()),Ze(i.Comma)&&++V;return++V,new ve(Qt)}case i.OpenCurlyBracket:{++V;const Qt=new Map;for(;!Ze(i.CloseCurlyBracket);){const dn=Je();me(i.Colon,"Expected colon between key and value in object literal");const Ar=Je();Qt.set(dn,Ar),Ze(i.Comma)&&++V}return++V,new oe(Qt)}default:throw new SyntaxError(`Unexpected token: ${Pt.type}`)}}for(;V=0?(re=(re??(re=0))<0?Math.max(q.length+re,0):Math.min(re,q.length),V=(V??(V=q.length))<0?Math.max(q.length+V,0):Math.min(V,q.length)):(re=(re??(re=q.length-1))<0?Math.max(q.length+re,-1):Math.min(re,q.length-1),V=(V??(V=-1))<-1?Math.max(q.length+V,-1):Math.min(V,q.length-1));const $e=[];for(let Ze=re;ge*Zere.toUpperCase())}var Ye=class{constructor(q=void 0){ft(this,"type","RuntimeValue");ft(this,"value");ft(this,"builtins",new Map);this.value=q}__bool__(){return new Et(!!this.value)}},et=class extends Ye{constructor(){super(...arguments);ft(this,"type","NumericValue")}},ct=class extends Ye{constructor(){super(...arguments);ft(this,"type","StringValue");ft(this,"builtins",new Map([["upper",new dt(()=>new ct(this.value.toUpperCase()))],["lower",new dt(()=>new ct(this.value.toLowerCase()))],["strip",new dt(()=>new ct(this.value.trim()))],["title",new dt(()=>new ct(pt(this.value)))],["length",new et(this.value.length)]]))}},Et=class extends Ye{constructor(){super(...arguments);ft(this,"type","BooleanValue")}},Rt=class extends Ye{constructor(){super(...arguments);ft(this,"type","ObjectValue");ft(this,"builtins",new Map([["get",new dt(([re,V])=>{if(!(re instanceof ct))throw new Error(`Object key must be a string: got ${re.type}`);return this.value.get(re.value)??V??new xt})],["items",new dt(()=>new Ie(Array.from(this.value.entries()).map(([re,V])=>new Ie([new ct(re),V]))))]]))}__bool__(){return new Et(this.value.size>0)}},je=class extends Rt{constructor(){super(...arguments);ft(this,"type","KeywordArgumentsValue")}},Ie=class extends Ye{constructor(){super(...arguments);ft(this,"type","ArrayValue");ft(this,"builtins",new Map([["length",new et(this.value.length)]]))}__bool__(){return new Et(this.value.length>0)}},rt=class extends Ie{constructor(){super(...arguments);ft(this,"type","TupleValue")}},dt=class extends Ye{constructor(){super(...arguments);ft(this,"type","FunctionValue")}},xt=class extends Ye{constructor(){super(...arguments);ft(this,"type","NullValue")}},z=class extends Ye{constructor(){super(...arguments);ft(this,"type","UndefinedValue")}},Fe=class{constructor(q){ft(this,"variables",new Map([["namespace",new dt(q=>{if(q.length===0)return new Rt(new Map);if(q.length!==1||!(q[0]instanceof Rt))throw new Error("`namespace` expects either zero arguments or a single object argument");return q[0]})]]));ft(this,"tests",new Map([["boolean",q=>q.type==="BooleanValue"],["callable",q=>q instanceof dt],["odd",q=>{if(q.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${q.type}`);return q.value%2!==0}],["even",q=>{if(q.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${q.type}`);return q.value%2===0}],["false",q=>q.type==="BooleanValue"&&!q.value],["true",q=>q.type==="BooleanValue"&&q.value],["string",q=>q.type==="StringValue"],["number",q=>q.type==="NumericValue"],["integer",q=>q.type==="NumericValue"&&Number.isInteger(q.value)],["iterable",q=>q instanceof Ie||q instanceof ct],["lower",q=>{const re=q.value;return q.type==="StringValue"&&re===re.toLowerCase()}],["upper",q=>{const re=q.value;return q.type==="StringValue"&&re===re.toUpperCase()}],["none",q=>q.type==="NullValue"],["defined",q=>q.type!=="UndefinedValue"],["undefined",q=>q.type==="UndefinedValue"],["equalto",(q,re)=>q.value===re.value],["eq",(q,re)=>q.value===re.value]]));this.parent=q}set(q,re){return this.declareVariable(q,he(re))}declareVariable(q,re){if(this.variables.has(q))throw new SyntaxError(`Variable already declared: ${q}`);return this.variables.set(q,re),re}setVariable(q,re){return this.variables.set(q,re),re}resolve(q){if(this.variables.has(q))return this;if(this.parent)return this.parent.resolve(q);throw new Error(`Unknown variable: ${q}`)}lookupVariable(q){try{return this.resolve(q).variables.get(q)??new z}catch{return new z}}},Re=class{constructor(q){ft(this,"global");this.global=q??new Fe}run(q){return this.evaluate(q,this.global)}evaluateBinaryExpression(q,re){const V=this.evaluate(q.left,re);switch(q.operator.value){case"and":return V.__bool__().value?this.evaluate(q.right,re):V;case"or":return V.__bool__().value?V:this.evaluate(q.right,re)}const me=this.evaluate(q.right,re);switch(q.operator.value){case"==":return new Et(V.value==me.value);case"!=":return new Et(V.value!=me.value)}if(V instanceof z||me instanceof z)throw new Error("Cannot perform operation on undefined values");if(V instanceof xt||me instanceof xt)throw new Error("Cannot perform operation on null values");if(V instanceof et&&me instanceof et)switch(q.operator.value){case"+":return new et(V.value+me.value);case"-":return new et(V.value-me.value);case"*":return new et(V.value*me.value);case"/":return new et(V.value/me.value);case"%":return new et(V.value%me.value);case"<":return new Et(V.value":return new Et(V.value>me.value);case">=":return new Et(V.value>=me.value);case"<=":return new Et(V.value<=me.value)}else if(V instanceof Ie&&me instanceof Ie)switch(q.operator.value){case"+":return new Ie(V.value.concat(me.value))}else if(me instanceof Ie){const ge=me.value.find($e=>$e.value===V.value)!==void 0;switch(q.operator.value){case"in":return new Et(ge);case"not in":return new Et(!ge)}}if(V instanceof ct||me instanceof ct)switch(q.operator.value){case"+":return new ct(V.value.toString()+me.value.toString())}if(V instanceof ct&&me instanceof ct)switch(q.operator.value){case"in":return new Et(me.value.includes(V.value));case"not in":return new Et(!me.value.includes(V.value))}if(V instanceof ct&&me instanceof Rt)switch(q.operator.value){case"in":return new Et(me.value.has(V.value));case"not in":return new Et(!me.value.has(V.value))}throw new SyntaxError(`Unknown operator "${q.operator.value}" between ${V.type} and ${me.type}`)}evaluateArguments(q,re){const V=[],me=new Map;for(const ge of q)if(ge.type==="KeywordArgumentExpression"){const $e=ge;me.set($e.key.value,this.evaluate($e.value,re))}else{if(me.size>0)throw new Error("Positional arguments must come before keyword arguments");V.push(this.evaluate(ge,re))}return[V,me]}evaluateFilterExpression(q,re){const V=this.evaluate(q.operand,re);if(q.filter.type==="Identifier"){const me=q.filter;if(me.value==="tojson")return new ct(ue(V));if(V instanceof Ie)switch(me.value){case"list":return V;case"first":return V.value[0];case"last":return V.value[V.value.length-1];case"length":return new et(V.value.length);case"reverse":return new Ie(V.value.reverse());case"sort":return new Ie(V.value.sort((ge,$e)=>{if(ge.type!==$e.type)throw new Error(`Cannot compare different types: ${ge.type} and ${$e.type}`);switch(ge.type){case"NumericValue":return ge.value-$e.value;case"StringValue":return ge.value.localeCompare($e.value);default:throw new Error(`Cannot compare type: ${ge.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${me.value}`)}else if(V instanceof ct)switch(me.value){case"length":return new et(V.value.length);case"upper":return new ct(V.value.toUpperCase());case"lower":return new ct(V.value.toLowerCase());case"title":return new ct(pt(V.value));case"capitalize":return new ct(V.value.charAt(0).toUpperCase()+V.value.slice(1));case"trim":return new ct(V.value.trim());case"indent":return new ct(V.value.split(` `).map((ge,$e)=>$e===0||ge.length===0?ge:" "+ge).join(` `));case"string":return V;default:throw new Error(`Unknown StringValue filter: ${me.value}`)}else if(V instanceof et)switch(me.value){case"abs":return new et(Math.abs(V.value));default:throw new Error(`Unknown NumericValue filter: ${me.value}`)}else if(V instanceof Rt)switch(me.value){case"items":return new Ie(Array.from(V.value.entries()).map(([ge,$e])=>new Ie([new ct(ge),$e])));case"length":return new et(V.value.size);default:throw new Error(`Unknown ObjectValue filter: ${me.value}`)}throw new Error(`Cannot apply filter "${me.value}" to type: ${V.type}`)}else if(q.filter.type==="CallExpression"){const me=q.filter;if(me.callee.type!=="Identifier")throw new Error(`Unknown filter: ${me.callee.type}`);const ge=me.callee.value;if(ge==="tojson"){const[,$e]=this.evaluateArguments(me.args,re),Ze=$e.get("indent")??new xt;if(!(Ze instanceof et||Ze instanceof xt))throw new Error("If set, indent must be a number");return new ct(ue(V,Ze.value))}if(V instanceof Ie){switch(ge){case"selectattr":{if(V.value.some(jt=>!(jt instanceof Rt)))throw new Error("`selectattr` can only be applied to array of objects");if(me.args.some(jt=>jt.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[$e,Ze,Dt]=me.args.map(jt=>this.evaluate(jt,re));let Tt;if(Ze){const jt=re.tests.get(Ze.value);if(!jt)throw new Error(`Unknown test: ${Ze.value}`);Tt=jt}else Tt=(...jt)=>jt[0].__bool__().value;const Nt=V.value.filter(jt=>{const ht=jt.value.get($e.value);return ht?Tt(ht,Dt):!1});return new Ie(Nt)}case"map":{const[,$e]=this.evaluateArguments(me.args,re);if($e.has("attribute")){const Ze=$e.get("attribute");if(!(Ze instanceof ct))throw new Error("attribute must be a string");const Dt=$e.get("default"),Tt=V.value.map(Nt=>{if(!(Nt instanceof Rt))throw new Error("items in map must be an object");return Nt.value.get(Ze.value)??Dt??new z});return new Ie(Tt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${ge}`)}else if(V instanceof ct){switch(ge){case"indent":{const[$e,Ze]=this.evaluateArguments(me.args,re),Dt=$e.at(0)??Ze.get("width")??new et(4);if(!(Dt instanceof et))throw new Error("width must be a number");const Tt=$e.at(1)??Ze.get("first")??new Et(!1),Nt=$e.at(2)??Ze.get("blank")??new Et(!1),jt=V.value.split(` `),ht=" ".repeat(Dt.value),_e=jt.map((Be,st)=>!Tt.value&&st===0||!Nt.value&&Be.length===0?Be:ht+Be);return new ct(_e.join(` `))}}throw new Error(`Unknown StringValue filter: ${ge}`)}else throw new Error(`Cannot apply filter "${ge}" to type: ${V.type}`)}throw new Error(`Unknown filter: ${q.filter.type}`)}evaluateTestExpression(q,re){const V=this.evaluate(q.operand,re),me=re.tests.get(q.test.value);if(!me)throw new Error(`Unknown test: ${q.test.value}`);const ge=me(V);return new Et(q.negate?!ge:ge)}evaluateUnaryExpression(q,re){const V=this.evaluate(q.argument,re);switch(q.operator.value){case"not":return new Et(!V.value);default:throw new SyntaxError(`Unknown operator: ${q.operator.value}`)}}evalProgram(q,re){return this.evaluateBlock(q.body,re)}evaluateBlock(q,re){let V="";for(const me of q){const ge=this.evaluate(me,re);ge.type!=="NullValue"&&ge.type!=="UndefinedValue"&&(V+=ge.value)}return new ct(V)}evaluateIdentifier(q,re){return re.lookupVariable(q.value)}evaluateCallExpression(q,re){const[V,me]=this.evaluateArguments(q.args,re);me.size>0&&V.push(new je(me));const ge=this.evaluate(q.callee,re);if(ge.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${ge.type}`);return ge.value(V,re)}evaluateSliceExpression(q,re,V){if(!(q instanceof Ie||q instanceof ct))throw new Error("Slice object must be an array or string");const me=this.evaluate(re.start,V),ge=this.evaluate(re.stop,V),$e=this.evaluate(re.step,V);if(!(me instanceof et||me instanceof z))throw new Error("Slice start must be numeric or undefined");if(!(ge instanceof et||ge instanceof z))throw new Error("Slice stop must be numeric or undefined");if(!($e instanceof et||$e instanceof z))throw new Error("Slice step must be numeric or undefined");return q instanceof Ie?new Ie(xe(q.value,me.value,ge.value,$e.value)):new ct(xe(Array.from(q.value),me.value,ge.value,$e.value).join(""))}evaluateMemberExpression(q,re){const V=this.evaluate(q.object,re);let me;if(q.computed){if(q.property.type==="SliceExpression")return this.evaluateSliceExpression(V,q.property,re);me=this.evaluate(q.property,re)}else me=new ct(q.property.value);let ge;if(V instanceof Rt){if(!(me instanceof ct))throw new Error(`Cannot access property with non-string: got ${me.type}`);ge=V.value.get(me.value)??V.builtins.get(me.value)}else if(V instanceof Ie||V instanceof ct)if(me instanceof et)ge=V.value.at(me.value),V instanceof ct&&(ge=new ct(V.value.at(me.value)));else if(me instanceof ct)ge=V.builtins.get(me.value);else throw new Error(`Cannot access property with non-string/non-number: got ${me.type}`);else{if(!(me instanceof ct))throw new Error(`Cannot access property with non-string: got ${me.type}`);ge=V.builtins.get(me.value)}return ge instanceof Ye?ge:new z}evaluateSet(q,re){const V=this.evaluate(q.value,re);if(q.assignee.type==="Identifier"){const me=q.assignee.value;re.setVariable(me,V)}else if(q.assignee.type==="MemberExpression"){const me=q.assignee,ge=this.evaluate(me.object,re);if(!(ge instanceof Rt))throw new Error("Cannot assign to member of non-object");if(me.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");ge.value.set(me.property.value,V)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(q.assignee)}`);return new xt}evaluateIf(q,re){const V=this.evaluate(q.test,re);return this.evaluateBlock(V.__bool__().value?q.body:q.alternate,re)}evaluateFor(q,re){const V=new Fe(re);let me,ge;if(q.iterable.type==="SelectExpression"){const Nt=q.iterable;ge=this.evaluate(Nt.iterable,V),me=Nt.test}else ge=this.evaluate(q.iterable,V);if(!(ge instanceof Ie))throw new Error(`Expected iterable type in for loop: got ${ge.type}`);const $e=[],Ze=[];for(let Nt=0;NtBe.setVariable(q.loopvar.value,ht);else if(q.loopvar.type==="TupleLiteral"){const Be=q.loopvar;if(ht.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ht.type}`);const st=ht;if(Be.value.length!==st.value.length)throw new Error(`Too ${Be.value.length>st.value.length?"few":"many"} items to unpack`);_e=Je=>{for(let _t=0;_t0?$e[Nt-1]:new z],["nextitem",Nt<$e.length-1?$e[Nt+1]:new z]]);V.setVariable("loop",new Rt(jt)),Ze[Nt](V);const ht=this.evaluateBlock(q.body,V);Dt+=ht.value,Tt=!1}if(Tt){const Nt=this.evaluateBlock(q.defaultBlock,V);Dt+=Nt.value}return new ct(Dt)}evaluateMacro(q,re){return re.setVariable(q.name.value,new dt((V,me)=>{var Ze;const ge=new Fe(me);V=V.slice();let $e;((Ze=V.at(-1))==null?void 0:Ze.type)==="KeywordArgumentsValue"&&($e=V.pop());for(let Dt=0;Dtthis.evaluate(V,re)));case"TupleLiteral":return new rt(q.value.map(V=>this.evaluate(V,re)));case"ObjectLiteral":{const V=new Map;for(const[me,ge]of q.value){const $e=this.evaluate(me,re);if(!($e instanceof ct))throw new Error(`Object keys must be strings: got ${$e.type}`);V.set($e.value,this.evaluate(ge,re))}return new Rt(V)}case"Identifier":return this.evaluateIdentifier(q,re);case"CallExpression":return this.evaluateCallExpression(q,re);case"MemberExpression":return this.evaluateMemberExpression(q,re);case"UnaryExpression":return this.evaluateUnaryExpression(q,re);case"BinaryExpression":return this.evaluateBinaryExpression(q,re);case"FilterExpression":return this.evaluateFilterExpression(q,re);case"TestExpression":return this.evaluateTestExpression(q,re);default:throw new SyntaxError(`Unknown node type: ${q.type}`)}}};function he(q){switch(typeof q){case"number":return new et(q);case"string":return new ct(q);case"boolean":return new Et(q);case"undefined":return new z;case"object":return q===null?new xt:Array.isArray(q)?new Ie(q.map(he)):new Rt(new Map(Object.entries(q).map(([re,V])=>[re,he(V)])));case"function":return new dt((re,V)=>{const me=q(...re.map(ge=>ge.value))??null;return he(me)});default:throw new Error(`Cannot convert to runtime value: ${q}`)}}function ue(q,re,V){const me=V??0;switch(q.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(q.value);case"ArrayValue":case"ObjectValue":{const ge=re?" ".repeat(re):"",$e=` `+ge.repeat(me),Ze=$e+ge;if(q.type==="ArrayValue"){const Dt=q.value.map(Tt=>ue(Tt,re,me+1));return re?`[${Ze}${Dt.join(`,${Ze}`)}${$e}]`:`[${Dt.join(", ")}]`}else{const Dt=Array.from(q.value.entries()).map(([Tt,Nt])=>{const jt=`"${Tt}": ${ue(Nt,re,me+1)}`;return re?`${Ze}${jt}`:jt});return re?`{${Dt.join(",")}${$e}}`:`{${Dt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${q.type}`)}}var Ee=class{constructor(q){ft(this,"parsed");const re=_(q,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ae(re)}render(q){const re=new Fe;re.set("false",!1),re.set("true",!0),re.set("raise_exception",ge=>{throw new Error(ge)}),re.set("range",ne);for(const[ge,$e]of Object.entries(q))re.set(ge,$e);return new Re(re).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>a,resolveBackendAndExecutionProviders:()=>d});const i=new Map,o=[],a=(c,p,v)=>{if(p&&typeof p.init=="function"&&typeof p.createInferenceSessionHandler=="function"){const _=i.get(c);if(_===void 0)i.set(c,{backend:p,priority:v});else{if(_.priority>v)return;if(_.priority===v&&_.backend!==p)throw new Error(`cannot register backend "${c}" using priority ${v}`)}if(v>=0){const T=o.indexOf(c);T!==-1&&o.splice(T,1);for(let M=0;M{const p=i.get(c);if(!p)return"backend not found.";if(p.initialized)return p.backend;if(p.aborted)return p.error;{const v=!!p.initPromise;try{return v||(p.initPromise=p.backend.init(c)),await p.initPromise,p.initialized=!0,p.backend}catch(_){return v||(p.error=`${_}`,p.aborted=!0),p.error}finally{delete p.initPromise}}},d=async c=>{const p=c.executionProviders||[],v=p.map(E=>typeof E=="string"?E:E.name),_=v.length===0?o:v;let T;const M=[],I=new Set;for(const E of _){const x=await l(E);typeof x=="string"?M.push({name:E,err:x}):(T||(T=x),T===x&&I.add(E))}if(!T)throw new Error(`no available backend found. ERR: ${M.map(E=>`[${E.name}] ${E.err}`).join(", ")}`);for(const{name:E,err:x}of M)v.includes(E)&&console.warn(`removing requested execution provider "${E}" from session options because it is not available: ${x}`);const C=p.filter(E=>I.has(typeof E=="string"?E:E.name));return[T,new Proxy(c,{get:(E,x)=>x==="executionProviders"?C:Reflect.get(E,x)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>i.registerBackend});var i=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(e,t,n)=>{n.r(t),n.d(t,{env:()=>a});var i=n("./node_modules/onnxruntime-common/dist/esm/version.js");let o="warning";const a={wasm:{},webgl:{},webgpu:{},versions:{common:i.version},set logLevel(l){if(l!==void 0){if(typeof l!="string"||["verbose","info","warning","error","fatal"].indexOf(l)===-1)throw new Error(`Unsupported logging level: ${l}`);o=l}},get logLevel(){return o}};Object.defineProperty(a,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(e,t,n)=>{n.r(t),n.d(t,{env:()=>o});var i=n("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const o=i.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>a.InferenceSession,TRACE:()=>d.TRACE,TRACE_FUNC_BEGIN:()=>d.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>d.TRACE_FUNC_END,Tensor:()=>l.Tensor,TrainingSession:()=>c.TrainingSession,env:()=>o.env,registerBackend:()=>i.registerBackend});var i=n("./node_modules/onnxruntime-common/dist/esm/backend.js"),o=n("./node_modules/onnxruntime-common/dist/esm/env.js"),a=n("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),l=n("./node_modules/onnxruntime-common/dist/esm/tensor.js");n("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),n("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var d=n("./node_modules/onnxruntime-common/dist/esm/trace.js");n("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),n("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var c=n("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>l});var i=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),o=n("./node_modules/onnxruntime-common/dist/esm/tensor.js"),a=n("./node_modules/onnxruntime-common/dist/esm/trace.js");class l{constructor(c){this.handler=c}async run(c,p,v){(0,a.TRACE_FUNC_BEGIN)();const _={};let T={};if(typeof c!="object"||c===null||c instanceof o.Tensor||Array.isArray(c))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let M=!0;if(typeof p=="object"){if(p===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(p instanceof o.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(p)){if(p.length===0)throw new TypeError("'fetches' cannot be an empty array.");M=!1;for(const E of p){if(typeof E!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);_[E]=null}if(typeof v=="object"&&v!==null)T=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else{let E=!1;const x=Object.getOwnPropertyNames(p);for(const k of this.outputNames)if(x.indexOf(k)!==-1){const A=p[k];(A===null||A instanceof o.Tensor)&&(E=!0,M=!1,_[k]=A)}if(E){if(typeof v=="object"&&v!==null)T=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else T=p}}else if(typeof p<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const E of this.inputNames)if(typeof c[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(M)for(const E of this.outputNames)_[E]=null;const I=await this.handler.run(c,_,T),C={};for(const E in I)if(Object.hasOwnProperty.call(I,E)){const x=I[E];x instanceof o.Tensor?C[E]=x:C[E]=new o.Tensor(x.type,x.data,x.dims)}return(0,a.TRACE_FUNC_END)(),C}async release(){return this.handler.dispose()}static async create(c,p,v,_){(0,a.TRACE_FUNC_BEGIN)();let T,M={};if(typeof c=="string"){if(T=c,typeof p=="object"&&p!==null)M=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof Uint8Array){if(T=c,typeof p=="object"&&p!==null)M=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&c instanceof SharedArrayBuffer){const x=c;let k=0,A=c.byteLength;if(typeof p=="object"&&p!==null)M=p;else if(typeof p=="number"){if(k=p,!Number.isSafeInteger(k))throw new RangeError("'byteOffset' must be an integer.");if(k<0||k>=x.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${x.byteLength}).`);if(A=c.byteLength-k,typeof v=="number"){if(A=v,!Number.isSafeInteger(A))throw new RangeError("'byteLength' must be an integer.");if(A<=0||k+A>x.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${x.byteLength-k}].`);if(typeof _=="object"&&_!==null)M=_;else if(typeof _<"u")throw new TypeError("'options' must be an object.")}else if(typeof v<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof p<"u")throw new TypeError("'options' must be an object.");T=new Uint8Array(x,k,A)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[I,C]=await(0,i.resolveBackendAndExecutionProviders)(M),E=await I.createInferenceSessionHandler(T,C);return(0,a.TRACE_FUNC_END)(),new l(E)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>o});var i=n("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const o=i.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(e,t,n)=>{n.r(t),n.d(t,{tensorToDataURL:()=>i,tensorToImageData:()=>o});const i=(a,l)=>{const d=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);d.width=a.dims[3],d.height=a.dims[2];const c=d.getContext("2d");if(c!=null){let p,v;(l==null?void 0:l.tensorLayout)!==void 0&&l.tensorLayout==="NHWC"?(p=a.dims[2],v=a.dims[3]):(p=a.dims[3],v=a.dims[2]);const _=(l==null?void 0:l.format)!==void 0?l.format:"RGB",T=l==null?void 0:l.norm;let M,I;T===void 0||T.mean===void 0?M=[255,255,255,255]:typeof T.mean=="number"?M=[T.mean,T.mean,T.mean,T.mean]:(M=[T.mean[0],T.mean[1],T.mean[2],0],T.mean[3]!==void 0&&(M[3]=T.mean[3])),T===void 0||T.bias===void 0?I=[0,0,0,0]:typeof T.bias=="number"?I=[T.bias,T.bias,T.bias,T.bias]:(I=[T.bias[0],T.bias[1],T.bias[2],0],T.bias[3]!==void 0&&(I[3]=T.bias[3]));const C=v*p;let E=0,x=C,k=C*2,A=-1;_==="RGBA"?(E=0,x=C,k=C*2,A=C*3):_==="RGB"?(E=0,x=C,k=C*2):_==="RBG"&&(E=0,k=C,x=C*2);for(let N=0;N{const d=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let c;if(d!=null){let p,v,_;(l==null?void 0:l.tensorLayout)!==void 0&&l.tensorLayout==="NHWC"?(p=a.dims[2],v=a.dims[1],_=a.dims[3]):(p=a.dims[3],v=a.dims[2],_=a.dims[1]);const T=l!==void 0&&l.format!==void 0?l.format:"RGB",M=l==null?void 0:l.norm;let I,C;M===void 0||M.mean===void 0?I=[255,255,255,255]:typeof M.mean=="number"?I=[M.mean,M.mean,M.mean,M.mean]:(I=[M.mean[0],M.mean[1],M.mean[2],255],M.mean[3]!==void 0&&(I[3]=M.mean[3])),M===void 0||M.bias===void 0?C=[0,0,0,0]:typeof M.bias=="number"?C=[M.bias,M.bias,M.bias,M.bias]:(C=[M.bias[0],M.bias[1],M.bias[2],0],M.bias[3]!==void 0&&(C[3]=M.bias[3]));const E=v*p;if(l!==void 0&&(l.format!==void 0&&_===4&&l.format!=="RGBA"||_===3&&l.format!=="RGB"&&l.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const x=4;let k=0,A=1,N=2,R=3,B=0,W=E,j=E*2,ae=-1;T==="RGBA"?(B=0,W=E,j=E*2,ae=E*3):T==="RGB"?(B=0,W=E,j=E*2):T==="RBG"&&(B=0,j=E,W=E*2),c=d.createImageData(p,v);for(let ve=0;ve{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(e,t,n)=>{n.r(t),n.d(t,{bufferToTensor:()=>o,tensorFromGpuBuffer:()=>d,tensorFromImage:()=>a,tensorFromPinnedBuffer:()=>c,tensorFromTexture:()=>l});var i=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const o=(p,v)=>{if(p===void 0)throw new Error("Image buffer must be defined");if(v.height===void 0||v.width===void 0)throw new Error("Image height and width must be defined");if(v.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:_,width:T}=v,M=v.norm??{mean:255,bias:0};let I,C;typeof M.mean=="number"?I=[M.mean,M.mean,M.mean,M.mean]:I=[M.mean[0],M.mean[1],M.mean[2],M.mean[3]??255],typeof M.bias=="number"?C=[M.bias,M.bias,M.bias,M.bias]:C=[M.bias[0],M.bias[1],M.bias[2],M.bias[3]??0];const E=v.format!==void 0?v.format:"RGBA",x=v.tensorFormat!==void 0&&v.tensorFormat!==void 0?v.tensorFormat:"RGB",k=_*T,A=x==="RGBA"?new Float32Array(k*4):new Float32Array(k*3);let N=4,R=0,B=1,W=2,j=3,ae=0,ve=k,Ne=k*2,oe=-1;E==="RGB"&&(N=3,R=0,B=1,W=2,j=-1),x==="RGBA"?oe=k*3:x==="RBG"?(ae=0,Ne=k,ve=k*2):x==="BGR"&&(Ne=0,ve=k,ae=k*2);for(let G=0;G{const _=typeof HTMLImageElement<"u"&&p instanceof HTMLImageElement,T=typeof ImageData<"u"&&p instanceof ImageData,M=typeof ImageBitmap<"u"&&p instanceof ImageBitmap,I=typeof p=="string";let C,E=v??{};const x=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},k=A=>A instanceof HTMLCanvasElement||A instanceof OffscreenCanvas?A.getContext("2d"):null;if(_){const A=x();A.width=p.width,A.height=p.height;const N=k(A);if(N!=null){let R=p.height,B=p.width;if(v!==void 0&&v.resizedHeight!==void 0&&v.resizedWidth!==void 0&&(R=v.resizedHeight,B=v.resizedWidth),v!==void 0){if(E=v,v.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");E.tensorFormat="RGBA",E.height=R,E.width=B}else E.tensorFormat="RGBA",E.height=R,E.width=B;N.drawImage(p,0,0),C=N.getImageData(0,0,B,R).data}else throw new Error("Can not access image data")}else if(T){let A,N;if(v!==void 0&&v.resizedWidth!==void 0&&v.resizedHeight!==void 0?(A=v.resizedHeight,N=v.resizedWidth):(A=p.height,N=p.width),v!==void 0&&(E=v),E.format="RGBA",E.height=A,E.width=N,v!==void 0){const R=x();R.width=N,R.height=A;const B=k(R);if(B!=null)B.putImageData(p,0,0),C=B.getImageData(0,0,N,A).data;else throw new Error("Can not access image data")}else C=p.data}else if(M){if(v===void 0)throw new Error("Please provide image config with format for Imagebitmap");const A=x();A.width=p.width,A.height=p.height;const N=k(A);if(N!=null){const R=p.height,B=p.width;return N.drawImage(p,0,0,B,R),C=N.getImageData(0,0,B,R).data,E.height=R,E.width=B,o(C,E)}else throw new Error("Can not access image data")}else{if(I)return new Promise((A,N)=>{const R=x(),B=k(R);if(!p||!B)return N();const W=new Image;W.crossOrigin="Anonymous",W.src=p,W.onload=()=>{R.width=W.width,R.height=W.height,B.drawImage(W,0,0,R.width,R.height);const j=B.getImageData(0,0,R.width,R.height);E.height=R.height,E.width=R.width,A(o(j.data,E))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(C!==void 0)return o(C,E);throw new Error("Input data provided is not supported - aborted tensor creation")},l=(p,v)=>{const{width:_,height:T,download:M,dispose:I}=v,C=[1,T,_,4];return new i.Tensor({location:"texture",type:"float32",texture:p,dims:C,download:M,dispose:I})},d=(p,v)=>{const{dataType:_,dims:T,download:M,dispose:I}=v;return new i.Tensor({location:"gpu-buffer",type:_??"float32",gpuBuffer:p,dims:T,download:M,dispose:I})},c=(p,v,_)=>new i.Tensor({location:"cpu-pinned",type:p,data:v,dims:_??[v.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(e,t,n)=>{n.r(t),n.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>o,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>i,checkTypedArray:()=>l});const i=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),o=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let a=!1;const l=()=>{if(!a){a=!0;const d=typeof BigInt64Array<"u"&&BigInt64Array.from,c=typeof BigUint64Array<"u"&&BigUint64Array.from,p=typeof Float16Array<"u"&&Float16Array.from;d&&(i.set("int64",BigInt64Array),o.set(BigInt64Array,"int64")),c&&(i.set("uint64",BigUint64Array),o.set(BigUint64Array,"uint64")),p?(i.set("float16",Float16Array),o.set(Float16Array,"float16")):i.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>d});var i=n("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),o=n("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),a=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),l=n("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class d{constructor(p,v,_){(0,a.checkTypedArray)();let T,M;if(typeof p=="object"&&"location"in p)switch(this.dataLocation=p.location,T=p.type,M=p.dims,p.location){case"cpu-pinned":{const C=a.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(T);if(!C)throw new TypeError(`unsupported type "${T}" to create tensor from pinned buffer`);if(!(p.data instanceof C))throw new TypeError(`buffer should be of type ${C.name}`);this.cpuData=p.data;break}case"texture":{if(T!=="float32")throw new TypeError(`unsupported type "${T}" to create tensor from texture`);this.gpuTextureData=p.texture,this.downloader=p.download,this.disposer=p.dispose;break}case"gpu-buffer":{if(T!=="float32"&&T!=="float16"&&T!=="int32"&&T!=="int64"&&T!=="uint32"&&T!=="uint8"&&T!=="bool")throw new TypeError(`unsupported type "${T}" to create tensor from gpu buffer`);this.gpuBufferData=p.gpuBuffer,this.downloader=p.download,this.disposer=p.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let C,E;if(typeof p=="string")if(T=p,E=_,p==="string"){if(!Array.isArray(v))throw new TypeError("A string tensor's data must be a string array.");C=v}else{const x=a.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(p);if(x===void 0)throw new TypeError(`Unsupported tensor type: ${p}.`);if(Array.isArray(v)){if(p==="float16"&&x===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");p==="uint64"||p==="int64"?C=x.from(v,BigInt):C=x.from(v)}else if(v instanceof x)C=v;else throw new TypeError(`A ${T} tensor's data must be type of ${x}`)}else if(E=v,Array.isArray(p)){if(p.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const x=typeof p[0];if(x==="string")T="string",C=p;else if(x==="boolean")T="bool",C=Uint8Array.from(p);else throw new TypeError(`Invalid element type of data array: ${x}.`)}else{const x=a.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(p.constructor);if(x===void 0)throw new TypeError(`Unsupported type for tensor data: ${p.constructor}.`);T=x,C=p}if(E===void 0)E=[C.length];else if(!Array.isArray(E))throw new TypeError("A tensor's dims must be a number array");M=E,this.cpuData=C,this.dataLocation="cpu"}const I=(0,l.calculateSize)(M);if(this.cpuData&&I!==this.cpuData.length)throw new Error(`Tensor's size(${I}) does not match data length(${this.cpuData.length}).`);this.type=T,this.dims=M,this.size=I}static async fromImage(p,v){return(0,o.tensorFromImage)(p,v)}static fromTexture(p,v){return(0,o.tensorFromTexture)(p,v)}static fromGpuBuffer(p,v){return(0,o.tensorFromGpuBuffer)(p,v)}static fromPinnedBuffer(p,v,_){return(0,o.tensorFromPinnedBuffer)(p,v,_)}toDataURL(p){return(0,i.tensorToDataURL)(this,p)}toImageData(p){return(0,i.tensorToImageData)(this,p)}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}async getData(p){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{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 v=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=v,p&&this.disposer&&(this.disposer(),this.disposer=void 0),v}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.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(p){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,l.tensorReshape)(this,p)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(e,t,n)=>{n.r(t),n.d(t,{calculateSize:()=>o,tensorReshape:()=>a});var i=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const o=l=>{let d=1;for(let c=0;c{switch(l.location){case"cpu":return new i.Tensor(l.type,l.data,d);case"cpu-pinned":return new i.Tensor({location:"cpu-pinned",data:l.data,type:l.type,dims:d});case"texture":return new i.Tensor({location:"texture",texture:l.texture,type:l.type,dims:d});case"gpu-buffer":return new i.Tensor({location:"gpu-buffer",gpuBuffer:l.gpuBuffer,type:l.type,dims:d});default:throw new Error(`tensorReshape: tensor location ${l.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>o});var i=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const o=i.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(e,t,n)=>{n.r(t),n.d(t,{TRACE:()=>o,TRACE_FUNC_BEGIN:()=>l,TRACE_FUNC_END:()=>d});var i=n("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const o=(c,p)=>{(typeof i.env.trace>"u"?!i.env.wasm.trace:!i.env.trace)||console.timeStamp(`${c}::ORT::${p}`)},a=(c,p)=>{var T;const v=((T=new Error().stack)==null?void 0:T.split(/\r\n|\r|\n/g))||[];let _=!1;for(let M=0;M{(typeof i.env.trace>"u"?!i.env.wasm.trace:!i.env.trace)||a("BEGIN",c)},d=c=>{(typeof i.env.trace>"u"?!i.env.wasm.trace:!i.env.trace)||a("END",c)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(e,t,n)=>{n.r(t),n.d(t,{TrainingSession:()=>l});var i=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),o=n("./node_modules/onnxruntime-common/dist/esm/tensor.js");const a="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class l{constructor(c,p,v){this.handler=c,this.hasOptimizerModel=p,this.hasEvalModel=v}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(c,p){const v=c.evalModel||"",_=c.optimizerModel||"",T=p||{},[M,I]=await(0,i.resolveBackendAndExecutionProviders)(T);if(M.createTrainingSessionHandler){const C=await M.createTrainingSessionHandler(c.checkpointState,c.trainModel,v,_,I);return new l(C,!!c.optimizerModel,!!c.evalModel)}else throw new Error(a)}typeNarrowingForRunStep(c,p,v,_,T){const M={};let I={};if(typeof v!="object"||v===null||v instanceof o.Tensor||Array.isArray(v))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let C=!0;if(typeof _=="object"){if(_===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(_ instanceof o.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(_)){if(_.length===0)throw new TypeError("'fetches' cannot be an empty array.");C=!1;for(const E of _){if(typeof E!="string")throw new TypeError("'fetches' must be a string array or an object.");if(p.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);M[E]=null}if(typeof T=="object"&&T!==null)I=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else{let E=!1;const x=Object.getOwnPropertyNames(_);for(const k of p)if(x.indexOf(k)!==-1){const A=_[k];(A===null||A instanceof o.Tensor)&&(E=!0,C=!1,M[k]=A)}if(E){if(typeof T=="object"&&T!==null)I=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else I=_}}else if(typeof _<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const E of c)if(typeof v[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(C)for(const E of p)M[E]=null;return[M,I]}convertHandlerReturnTypeToMapOfTensors(c){const p={};for(const v in c)if(Object.hasOwnProperty.call(c,v)){const _=c[v];_ instanceof o.Tensor?p[v]=_:p[v]=new o.Tensor(_.type,_.data,_.dims)}return p}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(c,p,v){const[_,T]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,c,p,v),M=await this.handler.runTrainStep(c,_,T);return this.convertHandlerReturnTypeToMapOfTensors(M)}async runOptimizerStep(c){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(c||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(c,p,v){if(this.hasEvalModel){const[_,T]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,c,p,v),M=await this.handler.runEvalStep(c,_,T);return this.convertHandlerReturnTypeToMapOfTensors(M)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(c=!0){return this.handler.getParametersSize(c)}async loadParametersBuffer(c,p=!0){const v=await this.getParametersSize(p);if(c.length!==4*v)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(c,p)}async getContiguousParameters(c=!0){return this.handler.getContiguousParameters(c)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(e,t,n)=>{n.r(t),n.d(t,{TrainingSession:()=>o});var i=n("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const o=i.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(e,t,n)=>{n.r(t),n.d(t,{version:()=>i});const i="1.19.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>ue,TRACE:()=>rt,TRACE_FUNC_BEGIN:()=>xt,TRACE_FUNC_END:()=>z,Tensor:()=>je,TrainingSession:()=>Dt,default:()=>_C,env:()=>j,registerBackend:()=>I});/*! * ONNX Runtime Web v1.20.0-dev.20240827-1d059b8702 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,l=Object.prototype.hasOwnProperty,d=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(s,u)=>(typeof require<"u"?require:s)[u]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),c=(r,s)=>()=>(r&&(s=r(r=0)),s),p=(r,s)=>{for(var u in s)i(r,u,{get:s[u],enumerable:!0})},v=(r,s,u,f)=>{if(s&&typeof s=="object"||typeof s=="function")for(let g of a(s))!l.call(r,g)&&g!==u&&i(r,g,{get:()=>s[g],enumerable:!(f=o(s,g))||f.enumerable});return r},_=r=>v(i({},"__esModule",{value:!0}),r),T,M,I,C,E,x=c(()=>{T=new Map,M=[],I=(r,s,u)=>{if(s&&typeof s.init=="function"&&typeof s.createInferenceSessionHandler=="function"){let f=T.get(r);if(f===void 0)T.set(r,{backend:s,priority:u});else{if(f.priority>u)return;if(f.priority===u&&f.backend!==s)throw new Error(`cannot register backend "${r}" using priority ${u}`)}if(u>=0){let g=M.indexOf(r);g!==-1&&M.splice(g,1);for(let w=0;w{let s=T.get(r);if(!s)return"backend not found.";if(s.initialized)return s.backend;if(s.aborted)return s.error;{let u=!!s.initPromise;try{return u||(s.initPromise=s.backend.init(r)),await s.initPromise,s.initialized=!0,s.backend}catch(f){return u||(s.error=`${f}`,s.aborted=!0),s.error}finally{delete s.initPromise}}},E=async r=>{let s=r.executionProviders||[],u=s.map(F=>typeof F=="string"?F:F.name),f=u.length===0?M:u,g,w=[],m=new Set;for(let F of f){let O=await C(F);typeof O=="string"?w.push({name:F,err:O}):(g||(g=O),g===O&&m.add(F))}if(!g)throw new Error(`no available backend found. ERR: ${w.map(F=>`[${F.name}] ${F.err}`).join(", ")}`);for(let{name:F,err:O}of w)u.includes(F)&&console.warn(`removing requested execution provider "${F}" from session options because it is not available: ${O}`);let P=s.filter(F=>m.has(typeof F=="string"?F:F.name));return[g,new Proxy(r,{get:(F,O)=>O==="executionProviders"?P:Reflect.get(F,O)})]}}),k=c(()=>{x()}),A,N=c(()=>{A="1.20.0-dev.20240827-5d54dc1462"}),R,B,W=c(()=>{N(),R="warning",B={wasm:{},webgl:{},webgpu:{},versions:{common:A},set logLevel(r){if(r!==void 0){if(typeof r!="string"||["verbose","info","warning","error","fatal"].indexOf(r)===-1)throw new Error(`Unsupported logging level: ${r}`);R=r}},get logLevel(){return R}},Object.defineProperty(B,"logLevel",{enumerable:!0})}),j,ae=c(()=>{W(),j=B}),ve,Ne,oe=c(()=>{ve=(r,s)=>{let u=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);u.width=r.dims[3],u.height=r.dims[2];let f=u.getContext("2d");if(f!=null){let g,w;(s==null?void 0:s.tensorLayout)!==void 0&&s.tensorLayout==="NHWC"?(g=r.dims[2],w=r.dims[3]):(g=r.dims[3],w=r.dims[2]);let m=(s==null?void 0:s.format)!==void 0?s.format:"RGB",P=s==null?void 0:s.norm,F,O;P===void 0||P.mean===void 0?F=[255,255,255,255]:typeof P.mean=="number"?F=[P.mean,P.mean,P.mean,P.mean]:(F=[P.mean[0],P.mean[1],P.mean[2],0],P.mean[3]!==void 0&&(F[3]=P.mean[3])),P===void 0||P.bias===void 0?O=[0,0,0,0]:typeof P.bias=="number"?O=[P.bias,P.bias,P.bias,P.bias]:(O=[P.bias[0],P.bias[1],P.bias[2],0],P.bias[3]!==void 0&&(O[3]=P.bias[3]));let Y=w*g,Q=0,S=Y,ie=Y*2,ce=-1;m==="RGBA"?(Q=0,S=Y,ie=Y*2,ce=Y*3):m==="RGB"?(Q=0,S=Y,ie=Y*2):m==="RBG"&&(Q=0,ie=Y,S=Y*2);for(let pe=0;pe{let u=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),f;if(u!=null){let g,w,m;(s==null?void 0:s.tensorLayout)!==void 0&&s.tensorLayout==="NHWC"?(g=r.dims[2],w=r.dims[1],m=r.dims[3]):(g=r.dims[3],w=r.dims[2],m=r.dims[1]);let P=s!==void 0&&s.format!==void 0?s.format:"RGB",F=s==null?void 0:s.norm,O,Y;F===void 0||F.mean===void 0?O=[255,255,255,255]:typeof F.mean=="number"?O=[F.mean,F.mean,F.mean,F.mean]:(O=[F.mean[0],F.mean[1],F.mean[2],255],F.mean[3]!==void 0&&(O[3]=F.mean[3])),F===void 0||F.bias===void 0?Y=[0,0,0,0]:typeof F.bias=="number"?Y=[F.bias,F.bias,F.bias,F.bias]:(Y=[F.bias[0],F.bias[1],F.bias[2],0],F.bias[3]!==void 0&&(Y[3]=F.bias[3]));let Q=w*g;if(s!==void 0&&(s.format!==void 0&&m===4&&s.format!=="RGBA"||m===3&&s.format!=="RGB"&&s.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let S=4,ie=0,ce=1,pe=2,ke=3,Pe=0,be=Q,We=Q*2,ze=-1;P==="RGBA"?(Pe=0,be=Q,We=Q*2,ze=Q*3):P==="RGB"?(Pe=0,be=Q,We=Q*2):P==="RBG"&&(Pe=0,We=Q,be=Q*2),f=u.createImageData(g,w);for(let Ge=0;Ge{Rt(),Se=(r,s)=>{if(r===void 0)throw new Error("Image buffer must be defined");if(s.height===void 0||s.width===void 0)throw new Error("Image height and width must be defined");if(s.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:u,width:f}=s,g=s.norm??{mean:255,bias:0},w,m;typeof g.mean=="number"?w=[g.mean,g.mean,g.mean,g.mean]:w=[g.mean[0],g.mean[1],g.mean[2],g.mean[3]??255],typeof g.bias=="number"?m=[g.bias,g.bias,g.bias,g.bias]:m=[g.bias[0],g.bias[1],g.bias[2],g.bias[3]??0];let P=s.format!==void 0?s.format:"RGBA",F=s.tensorFormat!==void 0&&s.tensorFormat!==void 0?s.tensorFormat:"RGB",O=u*f,Y=F==="RGBA"?new Float32Array(O*4):new Float32Array(O*3),Q=4,S=0,ie=1,ce=2,pe=3,ke=0,Pe=O,be=O*2,We=-1;P==="RGB"&&(Q=3,S=0,ie=1,ce=2,pe=-1),F==="RGBA"?We=O*3:F==="RBG"?(ke=0,be=O,Pe=O*2):F==="BGR"&&(be=0,Pe=O,ke=O*2);for(let ze=0;ze{let u=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,f=typeof ImageData<"u"&&r instanceof ImageData,g=typeof ImageBitmap<"u"&&r instanceof ImageBitmap,w=typeof r=="string",m,P=s??{},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")},O=Y=>Y instanceof HTMLCanvasElement||Y instanceof OffscreenCanvas?Y.getContext("2d"):null;if(u){let Y=F();Y.width=r.width,Y.height=r.height;let Q=O(Y);if(Q!=null){let S=r.height,ie=r.width;if(s!==void 0&&s.resizedHeight!==void 0&&s.resizedWidth!==void 0&&(S=s.resizedHeight,ie=s.resizedWidth),s!==void 0){if(P=s,s.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");P.tensorFormat="RGBA",P.height=S,P.width=ie}else P.tensorFormat="RGBA",P.height=S,P.width=ie;Q.drawImage(r,0,0),m=Q.getImageData(0,0,ie,S).data}else throw new Error("Can not access image data")}else if(f){let Y,Q;if(s!==void 0&&s.resizedWidth!==void 0&&s.resizedHeight!==void 0?(Y=s.resizedHeight,Q=s.resizedWidth):(Y=r.height,Q=r.width),s!==void 0&&(P=s),P.format="RGBA",P.height=Y,P.width=Q,s!==void 0){let S=F();S.width=Q,S.height=Y;let ie=O(S);if(ie!=null)ie.putImageData(r,0,0),m=ie.getImageData(0,0,Q,Y).data;else throw new Error("Can not access image data")}else m=r.data}else if(g){if(s===void 0)throw new Error("Please provide image config with format for Imagebitmap");let Y=F();Y.width=r.width,Y.height=r.height;let Q=O(Y);if(Q!=null){let S=r.height,ie=r.width;return Q.drawImage(r,0,0,ie,S),m=Q.getImageData(0,0,ie,S).data,P.height=S,P.width=ie,Se(m,P)}else throw new Error("Can not access image data")}else{if(w)return new Promise((Y,Q)=>{let S=F(),ie=O(S);if(!r||!ie)return Q();let ce=new Image;ce.crossOrigin="Anonymous",ce.src=r,ce.onload=()=>{S.width=ce.width,S.height=ce.height,ie.drawImage(ce,0,0,S.width,S.height);let pe=ie.getImageData(0,0,S.width,S.height);P.height=S.height,P.width=S.width,Y(Se(pe.data,P))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(m!==void 0)return Se(m,P);throw new Error("Input data provided is not supported - aborted tensor creation")},Ce=(r,s)=>{let{width:u,height:f,download:g,dispose:w}=s,m=[1,f,u,4];return new Et({location:"texture",type:"float32",texture:r,dims:m,download:g,dispose:w})},gt=(r,s)=>{let{dataType:u,dims:f,download:g,dispose:w}=s;return new Et({location:"gpu-buffer",type:u??"float32",gpuBuffer:r,dims:f,download:g,dispose:w})},Me=(r,s,u)=>new Et({location:"cpu-pinned",type:r,data:s,dims:u??[s.length]})}),fe,Ae,ne,xe,pt=c(()=>{fe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ae=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ne=!1,xe=()=>{if(!ne){ne=!0;let r=typeof BigInt64Array<"u"&&BigInt64Array.from,s=typeof BigUint64Array<"u"&&BigUint64Array.from,u=typeof Float16Array<"u"&&Float16Array.from;r&&(fe.set("int64",BigInt64Array),Ae.set(BigInt64Array,"int64")),s&&(fe.set("uint64",BigUint64Array),Ae.set(BigUint64Array,"uint64")),u?(fe.set("float16",Float16Array),Ae.set(Float16Array,"float16")):fe.set("float16",Uint16Array)}}}),Ye,et,ct=c(()=>{Rt(),Ye=r=>{let s=1;for(let u=0;u{switch(r.location){case"cpu":return new Et(r.type,r.data,s);case"cpu-pinned":return new Et({location:"cpu-pinned",data:r.data,type:r.type,dims:s});case"texture":return new Et({location:"texture",texture:r.texture,type:r.type,dims:s});case"gpu-buffer":return new Et({location:"gpu-buffer",gpuBuffer:r.gpuBuffer,type:r.type,dims:s});default:throw new Error(`tensorReshape: tensor location ${r.location} is not supported`)}}}),Et,Rt=c(()=>{oe(),te(),pt(),ct(),Et=class{constructor(r,s,u){xe();let f,g;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,f=r.type,g=r.dims,r.location){case"cpu-pinned":{let m=fe.get(f);if(!m)throw new TypeError(`unsupported type "${f}" to create tensor from pinned buffer`);if(!(r.data instanceof m))throw new TypeError(`buffer should be of type ${m.name}`);this.cpuData=r.data;break}case"texture":{if(f!=="float32")throw new TypeError(`unsupported type "${f}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(f!=="float32"&&f!=="float16"&&f!=="int32"&&f!=="int64"&&f!=="uint32"&&f!=="uint8"&&f!=="bool"&&f!=="uint4"&&f!=="int4")throw new TypeError(`unsupported type "${f}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let m,P;if(typeof r=="string")if(f=r,P=u,r==="string"){if(!Array.isArray(s))throw new TypeError("A string tensor's data must be a string array.");m=s}else{let F=fe.get(r);if(F===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(s)){if(r==="float16"&&F===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${F.name} as data.`);r==="uint64"||r==="int64"?m=F.from(s,BigInt):m=F.from(s)}else if(s instanceof F)m=s;else throw new TypeError(`A ${f} tensor's data must be type of ${F}`)}else if(P=s,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let F=typeof r[0];if(F==="string")f="string",m=r;else if(F==="boolean")f="bool",m=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${F}.`)}else{let F=Ae.get(r.constructor);if(F===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);f=F,m=r}if(P===void 0)P=[m.length];else if(!Array.isArray(P))throw new TypeError("A tensor's dims must be a number array");g=P,this.cpuData=m,this.dataLocation="cpu"}let w=Ye(g);if(this.cpuData&&w!==this.cpuData.length&&!((f==="uint4"||f==="int4")&&Math.ceil(w/2)===this.cpuData.length))throw new Error(`Tensor's size(${w}) does not match data length(${this.cpuData.length}).`);this.type=f,this.dims=g,this.size=w}static async fromImage(r,s){return G(r,s)}static fromTexture(r,s){return Ce(r,s)}static fromGpuBuffer(r,s){return gt(r,s)}static fromPinnedBuffer(r,s,u){return Me(r,s,u)}toDataURL(r){return ve(this,r)}toImageData(r){return Ne(this,r)}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}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{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 s=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=s,r&&this.disposer&&(this.disposer(),this.disposer=void 0),s}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.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return et(this,r)}}}),je,Ie=c(()=>{Rt(),je=Et}),rt,dt,xt,z,Fe=c(()=>{W(),rt=(r,s)=>{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||console.timeStamp(`${r}::ORT::${s}`)},dt=(r,s)=>{var g;let u=((g=new Error().stack)==null?void 0:g.split(/\r\n|\r|\n/g))||[],f=!1;for(let w=0;w{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||dt("BEGIN",r)},z=r=>{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||dt("END",r)}}),Re,he=c(()=>{x(),Ie(),Fe(),Re=class pS{constructor(s){this.handler=s}async run(s,u,f){xt();let g={},w={};if(typeof s!="object"||s===null||s instanceof je||Array.isArray(s))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let m=!0;if(typeof u=="object"){if(u===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(u instanceof je)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(u)){if(u.length===0)throw new TypeError("'fetches' cannot be an empty array.");m=!1;for(let O of u){if(typeof O!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(O)===-1)throw new RangeError(`'fetches' contains invalid output name: ${O}.`);g[O]=null}if(typeof f=="object"&&f!==null)w=f;else if(typeof f<"u")throw new TypeError("'options' must be an object.")}else{let O=!1,Y=Object.getOwnPropertyNames(u);for(let Q of this.outputNames)if(Y.indexOf(Q)!==-1){let S=u[Q];(S===null||S instanceof je)&&(O=!0,m=!1,g[Q]=S)}if(O){if(typeof f=="object"&&f!==null)w=f;else if(typeof f<"u")throw new TypeError("'options' must be an object.")}else w=u}}else if(typeof u<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let O of this.inputNames)if(typeof s[O]>"u")throw new Error(`input '${O}' is missing in 'feeds'.`);if(m)for(let O of this.outputNames)g[O]=null;let P=await this.handler.run(s,g,w),F={};for(let O in P)if(Object.hasOwnProperty.call(P,O)){let Y=P[O];Y instanceof je?F[O]=Y:F[O]=new je(Y.type,Y.data,Y.dims)}return z(),F}async release(){return this.handler.dispose()}static async create(s,u,f,g){xt();let w,m={};if(typeof s=="string"){if(w=s,typeof u=="object"&&u!==null)m=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(s instanceof Uint8Array){if(w=s,typeof u=="object"&&u!==null)m=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer){let Y=s,Q=0,S=s.byteLength;if(typeof u=="object"&&u!==null)m=u;else if(typeof u=="number"){if(Q=u,!Number.isSafeInteger(Q))throw new RangeError("'byteOffset' must be an integer.");if(Q<0||Q>=Y.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${Y.byteLength}).`);if(S=s.byteLength-Q,typeof f=="number"){if(S=f,!Number.isSafeInteger(S))throw new RangeError("'byteLength' must be an integer.");if(S<=0||Q+S>Y.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${Y.byteLength-Q}].`);if(typeof g=="object"&&g!==null)m=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(typeof f<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof u<"u")throw new TypeError("'options' must be an object.");w=new Uint8Array(Y,Q,S)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[P,F]=await E(m),O=await P.createInferenceSessionHandler(w,F);return z(),new pS(O)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),ue,Ee=c(()=>{he(),ue=Re}),q=c(()=>{}),re=c(()=>{}),V=c(()=>{}),me=c(()=>{}),ge,$e,Ze=c(()=>{x(),Ie(),ge="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",$e=class mS{constructor(s,u,f){this.handler=s,this.hasOptimizerModel=u,this.hasEvalModel=f}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(s,u){let f=s.evalModel||"",g=s.optimizerModel||"",w=u||{},[m,P]=await E(w);if(m.createTrainingSessionHandler){let F=await m.createTrainingSessionHandler(s.checkpointState,s.trainModel,f,g,P);return new mS(F,!!s.optimizerModel,!!s.evalModel)}else throw new Error(ge)}typeNarrowingForRunStep(s,u,f,g,w){let m={},P={};if(typeof f!="object"||f===null||f instanceof je||Array.isArray(f))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let F=!0;if(typeof g=="object"){if(g===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(g instanceof je)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(g)){if(g.length===0)throw new TypeError("'fetches' cannot be an empty array.");F=!1;for(let O of g){if(typeof O!="string")throw new TypeError("'fetches' must be a string array or an object.");if(u.indexOf(O)===-1)throw new RangeError(`'fetches' contains invalid output name: ${O}.`);m[O]=null}if(typeof w=="object"&&w!==null)P=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else{let O=!1,Y=Object.getOwnPropertyNames(g);for(let Q of u)if(Y.indexOf(Q)!==-1){let S=g[Q];(S===null||S instanceof je)&&(O=!0,F=!1,m[Q]=S)}if(O){if(typeof w=="object"&&w!==null)P=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else P=g}}else if(typeof g<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let O of s)if(typeof f[O]>"u")throw new Error(`input '${O}' is missing in 'feeds'.`);if(F)for(let O of u)m[O]=null;return[m,P]}convertHandlerReturnTypeToMapOfTensors(s){let u={};for(let f in s)if(Object.hasOwnProperty.call(s,f)){let g=s[f];g instanceof je?u[f]=g:u[f]=new je(g.type,g.data,g.dims)}return u}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(s,u,f){let[g,w]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,s,u,f),m=await this.handler.runTrainStep(s,g,w);return this.convertHandlerReturnTypeToMapOfTensors(m)}async runOptimizerStep(s){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(s||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(s,u,f){if(this.hasEvalModel){let[g,w]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,s,u,f),m=await this.handler.runEvalStep(s,g,w);return this.convertHandlerReturnTypeToMapOfTensors(m)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(s=!0){return this.handler.getParametersSize(s)}async loadParametersBuffer(s,u=!0){let f=await this.getParametersSize(u);if(s.length!==4*f)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(s,u)}async getContiguousParameters(s=!0){return this.handler.getContiguousParameters(s)}async release(){return this.handler.dispose()}}}),Dt,Tt=c(()=>{Ze(),Dt=$e}),Nt={};p(Nt,{InferenceSession:()=>ue,TRACE:()=>rt,TRACE_FUNC_BEGIN:()=>xt,TRACE_FUNC_END:()=>z,Tensor:()=>je,TrainingSession:()=>Dt,env:()=>j,registerBackend:()=>I});var jt=c(()=>{k(),ae(),Ee(),Ie(),q(),re(),Fe(),V(),me(),Tt()}),ht=c(()=>{}),_e={};p(_e,{default:()=>Je});var Be,st,Je,_t=c(()=>{var r;y1(),Nr(),zn(),Be="ort-wasm-proxy-worker",st=((r=globalThis.self)==null?void 0:r.name)===Be,st&&(self.onmessage=s=>{let{type:u,in:f}=s.data;try{switch(u){case"init-wasm":xs(f.wasm).then(()=>{f_(f).then(()=>{postMessage({type:u})},g=>{postMessage({type:u,err:g})})},g=>{postMessage({type:u,err:g})});break;case"init-ep":{let{epName:g,env:w}=f;h_(w,g).then(()=>{postMessage({type:u})},m=>{postMessage({type:u,err:m})});break}case"copy-from":{let{buffer:g}=f,w=Yp(g);postMessage({type:u,out:w});break}case"create":{let{model:g,options:w}=f;p_(g,w).then(m=>{postMessage({type:u,out:m})},m=>{postMessage({type:u,err:m})});break}case"release":m_(f),postMessage({type:u});break;case"run":{let{sessionId:g,inputIndices:w,inputs:m,outputIndices:P,options:F}=f;__(g,w,m,P,new Array(P.length).fill(null),F).then(O=>{O.some(Y=>Y[3]!=="cpu")?postMessage({type:u,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:u,out:O},v_([...m,...O]))},O=>{postMessage({type:u,err:O})});break}case"end-profiling":y_(f),postMessage({type:u});break;default:}}catch(g){postMessage({type:u,err:g})}}),Je=st?null:s=>new Worker(s??Mt,{type:"module",name:Be})}),$t={};p($t,{default:()=>nn});var Wt,ot,nn,Gt=c(()=>{var r;ot=(Wt=import.meta.url,async function(s={}){function u(){return fr.buffer!=sr.buffer&&Hi(),sr}function f(){return fr.buffer!=sr.buffer&&Hi(),vr}function g(){return fr.buffer!=sr.buffer&&Hi(),Ft}function w(){return fr.buffer!=sr.buffer&&Hi(),an}function m(){return fr.buffer!=sr.buffer&&Hi(),Nn}function P(){return fr.buffer!=sr.buffer&&Hi(),Pr}function F(){return fr.buffer!=sr.buffer&&Hi(),ai}function O(){return fr.buffer!=sr.buffer&&Hi(),em}var Y,Q,S=Object.assign({},s),ie=new Promise((b,L)=>{Y=b,Q=L}),ce=typeof window=="object",pe=typeof importScripts=="function",ke=pe&&self.name=="em-pthread";S.mountExternalData=(b,L)=>{b.startsWith("./")&&(b=b.substring(2)),(S.Fb||(S.Fb=new Map)).set(b,L)},S.unmountExternalData=()=>{delete S.Fb};var Pe=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let be=()=>{let b=(J,se,we)=>(...Ke)=>{let Ot=Zo,Ut=se==null?void 0:se();Ke=J(...Ke);let cn=se==null?void 0:se();return Ut!==cn&&(J=cn,we(Ut),se=we=null),Zo!=Ot?new Promise((_n,In)=>{R_={resolve:_n,reject:In}}):Ke},L=J=>async(...se)=>{var we;try{if(S.Eb)throw Error("Session already started");let Ke=S.Eb={bc:se[0],errors:[]},Ot=await J(...se);if(S.Eb!==Ke)throw Error("Session mismatch");(we=S.Mb)==null||we.flush();let Ut=Ke.errors;if(0_n),0S._OrtCreateSession,J=>S._OrtCreateSession=J),S._OrtRun=L(b(S._OrtRun,()=>S._OrtRun,J=>S._OrtRun=J)),S._OrtRunWithBinding=L(b(S._OrtRunWithBinding,()=>S._OrtRunWithBinding,J=>S._OrtRunWithBinding=J)),S._OrtBindInput=b(S._OrtBindInput,()=>S._OrtBindInput,J=>S._OrtBindInput=J),be=void 0};S.jsepInit=(b,L)=>{if(be==null||be(),b==="webgpu"){[S.Mb,S.Tb,S.Xb,S.Nb,S.Wb,S.jb,S.Yb,S.$b,S.Ub,S.Vb,S.Zb]=L;let J=S.Mb;S.jsepRegisterBuffer=(se,we,Ke,Ot)=>J.registerBuffer(se,we,Ke,Ot),S.jsepGetBuffer=se=>J.getBuffer(se),S.jsepCreateDownloader=(se,we,Ke)=>J.createDownloader(se,we,Ke),S.jsepOnReleaseSession=se=>{J.onReleaseSession(se)},S.jsepOnRunStart=se=>J.onRunStart(se)}};var We,ze,Ge=Object.assign({},S),zt="./this.program",It=(b,L)=>{throw L},Ht="";(ce||pe)&&(pe?Ht=self.location.href:typeof document<"u"&&document.currentScript&&(Ht=document.currentScript.src),Wt&&(Ht=Wt),Ht=Ht.startsWith("blob:")?"":Ht.substr(0,Ht.replace(/[?#].*/,"").lastIndexOf("/")+1),pe&&(ze=b=>{var L=new XMLHttpRequest;return L.open("GET",b,!1),L.responseType="arraybuffer",L.send(null),new Uint8Array(L.response)}),We=(b,L,J)=>{var se=new XMLHttpRequest;se.open("GET",b,!0),se.responseType="arraybuffer",se.onload=()=>{se.status==200||se.status==0&&se.response?L(se.response):J()},se.onerror=J,se.send(null)});var pn,wn=console.log.bind(console),Xn=console.error.bind(console),ar=wn,Dn=Xn;if(Object.assign(S,Ge),Ge=null,ke){let b=function(L){try{var J=L.data,se=J.cmd;if(se==="load"){let we=[];self.onmessage=Ke=>we.push(Ke),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let Ke of we)b(Ke);self.onmessage=b};for(let Ke of J.handlers)S[Ke]&&!S[Ke].proxy||(S[Ke]=(...Ot)=>{postMessage({Lb:"callHandler",kc:Ke,args:Ot})},Ke=="print"&&(ar=S[Ke]),Ke=="printErr"&&(Dn=S[Ke]));fr=J.wasmMemory,Hi(),Cr(J.wasmModule)}else if(se==="run"){j_(J.pthread_ptr,0,0,1,0,0),O_(J.pthread_ptr),wC(),U1(),Vr||(Nb(),Vr=!0);try{bC(J.start_routine,J.arg)}catch(we){if(we!="unwind")throw we}}else se==="cancel"?Ac()&&fm(-1):J.target!=="setimmediate"&&(se==="checkMailbox"?Vr&&rm():se&&(Dn(`worker: received unknown command ${se}`),Dn(J)))}catch(we){throw jb(),we}};var Cr,Vr=!1;Dn=function(...L){L=L.join(" "),console.error(L)},self.alert=function(...L){postMessage({Lb:"alert",text:L.join(" "),mc:Ac()})},S.instantiateWasm=(L,J)=>new Promise(se=>{Cr=we=>{we=new WebAssembly.Instance(we,L1()),J(we),se()}}),self.onunhandledrejection=L=>{throw L.reason||L},self.onmessage=b}S.wasmBinary&&(pn=S.wasmBinary);var fr,Or,Fn,sr,vr,Ft,an,Nn,Pr,ai,ki,ll,em,Ns=!1;function Hi(){var b=fr.buffer;S.HEAP8=sr=new Int8Array(b),S.HEAP16=Ft=new Int16Array(b),S.HEAPU8=vr=new Uint8Array(b),S.HEAPU16=an=new Uint16Array(b),S.HEAP32=Nn=new Int32Array(b),S.HEAPU32=Pr=new Uint32Array(b),S.HEAPF32=ai=new Float32Array(b),S.HEAPF64=em=new Float64Array(b),S.HEAP64=ki=new BigInt64Array(b),S.HEAPU64=ll=new BigUint64Array(b)}if(!ke){if(!((fr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof Pe))throw Dn("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),Error("bad memory");Hi()}var ph=[],Ki=[],_s=[],eo=0,ul=null;function tm(){if(--eo==0&&ul){var b=ul;ul=null,b()}}function Ec(b){throw Dn(b="Aborted("+b+")"),Ns=!0,Fn=1,b=new WebAssembly.RuntimeError(b+". Build with -sASSERTIONS for more info."),Q(b),b}var x_,O1=b=>b.startsWith("data:application/octet-stream;base64,"),D1=b=>b.startsWith("file://");function z1(b){if(b==x_&&pn)return new Uint8Array(pn);if(ze)return ze(b);throw"both async and sync fetching of the wasm failed"}function R1(b,L,J){return function(se){if(!pn&&(ce||pe)){if(typeof fetch=="function"&&!D1(se))return fetch(se,{credentials:"same-origin"}).then(we=>{if(!we.ok)throw`failed to load wasm binary file at '${se}'`;return we.arrayBuffer()}).catch(()=>z1(se));if(We)return new Promise((we,Ke)=>{We(se,Ot=>we(new Uint8Array(Ot)),Ke)})}return Promise.resolve().then(()=>z1(se))}(b).then(se=>WebAssembly.instantiate(se,L)).then(J,se=>{Dn(`failed to asynchronously prepare wasm: ${se}`),Ec(se)})}function L1(){return{a:{M:vC,za:yC,b:TC,$:H1,z:Q1,pa:Y1,X:J1,Z:eb,qa:tb,na:nb,ga:rb,ma:ib,J:sb,Y:ob,V:ab,oa:lb,W:ub,va:MC,D:kC,P:SC,O:CC,C:AC,s:$C,p:IC,E:FC,y:NC,Q:jC,ta:VC,ja:UC,T:WC,aa:GC,F:qC,ia:O_,sa:HC,u:KC,B:YC,o:ZC,m:eP,c:I_,n:tP,k:iP,Aa:sP,r:oP,g:aP,v:lP,l:uP,f:cP,i:dP,j:fP,h:hP,e:pP,da:mP,ea:gP,fa:_P,ba:Tb,ca:Mb,S:yP,d:vP,N:wP,G:bP,K:xP,w:TP,ra:MP,U:kP,t:Sb,x:SP,L:EP,R:CP,ya:PP,xa:AP,ka:Pb,la:Ab,_:E_,A:$b,I:Ib,ha:Fb,H:Ob,a:fr,wa:S_,ua:Rb,q:FP}}}var T_={858916:(b,L,J,se)=>{if(S===void 0||!S.Fb)return 1;if((b=Bi(b>>>0)).startsWith("./")&&(b=b.substring(2)),!(b=S.Fb.get(b)))return 2;if(se>>>=0,(L>>>=0)+(J>>>=0)>b.byteLength)return 3;try{return f().set(b.subarray(L,L+J),se>>>0),0}catch{return 4}},859417:()=>{S.Ub()},859448:()=>{S.Vb()},859477:()=>{S.Zb()},859502:b=>S.Tb(b),859535:b=>S.Xb(b),859567:(b,L,J)=>{S.Nb(b,L,J,!0)},859606:(b,L,J)=>{S.Nb(b,L,J)},859639:()=>typeof wasmOffsetConverter<"u",859696:b=>{S.jb("Abs",b,void 0)},859747:b=>{S.jb("Neg",b,void 0)},859798:b=>{S.jb("Floor",b,void 0)},859851:b=>{S.jb("Ceil",b,void 0)},859903:b=>{S.jb("Reciprocal",b,void 0)},859961:b=>{S.jb("Sqrt",b,void 0)},860013:b=>{S.jb("Exp",b,void 0)},860064:b=>{S.jb("Erf",b,void 0)},860115:b=>{S.jb("Sigmoid",b,void 0)},860170:(b,L,J)=>{S.jb("HardSigmoid",b,{alpha:L,beta:J})},860249:b=>{S.jb("Log",b,void 0)},860300:b=>{S.jb("Sin",b,void 0)},860351:b=>{S.jb("Cos",b,void 0)},860402:b=>{S.jb("Tan",b,void 0)},860453:b=>{S.jb("Asin",b,void 0)},860505:b=>{S.jb("Acos",b,void 0)},860557:b=>{S.jb("Atan",b,void 0)},860609:b=>{S.jb("Sinh",b,void 0)},860661:b=>{S.jb("Cosh",b,void 0)},860713:b=>{S.jb("Asinh",b,void 0)},860766:b=>{S.jb("Acosh",b,void 0)},860819:b=>{S.jb("Atanh",b,void 0)},860872:b=>{S.jb("Tanh",b,void 0)},860924:b=>{S.jb("Not",b,void 0)},860975:(b,L,J)=>{S.jb("Clip",b,{min:L,max:J})},861044:b=>{S.jb("Clip",b,void 0)},861096:(b,L)=>{S.jb("Elu",b,{alpha:L})},861154:b=>{S.jb("Gelu",b,void 0)},861206:b=>{S.jb("Relu",b,void 0)},861258:(b,L)=>{S.jb("LeakyRelu",b,{alpha:L})},861322:(b,L)=>{S.jb("ThresholdedRelu",b,{alpha:L})},861392:(b,L)=>{S.jb("Cast",b,{to:L})},861450:b=>{S.jb("Add",b,void 0)},861501:b=>{S.jb("Sub",b,void 0)},861552:b=>{S.jb("Mul",b,void 0)},861603:b=>{S.jb("Div",b,void 0)},861654:b=>{S.jb("Pow",b,void 0)},861705:b=>{S.jb("Equal",b,void 0)},861758:b=>{S.jb("Greater",b,void 0)},861813:b=>{S.jb("GreaterOrEqual",b,void 0)},861875:b=>{S.jb("Less",b,void 0)},861927:b=>{S.jb("LessOrEqual",b,void 0)},861986:(b,L,J,se,we)=>{S.jb("ReduceMean",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},862145:(b,L,J,se,we)=>{S.jb("ReduceMax",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},862303:(b,L,J,se,we)=>{S.jb("ReduceMin",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},862461:(b,L,J,se,we)=>{S.jb("ReduceProd",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},862620:(b,L,J,se,we)=>{S.jb("ReduceSum",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},862778:(b,L,J,se,we)=>{S.jb("ReduceL1",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},862935:(b,L,J,se,we)=>{S.jb("ReduceL2",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},863092:(b,L,J,se,we)=>{S.jb("ReduceLogSum",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},863253:(b,L,J,se,we)=>{S.jb("ReduceSumSquare",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},863417:(b,L,J,se,we)=>{S.jb("ReduceLogSumExp",b,{keepDims:!!L,noopWithEmptyAxes:!!J,axes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},863581:b=>{S.jb("Where",b,void 0)},863634:(b,L,J)=>{S.jb("Transpose",b,{perm:L?Array.from(m().subarray(L>>>0,J>>>0)):[]})},863742:(b,L,J,se)=>{S.jb("DepthToSpace",b,{blocksize:L,mode:Bi(J),format:se?"NHWC":"NCHW"})},863875:(b,L,J,se)=>{S.jb("DepthToSpace",b,{blocksize:L,mode:Bi(J),format:se?"NHWC":"NCHW"})},864008:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct,hr)=>{S.jb("ConvTranspose",b,{format:cn?"NHWC":"NCHW",autoPad:L,dilations:[J],group:se,kernelShape:[we],pads:[Ke,Ot],strides:[Ut],wIsConst:()=>!!u()[_n>>>0],outputPadding:In?Array.from(m().subarray(In>>>0,pr>>>0)):[],outputShape:Sr?Array.from(m().subarray(Sr>>>0,Ct>>>0)):[],activation:Bi(hr)})},864409:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct)=>{S.jb("ConvTranspose",b,{format:Ut?"NHWC":"NCHW",autoPad:L,dilations:Array.from(m().subarray(J>>>0,2+(J>>>0)>>>0)),group:se,kernelShape:Array.from(m().subarray(we>>>0,2+(we>>>0)>>>0)),pads:Array.from(m().subarray(Ke>>>0,4+(Ke>>>0)>>>0)),strides:Array.from(m().subarray(Ot>>>0,2+(Ot>>>0)>>>0)),wIsConst:()=>!!u()[cn>>>0],outputPadding:_n?Array.from(m().subarray(_n>>>0,In>>>0)):[],outputShape:pr?Array.from(m().subarray(pr>>>0,Sr>>>0)):[],activation:Bi(Ct)})},864974:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct,hr)=>{S.jb("ConvTranspose",b,{format:cn?"NHWC":"NCHW",autoPad:L,dilations:[J],group:se,kernelShape:[we],pads:[Ke,Ot],strides:[Ut],wIsConst:()=>!!u()[_n>>>0],outputPadding:In?Array.from(m().subarray(In>>>0,pr>>>0)):[],outputShape:Sr?Array.from(m().subarray(Sr>>>0,Ct>>>0)):[],activation:Bi(hr)})},865375:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct)=>{S.jb("ConvTranspose",b,{format:Ut?"NHWC":"NCHW",autoPad:L,dilations:Array.from(m().subarray(J>>>0,2+(J>>>0)>>>0)),group:se,kernelShape:Array.from(m().subarray(we>>>0,2+(we>>>0)>>>0)),pads:Array.from(m().subarray(Ke>>>0,4+(Ke>>>0)>>>0)),strides:Array.from(m().subarray(Ot>>>0,2+(Ot>>>0)>>>0)),wIsConst:()=>!!u()[cn>>>0],outputPadding:_n?Array.from(m().subarray(_n>>>0,In>>>0)):[],outputShape:pr?Array.from(m().subarray(pr>>>0,Sr>>>0)):[],activation:Bi(Ct)})},865940:(b,L)=>{S.jb("GlobalAveragePool",b,{format:L?"NHWC":"NCHW"})},866031:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct)=>{S.jb("AveragePool",b,{format:Ct?"NHWC":"NCHW",auto_pad:L,ceil_mode:J,count_include_pad:se,storage_order:we,dilations:Ke?Array.from(m().subarray(Ke>>>0,Ot>>>0)):[],kernel_shape:Ut?Array.from(m().subarray(Ut>>>0,cn>>>0)):[],pads:_n?Array.from(m().subarray(_n>>>0,In>>>0)):[],strides:pr?Array.from(m().subarray(pr>>>0,Sr>>>0)):[]})},866446:(b,L)=>{S.jb("GlobalAveragePool",b,{format:L?"NHWC":"NCHW"})},866537:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct)=>{S.jb("AveragePool",b,{format:Ct?"NHWC":"NCHW",auto_pad:L,ceil_mode:J,count_include_pad:se,storage_order:we,dilations:Ke?Array.from(m().subarray(Ke>>>0,Ot>>>0)):[],kernel_shape:Ut?Array.from(m().subarray(Ut>>>0,cn>>>0)):[],pads:_n?Array.from(m().subarray(_n>>>0,In>>>0)):[],strides:pr?Array.from(m().subarray(pr>>>0,Sr>>>0)):[]})},866952:(b,L)=>{S.jb("GlobalMaxPool",b,{format:L?"NHWC":"NCHW"})},867039:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct)=>{S.jb("MaxPool",b,{format:Ct?"NHWC":"NCHW",auto_pad:L,ceil_mode:J,count_include_pad:se,storage_order:we,dilations:Ke?Array.from(m().subarray(Ke>>>0,Ot>>>0)):[],kernel_shape:Ut?Array.from(m().subarray(Ut>>>0,cn>>>0)):[],pads:_n?Array.from(m().subarray(_n>>>0,In>>>0)):[],strides:pr?Array.from(m().subarray(pr>>>0,Sr>>>0)):[]})},867450:(b,L)=>{S.jb("GlobalMaxPool",b,{format:L?"NHWC":"NCHW"})},867537:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct)=>{S.jb("MaxPool",b,{format:Ct?"NHWC":"NCHW",auto_pad:L,ceil_mode:J,count_include_pad:se,storage_order:we,dilations:Ke?Array.from(m().subarray(Ke>>>0,Ot>>>0)):[],kernel_shape:Ut?Array.from(m().subarray(Ut>>>0,cn>>>0)):[],pads:_n?Array.from(m().subarray(_n>>>0,In>>>0)):[],strides:pr?Array.from(m().subarray(pr>>>0,Sr>>>0)):[]})},867948:(b,L,J,se,we)=>{S.jb("Gemm",b,{alpha:L,beta:J,transA:se,transB:we})},868052:b=>{S.jb("MatMul",b,void 0)},868106:(b,L,J,se)=>{S.jb("ArgMax",b,{keepDims:!!L,selectLastIndex:!!J,axis:se})},868214:(b,L,J,se)=>{S.jb("ArgMin",b,{keepDims:!!L,selectLastIndex:!!J,axis:se})},868322:(b,L)=>{S.jb("Softmax",b,{axis:L})},868385:(b,L)=>{S.jb("Concat",b,{axis:L})},868445:(b,L,J,se,we)=>{S.jb("Split",b,{axis:L,numOutputs:J,splitSizes:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},868585:b=>{S.jb("Expand",b,void 0)},868639:(b,L)=>{S.jb("Gather",b,{axis:Number(L)})},868710:(b,L)=>{S.jb("GatherElements",b,{axis:Number(L)})},868789:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In)=>{S.jb("Resize",b,{antialias:L,axes:J?Array.from(m().subarray(J>>>0,se>>>0)):[],coordinateTransformMode:Bi(we),cubicCoeffA:Ke,excludeOutside:Ot,extrapolationValue:Ut,keepAspectRatioPolicy:Bi(cn),mode:Bi(_n),nearestMode:Bi(In)})},869135:(b,L,J,se,we,Ke,Ot)=>{S.jb("Slice",b,{starts:L?Array.from(m().subarray(L>>>0,J>>>0)):[],ends:se?Array.from(m().subarray(se>>>0,we>>>0)):[],axes:Ke?Array.from(m().subarray(Ke>>>0,Ot>>>0)):[]})},869351:b=>{S.jb("Tile",b,void 0)},869403:(b,L,J)=>{S.jb("InstanceNormalization",b,{epsilon:L,format:J?"NHWC":"NCHW"})},869517:(b,L,J)=>{S.jb("InstanceNormalization",b,{epsilon:L,format:J?"NHWC":"NCHW"})},869631:b=>{S.jb("Range",b,void 0)},869684:(b,L)=>{S.jb("Einsum",b,{equation:Bi(L)})},869765:(b,L,J,se,we)=>{S.jb("Pad",b,{mode:L,value:J,pads:se?Array.from(m().subarray(se>>>0,we>>>0)):[]})},869892:(b,L,J,se,we,Ke)=>{S.jb("BatchNormalization",b,{epsilon:L,momentum:J,spatial:!!we,trainingMode:!!se,format:Ke?"NHWC":"NCHW"})},870061:(b,L,J,se,we,Ke)=>{S.jb("BatchNormalization",b,{epsilon:L,momentum:J,spatial:!!we,trainingMode:!!se,format:Ke?"NHWC":"NCHW"})},870230:(b,L,J)=>{S.jb("CumSum",b,{exclusive:Number(L),reverse:Number(J)})},870327:(b,L,J)=>{S.jb("DequantizeLinear",b,{axis:L,blockSize:J})},870417:(b,L,J,se,we,Ke,Ot,Ut,cn)=>{S.jb("Attention",b,{numHeads:L,isUnidirectional:J,maskFilterValue:se,scale:we,doRotary:Ke,qkvHiddenSizes:Ot?Array.from(m().subarray(Number(Ut)>>>0,Number(Ut)+Ot>>>0)):[],pastPresentShareBuffer:!!cn})},870689:b=>{S.jb("BiasAdd",b,void 0)},870744:b=>{S.jb("BiasSplitGelu",b,void 0)},870805:b=>{S.jb("FastGelu",b,void 0)},870861:(b,L,J,se,we,Ke,Ot,Ut,cn,_n,In,pr,Sr,Ct,hr,Yr)=>{S.jb("Conv",b,{format:pr?"NHWC":"NCHW",auto_pad:L,dilations:J?Array.from(m().subarray(J>>>0,se>>>0)):[],group:we,kernel_shape:Ke?Array.from(m().subarray(Ke>>>0,Ot>>>0)):[],pads:Ut?Array.from(m().subarray(Ut>>>0,cn>>>0)):[],strides:_n?Array.from(m().subarray(_n>>>0,In>>>0)):[],w_is_const:()=>!!u()[Sr>>>0],activation:Bi(Ct),activation_params:hr?Array.from(F().subarray(hr>>>0,Yr>>>0)):[]})},871357:b=>{S.jb("Gelu",b,void 0)},871409:(b,L,J,se)=>{S.jb("GroupQueryAttention",b,{numHeads:L,kvNumHeads:J,scale:se})},871522:(b,L,J,se)=>{S.jb("LayerNormalization",b,{axis:L,epsilon:J,simplified:!!se})},871633:(b,L,J,se)=>{S.jb("LayerNormalization",b,{axis:L,epsilon:J,simplified:!!se})},871744:(b,L,J,se,we,Ke)=>{S.jb("MatMulNBits",b,{k:L,n:J,accuracyLevel:se,bits:we,blockSize:Ke})},871871:(b,L,J,se,we,Ke)=>{S.jb("MultiHeadAttention",b,{numHeads:L,isUnidirectional:J,maskFilterValue:se,scale:we,doRotary:Ke})},872030:(b,L)=>{S.jb("QuickGelu",b,{alpha:L})},872094:(b,L,J,se,we)=>{S.jb("RotaryEmbedding",b,{interleaved:!!L,numHeads:J,rotaryEmbeddingDim:se,scale:we})},872233:(b,L,J)=>{S.jb("SkipLayerNormalization",b,{epsilon:L,simplified:!!J})},872335:(b,L,J)=>{S.jb("SkipLayerNormalization",b,{epsilon:L,simplified:!!J})},872437:(b,L,J,se)=>{S.jb("GatherBlockQuantized",b,{gatherAxis:L,quantizeAxis:J,blockSize:se})},872558:b=>{S.Yb(b)},872592:(b,L)=>S.$b(b,L,S.Eb.bc,S.Eb.errors)};function yC(b,L,J){return yb(async()=>{await S.Wb(b,L,J)})}function vC(){return typeof wasmOffsetConverter<"u"}function M_(b){this.name="ExitStatus",this.message=`Program terminated with exit(${b})`,this.status=b}var k_=b=>{b.terminate(),b.onmessage=()=>{}},B1=b=>{cl.length==0&&(G1(),W1(cl[0]));var L=cl.pop();if(!L)return 6;su.push(L),Qo[b.Ab]=L,L.Ab=b.Ab;var J={cmd:"run",start_routine:b.cc,arg:b.Pb,pthread_ptr:b.Ab};return L.postMessage(J,b.ic),0},iu=0,Kr=(b,L,...J)=>{for(var se=2*J.length,we=W_(),Ke=U_(8*se),Ot=Ke>>>3,Ut=0;Ut>>0]=cn)}return b=Vb(b,0,se,Ke,L),hm(we),b};function S_(b){if(ke)return Kr(0,1,b);if(Fn=b,!(0{if(Fn=b,ke)throw N1(b),"unwind";S_(b)},cl=[],su=[],j1=[],Qo={},V1=b=>{var L=b.Ab;delete Qo[L],cl.push(b),su.splice(su.indexOf(b),1),b.Ab=0,V_(L)};function U1(){j1.forEach(b=>b())}var W1=b=>new Promise(L=>{b.onmessage=we=>{var Ke=(we=we.data).cmd;if(we.targetThread&&we.targetThread!=Ac()){var Ot=Qo[we.targetThread];Ot?Ot.postMessage(we,we.transferList):Dn(`Internal error! Worker sent a message "${Ke}" to target pthread ${we.targetThread}, but that thread no longer exists!`)}else Ke==="checkMailbox"?rm():Ke==="spawnThread"?B1(we):Ke==="cleanupThread"?V1(Qo[we.thread]):Ke==="killThread"?(we=we.thread,Ke=Qo[we],delete Qo[we],k_(Ke),V_(we),su.splice(su.indexOf(Ke),1),Ke.Ab=0):Ke==="cancelThread"?Qo[we.thread].postMessage({cmd:"cancel"}):Ke==="loaded"?(b.loaded=!0,L(b)):Ke==="alert"?alert(`Thread ${we.threadId}: ${we.text}`):we.target==="setimmediate"?b.postMessage(we):Ke==="callHandler"?S[we.handler](...we.args):Ke&&Dn(`worker sent an unknown command ${Ke}`)},b.onerror=we=>{throw Dn(`worker sent an error! ${we.filename}:${we.lineno}: ${we.message}`),we};var J,se=[];for(J of[])S.hasOwnProperty(J)&&se.push(J);b.postMessage({cmd:"load",handlers:se,wasmMemory:fr,wasmModule:Or})});function G1(){var b=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});cl.push(b)}var nm=b=>{for(;0{var b=Ac(),L=P()[b+52>>>2>>>0];b=P()[b+56>>>2>>>0],Wb(L,L-b),hm(L)},bC=(b,L)=>{iu=0,b=Gb(b,L),0>>=0);throw L>>>=0,J>>>=0,P()[se.Ib+16>>>2>>>0]=0,P()[se.Ib+4>>>2>>>0]=L,P()[se.Ib+8>>>2>>>0]=J,b}function q1(b,L,J,se){return ke?Kr(2,1,b,L,J,se):H1(b,L,J,se)}function H1(b,L,J,se){if(b>>>=0,L>>>=0,J>>>=0,se>>>=0,Pe===void 0)return Dn("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var we=[];return ke&&we.length===0?q1(b,L,J,se):(b={cc:J,Ab:b,Pb:se,ic:we},ke?(b.Lb="spawnThread",postMessage(b,we),0):B1(b))}var K1=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,X1=(b,L,J)=>{var se=(L>>>=0)+J;for(J=L;b[J]&&!(J>=se);)++J;if(16(we=(240&we)==224?(15&we)<<12|Ke<<6|Ot:(7&we)<<18|Ke<<12|Ot<<6|63&b[L++])?se+=String.fromCharCode(we):(we-=65536,se+=String.fromCharCode(55296|we>>10,56320|1023&we))}}else se+=String.fromCharCode(we)}return se},Bi=(b,L)=>(b>>>=0)?X1(f(),b,L):"";function Q1(b,L,J){return ke?Kr(3,1,b,L,J):0}function Y1(b,L){if(ke)return Kr(4,1,b,L)}var C_=b=>{for(var L=0,J=0;J=se?L++:2047>=se?L+=2:55296<=se&&57343>=se?(L+=4,++J):L+=3}return L},Z1=(b,L,J,se)=>{if(!(0>>=0;se=J+se-1;for(var Ke=0;Ke=Ot&&(Ot=65536+((1023&Ot)<<10)|1023&b.charCodeAt(++Ke)),127>=Ot){if(J>=se)break;L[J++>>>0]=Ot}else{if(2047>=Ot){if(J+1>=se)break;L[J++>>>0]=192|Ot>>6}else{if(65535>=Ot){if(J+2>=se)break;L[J++>>>0]=224|Ot>>12}else{if(J+3>=se)break;L[J++>>>0]=240|Ot>>18,L[J++>>>0]=128|Ot>>12&63}L[J++>>>0]=128|Ot>>6&63}L[J++>>>0]=128|63&Ot}}return L[J>>>0]=0,J-we},Cc=(b,L,J)=>Z1(b,f(),L,J);function J1(b,L){if(ke)return Kr(5,1,b,L)}function eb(b,L,J){if(ke)return Kr(6,1,b,L,J)}function tb(b,L,J){return ke?Kr(7,1,b,L,J):0}function nb(b,L){if(ke)return Kr(8,1,b,L)}function rb(b,L,J){if(ke)return Kr(9,1,b,L,J)}function ib(b,L,J,se){if(ke)return Kr(10,1,b,L,J,se)}function sb(b,L,J,se){if(ke)return Kr(11,1,b,L,J,se)}function ob(b,L,J,se){if(ke)return Kr(12,1,b,L,J,se)}function ab(b){if(ke)return Kr(13,1,b)}function lb(b,L){if(ke)return Kr(14,1,b,L)}function ub(b,L,J){if(ke)return Kr(15,1,b,L,J)}var cb,dl,MC=()=>{Ec("")},Yo=b=>{for(var L="";f()[b>>>0];)L+=cb[f()[b++>>>0]];return L},P_={},A_={};function ka(b,L,J={}){if(!("argPackAdvance"in L))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(se,we,Ke={}){var Ot=we.name;if(!se)throw new dl(`type "${Ot}" must have a positive integer typeid pointer`);if(A_.hasOwnProperty(se)){if(Ke.Rb)return;throw new dl(`Cannot register type '${Ot}' twice`)}A_[se]=we,P_.hasOwnProperty(se)&&(we=P_[se],delete P_[se],we.forEach(Ut=>Ut()))}(b,L,J)}var db=(b,L,J)=>{switch(L){case 1:return J?se=>u()[se>>>0]:se=>f()[se>>>0];case 2:return J?se=>g()[se>>>1>>>0]:se=>w()[se>>>1>>>0];case 4:return J?se=>m()[se>>>2>>>0]:se=>P()[se>>>2>>>0];case 8:return J?se=>ki[se>>>3]:se=>ll[se>>>3];default:throw new TypeError(`invalid integer width (${L}): ${b}`)}};function kC(b,L,J){J>>>=0,ka(b>>>=0,{name:L=Yo(L>>>0),fromWireType:se=>se,toWireType:function(se,we){if(typeof we!="bigint"&&typeof we!="number")throw we=we===null?"null":(se=typeof we)=="object"||se==="array"||se==="function"?we.toString():""+we,new TypeError(`Cannot convert "${we}" to ${this.name}`);return typeof we=="number"&&(we=BigInt(we)),we},argPackAdvance:fl,readValueFromPointer:db(L,J,L.indexOf("u")==-1),Db:null})}var fl=8;function SC(b,L,J,se){ka(b>>>=0,{name:L=Yo(L>>>0),fromWireType:function(we){return!!we},toWireType:function(we,Ke){return Ke?J:se},argPackAdvance:fl,readValueFromPointer:function(we){return this.fromWireType(f()[we>>>0])},Db:null})}var $_=[],Sa=[];function I_(b){9<(b>>>=0)&&--Sa[b+1]==0&&(Sa[b]=void 0,$_.push(b))}var to=b=>{if(!b)throw new dl("Cannot use deleted val. handle = "+b);return Sa[b]},no=b=>{switch(b){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let L=$_.pop()||Sa.length;return Sa[L]=b,Sa[L+1]=1,L}};function F_(b){return this.fromWireType(P()[b>>>2>>>0])}var EC={name:"emscripten::val",fromWireType:b=>{var L=to(b);return I_(b),L},toWireType:(b,L)=>no(L),argPackAdvance:fl,readValueFromPointer:F_,Db:null};function CC(b){return ka(b>>>0,EC)}var PC=(b,L)=>{switch(L){case 4:return function(J){return this.fromWireType(F()[J>>>2>>>0])};case 8:return function(J){return this.fromWireType(O()[J>>>3>>>0])};default:throw new TypeError(`invalid float width (${L}): ${b}`)}};function AC(b,L,J){J>>>=0,ka(b>>>=0,{name:L=Yo(L>>>0),fromWireType:se=>se,toWireType:(se,we)=>we,argPackAdvance:fl,readValueFromPointer:PC(L,J),Db:null})}function $C(b,L,J,se,we){if(b>>>=0,J>>>=0,L=Yo(L>>>0),we===-1&&(we=4294967295),we=Ut=>Ut,se===0){var Ke=32-8*J;we=Ut=>Ut<>>Ke}var Ot=L.includes("unsigned")?function(Ut,cn){return cn>>>0}:function(Ut,cn){return cn};ka(b,{name:L,fromWireType:we,toWireType:Ot,argPackAdvance:fl,readValueFromPointer:db(L,J,se!==0),Db:null})}function IC(b,L,J){function se(Ke){var Ot=P()[Ke>>>2>>>0];return Ke=P()[Ke+4>>>2>>>0],new we(u().buffer,Ke,Ot)}var we=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][L];ka(b>>>=0,{name:J=Yo(J>>>0),fromWireType:se,argPackAdvance:fl,readValueFromPointer:se},{Rb:!0})}function FC(b,L){b>>>=0;var J=(L=Yo(L>>>0))==="std::string";ka(b,{name:L,fromWireType:function(se){var we=P()[se>>>2>>>0],Ke=se+4;if(J)for(var Ot=Ke,Ut=0;Ut<=we;++Ut){var cn=Ke+Ut;if(Ut==we||f()[cn>>>0]==0){if(Ot=Bi(Ot,cn-Ot),_n===void 0)var _n=Ot;else _n+="\0",_n+=Ot;Ot=cn+1}}else{for(_n=Array(we),Ut=0;Ut>>0]);_n=_n.join("")}return Jo(se),_n},toWireType:function(se,we){we instanceof ArrayBuffer&&(we=new Uint8Array(we));var Ke=typeof we=="string";if(!(Ke||we instanceof Uint8Array||we instanceof Uint8ClampedArray||we instanceof Int8Array))throw new dl("Cannot pass non-string to std::string");var Ot=J&&Ke?C_(we):we.length,Ut=dm(4+Ot+1),cn=Ut+4;if(P()[Ut>>>2>>>0]=Ot,J&&Ke)Cc(we,cn,Ot+1);else if(Ke)for(Ke=0;Ke>>0]=_n}else for(Ke=0;Ke>>0]=we[Ke];return se!==null&&se.push(Jo,Ut),Ut},argPackAdvance:fl,readValueFromPointer:F_,Db(se){Jo(se)}})}var fb=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,OC=(b,L)=>{for(var J=b>>1,se=J+L/2;!(J>=se)&&w()[J>>>0];)++J;if(32<(J<<=1)-b&&fb)return fb.decode(f().slice(b,J));for(J="",se=0;!(se>=L/2);++se){var we=g()[b+2*se>>>1>>>0];if(we==0)break;J+=String.fromCharCode(we)}return J},DC=(b,L,J)=>{if(J??(J=2147483647),2>J)return 0;var se=L;J=(J-=2)<2*b.length?J/2:b.length;for(var we=0;we>>1>>>0]=Ke,L+=2}return g()[L>>>1>>>0]=0,L-se},zC=b=>2*b.length,RC=(b,L)=>{for(var J=0,se="";!(J>=L/4);){var we=m()[b+4*J>>>2>>>0];if(we==0)break;++J,65536<=we?(we-=65536,se+=String.fromCharCode(55296|we>>10,56320|1023&we)):se+=String.fromCharCode(we)}return se},LC=(b,L,J)=>{if(L>>>=0,J??(J=2147483647),4>J)return 0;var se=L;J=se+J-4;for(var we=0;we=Ke&&(Ke=65536+((1023&Ke)<<10)|1023&b.charCodeAt(++we)),m()[L>>>2>>>0]=Ke,(L+=4)+4>J)break}return m()[L>>>2>>>0]=0,L-se},BC=b=>{for(var L=0,J=0;J=se&&++J,L+=4}return L};function NC(b,L,J){if(b>>>=0,L>>>=0,J=Yo(J>>>=0),L===2)var se=OC,we=DC,Ke=zC,Ot=Ut=>w()[Ut>>>1>>>0];else L===4&&(se=RC,we=LC,Ke=BC,Ot=Ut=>P()[Ut>>>2>>>0]);ka(b,{name:J,fromWireType:Ut=>{for(var cn,_n=P()[Ut>>>2>>>0],In=Ut+4,pr=0;pr<=_n;++pr){var Sr=Ut+4+pr*L;pr!=_n&&Ot(Sr)!=0||(In=se(In,Sr-In),cn===void 0?cn=In:(cn+="\0",cn+=In),In=Sr+L)}return Jo(Ut),cn},toWireType:(Ut,cn)=>{if(typeof cn!="string")throw new dl(`Cannot pass non-string to C++ string type ${J}`);var _n=Ke(cn),In=dm(4+_n+L);return P()[In>>>2>>>0]=_n/L,we(cn,In+4,_n+L),Ut!==null&&Ut.push(Jo,In),In},argPackAdvance:fl,readValueFromPointer:F_,Db(Ut){Jo(Ut)}})}function jC(b,L){ka(b>>>=0,{Sb:!0,name:L=Yo(L>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var VC=()=>1;function UC(b){j_(b>>>0,!pe,1,!ce,131072,!1),U1()}var hb=b=>{if(!Ns)try{if(b(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(m(),b>>>2,b).value.then(rm),b+=128,Atomics.store(m(),b>>>2,1))}var rm=()=>{var b=Ac();b&&(O_(b),hb(Ub))};function WC(b,L){(b>>>=0)==L>>>0?setTimeout(rm):ke?postMessage({targetThread:b,cmd:"checkMailbox"}):(b=Qo[b])&&b.postMessage({cmd:"checkMailbox"})}var D_=[];function GC(b,L,J,se,we){for(L>>>=0,se/=2,D_.length=se,J=we>>>0>>>3,we=0;we>>0];return(L?T_[L]:OP[b])(...D_)}function qC(b){b>>>=0,ke?postMessage({cmd:"cleanupThread",thread:b}):V1(Qo[b])}function HC(b){}var z_=(b,L)=>{var J=A_[b];if(J===void 0)throw b=Bb(b),J=Yo(b),Jo(b),new dl(`${L} has unknown type ${J}`);return J},pb=(b,L,J)=>{var se=[];return b=b.toWireType(se,J),se.length&&(P()[L>>>2>>>0]=no(se)),b};function KC(b,L,J){return L>>>=0,J>>>=0,b=to(b>>>0),L=z_(L,"emval::as"),pb(L,J,b)}var im=b=>{try{b()}catch(L){Ec(L)}},hl=0,Zo=null,mb=0,sm=[],gb={},_b={},XC=0,R_=null,QC=[];function yb(b){return function(L){if(!Ns){if(hl===0){var J=!1,se=!1;L((we=0)=>{if(!Ns&&(mb=we,J=!0,se)){hl=2,im(()=>Kb(Zo)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),we=!1;try{var Ke=function(){var cn=m()[Zo+8>>>2>>>0];return cn=An[_b[cn]],--iu,cn()}()}catch(cn){Ke=cn,we=!0}var Ot=!1;if(!Zo){var Ut=R_;Ut&&(R_=null,(we?Ut.reject:Ut.resolve)(Ke),Ot=!0)}if(we&&!Ot)throw Ke}}),se=!0,J||(hl=1,Zo=function(){var we=dm(65548),Ke=we+12;P()[we>>>2>>>0]=Ke,P()[we+4>>>2>>>0]=Ke+65536,Ke=sm[0];var Ot=gb[Ke];return Ot===void 0&&(Ot=XC++,gb[Ke]=Ot,_b[Ot]=Ke),Ke=Ot,m()[we+8>>>2>>>0]=Ke,we}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),im(()=>qb(Zo)))}else hl===2?(hl=0,im(Xb),Jo(Zo),Zo=null,QC.forEach(hb)):Ec(`invalid state: ${hl}`);return mb}}(L=>{b().then(L)})}function YC(b){return b>>>=0,yb(()=>(b=to(b)).then(no))}var om=[];function ZC(b,L,J,se){return J>>>=0,se>>>=0,(b=om[b>>>0])(null,L=to(L>>>0),J,se)}var JC={},am=b=>{var L=JC[b];return L===void 0?Yo(b):L};function eP(b,L,J,se,we){return J>>>=0,se>>>=0,we>>>=0,(b=om[b>>>0])(L=to(L>>>0),L[J=am(J)],se,we)}var vb=()=>typeof globalThis=="object"?globalThis:Function("return this")();function tP(b){return(b>>>=0)==0?no(vb()):(b=am(b),no(vb()[b]))}var nP=b=>{var L=om.length;return om.push(b),L},rP=(b,L)=>{for(var J=Array(b),se=0;se>>2>>>0],"parameter "+se);return J},wb=(b,L)=>Object.defineProperty(L,"name",{value:b});function iP(b,L,J){var se=(L=rP(b,L>>>0)).shift();b--;var we=`return function (obj, func, destructorsRef, args) { `,Ke=0,Ot=[];J===0&&Ot.push("obj");for(var Ut=["retType"],cn=[se],_n=0;_nIn.name).join(", ")}) => ${se.name}>`,nP(wb(J,b))}function sP(b){return b=am(b>>>0),no(S[b])}function oP(b,L){return L>>>=0,b=to(b>>>0),L=to(L),no(b[L])}function aP(b){9<(b>>>=0)&&(Sa[b+1]+=1)}function lP(){return no([])}function uP(b){b=to(b>>>0);for(var L=Array(b.length),J=0;J>>0))}function dP(){return no({})}function fP(b){for(var L=to(b>>>=0);L.length;){var J=L.pop();L.pop()(J)}I_(b)}function hP(b,L,J){L>>>=0,J>>>=0,b=to(b>>>0),L=to(L),J=to(J),b[L]=J}function pP(b,L){return L>>>=0,b=(b=z_(b>>>0,"_emval_take_value")).readValueFromPointer(L),no(b)}function mP(b,L){b=-9007199254740992>b||9007199254740992>>=0,b=new Date(1e3*b),m()[L>>>2>>>0]=b.getUTCSeconds(),m()[L+4>>>2>>>0]=b.getUTCMinutes(),m()[L+8>>>2>>>0]=b.getUTCHours(),m()[L+12>>>2>>>0]=b.getUTCDate(),m()[L+16>>>2>>>0]=b.getUTCMonth(),m()[L+20>>>2>>>0]=b.getUTCFullYear()-1900,m()[L+24>>>2>>>0]=b.getUTCDay(),b=(b.getTime()-Date.UTC(b.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,m()[L+28>>>2>>>0]=b}var Pc=b=>b%4==0&&(b%100!=0||b%400==0),bb=[0,31,60,91,121,152,182,213,244,274,305,335],xb=[0,31,59,90,120,151,181,212,243,273,304,334];function gP(b,L){b=-9007199254740992>b||9007199254740992>>=0,b=new Date(1e3*b),m()[L>>>2>>>0]=b.getSeconds(),m()[L+4>>>2>>>0]=b.getMinutes(),m()[L+8>>>2>>>0]=b.getHours(),m()[L+12>>>2>>>0]=b.getDate(),m()[L+16>>>2>>>0]=b.getMonth(),m()[L+20>>>2>>>0]=b.getFullYear()-1900,m()[L+24>>>2>>>0]=b.getDay();var J=(Pc(b.getFullYear())?bb:xb)[b.getMonth()]+b.getDate()-1|0;m()[L+28>>>2>>>0]=J,m()[L+36>>>2>>>0]=-60*b.getTimezoneOffset(),J=new Date(b.getFullYear(),6,1).getTimezoneOffset();var se=new Date(b.getFullYear(),0,1).getTimezoneOffset();b=0|(J!=se&&b.getTimezoneOffset()==Math.min(se,J)),m()[L+32>>>2>>>0]=b}function _P(b){b>>>=0;var L=new Date(m()[b+20>>>2>>>0]+1900,m()[b+16>>>2>>>0],m()[b+12>>>2>>>0],m()[b+8>>>2>>>0],m()[b+4>>>2>>>0],m()[b>>>2>>>0],0),J=m()[b+32>>>2>>>0],se=L.getTimezoneOffset(),we=new Date(L.getFullYear(),6,1).getTimezoneOffset(),Ke=new Date(L.getFullYear(),0,1).getTimezoneOffset(),Ot=Math.min(Ke,we);return 0>J?m()[b+32>>>2>>>0]=+(we!=Ke&&Ot==se):0>>2>>>0]=L.getDay(),J=(Pc(L.getFullYear())?bb:xb)[L.getMonth()]+L.getDate()-1|0,m()[b+28>>>2>>>0]=J,m()[b>>>2>>>0]=L.getSeconds(),m()[b+4>>>2>>>0]=L.getMinutes(),m()[b+8>>>2>>>0]=L.getHours(),m()[b+12>>>2>>>0]=L.getDate(),m()[b+16>>>2>>>0]=L.getMonth(),m()[b+20>>>2>>>0]=L.getYear(),b=L.getTime(),BigInt(isNaN(b)?-1:b/1e3)}function Tb(b,L,J,se,we,Ke,Ot){return ke?Kr(16,1,b,L,J,se,we,Ke,Ot):-52}function Mb(b,L,J,se,we,Ke){if(ke)return Kr(17,1,b,L,J,se,we,Ke)}function yP(b,L,J,se){b>>>=0,L>>>=0,J>>>=0,se>>>=0;var we=new Date().getFullYear(),Ke=new Date(we,0,1),Ot=new Date(we,6,1);we=Ke.getTimezoneOffset();var Ut=Ot.getTimezoneOffset(),cn=Math.max(we,Ut);P()[b>>>2>>>0]=60*cn,m()[L>>>2>>>0]=+(we!=Ut),Ke=(b=_n=>_n.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(Ke),Ot=b(Ot),Ut{L_.length=0;for(var J;J=f()[b++>>>0];){var se=J!=105;L+=(se&=J!=112)&&L%8?4:0,L_.push(J==112?P()[L>>>2>>>0]:J==106?ki[L>>>3]:J==105?m()[L>>>2>>>0]:O()[L>>>3>>>0]),L+=se?8:4}return L_};function vP(b,L,J){return b>>>=0,L=kb(L>>>0,J>>>0),T_[b](...L)}function wP(b,L,J){return b>>>=0,L=kb(L>>>0,J>>>0),T_[b](...L)}var bP=()=>{},xP=()=>Date.now();function TP(b,L){return Dn(Bi(b>>>0,L>>>0))}var Sb,MP=()=>{throw iu+=1,"unwind"};function kP(){return 4294901760}Sb=()=>performance.timeOrigin+performance.now();var SP=()=>navigator.hardwareConcurrency;function EP(){return Ec("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function CP(b){b>>>=0;var L=f().length;if(b<=L||4294901760=J;J*=2){var se=L*(1+.2/J);se=Math.min(se,b+100663296);var we=Math;se=Math.max(b,se);e:{we=(we.min.call(we,4294901760,se+(65536-se%65536)%65536)-fr.buffer.byteLength+65535)/65536;try{fr.grow(we),Hi();var Ke=1;break e}catch{}Ke=void 0}if(Ke)return!0}return!1}var lm=()=>(Ec("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),mh={},Eb=b=>{b.forEach(L=>{lm()})};function PP(){var b=Error().stack.toString().split(` `);return b[0]=="Error"&&b.shift(),Eb(b),mh.Ob=lm(),mh.ac=b,mh.Ob}function AP(b,L,J){if(b>>>=0,L>>>=0,mh.Ob==b)var se=mh.ac;else(se=Error().stack.toString().split(` `))[0]=="Error"&&se.shift(),Eb(se);for(var we=3;se[we]&&lm()!=b;)++we;for(b=0;b>>2>>>0]=lm();return b}var B_,N_={},Cb=()=>{if(!B_){var b,L={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:zt};for(b in N_)N_[b]===void 0?delete L[b]:L[b]=N_[b];var J=[];for(b in L)J.push(`${b}=${L[b]}`);B_=J}return B_};function Pb(b,L){if(ke)return Kr(18,1,b,L);b>>>=0,L>>>=0;var J=0;return Cb().forEach((se,we)=>{var Ke=L+J;for(we=P()[b+4*we>>>2>>>0]=Ke,Ke=0;Ke>>0]=se.charCodeAt(Ke);u()[we>>>0]=0,J+=se.length+1}),0}function Ab(b,L){if(ke)return Kr(19,1,b,L);b>>>=0,L>>>=0;var J=Cb();P()[b>>>2>>>0]=J.length;var se=0;return J.forEach(we=>se+=we.length+1),P()[L>>>2>>>0]=se,0}function $b(b){return ke?Kr(20,1,b):52}function Ib(b,L,J,se){return ke?Kr(21,1,b,L,J,se):52}function Fb(b,L,J,se){return ke?Kr(22,1,b,L,J,se):70}var $P=[null,[],[]];function Ob(b,L,J,se){if(ke)return Kr(23,1,b,L,J,se);L>>>=0,J>>>=0,se>>>=0;for(var we=0,Ke=0;Ke>>2>>>0],Ut=P()[L+4>>>2>>>0];L+=8;for(var cn=0;cn>>0],In=$P[b];_n===0||_n===10?((b===1?ar:Dn)(X1(In,0)),In.length=0):In.push(_n)}we+=Ut}return P()[se>>>2>>>0]=we,0}var Db=[31,29,31,30,31,30,31,31,30,31,30,31],zb=[31,28,31,30,31,30,31,31,30,31,30,31],IP=(b,L)=>{u().set(b,L>>>0)};function Rb(b,L,J,se){function we(Ct,hr,Yr){for(Ct=typeof Ct=="number"?Ct.toString():Ct||"";Ct.lengthYb?-1:0ou-Ct.getDate())){Ct.setDate(Ct.getDate()+hr);break}hr-=ou-Ct.getDate()+1,Ct.setDate(1),11>Yr?Ct.setMonth(Yr+1):(Ct.setMonth(0),Ct.setFullYear(Ct.getFullYear()+1))}return Yr=new Date(Ct.getFullYear()+1,0,4),hr=Ut(new Date(Ct.getFullYear(),0,4)),Yr=Ut(Yr),0>=Ot(hr,Ct)?0>=Ot(Yr,Ct)?Ct.getFullYear()+1:Ct.getFullYear():Ct.getFullYear()-1}b>>>=0,L>>>=0,J>>>=0,se>>>=0;var _n=P()[se+40>>>2>>>0];for(var In in se={fc:m()[se>>>2>>>0],ec:m()[se+4>>>2>>>0],Gb:m()[se+8>>>2>>>0],Kb:m()[se+12>>>2>>>0],Hb:m()[se+16>>>2>>>0],Cb:m()[se+20>>>2>>>0],ub:m()[se+24>>>2>>>0],Bb:m()[se+28>>>2>>>0],nc:m()[se+32>>>2>>>0],dc:m()[se+36>>>2>>>0],hc:_n?Bi(_n):""},J=Bi(J),_n={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})J=J.replace(new RegExp(In,"g"),_n[In]);var pr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Sr="January February March April May June July August September October November December".split(" ");for(In in _n={"%a":Ct=>pr[Ct.ub].substring(0,3),"%A":Ct=>pr[Ct.ub],"%b":Ct=>Sr[Ct.Hb].substring(0,3),"%B":Ct=>Sr[Ct.Hb],"%C":Ct=>Ke((Ct.Cb+1900)/100|0,2),"%d":Ct=>Ke(Ct.Kb,2),"%e":Ct=>we(Ct.Kb,2," "),"%g":Ct=>cn(Ct).toString().substring(2),"%G":cn,"%H":Ct=>Ke(Ct.Gb,2),"%I":Ct=>((Ct=Ct.Gb)==0?Ct=12:12{for(var hr=0,Yr=0;Yr<=Ct.Hb-1;hr+=(Pc(Ct.Cb+1900)?Db:zb)[Yr++]);return Ke(Ct.Kb+hr,3)},"%m":Ct=>Ke(Ct.Hb+1,2),"%M":Ct=>Ke(Ct.ec,2),"%n":()=>` `,"%p":Ct=>0<=Ct.Gb&&12>Ct.Gb?"AM":"PM","%S":Ct=>Ke(Ct.fc,2),"%t":()=>" ","%u":Ct=>Ct.ub||7,"%U":Ct=>Ke(Math.floor((Ct.Bb+7-Ct.ub)/7),2),"%V":Ct=>{var hr=Math.floor((Ct.Bb+7-(Ct.ub+6)%7)/7);if(2>=(Ct.ub+371-Ct.Bb-2)%7&&hr++,hr)hr==53&&((Yr=(Ct.ub+371-Ct.Bb)%7)==4||Yr==3&&Pc(Ct.Cb)||(hr=1));else{hr=52;var Yr=(Ct.ub+7-Ct.Bb-1)%7;(Yr==4||Yr==5&&Pc(Ct.Cb%400-1))&&hr++}return Ke(hr,2)},"%w":Ct=>Ct.ub,"%W":Ct=>Ke(Math.floor((Ct.Bb+7-(Ct.ub+6)%7)/7),2),"%y":Ct=>(Ct.Cb+1900).toString().substring(2),"%Y":Ct=>Ct.Cb+1900,"%z":Ct=>{var hr=0<=(Ct=Ct.dc);return Ct=Math.abs(Ct)/60,(hr?"+":"-")+("0000"+(Ct/60*100+Ct%60)).slice(-4)},"%Z":Ct=>Ct.hc,"%%":()=>"%"},J=J.replace(/%%/g,"\0\0"),_n)J.includes(In)&&(J=J.replace(new RegExp(In,"g"),_n[In](se)));return In=function(Ct){var hr=Array(C_(Ct)+1);return Z1(Ct,hr,0,hr.length),hr}(J=J.replace(/\0\0/g,"%")),In.length>L?0:(IP(In,b),In.length-1)}function FP(b,L,J,se){return Rb(b>>>0,L>>>0,J>>>0,se>>>0)}ke||function(){for(var b=S.numThreads-1;b--;)G1();ph.unshift(()=>{eo++,function(L){ke?L():Promise.all(cl.map(W1)).then(L)}(()=>tm())})}();for(var Lb=Array(256),um=0;256>um;++um)Lb[um]=String.fromCharCode(um);cb=Lb,dl=S.BindingError=class extends Error{constructor(b){super(b),this.name="BindingError"}},S.InternalError=class extends Error{constructor(b){super(b),this.name="InternalError"}},Sa.push(0,1,void 0,1,null,1,!0,1,!1,1),S.count_emval_handles=()=>Sa.length/2-5-$_.length;var OP=[S_,N1,q1,Q1,Y1,J1,eb,tb,nb,rb,ib,sb,ob,ab,lb,ub,Tb,Mb,Pb,Ab,$b,Ib,Fb,Ob],An=function(){function b(J,se){return An=J.exports,An=function(){var we=An,Ke={};for(let[Ot,Ut]of Object.entries(we))Ke[Ot]=typeof Ut=="function"?(...cn)=>{sm.push(Ot);try{return Ut(...cn)}finally{Ns||(sm.pop(),Zo&&hl===1&&sm.length===0&&(hl=0,iu+=1,im(Hb),typeof Fibers<"u"&&Fibers.oc()))}}:Ut;return Ke}(),An=function(){var we=An,Ke=Ut=>cn=>Ut(cn)>>>0,Ot=Ut=>()=>Ut()>>>0;return(we=Object.assign({},we)).Ca=Ke(we.Ca),we.fb=Ot(we.fb),we.gb=Ke(we.gb),we.emscripten_main_runtime_thread_id=Ot(we.emscripten_main_runtime_thread_id),we.sb=Ke(we.sb),we.tb=Ot(we.tb),we}(),j1.push(An.ib),Ki.unshift(An.Ba),Or=se,tm(),An}var L=L1();if(eo++,S.instantiateWasm)try{return S.instantiateWasm(L,b)}catch(J){Dn(`Module.instantiateWasm callback failed with error: ${J}`),Q(J)}return x_||(x_=S.locateFile?O1("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":S.locateFile?S.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ht):Ht+"ort-wasm-simd-threaded.jsep.wasm":new URL(n("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),n.b).href),function(J,se){var we=x_;return pn||typeof WebAssembly.instantiateStreaming!="function"||O1(we)||D1(we)||typeof fetch!="function"?R1(we,J,se):fetch(we,{credentials:"same-origin"}).then(Ke=>WebAssembly.instantiateStreaming(Ke,J).then(se,function(Ot){return Dn(`wasm streaming compile failed: ${Ot}`),Dn("falling back to ArrayBuffer instantiation"),R1(we,J,se)}))}(L,function(J){b(J.instance,J.module)}).catch(Q),{}}(),Bb=b=>(Bb=An.Ca)(b),Nb=()=>(Nb=An.Da)();S._OrtInit=(b,L)=>(S._OrtInit=An.Ea)(b,L),S._OrtGetLastError=(b,L)=>(S._OrtGetLastError=An.Fa)(b,L),S._OrtCreateSessionOptions=(b,L,J,se,we,Ke,Ot,Ut,cn,_n)=>(S._OrtCreateSessionOptions=An.Ga)(b,L,J,se,we,Ke,Ot,Ut,cn,_n),S._OrtAppendExecutionProvider=(b,L)=>(S._OrtAppendExecutionProvider=An.Ha)(b,L),S._OrtAddFreeDimensionOverride=(b,L,J)=>(S._OrtAddFreeDimensionOverride=An.Ia)(b,L,J),S._OrtAddSessionConfigEntry=(b,L,J)=>(S._OrtAddSessionConfigEntry=An.Ja)(b,L,J),S._OrtReleaseSessionOptions=b=>(S._OrtReleaseSessionOptions=An.Ka)(b),S._OrtCreateSession=(b,L,J)=>(S._OrtCreateSession=An.La)(b,L,J),S._OrtReleaseSession=b=>(S._OrtReleaseSession=An.Ma)(b),S._OrtGetInputOutputCount=(b,L,J)=>(S._OrtGetInputOutputCount=An.Na)(b,L,J),S._OrtGetInputName=(b,L)=>(S._OrtGetInputName=An.Oa)(b,L),S._OrtGetOutputName=(b,L)=>(S._OrtGetOutputName=An.Pa)(b,L),S._OrtFree=b=>(S._OrtFree=An.Qa)(b),S._OrtCreateTensor=(b,L,J,se,we,Ke)=>(S._OrtCreateTensor=An.Ra)(b,L,J,se,we,Ke),S._OrtGetTensorData=(b,L,J,se,we)=>(S._OrtGetTensorData=An.Sa)(b,L,J,se,we),S._OrtReleaseTensor=b=>(S._OrtReleaseTensor=An.Ta)(b),S._OrtCreateRunOptions=(b,L,J,se)=>(S._OrtCreateRunOptions=An.Ua)(b,L,J,se),S._OrtAddRunConfigEntry=(b,L,J)=>(S._OrtAddRunConfigEntry=An.Va)(b,L,J),S._OrtReleaseRunOptions=b=>(S._OrtReleaseRunOptions=An.Wa)(b),S._OrtCreateBinding=b=>(S._OrtCreateBinding=An.Xa)(b),S._OrtBindInput=(b,L,J)=>(S._OrtBindInput=An.Ya)(b,L,J),S._OrtBindOutput=(b,L,J,se)=>(S._OrtBindOutput=An.Za)(b,L,J,se),S._OrtClearBoundOutputs=b=>(S._OrtClearBoundOutputs=An._a)(b),S._OrtReleaseBinding=b=>(S._OrtReleaseBinding=An.$a)(b),S._OrtRunWithBinding=(b,L,J,se,we)=>(S._OrtRunWithBinding=An.ab)(b,L,J,se,we),S._OrtRun=(b,L,J,se,we,Ke,Ot,Ut)=>(S._OrtRun=An.bb)(b,L,J,se,we,Ke,Ot,Ut),S._OrtEndProfiling=b=>(S._OrtEndProfiling=An.cb)(b),S._JsepOutput=(b,L,J)=>(S._JsepOutput=An.db)(b,L,J),S._JsepGetNodeName=b=>(S._JsepGetNodeName=An.eb)(b);var cm,Ac=()=>(Ac=An.fb)(),dm=S._malloc=b=>(dm=S._malloc=An.gb)(b),Jo=S._free=b=>(Jo=S._free=An.hb)(b),j_=(b,L,J,se,we,Ke)=>(j_=An.kb)(b,L,J,se,we,Ke),jb=()=>(jb=An.lb)(),Vb=(b,L,J,se,we)=>(Vb=An.mb)(b,L,J,se,we),V_=b=>(V_=An.nb)(b),fm=b=>(fm=An.ob)(b),Ub=()=>(Ub=An.pb)(),Wb=(b,L)=>(Wb=An.qb)(b,L),hm=b=>(hm=An.rb)(b),U_=b=>(U_=An.sb)(b),W_=()=>(W_=An.tb)(),Gb=S.dynCall_ii=(b,L)=>(Gb=S.dynCall_ii=An.vb)(b,L),qb=b=>(qb=An.wb)(b),Hb=()=>(Hb=An.xb)(),Kb=b=>(Kb=An.yb)(b),Xb=()=>(Xb=An.zb)();function Qb(){0W_(),S.stackRestore=b=>hm(b),S.stackAlloc=b=>U_(b),S.UTF8ToString=Bi,S.stringToUTF8=Cc,S.lengthBytesUTF8=C_,ul=function b(){cm||Qb(),cm||(ul=b)},Qb(),ie}),nn=ot,((r=globalThis.self)==null?void 0:r.name)==="em-pthread"&&ot()}),Mt,mn,hn,Sn,Tn,yn,En,$n,zn=c(()=>{var r,s;ht(),Mt=import.meta.url??(typeof document<"u"?(r=document.currentScript)==null?void 0:r.src:typeof self<"u"?(s=self.location)==null?void 0:s.href:void 0),mn=typeof location>"u"?void 0:location.origin,hn=(u,f)=>{try{let g=f??Mt;return(g?new URL(u,g):new URL(u)).origin===mn}catch{return!1}},Sn=async u=>{let f=await(await fetch(u,{credentials:"same-origin"})).blob();return URL.createObjectURL(f)},Tn=(_t(),_(_e)).default,yn=async()=>{if(!Mt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(hn(Mt))return[void 0,Tn()];let u=await Sn(Mt);return[u,Tn(u)]},En=(Gt(),_($t)).default,$n=async(u,f,g)=>[void 0,En]}),kn,Pt,Qt,dn,Ar,Ci,xs,gr,Nr=c(()=>{zn(),Pt=!1,Qt=!1,dn=!1,Ar=()=>{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}},Ci=()=>{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}},xs=async r=>{if(Pt)return Promise.resolve();if(Qt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(dn)throw new Error("previous call to 'initializeWebAssembly()' failed.");Qt=!0;let s=r.initTimeout,u=r.numThreads;if(!Ci())throw new Error("WebAssembly SIMD is not supported in the current environment.");let f=Ar();u>1&&!f&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+u+", 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."),r.numThreads=u=1);let g=r.wasmPaths,w=typeof g=="string"?g:void 0,m=g==null?void 0:g.mjs,P=(m==null?void 0:m.href)??m,F=g==null?void 0:g.wasm,O=(F==null?void 0:F.href)??F,Y=r.wasmBinary,[Q,S]=await $n(P,w,u>1),ie=!1,ce=[];if(s>0&&ce.push(new Promise(pe=>{setTimeout(()=>{ie=!0,pe()},s)})),ce.push(new Promise((pe,ke)=>{let Pe={numThreads:u};Y?Pe.wasmBinary=Y:(O||w)&&(Pe.locateFile=(be,We)=>O??(w??We)+be),S(Pe).then(be=>{Qt=!1,Pt=!0,kn=be,pe(),Q&&URL.revokeObjectURL(Q)},be=>{Qt=!1,dn=!0,ke(be)})})),await Promise.race(ce),ie)throw new Error(`WebAssembly backend initializing failed due to timeout: ${s}ms`)},gr=()=>{if(Pt&&kn)return kn;throw new Error("WebAssembly is not initialized yet.")}}),yr,Pi,wr,gi=c(()=>{Nr(),yr=(r,s)=>{let u=gr(),f=u.lengthBytesUTF8(r)+1,g=u._malloc(f);return u.stringToUTF8(r,g,f),s.push(g),g},Pi=(r,s,u,f)=>{if(typeof r=="object"&&r!==null){if(u.has(r))throw new Error("Circular reference in options");u.add(r)}Object.entries(r).forEach(([g,w])=>{let m=s?s+g:g;if(typeof w=="object")Pi(w,m+".",u,f);else if(typeof w=="string"||typeof w=="number")f(m,w.toString());else if(typeof w=="boolean")f(m,w?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof w}`)})},wr=r=>{let s=gr(),u=s.stackSave();try{let f=s.stackAlloc(8);s._OrtGetLastError(f,f+4);let g=s.HEAP32[f/4],w=s.HEAPU32[f/4+1],m=w?s.UTF8ToString(w):"";throw new Error(`${r} ERROR_CODE: ${g}, ERROR_MESSAGE: ${m}`)}finally{s.stackRestore(u)}}}),ds,fs=c(()=>{Nr(),gi(),ds=r=>{let s=gr(),u=0,f=[],g=r||{};try{if((r==null?void 0:r.logSeverityLevel)===void 0)g.logSeverityLevel=2;else if(typeof r.logSeverityLevel!="number"||!Number.isInteger(r.logSeverityLevel)||r.logSeverityLevel<0||r.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${r.logSeverityLevel}`);if((r==null?void 0:r.logVerbosityLevel)===void 0)g.logVerbosityLevel=0;else if(typeof r.logVerbosityLevel!="number"||!Number.isInteger(r.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${r.logVerbosityLevel}`);(r==null?void 0:r.terminate)===void 0&&(g.terminate=!1);let w=0;return(r==null?void 0:r.tag)!==void 0&&(w=yr(r.tag,f)),u=s._OrtCreateRunOptions(g.logSeverityLevel,g.logVerbosityLevel,!!g.terminate,w),u===0&&wr("Can't create run options."),(r==null?void 0:r.extra)!==void 0&&Pi(r.extra,"",new WeakSet,(m,P)=>{let F=yr(m,f),O=yr(P,f);s._OrtAddRunConfigEntry(u,F,O)!==0&&wr(`Can't set a run config entry: ${m} - ${P}.`)}),[u,f]}catch(w){throw u!==0&&s._OrtReleaseRunOptions(u),f.forEach(m=>s._free(m)),w}}}),fo,Xs,$r,Ji,ui,Io=c(()=>{Nr(),gi(),fo=r=>{switch(r){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${r}`)}},Xs=r=>{switch(r){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${r}`)}},$r=r=>{r.extra||(r.extra={}),r.extra.session||(r.extra.session={});let s=r.extra.session;s.use_ort_model_bytes_directly||(s.use_ort_model_bytes_directly="1"),r.executionProviders&&r.executionProviders.some(u=>(typeof u=="string"?u:u.name)==="webgpu")&&(r.enableMemPattern=!1)},Ji=(r,s,u)=>{for(let f of s){let g=typeof f=="string"?f:f.name;switch(g){case"webnn":if(g="WEBNN",typeof f!="string"){let m=f==null?void 0:f.deviceType;if(m){let P=yr("deviceType",u),F=yr(m,u);gr()._OrtAddSessionConfigEntry(r,P,F)!==0&&wr(`Can't set a session config entry: 'deviceType' - ${m}.`)}}break;case"webgpu":if(g="JS",typeof f!="string"){let m=f;if(m!=null&&m.preferredLayout){if(m.preferredLayout!=="NCHW"&&m.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${m.preferredLayout}`);let P=yr("preferredLayout",u),F=yr(m.preferredLayout,u);gr()._OrtAddSessionConfigEntry(r,P,F)!==0&&wr(`Can't set a session config entry: 'preferredLayout' - ${m.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${g}`)}let w=yr(g,u);gr()._OrtAppendExecutionProvider(r,w)!==0&&wr(`Can't append execution provider: ${g}.`)}},ui=r=>{let s=gr(),u=0,f=[],g=r||{};$r(g);try{let w=fo(g.graphOptimizationLevel??"all"),m=Xs(g.executionMode??"sequential"),P=typeof g.logId=="string"?yr(g.logId,f):0,F=g.logSeverityLevel??2;if(!Number.isInteger(F)||F<0||F>4)throw new Error(`log serverity level is not valid: ${F}`);let O=g.logVerbosityLevel??0;if(!Number.isInteger(O)||O<0||O>4)throw new Error(`log verbosity level is not valid: ${O}`);let Y=typeof g.optimizedModelFilePath=="string"?yr(g.optimizedModelFilePath,f):0;if(u=s._OrtCreateSessionOptions(w,!!g.enableCpuMemArena,!!g.enableMemPattern,m,!!g.enableProfiling,0,P,F,O,Y),u===0&&wr("Can't create session options."),g.executionProviders&&Ji(u,g.executionProviders,f),g.enableGraphCapture!==void 0){if(typeof g.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${g.enableGraphCapture}`);let Q=yr("enableGraphCapture",f),S=yr(g.enableGraphCapture.toString(),f);s._OrtAddSessionConfigEntry(u,Q,S)!==0&&wr(`Can't set a session config entry: 'enableGraphCapture' - ${g.enableGraphCapture}.`)}if(g.freeDimensionOverrides)for(let[Q,S]of Object.entries(g.freeDimensionOverrides)){if(typeof Q!="string")throw new Error(`free dimension override name must be a string: ${Q}`);if(typeof S!="number"||!Number.isInteger(S)||S<0)throw new Error(`free dimension override value must be a non-negative integer: ${S}`);let ie=yr(Q,f);s._OrtAddFreeDimensionOverride(u,ie,S)!==0&&wr(`Can't set a free dimension override: ${Q} - ${S}.`)}return g.extra!==void 0&&Pi(g.extra,"",new WeakSet,(Q,S)=>{let ie=yr(Q,f),ce=yr(S,f);s._OrtAddSessionConfigEntry(u,ie,ce)!==0&&wr(`Can't set a session config entry: ${Q} - ${S}.`)}),[u,f]}catch(w){throw u!==0&&s._OrtReleaseSessionOptions(u),f.forEach(m=>s._free(m)),w}}}),es,Ai,hs,ts,$i,Qs,Ts,Pn=c(()=>{es=r=>{switch(r){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: ${r}`)}},Ai=r=>{switch(r){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: ${r}`)}},hs=(r,s)=>{let u=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][r],f=typeof s=="number"?s:s.reduce((g,w)=>g*w,1);return u>0?Math.ceil(f*u):void 0},ts=r=>{switch(r){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: ${r}`)}},$i=r=>{switch(r){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: ${r}`)}},Qs=r=>r==="float32"||r==="float16"||r==="int32"||r==="int64"||r==="uint32"||r==="uint8"||r==="bool"||r==="uint4"||r==="int4",Ts=r=>{switch(r){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${r}`)}}}),Zn,ho=c(()=>{ht(),Zn=async r=>{if(typeof r=="string"){let s=await fetch(r);if(!s.ok)throw new Error(`failed to load external data file: ${r}`);let u=s.headers.get("Content-Length"),f=u?parseInt(u,10):0;if(f<1073741824)return new Uint8Array(await s.arrayBuffer());{if(!s.body)throw new Error(`failed to load external data file: ${r}, no response body.`);let g=s.body.getReader(),w;try{w=new ArrayBuffer(f)}catch(P){if(P instanceof RangeError){let F=Math.ceil(f/65536);w=new WebAssembly.Memory({initial:F,maximum:F}).buffer}else throw P}let m=0;for(;;){let{done:P,value:F}=await g.read();if(P)break;let O=F.byteLength;new Uint8Array(w,m,O).set(F),m+=O}return new Uint8Array(w,0,f)}}else return r instanceof Blob?new Uint8Array(await r.arrayBuffer()):r instanceof Uint8Array?r:new Uint8Array(r)}}),po,Ys,br,Ms,ps,ms,kr,_i=c(()=>{Pn(),po=["V","I","W","E","F"],Ys=(r,s)=>{console.log(`[${po[r]},${new Date().toISOString()}]${s}`)},ps=(r,s)=>{br=r,Ms=s},ms=(r,s)=>{let u=$i(r),f=$i(br);u>=f&&Ys(u,typeof s=="function"?s():s)},kr=(...r)=>{Ms&&ms(...r)}}),it,K=c(()=>{Pn(),it=(r,s)=>new(ts(s))(r)}),ye=c(()=>{}),Oe,Ve,He,St,Zt,Lt,Jt,fn,Rn,Wn=c(()=>{_i(),ye(),Oe=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Ve=[],He=r=>Math.ceil(r/16)*16,St=r=>{for(let s=0;sZt++,Jt=async(r,s,u,f)=>{let g=He(u),w=r.device.createBuffer({size:g,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let m=r.getCommandEncoder();r.endComputePass(),m.copyBufferToBuffer(s,0,w,0,g),r.flush(),await w.mapAsync(GPUMapMode.READ);let P=w.getMappedRange();if(f){let F=f();return F.set(new Uint8Array(P,0,u)),F}else return new Uint8Array(P.slice(0,u))}finally{w.destroy()}},fn=class{constructor(r){this.backend=r,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[s]of Oe)Ve.push(s),this.freeBuffers.set(s,[]),this.freeUniformBuffers.set(s,[])}upload(r,s){let u=s.buffer,f=s.byteOffset,g=s.byteLength,w=He(g),m=this.storageCache.get(r);if(!m)throw new Error("gpu data for uploading does not exist");if(m.originalSize!==g)throw new Error(`inconsistent data size. gpu data size=${m.originalSize}, data size=${g}`);let P=this.backend.device.createBuffer({mappedAtCreation:!0,size:w,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),F=P.getMappedRange();new Uint8Array(F).set(new Uint8Array(u,f,g)),P.unmap();let O=this.backend.getCommandEncoder();this.backend.endComputePass(),O.copyBufferToBuffer(P,0,m.gpuData.buffer,0,w),kr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${r})`),this.buffersForUploadingPending.push(P)}memcpy(r,s){let u=this.storageCache.get(r);if(!u)throw new Error("source gpu data for memcpy does not exist");let f=this.storageCache.get(s);if(!f)throw new Error("destination gpu data for memcpy does not exist");if(u.originalSize!==f.originalSize)throw new Error("inconsistent source and destination gpu data size");let g=He(u.originalSize),w=this.backend.getCommandEncoder();this.backend.endComputePass(),w.copyBufferToBuffer(u.gpuData.buffer,0,f.gpuData.buffer,0,g)}registerExternalBuffer(r,s,u){let f;if(u){if(f=this.externalBuffers.get(u),f===void 0)throw new Error("previous buffer is not registered");if(r===u)return kr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${s}) => id=${f}, buffer is the same, skip.`),f;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`);this.externalBuffers.delete(u)}else f=Lt();return this.storageCache.set(f,{gpuData:{id:f,type:0,buffer:r},originalSize:s}),this.externalBuffers.set(r,f),kr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${s}) => id=${f}, registered.`),f}unregisterExternalBuffer(r){let s=this.externalBuffers.get(r);s!==void 0&&(this.storageCache.delete(s),this.externalBuffers.delete(r),kr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${s}`))}create(r,s=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let u=St(r),f,g=(s&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,w=(s&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(g||w){let P=(g?this.freeBuffers:this.freeUniformBuffers).get(u);P?P.length>0?f=P.pop():f=this.backend.device.createBuffer({size:u,usage:s}):f=this.backend.device.createBuffer({size:u,usage:s})}else f=this.backend.device.createBuffer({size:u,usage:s});let m={id:Lt(),type:0,buffer:f};return this.storageCache.set(m.id,{gpuData:m,originalSize:r}),kr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${r}) => id=${m.id}`),m}get(r){var s;return(s=this.storageCache.get(r))==null?void 0:s.gpuData}release(r){let s=this.storageCache.get(r);if(!s)throw new Error("releasing data does not exist");return kr("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(r,s){let u=this.storageCache.get(r);if(!u)throw new Error("data does not exist");await Jt(this.backend,u.gpuData.buffer,u.originalSize,s)}refreshPendingBuffers(){for(let r of this.buffersForUploadingPending)r.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let r of this.buffersPending){let s=Oe.get(r.size);if((r.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let u=this.freeBuffers.get(r.size)||[];s===void 0||u.length>=s?r.destroy():u.push(r)}else if((r.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let u=this.freeUniformBuffers.get(r.size)||[];s===void 0||u.length>=s?r.destroy():u.push(r)}else r.destroy()}this.buffersPending=[]}else{let r=this.capturedPendingBuffers.get(this.backend.currentSessionId);r||(r=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,r));for(let s of this.buffersPending)r.push(s);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(r=>{r.forEach(s=>{s.destroy()})}),this.freeUniformBuffers.forEach(r=>{r.forEach(s=>{s.destroy()})}),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(r=>{r.forEach(s=>{s.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(r){let s=this.capturedPendingBuffers.get(r);s&&(s.forEach(u=>{u.destroy()}),this.capturedPendingBuffers.delete(r))}},Rn=(...r)=>new fn(...r)}),On,bn,Bn=c(()=>{On=class{constructor(r){Object.assign(this,r)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(r=>`${this[r]}`).join(";")),this.key}},bn=r=>new On(r)}),ci,Qr,mt,jr,tr,Rr,di,Mn=c(()=>{ci=class{static calcMatMulShape(r,s){return r[1]!==s[0]?void 0:[r[0],s[1]]}},Qr=class{static calcShape(r,s,u=!1){let f=r.length,g=s.length;if(f===0)return s;if(g===0)return r;let w=Math.max(r.length,s.length),m=new Array(w);if(u){if(f<2||g<2)return;let P=ci.calcMatMulShape([r[f-2],r[f-1]],[s[g-2],s[g-1]]);if(P===void 0)return;[m[w-2],m[w-1]]=P}for(let P=u?3:1;P<=w;P++){let F=f-P<0?1:r[f-P],O=g-P<0?1:s[g-P];if(F!==O&&F>1&&O>1)return;let Y=Math.max(F,O);if(F&&O)m[w-P]=Math.max(F,O);else{if(Y>1)return;m[w-P]=0}}return m}static isValidBroadcast(r,s){let u=r.length,f=s.length;if(u>f)return!1;for(let g=1;g<=u;g++)if(r[u-g]!==1&&r[u-g]!==s[f-g])return!1;return!0}},mt=class Km{static size(s){return Km.getSizeFromDimensionRange(s,0,s.length)}static convertShape(s,u=4){let f=s.length;if(f===0)return[];let g=new Array(f),w=f-1;for(;w>=0;){if(s[w]%u===0){g[w]=s[w]/u;break}if(u%s[w]!==0)throw new Error("cannot convert shape");g[w]=1,u/=s[w],w--}for(w--;w>=0;w--)g[w]=s[w];return g}static sizeFromDimension(s,u){if(u<0||u>s.length)throw new Error(`invalid dimension of ${u} for sizeFromDimension as Tensor has ${s.length} dimensions.`);return Km.getSizeFromDimensionRange(s,u,s.length)}static sizeToDimension(s,u){if(u<0||u>s.length)throw new Error(`invalid dimension of ${u} for sizeToDimension as Tensor has ${s.length} dimensions.`);return Km.getSizeFromDimensionRange(s,0,u)}static getSizeFromDimensionRange(s,u,f){let g=1;for(let w=u;w=0;--g)f[g]=f[g+1]*s[g+1];return f}static normalizeAxis(s,u){if(s<-u&&s>=u)throw new Error("unsupported axis for this operation.");return s<0?s+u:s}static normalizeAxes(s,u){return s.map(f=>this.normalizeAxis(f,u??s.length))}static sortBasedOnPerm(s,u){return u?u.map(f=>s[f]):s.slice().reverse()}static padShape(s,u){let f=s.length;return s.map((g,w)=>g+u[w]+u[w+f])}static areEqual(s,u){return s.length!==u.length?!1:s.every((f,g)=>f===u[g])}},jr=class Ah{static adjustPoolAttributes(s,u,f,g,w,m){if(!s&&f.length!==u.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(s)for(let P=0;P=f.length?f.push(u[P+2]):f[P]=u[P+2];for(let P=0;P=f[P]||m[P+f.length]>=f[P])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(s,u,f,g,w,m,P){if(P){if(w.length!==2*(s.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(u.length!==s.length-2)throw new Error("length of strides should be the length of data dimensions");if(g.length!==s.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let F=0;F{Pn(),Mn(),Ii=64,Ir=(r,s)=>{if(s===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(r){case 10:return s>1?`vec${s}`:"f16";case 1:return s>1?`vec${s}`:"f32";case 6:return s>1?`vec${s}`:"i32";case 12:return s>1?`vec${s}`:"u32";case 7:if(s>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(s>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(s!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${r}`)}},lr=(r,s=1)=>{let u=Ir(r,s);return typeof u=="string"?u:u[0]},ur=(r,s=1)=>{let u=Ir(r,s);return typeof u=="string"?u:u[1]},sn=(...r)=>{let s=[];return r.forEach(u=>{u.length!==0&&s.push({type:12,data:u},{type:12,data:mt.computeStrides(u)})}),s},nr=r=>r%4===0?4:r%2===0?2:1,_r=(r="f32",s,u="0")=>!s||s===1?`${r}(${u})`:`vec${s}<${r}>(${u})`,Fr=(r,s,u)=>r==="f32"?u:s===1?`f32(${u})`:`vec${s}(${u})`,Fi=(r,s)=>s===4?`(${r}.x + ${r}.y + ${r}.z + ${r}.w)`:s===2?`(${r}.x + ${r}.y)`:s===3?`(${r}.x + ${r}.y + ${r}.z)`:r,gn=(r,s,u,f)=>r.startsWith("uniforms.")&&u>4?typeof s=="string"?f==="f16"?`${r}[(${s}) / 8][(${s}) % 8 / 4][(${s}) % 8 % 4]`:`${r}[(${s}) / 4][(${s}) % 4]`:f==="f16"?`${r}[${Math.floor(s/8)}][${Math.floor(s%8/4)}][${s%8%4}]`:`${r}[${Math.floor(s/4)}][${s%4}]`:u>1?`${r}[${s}]`:r,ua=(r,s,u,f,g)=>{let w=typeof u=="number",m=w?u:u.length,P=[...new Array(m).keys()],F=m<2?"u32":m<=4?`vec${m}`:`array`,O=Ir(s,g),Y=typeof O=="string"?O:O[1],Q=typeof O=="string"?O:O[0],S={indices:F,value:Y,storage:Q,tensor:s},ie=Ft=>typeof Ft=="string"?Ft:`${Ft}u`,ce={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},pe=w?"uniforms.":"",ke=`${pe}${r}_shape`,Pe=`${pe}${r}_strides`,be="";for(let Ft=0;Ft ${S.indices} { var indices: ${S.indices}; var current = offset; ${be} return indices; }`,ze=Ft=>(ce.offsetToIndices=!0,m<2?Ft:`o2i_${r}(${Ft})`),Ge=[];if(m>=2)for(let Ft=m-1;Ft>=0;Ft--)Ge.push(`${gn(Pe,Ft,m)} * (indices[${Ft}])`);let zt=m<2?"":` fn i2o_${r}(indices: ${S.indices}) -> u32 { return ${Ge.join("+")}; }`,It=Ft=>(ce.indicesToOffset=!0,m<2?Ft:`i2o_${r}(${Ft})`),Ht=(...Ft)=>m===0?"0u":`${S.indices}(${Ft.map(ie).join(",")})`,pn=(Ft,an)=>m<2?`${Ft}`:`${gn(Ft,an,m)}`,wn=(Ft,an,Nn)=>m<2?`${Ft}=${Nn};`:`${gn(Ft,an,m)}=${Nn};`,Xn={},ar=(Ft,an)=>{ce.broadcastedIndicesToOffset=!0;let Nn=`${an.name}broadcastedIndicesTo${r}Offset`;if(Nn in Xn)return`${Nn}(${Ft})`;let Pr=[];for(let ai=m-1;ai>=0;ai--){let ki=an.indicesGet("outputIndices",ai+an.rank-m);Pr.push(`${pn(Pe,ai)} * (${ki} % ${pn(ke,ai)})`)}return Xn[Nn]=`fn ${Nn}(outputIndices: ${an.type.indices}) -> u32 { return ${Pr.length>0?Pr.join("+"):"0u"}; }`,`${Nn}(${Ft})`},Dn=(Ft,an)=>(()=>{if(S.storage===S.value)return`${r}[${Ft}]=${an};`;if(S.storage==="vec2"&&S.value==="i32")return`${r}[${Ft}]=vec2(u32(${an}), select(0u, 0xFFFFFFFFu, ${an} < 0));`;if(S.storage==="vec2"&&S.value==="u32")return`${r}[${Ft}]=vec2(u32(${an}), 0u);`;if(S.storage==="u32"&&S.value==="vec4")return`${r}[${Ft}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${an}));`;throw new Error(`not supported combination of storage type ${S.storage} and value type ${S.value} yet`)})(),Cr=Ft=>(()=>{if(S.storage===S.value)return`${r}[${Ft}]`;if(S.storage==="vec2"&&S.value==="i32")return`i32(${r}[${Ft}].x)`;if(S.storage==="vec2"&&S.value==="u32")return`u32(${r}[${Ft}].x)`;if(S.storage==="u32"&&S.value==="vec4")return`vec4(bool(${r}[${Ft}] & 0xFFu), bool(${r}[${Ft}] & 0xFF00u), bool(${r}[${Ft}] & 0xFF0000u), bool(${r}[${Ft}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${S.storage} and value type ${S.value} yet`)})(),Vr=m<2?"":` fn get_${r}ByIndices(indices: ${S.indices}) -> ${Y} { return ${Cr(`i2o_${r}(indices)`)}; }`,fr=m<2?"":(()=>{let Ft=P.map(Nn=>`d${Nn}: u32`).join(", "),an=P.map(Nn=>`d${Nn}`).join(", ");return` fn get_${r}(${Ft}) -> ${Y} { return get_${r}ByIndices(${Ht(an)}); }`})(),Or=(...Ft)=>{if(Ft.length!==m)throw new Error(`indices length must be ${m}`);let an=Ft.map(ie).join(",");return m===0?Cr("0u"):m===1?Cr(an[0]):(ce.get=!0,ce.getByIndices=!0,ce.indicesToOffset=!0,`get_${r}(${an})`)},Fn=Ft=>m<2?Cr(Ft):(ce.getByIndices=!0,ce.indicesToOffset=!0,`get_${r}ByIndices(${Ft})`),sr=m<2?"":` fn set_${r}ByIndices(indices: ${S.indices}, value: ${Y}) { ${Dn(`i2o_${r}(indices)`,"value")} }`,vr=m<2?"":(()=>{let Ft=P.map(Nn=>`d${Nn}: u32`).join(", "),an=P.map(Nn=>`d${Nn}`).join(", ");return` fn set_${r}(${Ft}, value: ${Y}) { set_${r}ByIndices(${Ht(an)}, value); }`})();return{impl:()=>{let Ft=[],an=!1;return ce.offsetToIndices&&(Ft.push(We),an=!0),ce.indicesToOffset&&(Ft.push(zt),an=!0),ce.broadcastedIndicesToOffset&&(Object.values(Xn).forEach(Nn=>Ft.push(Nn)),an=!0),ce.set&&(Ft.push(vr),an=!0),ce.setByIndices&&(Ft.push(sr),an=!0),ce.get&&(Ft.push(fr),an=!0),ce.getByIndices&&(Ft.push(Vr),an=!0),!w&&an&&Ft.unshift(`const ${ke} = ${S.indices}(${u.join(",")});`,`const ${Pe} = ${S.indices}(${mt.computeStrides(u).join(",")});`),Ft.join(` `)},type:S,offsetToIndices:ze,indicesToOffset:It,broadcastedIndicesToOffset:ar,indices:Ht,indicesGet:pn,indicesSet:wn,set:(...Ft)=>{if(Ft.length!==m+1)throw new Error(`indices length must be ${m}`);let an=Ft[m];if(typeof an!="string")throw new Error("value must be string");let Nn=Ft.slice(0,m).map(ie).join(",");return m===0?Dn("0u",an):m===1?Dn(Nn[0],an):(ce.set=!0,ce.setByIndices=!0,ce.indicesToOffset=!0,`set_${r}(${Nn}, ${an})`)},setByOffset:Dn,setByIndices:(Ft,an)=>m<2?Dn(Ft,an):(ce.setByIndices=!0,ce.indicesToOffset=!0,`set_${r}ByIndices(${Ft}, ${an});`),get:Or,getByOffset:Cr,getByIndices:Fn,usage:f,name:r,strides:Pe,shape:ke,rank:m}},Bt=(r,s,u,f=1)=>ua(r,s,u,"input",f),vn=(r,s,u,f=1)=>ua(r,s,u,"output",f),mo=(r,s,u,f=1)=>ua(r,s,u,"internal",f),Fo=class{constructor(r,s){this.normalizedDispatchGroup=r,this.limits=s,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(r){return`if (global_idx >= ${typeof r=="number"?`${r}u`:r}) { return; }`}mainStart(r=Ii){let s=typeof r=="number"?r:r[0],u=typeof r=="number"?1:r[1],f=typeof r=="number"?1:r[2];if(s>this.limits.maxComputeWorkgroupSizeX||u>this.limits.maxComputeWorkgroupSizeY||f>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${s}, ${u}, ${f}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(s*u*f>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${s}, ${u}, ${f}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let g=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,w=g?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,m=g?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${s*u*f}u + local_idx;`;return`@compute @workgroup_size(${s}, ${u}, ${f}) fn main(${w}) { ${m} `}appendVariableUniforms(r){r.rank!==0&&(r.shape.startsWith("uniforms.")&&this.uniforms.push({name:r.shape.replace("uniforms.",""),type:"u32",length:r.rank}),r.strides.startsWith("uniforms.")&&this.uniforms.push({name:r.strides.replace("uniforms.",""),type:"u32",length:r.rank}))}declareVariable(r,s){if(r.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(r),this.appendVariableUniforms(r);let u=r.usage==="input"?"read":"read_write",f=r.type.storage;return`@group(0) @binding(${s}) var ${r.name}: array<${f}>;`}declareVariables(...r){return r.map(s=>this.declareVariable(s,this.variableIndex++)).join(` `)}registerInternalVariable(r){if(r.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(r),this.appendVariableUniforms(r)}registerInternalVariables(...r){return r.forEach(s=>this.registerInternalVariable(s)),this}registerUniform(r,s,u=1){return this.uniforms.push({name:r,type:s,length:u}),this}registerUniforms(r){return this.uniforms=this.uniforms.concat(r),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let r=[];for(let{name:s,type:u,length:f}of this.uniforms)if(f&&f>4)u==="f16"?r.push(`@align(16) ${s}:array, ${Math.ceil(f/8)}>`):r.push(`${s}:array, ${Math.ceil(f/4)}>`);else{let g=f==null||f===1?u:`vec${f}<${u}>`;r.push(`${s}:${g}`)}return` struct Uniforms { ${r.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(r=>r.impl()).join(` `)+this.internalVariables.map(r=>r.impl()).join(` `)}get variablesInfo(){if(this.uniforms.length===0)return;let r=s=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(s)];return this.uniforms.map(s=>[r(s.type),s.length??1])}},Bl=(r,s)=>new Fo(r,s),go=(r,s)=>{let u=r.length,f=[];for(let g=0;g1&&m===1&&f.unshift(w)}return f}}),ca,Oo,_o,Do,Oi,zo,da,yo=c(()=>{Pn(),Mn(),Bn(),Vn(),ca=r=>{if(!r||r.length!==1)throw new Error("Transpose requires 1 input.")},Oo=(r,s)=>s&&s.length!==r?[...new Array(r).keys()].reverse():s,_o=(r,s)=>mt.sortBasedOnPerm(r,Oo(r.length,s)),Do=(r,s,u,f)=>{let g=[];g.push(`fn perm(i: ${f.type.indices}) -> ${u.type.indices} { var a: ${u.type.indices};`);for(let w=0;w{let u=r.dataType,f=r.dims.length,g=Oo(f,s),w=_o(r.dims,g),m=vn("output",u,w.length),P=Bt("a",u,f),F;if(g.length===2&&g[0]===1&&g[1]===0){let O=m.type.value,Y=[16,16,1];F=Q=>` ${Q.registerUniform("output_size","u32").declareVariables(P,m)} var tile : array, ${Y[0]}>; ${Q.mainStart(Y)} var x = workgroup_id.x * ${Y[0]}u + local_id.x; var y = workgroup_id.y * ${Y[0]}u + local_id.y; let width = uniforms.output_shape[0]; let height = uniforms.output_shape[1]; if (x < width && y < height) { tile[local_id.y][local_id.x] = ${P.getByOffset("y * width + x")}; } workgroupBarrier(); x = workgroup_id.y * ${Y[0]}u + local_id.x; y = workgroup_id.x * ${Y[0]}u + local_id.y; if (x < height && y < width) { ${m.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} } }`}else F=O=>` ${O.registerUniform("output_size","u32").declareVariables(P,m)} ${Do(g,f,P,m)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${m.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${m.setByOffset("global_idx",P.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>{let O=mt.size(w);return{outputs:[{dims:w,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},...sn(r.dims,w)]}},getShaderSource:F}},zo=(r,s)=>{ca(r.inputs),r.compute(Oi(r.inputs[0],s.perm))},da=r=>bn({perm:r.perm})}),Ro,fa,ha,pa,Lo,fi,vo,Zs,qa,Bo,Di,Ha,No,jo,Ds,ma,Vo,Uo,ga,_a,Nl,Ka=c(()=>{Pn(),Mn(),Vn(),qo(),yo(),Ro={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},fa={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},ha={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},pa={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Lo=(r,s)=>{let u=[];for(let f=s-r;f{let u=[],f=r.length;for(let w=0;wr[w]);return[u,g]},vo=(r,s)=>{let u=r.length+s.length,f=[],g=0;for(let w=0;w{for(let u=0;u{let u=[];if(!Zs(r,s)){for(let f=0;fu.push(f))}return u},Bo=(r,s,u,f,g,w,m)=>{let P=u[0].dims,F=mt.size(w),O=mt.size(m),Y=Bt("_A",u[0].dataType,P),Q=vn("output",g,w),S=32,ie=` var aBestValues : array; `;return{name:r,shaderCache:s,getShaderSource:ce=>` ${ce.registerUniform("reduceSize","u32").declareVariables(Y,Q)} ${ie} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${ce.mainStart(S)} let outputIndex = global_idx / ${S}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${ha[f]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${S}) { let candidate = f32(${Y.getByOffset("offset + k")}); bestValue = ${Ro[f]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${S}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${fa[f]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${Q.setByOffset("outputIndex",`${f==="mean"?`${Q.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${Q.type.storage}(${pa[f]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:w,dataType:g}],dispatchGroup:{x:F},programUniforms:[{type:12,data:O}]})}},Di=(r,s,u,f)=>{let g=r.inputs.length===1?u:bo(r.inputs,u),w=g.axes;w.length===0&&!g.noopWithEmptyAxes&&(w=r.inputs[0].dims.map((ie,ce)=>ce));let m=mt.normalizeAxes(w,r.inputs[0].dims.length),P=m,F=r.inputs[0],O=qa(P,r.inputs[0].dims.length);O.length>0&&(F=r.compute(Oi(r.inputs[0],O),{inputs:[0],outputs:[-1]})[0],P=Lo(P.length,F.dims.length));let[Y,Q]=fi(F.dims,P),S=Y;g.keepDims&&(S=vo(Y,m)),r.compute(Bo(s,{hint:g.cacheKey,inputDependencies:["type"]},[F],f,r.inputs[0].dataType,S,Q),{inputs:[F]})},Ha=(r,s)=>{Di(r,"ReduceMeanShared",s,"mean")},No=(r,s)=>{Di(r,"ReduceL1Shared",s,"l1")},jo=(r,s)=>{Di(r,"ReduceL2Shared",s,"l2")},Ds=(r,s)=>{Di(r,"ReduceLogSumExpShared",s,"logSumExp")},ma=(r,s)=>{Di(r,"ReduceMaxShared",s,"max")},Vo=(r,s)=>{Di(r,"ReduceMinShared",s,"min")},Uo=(r,s)=>{Di(r,"ReduceProdShared",s,"prod")},ga=(r,s)=>{Di(r,"ReduceSumShared",s,"sum")},_a=(r,s)=>{Di(r,"ReduceSumSquareShared",s,"sumSquare")},Nl=(r,s)=>{Di(r,"ReduceLogSumShared",s,"logSum")}}),yi,jl,wo,bo,ns,Xa,Qa,Ya,Za,Ja,el,ya,va,tl,Vl,Vi,Ul,Wo,rs,Lr,Go,xi,Wl,wa,ba,zs,qo=c(()=>{Pn(),Mn(),Bn(),Vn(),Ka(),yi=r=>{if(!r||r.length===0||r.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(r.length===2&&r[1].dims.length!==1)throw new Error("Invalid axes input dims.")},jl=r=>["","",`var value = ${r.getByIndices("input_indices")};`,""],wo=(r,s,u,f,g,w,m=!1,P=!1)=>{let F=[],O=u[0].dims,Y=O.length,Q=mt.normalizeAxes(g,Y),S=!P&&Q.length===0;O.forEach((pe,ke)=>{S||Q.indexOf(ke)>=0?m&&F.push(1):F.push(pe)});let ie=F.length,ce=mt.size(F);return{name:r,shaderCache:s,getShaderSource:pe=>{let ke=[],Pe=Bt("_A",u[0].dataType,Y),be=vn("output",w,ie),We=f(Pe,be,Q),ze=We[2];for(let Ge=0,zt=0;Ge=0?(m&&zt++,ze=`for(var j${Ge}: u32 = 0; j${Ge} < ${O[Ge]}; j${Ge}++) { ${We[2].includes("last_index")?`let last_index = j${Ge};`:""} ${Pe.indicesSet("input_indices",Ge,`j${Ge}`)} ${ze} }`):(ke.push(`${Pe.indicesSet("input_indices",Ge,be.indicesGet("output_indices",zt))};`),zt++);return` ${pe.registerUniform("output_size","u32").declareVariables(Pe,be)} ${pe.mainStart()} ${pe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${Pe.type.indices}; let output_indices = ${be.offsetToIndices("global_idx")}; ${ke.join(` `)} ${We[0]} // init ops for reduce max/min ${We[1]} ${ze} ${We[3]} ${We.length===4?be.setByOffset("global_idx","value"):We.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:F,dataType:w}],dispatchGroup:{x:Math.ceil(ce/64)},programUniforms:[{type:12,data:ce},...sn(O,F)]})}},bo=(r,s)=>{let u=[];return r[1].dims[0]>0&&r[1].getBigInt64Array().forEach(f=>u.push(Number(f))),bn({axes:u,keepDims:s.keepDims,noopWithEmptyAxes:s.noopWithEmptyAxes})},ns=(r,s,u,f)=>{let g=r.inputs,w=g.length===1?u:bo(g,u);r.compute(wo(s,{hint:w.cacheKey,inputDependencies:["rank"]},[g[0]],w.noopWithEmptyAxes&&w.axes.length===0?jl:f,w.axes,g[0].dataType,w.keepDims,w.noopWithEmptyAxes),{inputs:[0]})},Xa=(r,s)=>{yi(r.inputs),ns(r,"ReduceLogSum",s,(u,f)=>[`var value = ${f.type.storage}(0);`,"",`value += ${u.getByIndices("input_indices")};`,"value = log(value);"])},Qa=(r,s)=>{yi(r.inputs),ns(r,"ReduceL1",s,(u,f)=>[`var value = ${f.type.storage}(0);`,"",`value += abs(${u.getByIndices("input_indices")});`,""])},Ya=(r,s)=>{yi(r.inputs),ns(r,"ReduceL2",s,(u,f)=>[`var t = ${f.type.value}(0); var value = ${f.type.value}(0);`,"",`t = ${u.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Za=(r,s)=>{yi(r.inputs),ns(r,"ReduceLogSumExp",s,(u,f)=>[`var value = ${f.type.storage}(0);`,"",`value += exp(${u.getByIndices("input_indices")});`,"value = log(value);"])},Ja=(r,s)=>{yi(r.inputs),ns(r,"ReduceMax",s,(u,f,g)=>{let w=[];for(let m=0;m=0||g.length===0)&&w.push(u.indicesSet("input_indices",m,0));return[`${w.join(` `)}`,`var value = ${u.getByIndices("input_indices")};`,`value = max(value, ${u.getByIndices("input_indices")});`,""]})},el=(r,s)=>{yi(r.inputs),ns(r,"ReduceMean",s,(u,f,g)=>{let w=1;for(let m=0;m=0||g.length===0)&&(w*=r.inputs[0].dims[m]);return["var sum = f32(0);","",`sum += f32(${u.getByIndices("input_indices")});`,`let value = ${f.type.value}(sum / ${w});`]})},ya=(r,s)=>{yi(r.inputs),ns(r,"ReduceMin",s,(u,f,g)=>{let w=[];for(let m=0;m=0||g.length===0)&&w.push(`input_indices[${m}] = 0;`);return[`${w.join(` `)}`,`var value = ${u.getByIndices("input_indices")};`,`value = min(value, ${u.getByIndices("input_indices")});`,""]})},va=(r,s)=>{yi(r.inputs),ns(r,"ReduceProd",s,(u,f)=>[`var value = ${f.type.storage}(1);`,"",`value *= ${u.getByIndices("input_indices")};`,""])},tl=(r,s)=>{yi(r.inputs),ns(r,"ReduceSum",s,(u,f)=>[`var value = ${f.type.storage}(0);`,"",`value += ${u.getByIndices("input_indices")};`,""])},Vl=(r,s)=>{yi(r.inputs),ns(r,"ReduceSumSquare",s,(u,f)=>[`var t = ${f.type.value}(0); var value = ${f.type.value}(0);`,"",`t = ${u.getByIndices("input_indices")}; value += t * t;`,""])},Vi=(r,s,u)=>{if(s.length===0)return u;let f=1,g=1;for(let w=0;w1024},Ul=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?el(r,s):Ha(r,s)},Wo=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Qa(r,s):No(r,s)},rs=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Ya(r,s):jo(r,s)},Lr=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Za(r,s):Ds(r,s)},Go=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Ja(r,s):ma(r,s)},xi=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?ya(r,s):Vo(r,s)},Wl=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?va(r,s):Uo(r,s)},wa=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?tl(r,s):ga(r,s)},ba=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Vl(r,s):_a(r,s)},zs=(r,s)=>{Vi(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Xa(r,s):Nl(r,s)}}),ks,Ss,nl,h,y=c(()=>{Pn(),Bn(),qo(),ks=r=>{if(!r||r.length===0||r.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(r[0].dataType!==1)throw new Error("Invalid input type.")},Ss=(r,s)=>{ks(r.inputs);let u=(f,g,w)=>{let m=[];for(let P=0;P=0||w.length===0)&&m.push(`input_indices[${P}] = 0;`);return[`${m.join(` `)}`,`var value = ${f.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${f.getByIndices("input_indices")} ${s.selectLastIndex>0?"<=":"<"} value) { value = ${f.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",g.setByOffset("global_idx","best_index")]};r.compute(wo("ArgMin",{hint:s.cacheKey,inputDependencies:["rank"]},[r.inputs[0]],u,[s.axis],7,s.keepDims),{inputs:[0]})},nl=(r,s)=>{ks(r.inputs);let u=(f,g,w)=>{let m=[];for(let P=0;P=0||w.length===0)&&m.push(`input_indices[${P}] = 0;`);return[`${m.join(` `)}`,`var value = ${f.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${f.getByIndices("input_indices")} ${s.selectLastIndex>0?">=":">"} value) { value = ${f.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",g.setByOffset("global_idx","best_index")]};r.compute(wo("argMax",{hint:s.cacheKey,inputDependencies:["rank"]},[r.inputs[0]],u,[s.axis],7,s.keepDims),{inputs:[0]})},h=r=>bn(r)}),$,U,Z,le,Te,Le,Qe,qe=c(()=>{Pn(),Mn(),ye(),Vn(),$=(r,s)=>{let u=r[0],f=r[1],g=r[2],w=r[3],m=r[4],P=r[5];if(m&&P)throw new Error("Attention cannot have both past and attention_bias");if(u.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let F=u.dims[0],O=u.dims[1],Y=u.dims[2];if(g.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(f.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(f.dims[0]!==Y)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(g.dims[0]!==f.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let Q=g.dims[0]/3,S=Q,ie=S;if(s.qkvHiddenSizes.length>0){if(s.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let We of s.qkvHiddenSizes)if(We%s.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");Q=s.qkvHiddenSizes[0],S=s.qkvHiddenSizes[1],ie=s.qkvHiddenSizes[2]}let ce=O;if(Q!==S)throw new Error("qkv_hidden_sizes first element should be same as the second");if(g.dims[0]!==Q+S+ie)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let pe=0;if(m){if(S!==ie)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(m.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(m.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(m.dims[1]!==F)throw new Error('Input "past" second dimension must be batch_size');if(m.dims[2]!==s.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(m.dims[4]!==S/s.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');s.pastPresentShareBuffer||(pe=m.dims[3])}let ke=ce+pe,Pe=-1,be=0;if(w)throw new Error("Mask not supported");if(m)throw new Error("past is not supported");if(P){if(P.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(P.dims[0]!==F||P.dims[1]!==s.numHeads||P.dims[2]!==O||P.dims[3]!==ke)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:F,sequenceLength:O,pastSequenceLength:pe,kvSequenceLength:ce,totalSequenceLength:ke,maxSequenceLength:Pe,inputHiddenSize:Y,hiddenSize:Q,vHiddenSize:ie,headSize:Math.floor(Q/s.numHeads),vHeadSize:Math.floor(ie/s.numHeads),numHeads:s.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:s.maskFilterValue,maskType:be,scale:s.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},U=(r,s,u)=>{let f=nr(u),g=64,w=u/f;w{let ie=vn("x",r.dataType,r.dims,f),ce=ur(r.dataType),pe=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${S.registerUniforms(pe).declareVariables(ie)} ${S.mainStart([g,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${g}) * uniforms.d_comp + local_offset; var thread_max_vector = ${O}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { thread_max_vector = max(${O}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(f){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${f}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${g}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${O}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { sum_vector += exp(${O}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(f){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${f}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${g}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { x[offset + i] = ${ie.type.value}(${ce}(uniforms.d_inv)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { var f32input = ${O}(x[offset + i]); x[offset + i] = ${ie.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${g};${F};${f}`,inputDependencies:Y},getShaderSource:Q,getRunData:()=>({outputs:[],dispatchGroup:{x:s},programUniforms:P})}},Z=(r,s,u,f,g,w,m,P)=>{let F=P+w.kvSequenceLength,O=[w.batchSize,w.numHeads,w.sequenceLength,F],Y=w.kvNumHeads===void 0&&r>1&&f,Q=Y?[w.batchSize,w.numHeads,F,w.headSize]:void 0,S=m.scale===0?1/Math.sqrt(w.headSize):m.scale,ie=nr(w.headSize),ce=w.headSize/ie,pe=12,ke={x:Math.ceil(F/pe),y:Math.ceil(w.sequenceLength/pe),z:w.batchSize*w.numHeads},Pe=[{type:12,data:w.sequenceLength},{type:12,data:ce},{type:12,data:F},{type:12,data:w.numHeads},{type:1,data:S},{type:12,data:P},{type:12,data:w.kvSequenceLength}],be=Y&&f&&mt.size(f.dims)>0,We=["type","type"];be&&We.push("type"),g&&We.push("type");let ze=[{dims:O,dataType:s.dataType,gpuDataType:0}];Y&&ze.push({dims:Q,dataType:s.dataType,gpuDataType:0});let Ge=zt=>{let It=Bt("q",s.dataType,s.dims,ie),Ht=Bt("key",u.dataType,u.dims,ie),pn=[It,Ht];if(be){let Cr=Bt("past_key",f.dataType,f.dims,ie);pn.push(Cr)}g&&pn.push(Bt("attention_bias",g.dataType,g.dims));let wn=vn("output",s.dataType,O),Xn=[wn];Y&&Xn.push(vn("present_key",s.dataType,Q,ie));let ar=ur(1,ie),Dn=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${pe}u; var tileQ: array<${It.type.storage}, ${pe*pe}>; var tileK: array<${It.type.storage}, ${pe*pe}>; ${zt.registerUniforms(Dn).declareVariables(...pn,...Xn)} ${zt.mainStart([pe,pe,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; ${be&&Y?` let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} ${Y?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} var value = ${ar}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${be&&Y?` if (n + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; } else { tileK[idx] = key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} ${Y?"present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];":""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += ${ar}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); } workgroupBarrier(); } let headOffset = headIdx * uniforms.M * uniforms.N; if (global_id.y < uniforms.M && global_id.x < uniforms.N) { let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; var sum: f32 = ${(()=>{switch(ie){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${ie}`)}})()}; output[outputIdx] = ${wn.type.value} (sum * uniforms.alpha) + ${g?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${ie};${g!==void 0};${f!==void 0};${r}`,inputDependencies:We},getRunData:()=>({outputs:ze,dispatchGroup:ke,programUniforms:Pe}),getShaderSource:Ge}},le=(r,s,u,f,g,w)=>{let m=w+g.kvSequenceLength,P=g.nReps?g.nReps:1,F=g.vHiddenSize*P,O=g.kvNumHeads==null&&r>1&&f,Y=O?[g.batchSize,g.numHeads,m,g.headSize]:void 0,Q=[g.batchSize,g.sequenceLength,F],S=12,ie={x:Math.ceil(g.vHeadSize/S),y:Math.ceil(g.sequenceLength/S),z:g.batchSize*g.numHeads},ce=[{type:12,data:g.sequenceLength},{type:12,data:m},{type:12,data:g.vHeadSize},{type:12,data:g.numHeads},{type:12,data:F},{type:12,data:w},{type:12,data:g.kvSequenceLength}],pe=O&&f&&mt.size(f.dims)>0,ke=["type","type"];pe&&ke.push("type");let Pe=[{dims:Q,dataType:s.dataType,gpuDataType:0}];O&&Pe.push({dims:Y,dataType:s.dataType,gpuDataType:0});let be=We=>{let ze=Bt("probs",s.dataType,s.dims),Ge=Bt("v",u.dataType,u.dims),zt=[ze,Ge];pe&&zt.push(Bt("past_value",f.dataType,f.dims));let It=[vn("output",s.dataType,Q)];O&&It.push(vn("present_value",s.dataType,Y));let Ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` const TILE_SIZE = ${S}u; var tileQ: array<${ze.type.value}, ${S*S}>; var tileK: array<${ze.type.value}, ${S*S}>; ${We.registerUniforms(Ht).declareVariables(...zt,...It)} ${We.mainStart([S,S,1])} let headIdx = workgroup_id.z; let m = global_id.y; let n = global_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; ${pe&&O?` let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; `:` let offsetB = headIdx * uniforms.N * uniforms.K + n; `} ${O?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} var value = ${ze.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${pe&&O?` if (w + local_id.y < uniforms.past_sequence_length) { tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; } else { tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; } `:` tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; `} ${O?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} } workgroupBarrier(); for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; } workgroupBarrier(); } // we need to transpose output from BNSH_v to BSND_v let batchIdx = workgroup_id.z / uniforms.num_heads; let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; if (m < uniforms.M && n < uniforms.N) { let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + currentBatchHeadNumber * uniforms.N + n; output[outputIdx] = value; } }`};return{name:"AttentionScore",shaderCache:{hint:`${f!==void 0};${r}`,inputDependencies:ke},getRunData:()=>({outputs:Pe,dispatchGroup:ie,programUniforms:ce}),getShaderSource:be}},Te=(r,s,u,f,g,w,m,P,F,O,Y)=>{let Q=Math.min(r.outputCount,1+(m?1:0)+(P?1:0)),S=O.kvNumHeads!==void 0||Q>1?O.pastSequenceLength:0,ie=S+O.kvSequenceLength,ce=F&&mt.size(F.dims)>0?F:void 0,pe=[s,u];O.kvNumHeads===void 0&&Q>1&&m&&mt.size(m.dims)>0&&pe.push(m),ce&&pe.push(ce);let ke=r.compute(Z(Q,s,u,m,ce,O,Y,S),{inputs:pe,outputs:O.kvNumHeads===void 0&&Q>1?[-1,1]:[-1]})[0];r.compute(U(ke,O.batchSize*O.numHeads*O.sequenceLength,ie),{inputs:[ke],outputs:[]});let Pe=[ke,f];O.kvNumHeads===void 0&&Q>1&&P&&mt.size(P.dims)>0&&Pe.push(P),r.compute(le(Q,ke,f,P,O,S),{inputs:Pe,outputs:O.kvNumHeads===void 0&&Q>1?[0,2]:[0]})},Le=(r,s)=>{let u=[s.batchSize,s.numHeads,s.sequenceLength,s.headSize],f=s.sequenceLength,g=s.inputHiddenSize,w=s.headSize,m=12,P={x:Math.ceil(s.headSize/m),y:Math.ceil(s.sequenceLength/m),z:s.batchSize*s.numHeads},F=[r.inputs[0],r.inputs[1],r.inputs[2]],O=[{type:12,data:f},{type:12,data:g},{type:12,data:w},{type:12,data:s.numHeads},{type:12,data:s.headSize},{type:12,data:s.hiddenSize},{type:12,data:s.hiddenSize+s.hiddenSize+s.vHiddenSize}],Y=Q=>{let S=vn("output_q",F[0].dataType,u),ie=vn("output_k",F[0].dataType,u),ce=vn("output_v",F[0].dataType,u),pe=Bt("input",F[0].dataType,F[0].dims),ke=Bt("weight",F[1].dataType,F[1].dims),Pe=Bt("bias",F[2].dataType,F[2].dims),be=pe.type.storage,We=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${m}u; var tileInput: array<${be}, ${m*m}>; var tileWeightQ: array<${be}, ${m*m}>; var tileWeightK: array<${be}, ${m*m}>; var tileWeightV: array<${be}, ${m*m}>; ${Q.registerUniforms(We).declareVariables(pe,ke,Pe,S,ie,ce)} ${Q.mainStart([m,m,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${be}(0); var valueK = ${be}(0); var valueV = ${be}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:u,dataType:r.inputs[0].dataType,gpuDataType:0},{dims:u,dataType:r.inputs[0].dataType,gpuDataType:0},{dims:u,dataType:r.inputs[0].dataType,gpuDataType:0}],dispatchGroup:P,programUniforms:O}),getShaderSource:Y},{inputs:F,outputs:[-1,-1,-1]})},Qe=(r,s)=>{let u=$(r.inputs,s),[f,g,w]=Le(r,u);return Te(r,f,g,w,r.inputs[4],void 0,void 0,void 0,r.inputs[5],u,s)}}),at,Ue,lt,Xe,nt=c(()=>{jt(),Pn(),Mn(),Bn(),Vn(),at=(r,s)=>{if(!r||r.length!==5)throw new Error("BatchNormalization requires 5 inputs");let u=(f,g,w)=>{let m=g.length;if(m!==f.length)throw new Error(`${w}: num dimensions != ${m}`);g.forEach((P,F)=>{if(P!==f[F])throw new Error(`${w}: dim[${F}] do not match`)})};if(r[0].dims.length>1){let f=s.format==="NHWC"?s.spatial?r[0].dims.slice(-1):r[0].dims.slice(-1).concat(r[0].dims.slice(1,r[0].dims.length-1)):r[0].dims.slice(1,s.spatial?2:void 0);u(r[1].dims,f,"Invalid input scale"),u(r[2].dims,f,"Invalid input B"),u(r[3].dims,f,"Invalid input mean"),u(r[4].dims,f,"Invalid input var")}else u(r[1].dims,[1],"Invalid input scale"),u(r[2].dims,[1],"Invalid input B"),u(r[3].dims,[1],"Invalid input mean"),u(r[4].dims,[1],"Invalid input var")},Ue=(r,s)=>{let{epsilon:u,spatial:f,format:g}=s,w=r[0].dims,m=f?nr(w[w.length-1]):1,P=g==="NHWC"&&w.length>1?m:1,F=mt.size(w)/m,O=f,Y=O?w.length:w,Q=Bt("x",r[0].dataType,r[0].dims,m),S=Bt("scale",r[1].dataType,r[1].dims,P),ie=Bt("bias",r[2].dataType,r[2].dims,P),ce=Bt("inputMean",r[3].dataType,r[3].dims,P),pe=Bt("inputVar",r[4].dataType,r[4].dims,P),ke=vn("y",r[0].dataType,Y,m),Pe=()=>{let We="";if(f)We=`let cOffset = ${w.length===1?"0u":g==="NHWC"?`outputIndices[${w.length-1}] / ${m}`:"outputIndices[1]"};`;else if(g==="NCHW")We=` ${ke.indicesSet("outputIndices","0","0")} let cOffset = ${ke.indicesToOffset("outputIndices")};`;else{We=`var cIndices = ${S.type.indices}(0); cIndices[0] = outputIndices[${w.length-1}];`;for(let ze=1;ze` const epsilon = ${u}; ${We.registerUniform("outputSize","u32").declareVariables(Q,S,ie,ce,pe,ke)} ${We.mainStart()} ${We.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${ke.offsetToIndices(`global_idx * ${m}`)}; ${Pe()} let scale = ${S.getByOffset("cOffset")}; let bias = ${ie.getByOffset("cOffset")}; let inputMean = ${ce.getByOffset("cOffset")}; let inputVar = ${pe.getByOffset("cOffset")}; let x = ${Q.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${ke.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${s.epsilon}_${s.format}_${f}_${m}`,inputDependencies:O?["rank","type","type","type","type"]:void 0},getShaderSource:be,getRunData:()=>({outputs:[{dims:r[0].dims,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(F/64)},programUniforms:O?[{type:12,data:F},...sn(w)]:[{type:12,data:F}]})}},lt=r=>bn(r),Xe=(r,s)=>{let{inputs:u,outputCount:f}=r,g=lt({...s,outputCount:f});if(j.webgpu.validateInputContent&&at(u,g),s.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");r.compute(Ue(u,g))}}),ut,tt,yt,wt=c(()=>{Mn(),Vn(),ut=r=>{if(r[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(r[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(r[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(r[0].dims[2]!==r[1].dims[0])throw new Error("last dimension of input and bias are not the same")},tt=r=>{let s=r[0].dims,u=r[0].dims[2],f=mt.size(s)/4,g=r[0].dataType,w=Bt("input",g,s,4),m=Bt("bias",g,[u],4),P=Bt("residual",g,s,4),F=vn("output",g,s,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)}}),getShaderSource:O=>` const channels = ${u}u / 4; ${O.declareVariables(w,m,P,F)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes(f)} let value = ${w.getByOffset("global_idx")} + ${m.getByOffset("global_idx % channels")} + ${P.getByOffset("global_idx")}; ${F.setByOffset("global_idx","value")} }`}},yt=r=>{ut(r.inputs),r.compute(tt(r.inputs))}}),bt,vt,Xt,on,Kt,rn,ln,qt,Un,Gn,Qn,Yn,Ui,Hn,ri,ii,Rs,si,gs,Ho,_d,yd,vd,Eu,wd,bd,xd,Cu,Td,Md,Pu,kd,Sd,Au,Ed,$u,Iu,Fu,Ou,Du,Cd,Pd,Ad,$d,Gl,zu=c(()=>{Pn(),Mn(),Bn(),Vn(),bt=(r,s,u,f,g,w)=>{let m=Math.ceil(s/4),P="";typeof g=="string"?P=`${g}(a)`:P=g("a");let F=Bt("inputData",u,[m],4),O=vn("outputData",f,[m],4);return` ${r.registerUniform("vec_size","u32").declareVariables(F,O)} ${w??""} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${F.getByOffset("global_idx")}; ${O.setByOffset("global_idx",P)} }`},vt=(r,s,u,f,g,w=r.dataType)=>({name:s,shaderCache:{hint:g,inputDependencies:["type"]},getShaderSource:m=>bt(m,mt.size(r.dims),r.dataType,w,u,f),getRunData:m=>({outputs:[{dims:r.dims,dataType:w}],dispatchGroup:{x:Math.ceil(mt.size(m[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(mt.size(r.dims)/4)}]})}),Xt=r=>{r.compute(vt(r.inputs[0],"Abs","abs"))},on=r=>{r.compute(vt(r.inputs[0],"Acos","acos"))},Kt=r=>{r.compute(vt(r.inputs[0],"Acosh","acosh"))},rn=r=>{r.compute(vt(r.inputs[0],"Asin","asin"))},ln=r=>{r.compute(vt(r.inputs[0],"Asinh","asinh"))},qt=r=>{r.compute(vt(r.inputs[0],"Atan","atan"))},Un=r=>{r.compute(vt(r.inputs[0],"Atanh","atanh"))},Gn=r=>bn(r),Qn=(r,s)=>{let u;switch(s.to){case 10:u="vec4";break;case 1:u="vec4";break;case 12:u="vec4";break;case 6:u="vec4";break;case 9:u="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${s.to}`)}r.compute(vt(r.inputs[0],"Cast",u,void 0,s.cacheKey,s.to))},Yn=r=>{let s=r.length>=2&&r[1].data!==0?r[1].getFloat32Array()[0]:Rr,u=r.length>=3&&r[2].data!==0?r[2].getFloat32Array()[0]:di;return bn({min:s,max:u})},Ui=(r,s)=>{let u=r.inputs.length===1?s:Yn(r.inputs),f=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"Clip",g=>`clamp(${g}, clip_min_, clip_max_)`,` const clip_min_: vec4<${f}> = vec4(${f}(${u.min})); const clip_max_: vec4<${f}> = vec4(${f}(${u.max})); `,u.cacheKey),{inputs:[0]})},Hn=r=>{r.compute(vt(r.inputs[0],"Ceil","ceil"))},ri=r=>{r.compute(vt(r.inputs[0],"Cos","cos"))},ii=r=>{r.compute(vt(r.inputs[0],"Cosh","cosh"))},Rs=r=>bn(r),si=(r,s)=>{let u=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"Elu",f=>`elu_vf32(${f})`,` const elu_alpha_ = ${u}(${s.alpha}); fn elu_f32(a: ${u}) -> ${u} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${u}>) -> vec4<${u}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,s.cacheKey))},gs=(r="f32")=>` const r0: ${r} = 0.3275911; const r1: ${r} = 0.254829592; const r2: ${r} = -0.284496736; const r3: ${r} = 1.421413741; const r4: ${r} = -1.453152027; const r5: ${r} = 1.061405429; fn erf_vf32(v: vec4<${r}>) -> vec4<${r}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,Ho=r=>{let s=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"Erf",u=>`erf_vf32(${u})`,gs(s)))},_d=r=>{r.compute(vt(r.inputs[0],"Exp","exp"))},yd=r=>{r.compute(vt(r.inputs[0],"Floor","floor"))},vd=r=>{let s=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"Gelu",u=>`0.5 * ${u} * (1.0 + erf_vf32(${u} * 0.7071067811865475))`,gs(s)))},Eu=(r,s)=>{let u=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"LeakyRelu",f=>`select(leaky_relu_alpha_ * ${f}, ${f}, ${f} >= vec4<${u}>(0.0))`,`const leaky_relu_alpha_ = ${u}(${s.alpha});`,s.cacheKey))},wd=r=>{r.compute(vt(r.inputs[0],"Not",s=>`!${s}`))},bd=r=>{r.compute(vt(r.inputs[0],"Neg",s=>`-${s}`))},xd=r=>{r.compute(vt(r.inputs[0],"Reciprocal",s=>`1.0/${s}`))},Cu=r=>{let s=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"Relu",u=>`select(vec4<${s}>(0.0), ${u}, ${u} > vec4<${s}>(0.0))`))},Td=r=>{r.compute(vt(r.inputs[0],"Sigmoid",s=>`(1.0 / (1.0 + exp(-${s})))`))},Md=r=>bn(r),Pu=(r,s)=>{let u=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"HardSigmoid",f=>`max(vec4<${u}>(0.0), min(vec4<${u}>(1.0), ${s.alpha} * ${f} + vec4<${u}>(${s.beta})))`,void 0,s.cacheKey))},kd=r=>{r.compute(vt(r.inputs[0],"Sin","sin"))},Sd=r=>{r.compute(vt(r.inputs[0],"Sinh","sinh"))},Au=r=>{r.compute(vt(r.inputs[0],"Sqrt","sqrt"))},Ed=r=>{r.compute(vt(r.inputs[0],"Tan","tan"))},$u=r=>`sign(${r}) * (1 - exp(-2 * abs(${r}))) / (1 + exp(-2 * abs(${r})))`,Iu=r=>{r.compute(vt(r.inputs[0],"Tanh",$u))},Fu=(r="f32")=>` const fast_gelu_a: ${r} = 0.5; const fast_gelu_b: ${r} = 0.7978845608028654; const fast_gelu_c: ${r} = 0.035677408136300125; fn tanh_v(v: vec4<${r}>) -> vec4<${r}> { return ${$u("v")}; } `,Ou=r=>`(fast_gelu_a + fast_gelu_a * tanh_v(${r} * (fast_gelu_c * ${r} * ${r} + fast_gelu_b))) * ${r}`,Du=r=>{let s=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"FastGelu",Ou,Fu(s),void 0,r.inputs[0].dataType))},Cd=(r,s)=>{let u=ur(r.inputs[0].dataType);return r.compute(vt(r.inputs[0],"ThresholdedRelu",f=>`select(vec4<${u}>(0.0), ${f}, ${f} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${u}>(${s.alpha});`,s.cacheKey)),0},Pd=r=>{r.compute(vt(r.inputs[0],"Log","log"))},Ad=(r,s)=>` const alpha = vec4<${r}>(${s}); const one = ${r}(1.0); const zero = ${r}(0.0); fn quick_gelu_impl(x: vec4<${r}>) -> vec4<${r}> { let v = x *alpha; var x1 : vec4<${r}>; for (var i = 0; i < 4; i = i + 1) { if (v[i] >= zero) { x1[i] = one / (one + exp(-v[i])); } else { x1[i] = one - one / (one + exp(v[i])); } } return x * x1; } `,$d=r=>`quick_gelu_impl(${r})`,Gl=(r,s)=>{let u=ur(r.inputs[0].dataType);r.compute(vt(r.inputs[0],"QuickGelu",$d,Ad(u,s.alpha),s.cacheKey,r.inputs[0].dataType))}}),Id,Fd,Ru,kp=c(()=>{Mn(),Vn(),zu(),Id=r=>{if(r[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(r[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(r[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(r[0].dims[2]!==r[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Fd=r=>{let s=r[0].dims.slice();s[2]=s[2]/2;let u=Bt("input",r[0].dataType,r[0].dims,4),f=Bt("bias",r[0].dataType,[r[0].dims[2]],4),g=vn("output",r[0].dataType,s,4),w=mt.size(s)/4,m=lr(r[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)}}),getShaderSource:P=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${r[0].dims[2]/4/2}u; ${P.declareVariables(u,f,g)} ${gs(m)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes(w)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${g.setByOffset("global_idx","valueLeft * geluRight")} }`}},Ru=r=>{Id(r.inputs),r.compute(Fd(r.inputs))}}),Od,Dd,Es,Lu,zd,Rd,Bu,Ld,Bd,Nu,Nd,jd,ju,Sp=c(()=>{Pn(),Mn(),Vn(),Od=(r,s,u,f,g,w,m,P,F,O,Y,Q)=>{let S,ie;typeof P=="string"?S=ie=(be,We)=>`${P}((${be}),(${We}))`:typeof P=="function"?S=ie=P:(S=P.scalar,ie=P.vector);let ce=vn("outputData",Y,f.length,4),pe=Bt("aData",F,s.length,4),ke=Bt("bData",O,u.length,4),Pe;if(g)if(w){let be=mt.size(s)===1,We=mt.size(u)===1,ze=s.length>0&&s[s.length-1]%4===0,Ge=u.length>0&&u[u.length-1]%4===0;be||We?Pe=ce.setByOffset("global_idx",ie(be?`${pe.type.value}(${pe.getByOffset("0")}.x)`:pe.getByOffset("global_idx"),We?`${ke.type.value}(${ke.getByOffset("0")}.x)`:ke.getByOffset("global_idx"))):Pe=` let outputIndices = ${ce.offsetToIndices("global_idx * 4u")}; let offsetA = ${pe.broadcastedIndicesToOffset("outputIndices",ce)}; let offsetB = ${ke.broadcastedIndicesToOffset("outputIndices",ce)}; ${ce.setByOffset("global_idx",ie(m||ze?pe.getByOffset("offsetA / 4u"):`${pe.type.value}(${pe.getByOffset("offsetA / 4u")}[offsetA % 4u])`,m||Ge?ke.getByOffset("offsetB / 4u"):`${ke.type.value}(${ke.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else Pe=ce.setByOffset("global_idx",ie(pe.getByOffset("global_idx"),ke.getByOffset("global_idx")));else{if(!w)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let be=(We,ze,Ge="")=>{let zt=`aData[indexA${ze}][componentA${ze}]`,It=`bData[indexB${ze}][componentB${ze}]`;return` let outputIndices${ze} = ${ce.offsetToIndices(`global_idx * 4u + ${ze}u`)}; let offsetA${ze} = ${pe.broadcastedIndicesToOffset(`outputIndices${ze}`,ce)}; let offsetB${ze} = ${ke.broadcastedIndicesToOffset(`outputIndices${ze}`,ce)}; let indexA${ze} = offsetA${ze} / 4u; let indexB${ze} = offsetB${ze} / 4u; let componentA${ze} = offsetA${ze} % 4u; let componentB${ze} = offsetB${ze} % 4u; ${We}[${ze}] = ${Ge}(${S(zt,It)}); `};Y===9?Pe=` var data = vec4(0); ${be("data",0,"u32")} ${be("data",1,"u32")} ${be("data",2,"u32")} ${be("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:Pe=` ${be("outputData[global_idx]",0)} ${be("outputData[global_idx]",1)} ${be("outputData[global_idx]",2)} ${be("outputData[global_idx]",3)} `}return` ${r.registerUniform("vec_size","u32").declareVariables(pe,ke,ce)} ${Q??""} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${Pe} }`},Dd=(r,s,u,f,g,w,m=u.dataType)=>{let P=!mt.areEqual(u.dims,f.dims),F=u.dims,O=mt.size(u.dims),Y=!1,Q=!1,S=[P];if(P){let ie=Qr.calcShape(u.dims,f.dims,!1);if(!ie)throw new Error("Can't perform binary op on the given tensors");F=ie,O=mt.size(F);let ce=mt.size(u.dims)===1,pe=mt.size(f.dims)===1,ke=u.dims.length>0&&u.dims[u.dims.length-1]%4===0,Pe=f.dims.length>0&&f.dims[f.dims.length-1]%4===0;S.push(ce),S.push(pe),S.push(ke),S.push(Pe);let be=1;for(let We=1;Weie.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:ie=>Od(ie,u.dims,f.dims,F,Y,P,Q,g,u.dataType,f.dataType,m,w),getRunData:()=>({outputs:[{dims:F,dataType:m}],dispatchGroup:{x:Math.ceil(O/64/4)},programUniforms:[{type:12,data:Math.ceil(mt.size(F)/4)},...sn(u.dims,f.dims,F)]})}},Es=(r,s,u,f,g,w)=>{r.compute(Dd(s,g??"",r.inputs[0],r.inputs[1],u,f,w))},Lu=r=>{Es(r,"Add",(s,u)=>`${s}+${u}`)},zd=r=>{Es(r,"Div",(s,u)=>`${s}/${u}`)},Rd=r=>{Es(r,"Equal",{scalar:(s,u)=>`u32(${s}==${u})`,vector:(s,u)=>`vec4(${s}==${u})`},void 0,void 0,9)},Bu=r=>{Es(r,"Mul",(s,u)=>`${s}*${u}`)},Ld=r=>{let s=Bt("input",r.inputs[0].dataType,r.inputs[0].dims).type.value;Es(r,"Pow",{scalar:(u,f)=>`pow_custom(${u},${f})`,vector:(u,f)=>`pow_vector_custom(${u},${f})`},` fn pow_custom(a : ${s}, b : ${s}) -> ${s} { if (b == ${s}(0.0)) { return ${s}(1.0); } else if (a < ${s}(0.0) && f32(b) != floor(f32(b))) { return ${s}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${s}(1.0), round(f32(abs(b) % ${s}(2.0))) != 1.0) * ${s}(${s==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${s}>, b : vec4<${s}>) -> vec4<${s}> { // TODO: implement vectorized pow return vec4<${s}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},Bd=r=>{Es(r,"Sub",(s,u)=>`${s}-${u}`)},Nu=r=>{Es(r,"Greater",{scalar:(s,u)=>`u32(${s}>${u})`,vector:(s,u)=>`vec4(${s}>${u})`},void 0,void 0,9)},Nd=r=>{Es(r,"Less",{scalar:(s,u)=>`u32(${s}<${u})`,vector:(s,u)=>`vec4(${s}<${u})`},void 0,void 0,9)},jd=r=>{Es(r,"GreaterOrEqual",{scalar:(s,u)=>`u32(${s}>=${u})`,vector:(s,u)=>`vec4(${s}>=${u})`},void 0,void 0,9)},ju=r=>{Es(r,"LessOrEqual",{scalar:(s,u)=>`u32(${s}<=${u})`,vector:(s,u)=>`vec4(${s}<=${u})`},void 0,void 0,9)}}),Vd,Ud,Wd,Gd,qd,Vu,Ep=c(()=>{Pn(),Mn(),Bn(),Vn(),Vd=(r,s)=>{if(!r||r.length<1)throw new Error("too few inputs");let u=0,f=r[u],g=f.dataType,w=f.dims.length;r.forEach((m,P)=>{if(P!==u){if(m.dataType!==g)throw new Error("input tensors should be one type");if(m.dims.length!==w)throw new Error("input tensors should have the same shape");m.dims.forEach((F,O)=>{if(O!==s&&F!==f.dims[O])throw new Error("non concat dimensions must match")})}})},Ud=(r,s)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${s}); for (var i: u32 = 0u; i < ${r}; i += 1u ) { if (index < sizeInConcatAxis[i]) { return i; } } return ${r}u; }`,Wd=(r,s)=>{let u=r.length,f=[];for(let g=0;g{let g=mt.size(u),w=new Array(r.length),m=new Array(r.length),P=0,F=[],O=[],Y=[{type:12,data:g}];for(let pe=0;pe`uniforms.sizeInConcatAxis${pe}`).join(","),ce=pe=>` ${(()=>{pe.registerUniform("outputSize","u32");for(let ke=0;ke(${ie}); ${S} -= sizeInConcatAxis[inputIndex - 1u]; } ${Wd(m,Q)} }`;return{name:"Concat",shaderCache:{hint:`${s}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:u,dataType:f}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:Y}),getShaderSource:ce}},qd=(r,s)=>{let u=r.inputs,f=u[0].dims,g=mt.normalizeAxis(s.axis,f.length);Vd(u,g);let w=f.slice();w[g]=u.reduce((P,F)=>P+(F.dims.length>g?F.dims[g]:0),0);let m=u.filter(P=>mt.size(P.dims)>0);r.compute(Gd(m,g,w,u[0].dataType),{inputs:m})},Vu=r=>bn({axis:r.axis})}),xo,Js,To,Uu,Wi=c(()=>{Pn(),Mn(),xo=(r,s,u="f32")=>{switch(r.activation){case"Relu":return`value = max(value, ${s}(0.0));`;case"Sigmoid":return`value = (${s}(1.0) / (${s}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${s}(${u}(uniforms.clip_min)), ${s}(${u}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${s}(0.0), min(${s}(1.0), ${u}(uniforms.alpha) * value + ${u}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${u}(uniforms.alpha) * value, value, value >= ${s}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); `;case"":return"";default:throw new Error(`Unsupported activation ${r.activation}`)}},Js=(r,s)=>{r.activation==="Clip"?s.push({type:1,data:r.clipMax},{type:1,data:r.clipMin}):r.activation==="HardSigmoid"?s.push({type:1,data:r.alpha},{type:1,data:r.beta}):r.activation==="LeakyRelu"&&s.push({type:1,data:r.alpha})},To=(r,s)=>{r.activation==="Clip"?s.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):r.activation==="HardSigmoid"?s.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):r.activation==="LeakyRelu"&&s.push({name:"alpha",type:"f32"})},Uu=r=>{let s=(r==null?void 0:r.activation)||"";if(s==="HardSigmoid"){let[u,f]=(r==null?void 0:r.activation_params)||[.2,.5];return{activation:s,alpha:u,beta:f}}else if(s==="Clip"){let[u,f]=(r==null?void 0:r.activation_params)||[Rr,di];return{activation:s,clipMax:f,clipMin:u}}else if(s==="LeakyRelu"){let[u]=(r==null?void 0:r.activation_params)||[.01];return{activation:s,alpha:u}}return{activation:s}}}),Ti,Wu,ql=c(()=>{Ti=(r,s)=>{switch(r){case 1:return s;case 2:return`vec2<${s}>`;case 3:return`vec3<${s}>`;case 4:return`vec4<${s}>`;default:throw new Error(`${r}-component is not supported.`)}},Wu=r=>` ${r?"value = value + getBiasByOutputCoords(coords);":""} `}),Gu,qu=c(()=>{Gu=r=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${r}.x), i32(${r}.y), i32(${r}.z), 1)); } `}),Hd,Kd,Hl,Hu,Kl,Xl,Xd,Ku,Ko=c(()=>{Pn(),Mn(),Vn(),Wi(),ql(),Hd=(r,s)=>r?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${s?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${s?", batchIndices":""}); `,Kd=(r,s)=>r?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${s===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${s===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${s===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`,Hl=(r,s,u="f32",f,g=!1,w=32,m=!1,P=32)=>{let F=s[1]*r[1],O=s[0]*r[0],Y=g?F:w,Q=g?w:F,S=Y/s[0],ie=w/s[1];if(!((g&&S===4&&r[1]===4||!g&&(S===3||S===4))&&Y%s[0]===0&&w%s[1]===0&&r[0]===4))throw new Error(`If transposeA ${g} is true, innerElementSize ${S} and workPerThread[1] ${r[1]} must be 4. Otherwise, innerElementSize ${S} must be 3 or 4. tileAWidth ${Y} must be divisible by workgroupSize[0]${s[0]}. tileInner ${w} must be divisible by workgroupSize[1] ${s[1]}. colPerThread ${r[0]} must be 4.`);return` var mm_Asub: array, ${Y/S}>, ${Q}>; var mm_Bsub: array, ${O/r[0]}>, ${w}>; const rowPerThread = ${r[1]}; const colPerThread = ${r[0]}; const innerElementSize = ${S}; const tileInner = ${w}; @compute @workgroup_size(${s[0]}, ${s[1]}, ${s[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${m?"0":"i32(globalId.z)"}; ${f?`let batchIndices = ${f.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${F}; let num_tiles = ${m?`${Math.ceil(P/w)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${m?`i32(globalId.z) * ${P}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${ie}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${Hd(g,f)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${ie}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${f?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${S===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Kd(g,S)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Hu=(r,s)=>r?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${s?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${s?", batchIndices":""}); `,Kl=r=>r?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Xl=(r,s,u="f32",f,g=!1,w=32,m=!1,P=32,F=!1)=>{let O=r[1]*s[1],Y=r[0]*s[0],Q=g?O:w,S=g?w:O;if(!(S%s[1]===0&&Q%s[0]===0&&w%s[1]===0))throw new Error(`tileAHight ${S} must be divisible by workgroupSize[1]${s[1]}, tileAWidth ${Q} must be divisible by workgroupSize[0]${s[0]}, tileInner ${w} must be divisible by workgroupSize[1]${s[1]}`);let ie=S/s[1],ce=Q/s[0],pe=w/s[1],ke=F?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${O}; let globalColStart = i32(workgroupId.x) * ${Y}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${S}; inputRow = inputRow + ${s[1]}) { for (var inputCol = localCol; inputCol < ${Q}; inputCol = inputCol + ${s[0]}) { ${Hu(g,f)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${w}; inputRow = inputRow + ${s[1]}) { for (var inputCol = localCol; inputCol < ${Y}; inputCol = inputCol + ${s[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${f?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${u}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${s[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${g?`mm_Asub[k][localRow + innerRow * ${s[1]}];`:`mm_Asub[localRow + innerRow * ${s[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${s[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${s[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${O}; let tileRowA = i32(localId.y) * ${ie}; let tileColA = i32(localId.x) * ${ce}; let tileRowB = i32(localId.y) * ${pe}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${ie}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${ce}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Hu(g,f)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${pe}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${f?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${u}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Kl(g)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${S}>; var mm_Bsub : array, ${w}>; const rowPerThread = ${r[1]}; const colPerThread = ${r[0]}; const tileInner = ${w}; @compute @workgroup_size(${s[0]}, ${s[1]}, ${s[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${m?"0":"i32(globalId.z)"}; ${f?`let batchIndices = ${f.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${m?`${Math.ceil(P/w)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${m?`i32(globalId.z) * ${P}`:"0"}; var acc : array, rowPerThread>; ${ke} } `},Xd=(r,s,u,f,g,w=!1)=>{let[m,P,F]=g,[O,Y,Q,S]=f,ie=go(m,F),ce=go(P,F),pe=lr(f[0].type.tensor),ke=()=>{let be=Y.rank,We=O.rank,ze=`var aIndices: ${Y.type.indices};`;for(let Ge=be-2-1,zt=We-1;Ge>=0;Ge--,zt--)ze+=` aIndices[${Ge}] = ${We>1?`batchIndices[${zt}]`:"batchIndices"};`;return ie.forEach(Ge=>{ze+=` aIndices[${Ge}] = 0;`}),ze+=` aIndices[${be-2}] = u32(row); aIndices[${be-1}] = u32(colIn);`,ze},Pe=()=>{let be=Q.rank,We=O.rank,ze=`var bIndices: ${Q.type.indices};`;for(let Ge=be-2-1,zt=We-1;Ge>=0;Ge--,zt--)ze+=` bIndices[${Ge}] = ${We>1?`batchIndices[${zt}]`:"batchIndices"};`;return ce.forEach(Ge=>{ze+=` bIndices[${Ge}] = 0;`}),ze+=` bIndices[${be-2}] = u32(row); bIndices[${be-1}] = u32(colIn);`,ze};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${O.type.indices}) -> ${Ti(r,pe)} { var value = ${Ti(r,pe)}(0.0); let col = colIn * ${r}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${ke()} value = ${Y.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${O.type.indices}) -> ${Ti(r,pe)} { var value = ${Ti(r,pe)}(0.0); let col = colIn * ${r}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${Pe()} value = ${Q.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ti(r,pe)}) { let col = colIn * ${r}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${s?`value = value + ${w?"bias[colIn]":`${Ti(r,pe)}(bias[row])`};`:""} ${u} ${S.setByIndices("vec3(coords)","value")} } } `},Ku=(r,s,u,f,g=!1,w)=>{let m=r[0].dims,P=r[1].dims,F=m.slice(0,-2),O=P.slice(0,-2),Y=f?f.slice(0,-2):u.slice(0,-2),Q=mt.size(Y),S=m[m.length-2],ie=m[m.length-1],ce=P[P.length-1],pe=ie%4===0&&ce%4===0,ke=S<=8?[4,1,1]:[4,4,1],Pe=[8,8,1],be=[Math.ceil(ce/Pe[0]/ke[0]),Math.ceil(S/Pe[1]/ke[1]),Math.ceil(Q/Pe[2]/ke[2])],We=pe?4:1,ze=[...F,S,ie/We],Ge=ze.length,zt=[...O,ie,ce/We],It=zt.length,Ht=[Q,S,ce/We],pn=[{type:6,data:S},{type:6,data:ce},{type:6,data:ie}];Js(s,pn),pn.push(...sn(Y,ze,zt));let wn=["rank","rank"],Xn=r.length>2;Xn&&(pn.push(...sn(r[2].dims)),wn.push("rank")),pn.push(...sn(Ht));let ar=Dn=>{let Cr=Y.length,Vr=mo("batchDims",r[0].dataType,Cr,1),fr=lr(r[0].dataType),Or=Bt("a",r[0].dataType,Ge,We),Fn=Bt("b",r[1].dataType,It,We),sr=vn("result",r[0].dataType,Ht.length,We),vr=[Or,Fn];if(Xn){let ai=g?We:1;vr.push(Bt("bias",r[2].dataType,r[2].dims.length,ai))}let Ft=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];To(s,Ft);let an=lr(sr.type.tensor),Nn=xo(s,sr.type.value,an),Pr=Xd(We,Xn,Nn,[Vr,Or,Fn,sr],[F,O,Y],g);return` ${Dn.registerUniforms(Ft).registerInternalVariables(Vr).declareVariables(...vr,sr)} ${Pr} ${pe?Hl(ke,Pe,fr,Vr):Xl(ke,Pe,fr,Vr)} `};return{name:"MatMul",shaderCache:{hint:`${ke};${s.activation};${pe};${g}`,inputDependencies:wn},getRunData:()=>({outputs:[{dims:w?w(u):u,dataType:r[0].dataType}],dispatchGroup:{x:be[0],y:be[1],z:be[2]},programUniforms:pn}),getShaderSource:ar}}}),Qd,Yd,Cp=c(()=>{Pn(),_i(),Vn(),Wi(),ql(),qu(),Ko(),Qd=(r,s,u,f,g=!1,w,m=4,P=4,F=4,O="f32")=>{let Y=pn=>{switch(pn){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${O}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${pn} is not supported.`)}},Q=pn=>{switch(pn){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${pn} is not supported.`)}},S=r?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,ie=r?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,ce=r?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",pe=r?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",ke=r?"row":"col",Pe=r?"col":"row",be=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${ke} / outWidth; let outCol = ${ke} % outWidth; let WRow = ${Pe} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${Pe} / inChannels % i32(uniforms.w_shape[1]); let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; let xCh = ${Pe} % inChannels; var resData = ${Ti(m,O)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${ce} && xCol >= 0 && xCol < ${pe}) { ${S} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${Y(m)} } return resData;`,We=r?s&&f?` let col = colIn * ${m}; ${be}`:` let col = colIn * ${m}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${be} } return ${Ti(m,O)}(0.0);`:f&&u?` let col = colIn * ${m}; ${be}`:` let col = colIn * ${m}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${be} } return ${Ti(m,O)}(0.0);`,ze=`${Q(P)}`,Ge=Ti(F,O),zt=Ti(r?m:P,O),It=Ti(r?P:m,O),Ht=xo(w,Ge,O);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${zt} { ${r?We:ze} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${It} { ${r?ze:We} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Ge}) { let col = colIn * ${F}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${ie} ${Wu(g)} ${Ht} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Yd=(r,s,u,f,g,w,m,P,F)=>{let O=s.format==="NHWC",Y=O?r[0].dims[3]:r[0].dims[1],Q=u[0],S=O?u[2]:u[3],ie=O?u[1]:u[2],ce=O?u[3]:u[1],pe=O&&(Y%4===0||Y%3===0)&&ce%4===0,ke=O?ce:S*ie,Pe=O?S*ie:ce,be=[8,8,1],We=f<=8?[4,1,1]:[4,4,1],ze=[Math.ceil(ke/be[0]/We[0]),Math.ceil(Pe/be[1]/We[1]),Math.ceil(Q/be[2]/We[2])];kr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${ze}`);let Ge=pe?O&&Y%4!==0?3:4:1,zt=be[1]*We[1],It=be[0]*We[0],Ht=Math.max(be[0]*Ge,be[1]),pn=f%zt===0,wn=g%It===0,Xn=w%Ht===0,ar=pe?[Ge,4,4]:[1,1,1],Dn=[{type:6,data:f},{type:6,data:g},{type:6,data:w},{type:6,data:[s.pads[0],s.pads[1]]},{type:6,data:s.strides},{type:6,data:s.dilations}];Js(s,Dn),Dn.push(...sn(r[0].dims,r[1].dims));let Cr=["rank","rank"];m&&(Dn.push(...sn(r[2].dims)),Cr.push("rank")),Dn.push(...sn(u));let Vr=fr=>{let Or=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];To(s,Or);let Fn=pe?4:1,sr=lr(r[0].dataType),vr=` fn setOutputAtIndex(flatIndex : i32, value : ${pe?`vec4<${sr}>`:sr}) { result[flatIndex] = ${pe?`vec4<${sr}>`:sr}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${pe?`vec4<${sr}>`:sr}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${pe?"/ 4":""}, value); }`,Ft=Bt("x",r[0].dataType,r[0].dims.length,Ge===3?1:Ge),an=Bt("w",r[1].dataType,r[1].dims.length,Fn),Nn=[Ft,an],Pr=vn("result",r[0].dataType,u.length,Fn);if(m){let ai=Bt("bias",r[2].dataType,r[2].dims.length,Fn);Nn.push(ai),vr+=` fn getBiasByOutputCoords(coords : vec4) -> ${pe?`vec4<${sr}>`:sr} { return bias[coords.${O?"w":"y"}${pe?"/ 4":""}]; }`}return` ${Gu("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${fr.registerUniforms(Or).declareVariables(...Nn,Pr)} ${vr} ${Qd(O,pn,wn,Xn,m,s,ar[0],ar[1],ar[2],sr)} ${pe?Hl(We,be,sr,void 0,!O,Ht):Xl(We,be,sr,void 0,!O,Ht,!1,void 0,P)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${s.cacheKey};${Ge};${pe};${pn};${wn};${Xn};${zt};${It};${Ht}`,inputDependencies:Cr},getRunData:()=>({outputs:[{dims:F?F(u):u,dataType:r[0].dataType}],dispatchGroup:{x:ze[0],y:ze[1],z:ze[2]},programUniforms:Dn}),getShaderSource:Vr}}}),Zd,rl,il,Jd,Xu,Pp,ef,tf,Ap=c(()=>{Pn(),_i(),Mn(),Vn(),Wi(),ql(),Zd=r=>{let s=1;for(let u=0;utypeof r=="number"?[r,r,r]:r,il=(r,s)=>s<=1?r:r+(r-1)*(s-1),Jd=(r,s,u,f=1)=>{let g=il(s,f);return Math.floor((r[0]*(u-1)-u+g)/2)},Xu=(r,s,u,f,g)=>{g==null&&(g=Jd(r,s[0],f[0]));let w=[0,0,0,u];for(let m=0;m<3;m++)r[m]+2*g>=s[m]&&(w[m]=Math.trunc((r[m]-s[m]+2*g)/f[m]+1));return w},Pp=(r,s,u,f,g,w,m,P,F,O)=>{let Y,Q,S,ie;if(r==="VALID"&&(r=0),typeof r=="number"){Y={top:r,bottom:r,left:r,right:r,front:r,back:r};let ce=Xu([s,u,f,1],[P,F,O],1,[g,w,m],r);Q=ce[0],S=ce[1],ie=ce[2]}else if(Array.isArray(r)){if(!r.every((pe,ke,Pe)=>pe===Pe[0]))throw Error(`Unsupported padding parameter: ${r}`);Y={top:r[0],bottom:r[1],left:r[2],right:r[3],front:r[4],back:r[5]};let ce=Xu([s,u,f,1],[P,F,O],1,[g,w,m],r[0]);Q=ce[0],S=ce[1],ie=ce[2]}else if(r==="SAME_UPPER"){Q=Math.ceil(s/g),S=Math.ceil(u/w),ie=Math.ceil(f/m);let ce=(Q-1)*g+P-s,pe=(S-1)*w+F-u,ke=(ie-1)*m+O-f,Pe=Math.floor(ce/2),be=ce-Pe,We=Math.floor(pe/2),ze=pe-We,Ge=Math.floor(ke/2),zt=ke-Ge;Y={top:We,bottom:ze,left:Ge,right:zt,front:Pe,back:be}}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:Y,outDepth:Q,outHeight:S,outWidth:ie}},ef=(r,s,u,f,g,w=!1,m="channelsLast")=>{let P,F,O,Y,Q;if(m==="channelsLast")[P,F,O,Y,Q]=r;else if(m==="channelsFirst")[P,Q,F,O,Y]=r;else throw new Error(`Unknown dataFormat ${m}`);let[S,,ie,ce,pe]=s,[ke,Pe,be]=rl(u),[We,ze,Ge]=rl(f),zt=il(ie,We),It=il(ce,ze),Ht=il(pe,Ge),{padInfo:pn,outDepth:wn,outHeight:Xn,outWidth:ar}=Pp(g,F,O,Y,ke,Pe,be,zt,It,Ht),Dn=w?S*Q:S,Cr=[0,0,0,0,0];return m==="channelsFirst"?Cr=[P,Dn,wn,Xn,ar]:m==="channelsLast"&&(Cr=[P,wn,Xn,ar,Dn]),{batchSize:P,dataFormat:m,inDepth:F,inHeight:O,inWidth:Y,inChannels:Q,outDepth:wn,outHeight:Xn,outWidth:ar,outChannels:Dn,padInfo:pn,strideDepth:ke,strideHeight:Pe,strideWidth:be,filterDepth:ie,filterHeight:ce,filterWidth:pe,effectiveFilterDepth:zt,effectiveFilterHeight:It,effectiveFilterWidth:Ht,dilationDepth:We,dilationHeight:ze,dilationWidth:Ge,inShape:r,outShape:Cr,filterShape:s}},tf=(r,s,u,f,g,w)=>{let m=w==="channelsLast";m?r[0].dims[3]:r[0].dims[1];let P=[64,1,1],F={x:u.map((ke,Pe)=>Pe)},O=[Math.ceil(Zd(F.x.map(ke=>u[ke]))/P[0]),1,1];kr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${O}`);let Y=1,Q=mt.size(u),S=[{type:12,data:Q},{type:12,data:f},{type:12,data:g},{type:12,data:s.strides},{type:12,data:s.dilations}];Js(s,S),S.push(...sn(r[0].dims,r[1].dims));let ie=["rank","rank"],ce=r.length===3;ce&&(S.push(...sn(r[2].dims)),ie.push("rank")),S.push(...sn(u));let pe=ke=>{let Pe=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:f.length},{name:"pads",type:"u32",length:g.length},{name:"strides",type:"u32",length:s.strides.length},{name:"dilations",type:"u32",length:s.dilations.length}];To(s,Pe);let be=1,We=lr(r[0].dataType),ze=Bt("x",r[0].dataType,r[0].dims.length,Y),Ge=Bt("W",r[1].dataType,r[1].dims.length,be),zt=[ze,Ge],It=vn("result",r[0].dataType,u.length,be),Ht="";if(ce){let Xn=Bt("bias",r[2].dataType,r[2].dims.length,be);zt.push(Xn),Ht+=` fn getBiasByOutputCoords(coords : array) -> ${We} { return bias[${m?gn("coords",4,5):gn("coords",1,5)}]; }`}let pn=Ti(Y,We),wn=xo(s,pn,We);return` ${Ht} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${ze.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${Ge.getByIndices("aIndices")}; } ${ke.registerUniforms(Pe).declareVariables(...zt,It)} ${ke.mainStart()} ${ke.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${It.offsetToIndices("global_idx")}; let batch = ${gn("coords",0,ze.rank)}; let d2 = ${m?gn("coords",ze.rank-1,ze.rank):gn("coords",1,ze.rank)}; let xFRCCorner = vec3(${m?gn("coords",1,ze.rank):gn("coords",2,ze.rank)}, ${m?gn("coords",2,ze.rank):gn("coords",3,ze.rank)}, ${m?gn("coords",3,ze.rank):gn("coords",4,ze.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${m?gn("uniforms.x_shape",1,ze.rank):gn("uniforms.x_shape",2,ze.rank)}; let xShapeZ = ${m?gn("uniforms.x_shape",2,ze.rank):gn("uniforms.x_shape",3,ze.rank)}; let xShapeW = ${m?gn("uniforms.x_shape",3,ze.rank):gn("uniforms.x_shape",4,ze.rank)}; let xShapeU = ${m?gn("uniforms.x_shape",4,ze.rank):gn("uniforms.x_shape",1,ze.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${m?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${m?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${m?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${m?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${ce?"value = value + getBiasByOutputCoords(coords)":""}; ${wn} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${s.cacheKey};${m};${Y};${ce}`,inputDependencies:ie},getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:O[0],y:O[1],z:O[2]},programUniforms:S}),getShaderSource:pe}}}),xa,nf,$p=c(()=>{Pn(),Mn(),Vn(),nc(),Wi(),xa=(r,s,u)=>{let f=r.length>2,g=f?"value += b[output_channel];":"",w=r[0].dims,m=r[1].dims,P=m[0]/s.group,F=s.format==="NHWC",O=Yu(w,m,s.dilations,s.pads,s.strides,F),Y=mt.size(O),Q=[{type:12,data:Y},{type:12,data:s.dilations},{type:12,data:[s.strides[0],s.strides[1]]},{type:12,data:[s.pads[0],s.pads[1]]},{type:12,data:P}];Js(s,Q),Q.push(...sn(w,m));let S=["rank","rank"];f&&(Q.push(...sn(r[2].dims)),S.push("rank")),Q.push(...sn(O));let ie=ce=>{let pe=vn("output",r[0].dataType,O.length),ke=lr(pe.type.tensor),Pe=xo(s,pe.type.value,ke),be=Bt("x",r[0].dataType,w.length),We=Bt("w",r[1].dataType,m.length),ze=[be,We];f&&ze.push(Bt("b",r[2].dataType,r[2].dims.length));let Ge=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:s.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return To(s,Ge),` ${ce.registerUniforms(Ge).declareVariables(...ze,pe)} ${ce.mainStart()} ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${pe.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${F?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${F?1:2}], outputIndices[${F?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${pe.type.value} = ${pe.type.value}(0); for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = group_id * uniforms.w_shape[1] + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[${F?1:2}]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[${F?2:3}]) { continue; } let xVal = ${F?be.get("batch","xHeight","xWidth","input_channel"):be.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${We.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${g} ${Pe} ${pe.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:s.cacheKey,inputDependencies:S},getRunData:()=>({outputs:[{dims:u?u(O):O,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(Y/64)},programUniforms:Q}),getShaderSource:ie}},nf=(r,s,u,f)=>{let g=r.length>2,w=nr(u[3]),m=nr(u[2]),P=mt.size(u)/w/m,F=[r[0].dims[0],r[0].dims[1],r[0].dims[2],r[0].dims[3]/w],O=[r[1].dims[0],r[1].dims[1],r[1].dims[2],r[1].dims[3]/w],Y=[u[0],u[1],u[2],u[3]/w],Q=[{type:12,data:P},{type:6,data:[s.strides[0],s.strides[1]]},{type:6,data:[s.pads[0],s.pads[1]]}];Js(s,Q),Q.push(...sn(F,O,Y));let S=(m-1)*s.strides[1]+O[1],ie=ce=>{let pe=vn("output",r[0].dataType,Y.length,w),ke=lr(pe.type.tensor),Pe=xo(s,pe.type.value,ke),be=Bt("x",r[0].dataType,F.length,w),We=Bt("w",r[1].dataType,O.length,w),ze=[be,We];g&&ze.push(Bt("b",r[2].dataType,r[2].dims,w));let Ge=g?"value += b[output_channel];":"",zt=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return To(s,zt),` ${ce.registerUniforms(zt).declareVariables(...ze,pe)} ${ce.mainStart()} ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${m}u; let col = (index1 % width1) * ${m}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${be.type.value}, ${S}>; var values: array<${pe.type.value}, ${m}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${O[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${S}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${be.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${be.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${O[1]}; w_width++) { let w_val = ${We.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${m}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${m}u; i++) { var value = values[i]; ${Ge} ${Pe} ${pe.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${s.cacheKey};${w};${m};${S};${O[0]};${O[1]}`,inputDependencies:g?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:f?f(u):u,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:Q}),getShaderSource:ie}}}),Qu,rf,sf,Ql=c(()=>{Pn(),Mn(),Ko(),Vn(),Wi(),Qu=(r,s,u,f,g=!1,w)=>{let m=r[0].dims,P=r[1].dims,F=m[m.length-2],O=P[P.length-1],Y=m[m.length-1],Q=nr(O),S=nr(Y),ie=nr(F),ce=mt.size(u)/Q/ie,pe=r.length>2,ke=f?f.slice(0,-2):u.slice(0,-2),Pe=[mt.size(ke),F,O],be=[{type:12,data:ce},{type:12,data:F},{type:12,data:O},{type:12,data:Y}];Js(s,be),be.push(...sn(ke,m,P)),pe&&be.push(...sn(r[2].dims)),be.push(...sn(Pe));let We=ze=>{let Ge=mo("batch_dims",r[0].dataType,ke.length),zt=Bt("a",r[0].dataType,m.length,S),It=Bt("b",r[1].dataType,P.length,Q),Ht=vn("output",r[0].dataType,Pe.length,Q),pn=lr(Ht.type.tensor),wn=xo(s,Ht.type.value,pn),Xn=[zt,It],ar="";if(pe){let vr=g?Q:1;Xn.push(Bt("bias",r[2].dataType,r[2].dims.length,vr)),ar=`${g?`value += bias[col / ${vr}];`:`value += ${Ht.type.value}(bias[row + i]);`}`}let Dn=m.slice(0,-2),Cr=P.slice(0,-2),Vr=go(Dn,ke),fr=go(Cr,ke),Or=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];To(s,Or);let Fn=(vr,Ft)=>{let an=vr.rank,Nn=vr.name;if(an===2)return`var ${Nn}_indices = ${vr.type.indices}(0u, 0u);`;let Pr=Ge.rank,ai=`var ${Nn}_indices: ${vr.type.indices};`;for(let ki=an-2-1,ll=Pr-1;ki>=0;ki--,ll--)ai+=` ${Nn}_indices[${ki}] = ${Pr>1?`batch_indices[${ll}]`:"batch_indices"};`;return Ft.forEach(ki=>{ai+=` ${Nn}_indices[${ki}] = 0;`}),ai+=`${Nn}_indices[${an-2}] = 0u; ${Nn}_indices[${an-1}] = 0u;`,ai},sr=()=>{let vr=`var a_data: ${zt.type.value};`;for(let Ft=0;Ft; for (var k: u32 = 0u; k < uniforms.K; k = k + ${S}) { ${sr()} } for (var i = 0u; i < ${ie}u; i++) { var value = values[i]; ${ar} ${wn} let cur_indices = ${Ht.type.indices}(batch, row + i, col); let offset = ${Ht.indicesToOffset("cur_indices")}; ${Ht.setByOffset(`offset / ${Q}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${s.activation};${Q};${S};${ie};${g}`,inputDependencies:pe?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:w?w(u):u,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(ce/64)},programUniforms:be}),getShaderSource:We}},rf=r=>{if(!r||r.length!==2)throw new Error("MatMul requires 2 inputs.");if(r[0].dims[r[0].dims.length-1]!==r[1].dims[r[1].dims.length-2])throw new Error("shared dimension does not match.")},sf=r=>{rf(r.inputs);let s=Qr.calcShape(r.inputs[0].dims,r.inputs[1].dims,!0);if(!s)throw new Error("Can't use matmul on the given tensors");let u=s[s.length-1],f=r.inputs[0].dims[r.inputs[0].dims.length-1];u<8&&f<8?r.compute(Qu(r.inputs,{activation:""},s)):r.compute(Ku(r.inputs,{activation:""},s))}}),Yu,Yl,of,Zl,Zu,Ju,ec,af,tc,nc=c(()=>{Mn(),Cp(),Ap(),Ko(),$p(),Wi(),Ql(),yo(),Yu=(r,s,u,f,g,w)=>{let m=r[0],P=r.slice(w?1:2,w?3:4),F=P.length,O=s[0],Y=s.slice(2).map((S,ie)=>S+(S-1)*(u[ie]-1)),Q=P.map((S,ie)=>S+f[ie]+f[ie+F]).map((S,ie)=>Math.floor((S-Y[ie]+g[ie])/g[ie]));return Q.splice(0,0,m),Q.splice(w?3:1,0,O),Q},Yl=[2,3,1,0],of=(r,s)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length>5)throw new Error("greater than 5D is not supported");if(r[0].dims.length!==r[1].dims.length)throw new Error("filter does not have same dimension as input");let u=r[0].dims[s.format==="NHWC"?r[0].dims.length-1:1],f=r[1].dims[1]*s.group;if(u!==f)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(r.length===3&&(r[2].dims.length!==1||r[1].dims[0]!==r[2].dims[0]))throw new Error("invalid bias");let g=r[0].dims.length-2;if(s.dilations.length!==g)throw new Error(`dilations should be ${g}D`);if(s.strides.length!==g)throw new Error(`strides should be ${g}D`);if(s.pads.length!==g*2)throw new Error(`pads should be ${g*2}D`);if(s.kernelShape.length!==0&&s.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape")},Zl=(r,s)=>{let u=r.kernelShape.slice();for(let w=2;w{let s=Uu(r),u=r.format,f=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][r.auto_pad],g=r.dilations,w=r.group,m=r.kernel_shape,P=r.pads,F=r.strides,O=r.w_is_const();return{autoPad:f,format:u,dilations:g,group:w,kernelShape:m,pads:P,strides:F,wIsConst:O,...s,cacheKey:`${r.format};${s.activation};`}},Ju=(r,s,u,f)=>{let g=u.format==="NHWC";if(u.group!==1){if(!r.adapterInfo.isArchitecture("ampere")&&g&&s[1].dims[0]===u.group&&s[1].dims[1]===1&&u.dilations[0]===1&&u.dilations[1]===1){let zt=Yu(s[0].dims,s[1].dims,u.dilations,u.pads,u.strides,g),It=r.kernelCustomData.wT??r.compute(Oi(s[1],Yl),{inputs:[1],outputs:[u.wIsConst?-2:-1]})[0];u.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=It);let Ht=[s[0],It];s.length===3&&Ht.push(s[2]),r.compute(nf(Ht,u,zt,f),{inputs:Ht})}else r.compute(xa(s,u,f));return}let w=s.length===3,m=s[0].dims[g?1:2],P=s[0].dims[g?2:3],F=s[0].dims[g?3:1],O=s[1].dims[2],Y=s[1].dims[3],Q=Yu(s[0].dims,s[1].dims,u.dilations,u.pads,u.strides,g),S=Q[g?1:2],ie=Q[g?2:3],ce=Q[g?3:1],pe=g&&O===m&&Y===P&&u.pads[0]===0&&u.pads[1]===0;if(pe||O===1&&Y===1&&u.dilations[0]===1&&u.dilations[1]===1&&u.strides[0]===1&&u.strides[1]===1&&u.pads[0]===0&&u.pads[1]===0){let zt=Q[0],It,Ht,pn,wn=[];if(g){let Dn=r.kernelCustomData.wT??r.compute(Oi(s[1],Yl),{inputs:[1],outputs:[u.wIsConst?-2:-1]})[0];if(u.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=Dn),pe){let Cr=m*P*F;It=s[0].reshape([1,zt,Cr]),Ht=Dn.reshape([1,Cr,ce]),pn=[1,zt,ce]}else It=s[0].reshape([zt,m*P,F]),Ht=Dn.reshape([1,F,ce]),pn=[zt,S*ie,ce];wn.push(It),wn.push(Ht)}else It=s[0].reshape([zt,F,m*P]),Ht=s[1].reshape([1,ce,F]),pn=[zt,ce,S*ie],wn.push(Ht),wn.push(It);w&&wn.push(s[2]);let Xn=pn[2],ar=wn[0].dims[wn[0].dims.length-1];Xn<8&&ar<8?r.compute(Qu(wn,u,Q,pn,g,f),{inputs:wn}):r.compute(Ku(wn,u,Q,pn,g,f),{inputs:wn});return}let ke=!0,Pe=r.kernelCustomData.wT??r.compute(Oi(s[1],Yl),{inputs:[1],outputs:[u.wIsConst?-2:-1]})[0];u.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=Pe);let be=[s[0],Pe];w&&be.push(s[2]);let We=g?S*ie:ce,ze=g?ce:S*ie,Ge=O*Y*F;r.compute(Yd(be,u,Q,We,ze,Ge,w,ke,f),{inputs:be})},ec=(r,s)=>{let u=s.format==="NHWC",f=[r.inputs[0].reshape(u?[r.inputs[0].dims[0],1,r.inputs[0].dims[1],r.inputs[0].dims[2]]:[r.inputs[0].dims[0],r.inputs[0].dims[1],1,r.inputs[0].dims[2]]),r.inputs[1].reshape([r.inputs[1].dims[0],r.inputs[1].dims[1],1,r.inputs[1].dims[2]])];r.inputs.length===3&&f.push(r.inputs[2]);let g=[0,s.pads[0],0,s.pads[1]],w=[1].concat(s.strides),m=[1].concat(s.dilations),P=[1].concat(s.kernelShape),F=Zl({...s,pads:g,strides:w,dilations:m,kernelShape:P},f);Ju(r,f,F,O=>u?[O[0],O[2],O[3]]:[O[0],O[1],O[3]])},af=(r,s,u)=>{let f=u.format==="NHWC"?"channelsLast":"channelsFirst",g=Zl(u,s),w=u.autoPad==="NOTSET"?u.pads:u.autoPad,m=ef(s[0].dims,s[1].dims,u.strides,u.dilations,w,!1,f);r.compute(tf(s,g,m.outShape,[m.filterDepth,m.filterHeight,m.filterWidth],[m.padInfo.front,m.padInfo.top,m.padInfo.left],f))},tc=(r,s)=>{if(of(r.inputs,s),r.inputs[0].dims.length===3)ec(r,s);else if(r.inputs[0].dims.length===5)af(r,r.inputs,s);else{let u=Zl(s,r.inputs);Ju(r,r.inputs,u)}}}),lf,uf,cf=c(()=>{Pn(),_i(),Vn(),Wi(),ql(),qu(),Ko(),lf=(r,s=!1,u,f,g=4)=>{let w=ke=>{switch(ke){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return ${f}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${ke} is not supported.`)}},m=r?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,P=r?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,F=r?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",O=r?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Y=r?"row":"col",Q=r?"col":"row",S=` let inChannels = ${r?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${Y} / outWidth; let outCol = ${Y} % outWidth; let WRow = ${Q} / (uniforms.filter_dims[1] * inChannels); let WCol = ${Q} / inChannels % uniforms.filter_dims[1]; let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); if (xR < 0.0 || xR >= f32(${F}) || fract(xR) > 0.0) { return ${f}(0.0); } if (xC < 0.0 || xC >= f32(${O}) || fract(xC) > 0.0) { return ${f}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${Q} % inChannels; ${m} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${g}];`,ie=r?` let col = colIn * ${g}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${S} } return ${f}(0.0);`:` let col = colIn * ${g}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${S} } return ${f}(0.0);`,ce=` let col = colIn * ${g}; let inChannels = ${r?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; if (${r?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${w(g)} } return ${f}(0.0); `,pe=xo(u,f);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${f} { ${r?ie:ce} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${f} { ${r?ce:ie} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${f}) { let col = colIn * ${g}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueInput; let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${P} ${Wu(s)} ${pe} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${g}] = value; } }`},uf=(r,s,u,f,g,w,m,P)=>{let F=s.format==="NHWC",O=F?r[0].dims[3]:r[0].dims[1],Y=u[0],Q=F?u[2]:u[3],S=F?u[1]:u[2],ie=F?u[3]:u[1],ce=F&&O%4===0&&O%3&&ie%4===0,pe=F?ie:Q*S,ke=F?Q*S:ie,Pe=[8,8,1],be=f<=8?[4,1,1]:[4,4,1],We=[Math.ceil(pe/Pe[0]/be[0]),Math.ceil(ke/Pe[1]/be[1]),Math.ceil(Y/Pe[2]/be[2])];kr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${We}`);let ze=ce?4:1,Ge=Math.max(Pe[0]*ze,Pe[1]),zt=ce?4:1,It=[s.kernelShape[F?1:2],s.kernelShape[F?2:3]],Ht=[It[0]+(s.dilations[0]<=1?0:(It[0]-1)*(s.dilations[0]-1)),It[1]+(s.dilations[1]<=1?0:(It[1]-1)*(s.dilations[1]-1))],pn=[Ht[0]-1-Math.floor((s.pads[0]+s.pads[2])/2),Ht[1]-1-Math.floor((s.pads[1]+s.pads[3])/2)],wn=[{type:6,data:f},{type:6,data:g},{type:6,data:w},{type:6,data:s.strides},{type:6,data:s.dilations},{type:6,data:It},{type:6,data:pn}];Js(s,wn),wn.push(...sn(r[0].dims,r[1].dims));let Xn=["rank","rank"];m&&(wn.push(...sn(r[2].dims)),Xn.push("rank")),wn.push(...sn(u));let ar=Dn=>{let Cr=Bt("x",r[0].dataType,r[0].dims.length,zt),Vr=Bt("w",r[1].dataType,r[1].dims.length,1),fr=vn("result",r[0].dataType,u.length,zt),Or=[Cr,Vr],Fn="";if(m){let Ft=Bt("bias",r[2].dataType,r[2].dims.length,zt);Or.push(Ft),Fn+=` fn getBiasByOutputCoords(coords : vec4) -> ${Ft.type.value} { return bias[coords.${F?"w":"y"}${ce?"/ 4":""}]; }`}let sr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:It.length},{name:"pads",type:"i32",length:pn.length}];To(s,sr);let vr=lr(r[0].dataType,1);if(vr!=="f16"&&vr!=="f32")throw new Error(`elemType ${vr} is not supported.`);return` ${Gu("uniforms.result_strides")} ${Dn.registerUniforms(sr).declareVariables(...Or,fr)}; ${Fn} ${lf(F,m,s,Cr.type.value,ze)} ${ce?Hl(be,Pe,vr,void 0,!F,Ge):Xl(be,Pe,vr,void 0,!F,Ge,!1,void 0,P)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${s.cacheKey};${be};${Pe};${ce}`,inputDependencies:Xn},getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:We[0],y:We[1],z:We[2]},programUniforms:wn}),getShaderSource:ar}}}),df,rc,ic=c(()=>{Pn(),_i(),Mn(),Vn(),df=(r,s,u,f,g,w=!1,m,P,F=!1)=>{let O=F?1:2,Y=F?2:3,Q=F?3:1,S=w?2:1,ie=` fn setOutputAtIndex(flatIndex : u32, value : ${w?`vec4<${m}>`:m}) { result[flatIndex] = ${w?`vec4<${m}>`:m}(value); }`;f&&(ie+=` fn getBiasByOutputCoords(coords : vec4) -> ${w?`vec4<${m}>`:m} { return bias[coords.${F?"w":"y"}${w?"/ 4":""}]; }`);let ce=w?4:1,pe=Bt("W",s[1].dataType,s[1].dims.length,ce),ke=Bt("Dy",s[0].dataType,s[0].dims.length,ce),Pe=[ke,pe];f&&Pe.push(Bt("bias",s[2].dataType,[u[Q]].length,ce));let be=vn("result",s[0].dataType,u.length,ce),We=`{ let batch: u32 = ${g?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${g?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${g?"global_id.y":"workgroup_id.y"} * ${S}; let d1: u32 = ${g?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${S}>; for (var i = 0; i < ${S}; i++) { dotProd[i] = vec4<${m}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${m}(dyCorner.x) + ${m}(wR)) / ${m}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${m}(uniforms.Dy_shape[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { let dyC = (${m}(dyCorner.y) + ${m}(wC)) / ${m}(uniforms.strides.y); let dyC2 = (${m}(dyCorner.y) + 1.0 + ${m}(wC)) / ${m}(uniforms.strides.y); let wCPerm = uniforms.filter_dims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${m}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${m}(uniforms.Dy_shape[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${ke.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${m}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${ke.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${m}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${Q}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${ke.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${m}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = uniforms.Dy_shape[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${pe.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${ke.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${m}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${S}; i = i + 1) { let value = dotProd[i] + ${f?"bias[c+i]":`vec4<${m}>(0.0)`}; ${be.set("batch","r","c + i","d1","value")}; } }`,ze=` let outputIndices = ${be.offsetToIndices("global_idx")}; let batch = ${be.indicesGet("outputIndices",0)}; let d1 = ${be.indicesGet("outputIndices",Q)}; let r = ${be.indicesGet("outputIndices",O)}; let c = ${be.indicesGet("outputIndices",Y)}; let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / uniforms.output_channels_per_group; let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${m}(0.0); for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { if (wR % uniforms.dilations.x != 0) { continue; } let dyR = (${m}(dyRCorner) + ${m}(wR)) / ${m}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${m}(uniforms.Dy_shape[${O}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { if (wC % uniforms.dilations.y != 0) { continue; } let dyC = (${m}(dyCCorner) + ${m}(wC)) / ${m}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${m}(uniforms.Dy_shape[${Y}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { let xValue = ${F?ke.get("batch","idyR","idyC","inputChannel"):ke.get("batch","inputChannel","idyR","idyC")}; let wValue = ${pe.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${f?"bias[d1]":`${m}(0.0)`}; ${be.setByOffset("global_idx","value")}; `;return` ${r.registerUniforms(P).declareVariables(...Pe,be)} ${ie} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${w?We:ze}}`},rc=(r,s,u)=>{let f=r.length>2,g=s.outputShape,w=mt.size(g),m=[Math.ceil(w/64),1,1];kr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${m}`);let P=s.format==="NHWC",F=["rank","rank"],O=[s.strides[0],s.strides[1]],Y=[s.kernelShape[P?1:2],s.kernelShape[P?2:3]],Q=[s.dilations[0],s.dilations[1]],S=[Y[0]+(s.dilations[0]<=1?0:(s.kernelShape[P?1:2]-1)*(s.dilations[0]-1)),Y[1]+(s.dilations[1]<=1?0:(s.kernelShape[P?2:3]-1)*(s.dilations[1]-1))],ie=[S[0]-1-Math.floor((s.pads[0]+s.pads[2])/2),S[1]-1-Math.floor(s.pads[1]+s.pads[3])/2],ce=!1,pe=s.group,ke=r[1].dims,Pe=ke[0]/pe,be=ke[1],We=[{type:12,data:w},{type:12,data:O},{type:12,data:Y},{type:12,data:Q},{type:12,data:S},{type:6,data:ie},{type:12,data:Pe},{type:12,data:be},...sn(r[0].dims,r[1].dims)];f&&(We.push(...sn(r[2].dims)),F.push("rank")),We.push(...sn(g));let ze=m[1]===1&&m[2]===1,Ge=zt=>{let It=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:O.length},{name:"filter_dims",type:"u32",length:Y.length},{name:"dilations",type:"u32",length:Y.length},{name:"effective_filter_dims",type:"u32",length:S.length},{name:"pads",type:"i32",length:ie.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Ht=lr(r[0].dataType);return`${df(zt,r,g,f,ze,ce,Ht,It,P)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${s.cacheKey};`,inputDependencies:F},getRunData:()=>({dispatchGroup:{x:m[0],y:m[1],z:m[2]},outputs:[{dims:u?u(g):g,dataType:r[0].dataType}],programUniforms:We}),getShaderSource:Ge}}}),ff,hf,pf,sc,oc,Jl,Ip,mf,gf,ac,Fp=c(()=>{cf(),ic(),Wi(),yo(),ff=(r,s,u,f,g,w)=>(r-1)*s+u+(f-1)*g+1-w,hf=(r,s,u,f,g)=>{let w=Math.floor(r/2);s==="SAME_UPPER"?(u[f]=w,u[g]=r-w):s==="SAME_LOWER"&&(u[f]=r-w,u[g]=w)},pf=(r,s,u,f,g,w,m,P,F,O)=>{let Y=r.length-2,Q=O.length===0;if(F.length===0)for(let ce=0;ce{let u=r.kernelShape.slice();if(r.kernelShape.length===0||r.kernelShape.reduce((Q,S)=>Q*S,1)===0){u.length=0;for(let Q=2;QQ+S,0)===0){let Q=s[0].dims.length-2;F=new Array(Q).fill(1)}let O=r.strides.slice();if(O.reduce((Q,S)=>Q+S,0)===0){let Q=s[0].dims.length-2;O=new Array(Q).fill(1)}pf(P,u,F,r.autoPad,r.group,g,O,f,m,w);let Y=Object.assign({},r);return Object.assign(Y,{kernelShape:u,pads:g,outputPadding:m,outputShape:w,dilations:F,strides:O}),Y},oc=r=>{let s=Uu(r),u=r.format,f=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof r.autoPad>"u"?0:r.autoPad],g=r.dilations,w=r.group,m=r.kernelShape,P=r.pads,F=r.strides,O=r.wIsConst(),Y=r.outputPadding,Q=r.outputShape;return{autoPad:f,format:u,dilations:g,group:w,kernelShape:m,outputPadding:Y,outputShape:Q,pads:P,strides:F,wIsConst:O,...s,cacheKey:`${r.format};${s.activation};`}},Jl=(r,s)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length!==4&&r[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(r[0].dims.length!==r[1].dims.length)throw new Error("filter does not have same dimension as input");let u=r[0].dims[s.format==="NHWC"?r[0].dims.length-1:1],f=r[1].dims[0];if(u!==f)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let g=r[1].dims[1]*s.group;if(r.length===3&&(r[2].dims.length!==1||r[2].dims[0]!==g))throw new Error("invalid bias");let w=r[0].dims.length-2;if(s.dilations.reduce((m,P)=>m+P,0)>0&&s.dilations.length!==w)throw new Error(`dilations should be ${w}D`);if(s.strides.reduce((m,P)=>m+P,0)>0&&s.strides.length!==w)throw new Error(`strides should be ${w}D`);if(s.pads.reduce((m,P)=>m+P,0)>0&&s.pads.length!==w*2)throw new Error(`pads should be ${w*2}D`);if(s.outputPadding.length!==w&&s.outputPadding.length!==0)throw new Error(`output_padding should be ${w}D`);if(s.kernelShape.reduce((m,P)=>m+P,0)>0&&s.kernelShape.length!==0&&s.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape");if(s.outputShape.length!==0&&s.outputShape.length!==r[0].dims.length-2)throw new Error("invalid output shape")},Ip=[2,3,1,0],mf=(r,s,u)=>{let f=sc(u,s),g=u.format==="NHWC",w=f.outputShape,m=w[g?3:1],P=s[0].dims[g?3:1];if(f.group!==1||m===1&&P===1){r.compute(rc(s,f));return}let F=w[g?1:2],O=w[g?2:3],Y=s[1].dims[2],Q=s[1].dims[3],S=g?F*O:m,ie=g?m:F*O,ce=Y*Q*P,pe=!0,ke=r.kernelCustomData.wT??r.compute(Oi(s[1],Ip),{inputs:[1],outputs:[u.wIsConst?-2:-1]})[0];u.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=ke);let Pe=[s[0],ke],be=s.length===3;be&&(!g&&s[2].dims.length===1?Pe.push(s[2].reshape([s[2].dims[0],1,1])):Pe.push(s[2])),r.compute(uf(Pe,f,w,S,ie,ce,be,pe),{inputs:Pe})},gf=(r,s)=>{let u=s.format==="NHWC",f=[r.inputs[0].reshape(u?[r.inputs[0].dims[0],1,r.inputs[0].dims[1],r.inputs[0].dims[2]]:[r.inputs[0].dims[0],r.inputs[0].dims[1],1,r.inputs[0].dims[2]]),r.inputs[1].reshape([r.inputs[1].dims[0],r.inputs[1].dims[1],1,r.inputs[1].dims[2]])];r.inputs.length===3&&f.push(r.inputs[2]);let g=s.kernelShape;(g.length===0||g[0]===0)&&(g=[r.inputs[1].dims[2]]);let w=s.dilations;(w.length===0||w[0]===0)&&(w=[1]);let m=s.strides;(m.length===0||m[0]===0)&&(m=[1]);let P=s.pads;P.length===0&&(P=[0,0]),P=[0,P[0],0,P[1]],m=[1].concat(m),w=[1].concat(w),g=[1].concat(g);let F=sc({...s,pads:P,strides:m,dilations:w,kernelShape:g},f);r.compute(rc(f,F,O=>u?[O[0],O[2],O[3]]:[O[0],O[1],O[3]]))},ac=(r,s)=>{Jl(r.inputs,s),r.inputs[0].dims.length===3?gf(r,s):mf(r,r.inputs,s)}}),_f,lc,yf,Op=c(()=>{Pn(),Mn(),Bn(),Vn(),_f=(r,s,u,f)=>{let g=mt.size(s),w=s.length,m=Bt("input",r,w),P=vn("output",r,w),F=u.dataType===6?u.getInt32Array()[0]:Number(u.getBigInt64Array()[0]),O=mt.normalizeAxis(F,w),Y=Q=>{let S=` i32(${m.indicesGet("inputIndices","uniforms.axis")}) `,ie=gn("uniforms.input_shape","uniforms.axis",w),ce=f.reverse?S+(f.exclusive?" + 1":""):"0",pe=f.reverse?ie:S+(f.exclusive?"":" + 1");return` ${Q.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(m,P)} ${Q.mainStart()} ${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${P.offsetToIndices("global_idx")}; var sum = ${P.type.value}(0); let first : i32 = ${ce}; let last : i32 = ${pe}; for (var i : i32 = first; i < last; i++) { ${m.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${m.getByIndices("inputIndices")}; } ${P.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:f.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},{type:12,data:O},...sn(s,s)]}),getShaderSource:Y}},lc=(r,s)=>{let u=r.inputs[0].dims,f=r.inputs[0].dataType,g=r.inputs[1];r.compute(_f(f,u,g,s),{inputs:[0]})},yf=r=>{let s=r.exclusive===1,u=r.reverse===1;return bn({exclusive:s,reverse:u})}}),uc,Dp,zp,cc,dc,Rp=c(()=>{Pn(),Mn(),Bn(),Vn(),uc=r=>{if(!r||r.length!==1)throw new Error("DepthToSpace requires 1 input.");if(r[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Dp=(r,s,u,f)=>{let g=[];g.push(`fn perm(i: ${f.type.indices}) -> ${u.type.indices} { var a: ${u.type.indices};`);for(let w=0;w{let u,f,g,w,m,P,F=s.format==="NHWC",O=s.blocksize,Y=s.mode==="DCR";F?([u,f,g,w]=r.dims,m=Y?[u,f,g,O,O,w/O**2]:[u,f,g,w/O**2,O,O],P=Y?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([u,f,g,w]=[r.dims[0],r.dims[2],r.dims[3],r.dims[1]],m=Y?[u,O,O,w/O**2,f,g]:[u,w/O**2,O,O,f,g],P=Y?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let Q=r.reshape(m),S=Q.dims.length,ie=r.dataType,ce=Bt("a",ie,S),pe=vn("output",ie,S),ke=Pe=>` ${Pe.registerUniform("output_size","u32").declareVariables(ce,pe)} ${Dp(P,S,ce,pe)} ${Pe.mainStart()} ${Pe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${pe.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${pe.setByOffset("global_idx",ce.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${r.dims};${s.blocksize};${s.mode}`,inputDependencies:["rank"]},getRunData:Pe=>{let be=F?[u,f*O,g*O,w/O**2]:[u,w/O**2,f*O,g*O],We=mt.size(be),ze=Q.dims,Ge=mt.sortBasedOnPerm(ze,P);return{outputs:[{dims:be,dataType:Pe[0].dataType}],dispatchGroup:{x:Math.ceil(We/64)},programUniforms:[{type:12,data:We},...sn(ze,Ge)]}},getShaderSource:ke}},cc=(r,s)=>{uc(r.inputs),r.compute(zp(r.inputs[0],s))},dc=r=>bn({blocksize:r.blocksize,mode:r.mode,format:r.format})}),eu,Ta,fc,vf,hc,wf,bf,tu,xf,Tf,xr,s_=c(()=>{Pn(),Mn(),Bn(),Vn(),eu="[a-zA-Z]|\\.\\.\\.",Ta="("+eu+")+",fc="^"+Ta+"$",vf="("+Ta+",)*"+Ta,hc="^"+vf+"$",wf=class{constructor(r=-1){this.symbolToIndices=new Map,this.inputIndex=r}addSymbol(r,s){let u=this.symbolToIndices.get(r);u===void 0?u=[s]:u.push(s),this.symbolToIndices.set(r,u)}},bf=class{constructor(r,s){var g;this.equation=s,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[u,f]=s.includes("->")?s.split("->",2):[s,""];if(!u.match(RegExp(hc)))throw new Error("Invalid LHS term");if(u.split(",").forEach((w,m)=>{let P=r[m].dims.slice();if(!w.match(RegExp(fc)))throw new Error("Invalid LHS term");let F=this.processTerm(w,!0,P,m);this.lhs.push(F)}),f==="")f+=[...this.symbolToInfo.entries()].filter(([w,m])=>m.count===1||w==="...").map(([w])=>w).join("");else if(!f.match(RegExp(Ta)))throw new Error("Invalid RHS");(g=f.match(RegExp(eu,"g")))==null||g.forEach(w=>{if(w==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let m=this.symbolToInfo.get(w);if(m===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(m.dimValue)}}),this.rhs=this.processTerm(f,!1,this.outputDims)}addSymbol(r,s,u){let f=this.symbolToInfo.get(r);if(f!==void 0){if(f.dimValue!==s&&f.count!==1)throw new Error("Dimension mismatch");f.count++,f.inputIndices.push(u)}else f={count:1,dimValue:s,inputIndices:[u]};this.symbolToInfo.set(r,f)}processTerm(r,s,u,f=-1){let g=u.length,w=!1,m=[],P=0;if(!r.match(RegExp(fc))&&!s&&r!=="")throw new Error("Invalid LHS term");let F=r.match(RegExp(eu,"g")),O=new wf(f);return F==null||F.forEach((Y,Q)=>{if(Y==="..."){if(w)throw new Error("Only one ellipsis is allowed per input term");w=!0;let S=g-F.length+1;if(S<0)throw new Error("Ellipsis out of bounds");if(m=u.slice(P,P+S),this.hasEllipsis){if(this.ellipsisDims.length!==m.length||this.ellipsisDims.toString()!==m.toString())throw new Error("Ellipsis dimensions mismatch")}else if(s)this.hasEllipsis=!0,this.ellipsisDims=m;else throw new Error("Ellipsis must be specified in the LHS");for(let ie=0;ier+"_max",xf=(r,s,u,f)=>{let g=r.map(O=>O.length).map((O,Y)=>Bt(`input${Y}`,s,O)),w=mt.size(f),m=vn("output",s,f.length),P=[...u.symbolToInfo.keys()].filter(O=>!u.rhs.symbolToIndices.has(O)),F=O=>{let Y=[],Q="var prod = 1.0;",S="var sum = 0.0;",ie="sum += prod;",ce=[],pe=[],ke=[],Pe=[],be=u.symbolToInfo.size===u.rhs.symbolToIndices.size;u.symbolToInfo.forEach((ze,Ge)=>{var zt;if(u.rhs.symbolToIndices.has(Ge)){let It=(zt=u.rhs.symbolToIndices.get(Ge))==null?void 0:zt[0];It!==void 0&&u.lhs.forEach((Ht,pn)=>{if(ze.inputIndices.includes(pn)){let wn=Ht.symbolToIndices.get(Ge);if(wn===void 0)throw new Error("Invalid symbol error");wn.forEach(Xn=>{Y.push(`${g[pn].indicesSet(`input${pn}Indices`,Xn,m.indicesGet("outputIndices",It))}`)})}})}else u.lhs.forEach((It,Ht)=>{if(ze.inputIndices.includes(Ht)){let pn=It.symbolToIndices.get(Ge);if(pn===void 0)throw new Error("Invalid symbol error");pn.forEach(wn=>{ce.push(`${g[Ht].indicesSet(`input${Ht}Indices`,wn,`${Ge}`)}`)}),Pe.push(`prod *= ${g[Ht].getByIndices(`input${Ht}Indices`)};`)}}),pe.push(`for(var ${Ge}: u32 = 0; ${Ge} < uniforms.${tu(Ge)}; ${Ge}++) {`),ke.push("}")});let We=be?[...Y,`let sum = ${g.map((ze,Ge)=>ze.getByIndices(`input${Ge}Indices`)).join(" * ")};`]:[...Y,S,...pe,...ce,Q,...Pe,ie,...ke];return` ${O.registerUniforms(P.map(ze=>({name:`${tu(ze)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...g,m)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${m.offsetToIndices("global_idx")}; ${g.map((ze,Ge)=>`var input${Ge}Indices: ${g[Ge].type.indices};`).join(` `)} ${We.join(` `)}; ${m.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:u.equation,inputDependencies:r.map(()=>"rank")},getRunData:()=>{let O=P.filter(Q=>u.symbolToInfo.has(Q)).map(Q=>{var S;return{type:12,data:((S=u.symbolToInfo.get(Q))==null?void 0:S.dimValue)||0}});O.push({type:12,data:w});let Y=r.map((Q,S)=>[...sn(Q)]).reduce((Q,S)=>Q.concat(S),O);return Y.push(...sn(f)),{outputs:[{dims:f,dataType:s}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:Y}},getShaderSource:F}},Tf=(r,s)=>{let u=new bf(r.inputs,s.equation),f=u.outputDims,g=r.inputs.map((w,m)=>w.dims);r.compute(xf(g,r.inputs[0].dataType,u,f))},xr=r=>{let s=r.equation.replace(/\s+/g,"");return bn({equation:s})}}),Lp,Mf,pc,kf,Sf,Bp=c(()=>{Pn(),Mn(),Vn(),Lp=r=>{if(!r||r.length!==2)throw new Error("Expand requires 2 input.");let s=r[0].dims,u=Array.from(r[1].getBigInt64Array(),Number),f=u.length{let u=r.length-s.length,f=[];for(let g=0;gr.length>s.length?Mf(r,s):Mf(s,r),kf=r=>{let s=r[0].dims,u=Array.from(r[1].getBigInt64Array(),Number),f=pc(s,u),g=r[0].dataType,w=g===9?4:1,m=Math.ceil(mt.size(f)/w),P=O=>{let Y=Bt("input",g,s.length,w),Q=vn("output",g,f.length,w),S;if(g===9){let ie=(ce,pe,ke="")=>` let outputIndices${pe} = ${Q.offsetToIndices(`outputOffset + ${pe}u`)}; let offset${pe} = ${Y.broadcastedIndicesToOffset(`outputIndices${pe}`,Q)}; let index${pe} = offset${pe} / 4u; let component${pe} = offset${pe} % 4u; ${ce}[${pe}] = ${ke}(${Y.getByOffset(`index${pe}`)}[component${pe}]); `;S=` let outputOffset = global_idx * ${w}; var data = vec4(0); ${ie("data",0,"u32")} ${ie("data",1,"u32")} ${ie("data",2,"u32")} ${ie("data",3,"u32")} ${Q.setByOffset("global_idx","data")} }`}else S=` let outputIndices = ${Q.offsetToIndices("global_idx")}; let inputOffset = ${Y.broadcastedIndicesToOffset("outputIndices",Q)}; ${Q.setByOffset("global_idx",Y.getByOffset("inputOffset"))} }`;return` ${O.registerUniform("vec_size","u32").declareVariables(Y,Q)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${S}`},F=[{type:12,data:m},...sn(s,f)];return{name:"Expand",shaderCache:{hint:`${f.length}`,inputDependencies:["rank"]},getShaderSource:P,getRunData:()=>({outputs:[{dims:f,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:F})}},Sf=r=>{Lp(r.inputs),r.compute(kf(r.inputs),{inputs:[0]})}}),Ef,mc,Cf=c(()=>{Pn(),Mn(),Vn(),zu(),Ef=r=>{let s=r[0].dataType,u=mt.size(r[0].dims),f=mt.size(r[1].dims),g=f%4===0,w=m=>{let P=Bt("x",s,[1],4),F=Bt("bias",s,[1],4),O=vn("y",s,[1],4),Y=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],Q=ie=>` let bias${ie}_offset: u32 = (global_idx * 4 + ${ie}) % uniforms.bias_size; let bias${ie} = ${F.getByOffset(`bias${ie}_offset / 4`)}[bias${ie}_offset % 4];`,S=g?` let bias = ${F.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${Q(0)}${Q(1)}${Q(2)}${Q(3)} let bias = ${P.type.value}(bias0, bias1, bias2, bias3);`;return`${m.registerUniforms(Y).declareVariables(P,F,O)} ${Fu(ur(s))} ${m.mainStart(Ii)} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${P.getByOffset("global_idx")}; ${S} let x_in = x + bias; ${O.setByOffset("global_idx",Ou("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${g}`,inputDependencies:["type","type"]},getShaderSource:w,getRunData:m=>({outputs:[{dims:m[0].dims,dataType:m[0].dataType}],programUniforms:[{type:12,data:Math.ceil(u/4)},{type:12,data:f}],dispatchGroup:{x:Math.ceil(u/Ii/4)}})}},mc=r=>{r.inputs.length<2||mt.size(r.inputs[1].dims)===0?Du(r):r.compute(Ef(r.inputs))}}),Pf,Af,gc,Np,o_=c(()=>{Pn(),Mn(),Bn(),Vn(),Pf=r=>{if(!r||r.length!==2)throw new Error("Gather requires 2 inputs.")},Af=(r,s)=>{let u=r[0].dims,f=r[1].dims,g=u.length,w=mt.normalizeAxis(s.axis,g),m=u.slice(0);m.splice(w,1,...f);let P=u[w],F=r[0].dataType===9?4:1,O=Math.ceil(mt.size(m)/F),Y=[{type:12,data:O},{type:6,data:P},{type:12,data:w},...sn(r[0].dims,r[1].dims,m)],Q=S=>{let ie=Bt("data",r[0].dataType,r[0].dims.length,F),ce=Bt("inputIndices",r[1].dataType,r[1].dims.length),pe=vn("output",r[0].dataType,m.length,F),ke=be=>{let We=f.length,ze=`var indicesIndices${be} = ${ce.type.indices}(0);`;for(let Ge=0;Ge1?`indicesIndices${be}[${Ge}]`:`indicesIndices${be}`} = ${m.length>1?`outputIndices${be}[uniforms.axis + ${Ge}]`:`outputIndices${be}`};`;ze+=` var idx${be} = ${ce.getByIndices(`indicesIndices${be}`)}; if (idx${be} < 0) { idx${be} = idx${be} + uniforms.axisDimLimit; } var dataIndices${be} : ${ie.type.indices}; `;for(let Ge=0,zt=0;Ge1?`dataIndices${be}[${Ge}]`:`dataIndices${be}`} = u32(idx${be});`,zt+=We):(ze+=`${g>1?`dataIndices${be}[${Ge}]`:`dataIndices${be}`} = ${m.length>1?`outputIndices${be}[${zt}]`:`outputIndices${be}`};`,zt++);return ze},Pe;if(r[0].dataType===9){let be=(We,ze,Ge="")=>` let outputIndices${ze} = ${pe.offsetToIndices(`outputOffset + ${ze}u`)}; ${ke(ze)}; let offset${ze} = ${ie.indicesToOffset(`dataIndices${ze}`)}; let index${ze} = offset${ze} / 4u; let component${ze} = offset${ze} % 4u; ${We}[${ze}] = ${Ge}(${ie.getByOffset(`index${ze}`)}[component${ze}]); `;Pe=` let outputOffset = global_idx * ${F}; var value = vec4(0); ${be("value",0,"u32")} ${be("value",1,"u32")} ${be("value",2,"u32")} ${be("value",3,"u32")} ${pe.setByOffset("global_idx","value")} `}else Pe=` let outputIndices = ${pe.offsetToIndices("global_idx")}; ${ke("")}; let value = ${ie.getByIndices("dataIndices")}; ${pe.setByOffset("global_idx","value")}; `;return` ${S.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(ie,ce,pe)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${Pe} }`};return{name:"Gather",shaderCache:{hint:s.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:m,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:Y}),getShaderSource:Q}},gc=r=>bn({axis:r.axis}),Np=(r,s)=>{let u=r.inputs;Pf(u),r.compute(Af(r.inputs,s))}}),$f,If,Ff,Of,jp=c(()=>{Pn(),Mn(),Bn(),Vn(),$f=(r,s)=>{if(r.length<3||r.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let u=mt.normalizeAxis(s.quantizeAxis,r[0].dims.length),f=s.blockSize,g=r[0],w=r[2],m=r.length===4?r[3]:void 0;if(w.dims.length!==g.dims.length||!g.dims.map((P,F)=>F===u?Math.ceil(P/f)===w.dims[F]:P===w.dims[F]).reduce((P,F)=>P&&F,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(m){if(m.dataType!==g.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(m.dims.length!==w.dims.length||!m.dims.map((P,F)=>P===w.dims[F]).reduce((P,F)=>P&&F,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},If=(r,s)=>{let u=r[0].dims,f=r[1].dims,g=u.length,w=mt.normalizeAxis(s.gatherAxis,g),m=mt.normalizeAxis(s.quantizeAxis,g),P=u.slice(0);P.splice(w,1,...f);let F=mt.size(P),O=r[2].dataType,Y=r[0].dataType===22,Q=[{type:12,data:F},{type:12,data:m},{type:12,data:w},{type:12,data:s.blockSize},...sn(...r.map((ie,ce)=>ie.dims),P)],S=ie=>{let ce=Bt("data",r[0].dataType,r[0].dims.length),pe=Bt("inputIndices",r[1].dataType,r[1].dims.length),ke=Bt("scales",r[2].dataType,r[2].dims.length),Pe=r.length>3?Bt("zeroPoint",r[3].dataType,r[3].dims.length):void 0,be=vn("output",O,P.length),We=[ce,pe,ke];Pe&&We.push(Pe);let ze=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${ie.registerUniforms(ze).declareVariables(...We,be)} ${ie.mainStart()} let output_indices = ${be.offsetToIndices("global_idx")}; var indices_indices = ${pe.type.indices}(0); ${f.length>1?` for (var i: u32 = 0; i < ${f.length}; i++) { let index = ${be.indicesGet("output_indices","uniforms.gather_axis + i")}; ${pe.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${be.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${ce.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${be.indicesGet("output_indices","i")}; ${ce.indicesSet("data_indices","i","index")}; } var index_from_indices = ${pe.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${u[w]}; } ${ce.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${P.length}; i++) { let index = ${be.indicesGet("output_indices",`i + ${f.length} - 1`)}; ${ce.indicesSet("data_indices","i","index")}; } let data_offset = ${ce.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${ce.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${Y?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${ke.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${ke.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${ke.getByIndices("scale_indices")}; ${Pe?` let zero_point_indices = scale_indices; let zero_point_offset = ${Pe.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${Pe.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${Y?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${ur(O)}(quantized_data - zero_point) * scale; ${be.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${s.cacheKey};${r.filter((ie,ce)=>ce!==1).map(ie=>ie.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:r.length},(ie,ce)=>"rank")},getRunData:()=>({outputs:[{dims:P,dataType:O}],dispatchGroup:{x:Math.ceil(F/64)},programUniforms:Q}),getShaderSource:S}},Ff=(r,s)=>{let u=r.inputs;$f(u,s),r.compute(If(r.inputs,s))},Of=r=>bn({blockSize:r.blockSize,gatherAxis:r.gatherAxis,quantizeAxis:r.quantizeAxis})}),Df,zf,Rf,Lf,Vp=c(()=>{Pn(),Mn(),Bn(),Vn(),Df=r=>{if(!r||r.length!==2)throw new Error("GatherElements requires 2 inputs.");if(r[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(r[0].dims.length!==r[1].dims.length)throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`)},zf=(r,s)=>{let u=r[0].dims,f=r[0].dataType,g=u.length,w=r[1].dims,m=r[1].dataType,P=mt.normalizeAxis(s.axis,g),F=u[P],O=w.slice(0),Y=mt.size(O),Q=Bt("input",f,g),S=Bt("indicesInput",m,w.length),ie=vn("output",f,O.length),ce=[{type:12,data:Y},{type:6,data:F},{type:12,data:P}];return ce.push(...sn(u,w,O)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:O,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(Y/64)},programUniforms:ce}),getShaderSource:pe=>` ${pe.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(Q,S,ie)} ${pe.mainStart()} ${pe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${ie.offsetToIndices("global_idx")}; var idx = ${S.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${Q.type.indices}(outputIndices); ${Q.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${Q.getByIndices("inputIndices")}; ${ie.setByOffset("global_idx","value")}; }`}},Rf=r=>bn({axis:r.axis}),Lf=(r,s)=>{let u=r.inputs;Df(u),r.compute(zf(r.inputs,s))}}),Bf,Nf,jf,Vf,Up=c(()=>{Pn(),Mn(),Vn(),Bf=r=>{if(!r)throw new Error("Input is missing");if(r.length<2||r.length>3)throw new Error("Invaid input number.");if(r.length===3&&r[2].dims.length>2)throw new Error("Invalid input shape of C");if(r[0].dataType!==r[1].dataType||r.length===3&&r[0].dataType!==r[2].dataType)throw new Error("Input types are mismatched")},Nf=(r,s)=>{let u=r[0].dims.slice(),f=r[1].dims.slice(),[g,w,m]=tr.getShapeOfGemmResult(u,s.transA,f,s.transB,r.length===3?r[2].dims:void 0),P=[g,w];if(!P)throw new Error("Can't use gemm on the given tensors");let F=mt.size(P),O=[{type:12,data:F},{type:12,data:g},{type:12,data:w},{type:12,data:m},{type:1,data:s.alpha},{type:1,data:s.beta}],Y=["type","type"];r.length===3&&(O.push(...sn(r[2].dims)),Y.push("rank")),O.push(...sn(P));let Q=S=>{let ie="";s.transA&&s.transB?ie="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":s.transA&&!s.transB?ie="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!s.transA&&s.transB?ie="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!s.transA&&!s.transB&&(ie="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let ce=s.alpha===1?"":"value *= uniforms.alpha;",pe=Bt("a",r[0].dataType,r[0].dims),ke=Bt("b",r[1].dataType,r[1].dims),Pe=pe.type.value,be=null,We=[pe,ke];r.length===3&&(be=Bt("c",r[2].dataType,r[2].dims.length),We.push(be));let ze=vn("output",r[0].dataType,P.length);We.push(ze);let Ge=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${S.registerUniforms(Ge).declareVariables(...We)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${Pe}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${ie} } ${ce} ${be!=null?`let cOffset = ${be.broadcastedIndicesToOffset("vec2(m, n)",ze)}; value += ${Pe}(uniforms.beta) * ${be.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${s.cacheKey}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:P,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(F/64)},programUniforms:O}),getShaderSource:Q}},jf=r=>{let s=r.transA,u=r.transB,f=r.alpha,g=r.beta;return{transA:s,transB:u,alpha:f,beta:g,cacheKey:`${r.transA};${r.transB};${r.alpha===1}`}},Vf=(r,s)=>{Bf(r.inputs),r.compute(Nf(r.inputs,s))}}),zi,Wp,_c,yc,Uf,sl,Wf,Gf=c(()=>{Pn(),Mn(),Bn(),ye(),qe(),Vn(),yo(),zi=(r,s)=>r.length>s&&r[s].dims.length>0?r[s]:void 0,Wp=(r,s)=>{let u=r[0],f=zi(r,1),g=zi(r,2),w=zi(r,3),m=zi(r,4),P=zi(r,5),F=zi(r,6),O=zi(r,7);if(u.dims.length!==3&&u.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let Y=u.dims[0],Q=u.dims[1],S=u.dims.length===3?u.dims[2]:s.numHeads*u.dims[4],ie=Q,ce=0,pe=0,ke=Math.floor(S/s.numHeads);if(F&&O&&mt.size(F.dims)&&mt.size(O.dims)){if(F.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(F.dims[0]!==Y||F.dims[1]!==s.numHeads||F.dims[3]!==ke)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(O.dims[0]!==Y||O.dims[1]!==s.numHeads||O.dims[3]!==ke)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(F.dims[2]!==O.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(O.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');ce=F.dims[2],pe=F.dims[2]}else if(F&&mt.size(F.dims)||O&&mt.size(O.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let Pe;if(f&&mt.size(f.dims)>0){if(u.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(f.dims.length<3||f.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(u.dims[0]!==f.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(f.dims.length===3){if(f.dims[2]!==u.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');Pe=2,ie=f.dims[1]}else if(f.dims.length===5){if(f.dims[2]!==s.numHeads||f.dims[3]!==2||f.dims[4]!==ke)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(g)throw new Error('Expect "value" be none when "key" has packed kv format.');Pe=5,ie=f.dims[1]}else{if(f.dims[1]!==s.numHeads||f.dims[3]!==ke)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');Pe=0,ie=f.dims[2]}}else{if(u.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(u.dims[2]!==s.numHeads||u.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');Pe=3}if(w&&mt.size(w.dims)>0){if(w.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(f&&f.dims.length===5&&f.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let be=ce+ie,We=0;if(m&&mt.size(m.dims)>0){We=8;let It=m.dims;throw It.length===1?It[0]===Y?We=1:It[0]===3*Y+2&&(We=3):It.length===2&&It[0]===Y&&It[1]===be&&(We=5),We===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let ze=!1,Ge=S;if(g&&mt.size(g.dims)>0){if(g.dims.length!==3&&g.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(u.dims[0]!==g.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(g.dims.length===3){if(ie!==g.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Ge=g.dims[2]}else{if(ie!==g.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Ge=g.dims[1]*g.dims[3],ze=!0}}let zt=!1;if(m&&mt.size(m.dims)>0)throw new Error("Key padding mask is not supported");if(P&&mt.size(P.dims)>0){if(P.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(P.dims[0]!==Y||P.dims[1]!==s.numHeads||P.dims[2]!==Q||P.dims[3]!==be)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:Y,sequenceLength:Q,pastSequenceLength:ce,kvSequenceLength:ie,totalSequenceLength:be,maxSequenceLength:pe,inputHiddenSize:0,hiddenSize:S,vHiddenSize:Ge,headSize:ke,vHeadSize:Math.floor(Ge/s.numHeads),numHeads:s.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:s.maskFilterValue,maskType:We,scale:s.scale,broadcastResPosBias:zt,passPastInKv:ze,qkvFormat:Pe}},_c=r=>bn({...r}),yc=bn({perm:[0,2,1,3]}),Uf=(r,s,u,f,g,w,m)=>{let P=[f,g,w],F=mt.size(P),O=[{type:12,data:F},{type:12,data:m},{type:12,data:w}],Y=Q=>{let S=vn("qkv_with_bias",s.dataType,P),ie=Bt("qkv",s.dataType,P),ce=Bt("bias",u.dataType,P),pe=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${Q.registerUniforms(pe).declareVariables(ie,ce,S)} ${Q.mainStart()} ${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return r.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:P,dataType:s.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(F/64)},programUniforms:O}),getShaderSource:Y},{inputs:[s,u],outputs:[-1]})[0]},sl=(r,s,u,f,g,w,m,P)=>{let F=w;if(m&&mt.size(m.dims)>0){if(f===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return F=Uf(r,w,m,s,f,u*g,P),F=F.reshape([s,f,u,g]),r.compute(Oi(F,yc.perm),{inputs:[F],outputs:[-1]})[0]}else return w.dims.length===3&&(F=w.reshape([s,f,u,g])),r.compute(Oi(F,yc.perm),{inputs:[F],outputs:[-1]})[0]},Wf=(r,s)=>{let u=Wp(r.inputs,s),f=r.inputs[0],g=zi(r.inputs,1),w=zi(r.inputs,2),m=zi(r.inputs,3),P=zi(r.inputs,4),F=zi(r.inputs,5),O=zi(r.inputs,6),Y=zi(r.inputs,7);if(f.dims.length===5)throw new Error("Packed QKV is not implemented");if((g==null?void 0:g.dims.length)===5)throw new Error("Packed KV is not implemented");let Q=g&&w&&g.dims.length===4&&w.dims.length===4,S=sl(r,u.batchSize,u.numHeads,u.sequenceLength,u.headSize,f,m,0);if(Q)return Te(r,S,g,w,P,void 0,O,Y,F,u,s);if(!g||!w)throw new Error("key and value must be provided");let ie=sl(r,u.batchSize,u.numHeads,u.kvSequenceLength,u.headSize,g,m,u.hiddenSize),ce=sl(r,u.batchSize,u.numHeads,u.kvSequenceLength,u.vHeadSize,w,m,2*u.hiddenSize);Te(r,S,ie,ce,P,void 0,O,Y,F,u,s)}}),vc,qf,Hf,wc,Kf,Xf=c(()=>{Pn(),Mn(),Vn(),vc=r=>Array.from(r.getBigInt64Array(),Number),qf=r=>{if(!r||r.length!==2)throw new Error("Tile requires 2 inputs.");if(r[0].dataType!==1&&r[0].dataType!==10&&r[0].dataType!==6&&r[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(r[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(r[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(vc(r[1]).length!==r[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Hf=(r,s)=>{let u=[];for(let f=0;f{let u=r[0].dims,f=s??vc(r[1]),g=Hf(u,f),w=mt.size(g),m=r[0].dataType,P=Bt("input",m,u.length),F=vn("output",m,g.length),O=Y=>` const inputShape = ${P.indices(...u)}; ${Y.registerUniform("output_size","u32").declareVariables(P,F)} ${Y.mainStart()} ${Y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${F.offsetToIndices("global_idx")}; var input_indices: ${P.type.indices}; for (var i = 0; i < ${u.length}; i++) { let input_dim_i = ${P.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${F.indicesGet("output_indices","i")} % input_dim_i; ${P.indicesSet("input_indices","i","input_dim_value")} } ${F.setByOffset("global_idx",P.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${f}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:g,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},...sn(r[0].dims,g)]}),getShaderSource:O}},Kf=r=>{qf(r.inputs),r.compute(wc(r.inputs),{inputs:[0]})}}),Qf,bc,Yf,Zf,xc,Jf,Gp=c(()=>{Pn(),Mn(),Bn(),qe(),Vn(),Gf(),Xf(),yo(),Qf=(r,s)=>{let u=r[0],f=r[1],g=r[2],w=r[3],m=r[4];if(u.dims.length!==3&&u.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let P=!1,F=u.dims[0],O=u.dims[1],Y=u.dims.length===3?P?u.dims[2]/3:u.dims[2]:s.numHeads*u.dims[4],Q=O,S=0,ie=0,ce=Math.floor(Y/s.numHeads),pe=w&&w.dims.length!==0,ke=m&&m.dims.length!==0,Pe=!0;if(pe&&ke){if(w.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(m.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');S=w.dims[1],ie=w.dims[1]}else if(pe||ke)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let be;if(f){if(u.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(f.dims.length<3||f.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(u.dims[0]!==f.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(f.dims.length===3){if(u.dims[2]%f.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');be=2,Q=f.dims[1]}else if(f.dims.length===5){if(f.dims[2]!==s.numHeads||f.dims[3]!==2||f.dims[4]!==ce)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(g)throw new Error('Expect "value" be none when "key" has packed kv format.');be=5,Q=f.dims[1]}else{if(f.dims[1]!==s.numHeads||f.dims[3]!==ce)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');be=0,Q=f.dims[2]}}else{if(u.dims.length!==3&&u.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(u.dims.length===5&&(u.dims[2]!==s.numHeads||u.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');be=3}let We=0,ze=!1,Ge=Y;if(g){if(g.dims.length!==3&&g.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(u.dims[0]!==g.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(g.dims.length===3){if(Q!==g.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Ge=g.dims[2]}else{if(Q!==g.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');Ge=g.dims[1]*g.dims[3],ze=!0}}let zt=S+Q;return{batchSize:F,sequenceLength:O,pastSequenceLength:S,kvSequenceLength:Q,totalSequenceLength:zt,maxSequenceLength:ie,inputHiddenSize:0,hiddenSize:Y,vHiddenSize:Ge,headSize:ce,vHeadSize:Math.floor(Ge/s.kvNumHeads),numHeads:s.numHeads,kvNumHeads:s.kvNumHeads,nReps:s.numHeads/s.kvNumHeads,pastPresentShareBuffer:!1,maskType:We,scale:s.scale,broadcastResPosBias:!1,passPastInKv:ze,qkvFormat:be,isPastkvBSNH:Pe}},bc=(r,s,u,f)=>{let g=[f.batchSize,f.totalSequenceLength,f.kvNumHeads,f.headSize],w=4,m=mt.size(g)/w,P=f.totalSequenceLength,F=vn("present_kv",u,g.length,w),O=Bt("new_kv",r.dataType,r.dims.length,w),Y=s?Bt("past_kv",s.dataType,s.dims.length,w):void 0,Q=Math.ceil(f.headSize/w),S={x:P,y:r.dims[0],z:1},ie=s?["rank","rank"]:["rank"],ce=[{type:12,data:m},{type:12,data:f.pastSequenceLength},{type:12,data:f.kvSequenceLength},{type:12,data:f.totalSequenceLength}],pe=[O];Y?(ce.push(...sn(r.dims),...sn(s.dims),...sn(g)),pe.push(Y)):ce.push(...sn(r.dims),...sn(g));let ke=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],Pe=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; var past_head_stride = uniforms.past_seqlen * H; if (is_bsnh) { past_head_stride = H; } let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; present_kv[out_offset] = past_kv[in_offset];`,be=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; let new_row_stride = num_heads * H; let new_head_stride = H; let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; present_kv[out_offset] = new_kv[in_offset];`,We=s?`if (s < past_seqlen) { ${Pe} } else if (s < past_seqlen + uniforms.new_seqlen) { ${be} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${be} }`,ze=Ge=>` ${Ge.registerUniforms(ke).declareVariables(...pe,F)} ${Ge.mainStart([Q,f.kvNumHeads,1])} ${Ge.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${F.offsetToIndices("global_idx")}; let h = local_id.x; let n = local_id.y; let s = workgroup_id.x; let b = workgroup_id.y; let num_heads = ${f.kvNumHeads}u; let H = ${Q}u; let present_seqlen = uniforms.present_seqlen; let present_batch_stride = present_seqlen * num_heads * H; var row_stride = H; let is_bsnh = ${f.isPastkvBSNH}; if (is_bsnh) { row_stride = num_heads * H; } var present_head_stride = present_seqlen * H; if (is_bsnh) { present_head_stride = H; } let past_seqlen = uniforms.past_seqlen; let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; ${We} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${f.kvNumHeads}${Q}${!!s}`,inputDependencies:ie},getRunData:()=>({outputs:[{dims:g,dataType:u}],dispatchGroup:S,programUniforms:ce}),getShaderSource:ze}},Yf=r=>bn({...r}),Zf=bn({perm:[0,2,1,3]}),xc=(r,s,u,f,g)=>{let w=s,m=f.kvNumHeads,P=f.nReps;return s.dims.length===3&&f.kvSequenceLength!==0&&(w=s.reshape([f.batchSize,f.kvSequenceLength,m,f.headSize])),u?w=r.compute(bc(w,u,w.dataType,f),{inputs:[w,u],outputs:[f.isPastkvBSNH?g:-1]})[0]:w=r.compute(bc(w,void 0,w.dataType,f),{inputs:[w],outputs:[f.isPastkvBSNH?g:-1]})[0],P!==1&&(w=r.compute(wc([w],[1,1,1,P]),{inputs:[w],outputs:[-1]})[0],w=w.reshape([f.batchSize,f.totalSequenceLength,m*P,f.headSize])),r.compute(Oi(w,Zf.perm),{inputs:[w],outputs:[-1]})[0]},Jf=(r,s)=>{var F;let u=Qf(r.inputs,s);if(r.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((F=r.inputs[1])==null?void 0:F.dims.length)===5)throw new Error("Packed KV is not implemented");let f=sl(r,u.batchSize,u.numHeads,u.sequenceLength,u.headSize,r.inputs[0],void 0,0),g=r.inputs[3]&&r.inputs[3].dims.length!==0?r.inputs[3]:void 0,w=r.inputs[4]&&r.inputs[4].dims.length!==0?r.inputs[4]:void 0,m=xc(r,r.inputs[1],g,u,1),P=xc(r,r.inputs[2],w,u,2);Te(r,f,m,P,void 0,void 0,void 0,void 0,void 0,u,s)}}),eh,th,nh,rh,qp=c(()=>{Pn(),Mn(),Vn(),eh=(r,s)=>{let u=r[0].dims,f=u,g=2,w=mt.sizeToDimension(u,g),m=mt.sizeFromDimension(u,g),P=nr(m),F=m/P,O=[u[0],u[1],F],Y=["rank","type","type"],Q=[{type:12,data:m},{type:12,data:F}];Q.push(...sn(O,O));let S=ie=>{let ce=Bt("x",r[0].dataType,O.length,P),pe=Bt("scale",r[1].dataType,r[1].dims),ke=Bt("bias",r[2].dataType,r[2].dims),Pe=vn("output",r[0].dataType,O.length,P),be=[ce,pe,ke,Pe],We=ce.type.value,ze=P===1?"f32":`vec${P}`,Ge=64,zt=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${ze}, ${Ge}>; const workgroupSize = ${Ge}u; ${ie.registerUniforms(zt).declareVariables(...be)} ${ie.mainStart(Ge)} let norm = global_idx / workgroupSize; let batch = norm / uniforms.x_shape[1]; let channel = norm % uniforms.x_shape[1]; let localIndex = local_id.x; // initialize workgroup memory var initial = ${ze}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${ze}(${ce.get("batch","channel","h")}); } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the mean of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { meanShared = ${Fi("workgroupShared[0]",P)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${ze}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${ze}(${ce.get("batch","channel","h")}) - ${ze}(meanShared); initial = initial + deviation * deviation; } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the sum of square of deviation of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { squaredNormShared = ${Fi("workgroupShared[0]",P)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${s.epsilon})); let channelScale = invStdDev * f32(${pe.getByOffset("channel")}); let channelShift = f32(${ke.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${ce.get("batch","channel","h")} * ${We}(${ze}(channelScale)) + ${We}(${ze}(channelShift)); ${Pe.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${s.epsilon};${P}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:f,dataType:r[0].dataType}],dispatchGroup:{x:w},programUniforms:Q}),getShaderSource:S}},th=(r,s,u,f,g,w,m,P)=>{let F=nr(m),O=64,Y=F===1?"vec2f":`mat2x${F}f`,Q=F===1?"f32":`vec${F}f`,S=(zt,It)=>`${Y}(${zt}, ${It})`,ie=g*m/F,ce=Math.ceil(w/O),pe=["type"],ke=[{type:12,data:ce},{type:12,data:w},{type:12,data:Math.floor(m/F)},{type:12,data:Math.floor(w*m/F)}],Pe=zt=>{let It=Bt("input",s.dataType,s.dims,F);return` ${zt.declareVariables(It)} @group(0) @binding(1) var output : array<${Y}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${zt.mainStart(O)} let currentImageNumber = global_idx / ${O} / uniforms.C; let currentChannelNumber = (global_idx / ${O}) % uniforms.C; let wgOffset = local_id.x * uniforms.wg_size; if (wgOffset >= uniforms.H) { return; } let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; var sum = ${_r("f32",F)}; var squaredSum = ${_r("f32",F)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${Q}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${S("sum","squaredSum")}; }`},be=r.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${F}`,inputDependencies:pe},getRunData:()=>({outputs:[{dims:[g,m,O,2],dataType:1}],dispatchGroup:{x:g*m/F},programUniforms:ke}),getShaderSource:Pe},{inputs:[s],outputs:[-1]})[0],We=[{type:12,data:ie},{type:12,data:w},{type:12,data:Math.floor(m/F)},{type:12,data:Math.floor(O*m/F)}],ze=["type","type","type"],Ge=zt=>{let It=Bt("scale",u.dataType,u.dims,F),Ht=Bt("bias",f.dataType,f.dims,F);return` @group(0) @binding(0) var input : array<${Y}>; @group(0) @binding(1) var scale : array<${It.type.storage}>; @group(0) @binding(2) var bias : array<${Ht.type.storage}>; @group(0) @binding(3) var output : array<${Y}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${zt.mainStart()} ${zt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} let currentImageNumber = global_idx / uniforms.C; let currentChannelNumber = global_idx % uniforms.C; let offset = currentImageNumber * uniforms.image_size; var sum = ${_r("f32",F)}; var squaredSum = ${_r("f32",F)}; for (var i: u32 = 0; i < min(${O}, uniforms.H); i++) { let value = input[offset + i + currentChannelNumber * ${O}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${P})); let channelScale = invStdDev * ${Q}(scale[currentChannelNumber]); let channelShift = ${Q}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${S("channelScale","channelShift")}; }`};return r.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${F};${P}`,inputDependencies:ze},getRunData:()=>({outputs:[{dims:[g,m,2],dataType:1}],dispatchGroup:{x:Math.ceil(ie/64)},programUniforms:We}),getShaderSource:Ge},{inputs:[be,u,f],outputs:[-1]})[0]},nh=(r,s,u)=>{let f=s[0].dims,g=f,w=f[0],m=f[f.length-1],P=mt.sizeFromDimension(f,1)/m,F=nr(m),O=mt.size(g)/F,Y=[{type:12,data:P},{type:12,data:Math.floor(m/F)}],Q=["type","type"],S=th(r,s[0],s[1],s[2],w,P,m,u.epsilon),ie=ce=>{let pe=lr(s[0].dataType),ke=F===1?"vec2f":`mat2x${F}f`,Pe=F===1?pe:`vec${F}<${pe}>`,be=Bt("input",s[0].dataType,s[0].dims,F),We=vn("output",s[0].dataType,g,F);return` @group(0) @binding(0) var input : array<${be.type.storage}>; @group(0) @binding(1) var scaleInput : array<${ke}>; @group(0) @binding(2) var output : array<${We.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${ce.mainStart()} let currentImageNumber = global_idx / (uniforms.C * uniforms.H); let currentChannelNumber = global_idx % uniforms.C; let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; let scale = scaleInput[scaleOffset]; output[global_idx] = fma(input[global_idx], ${Pe}(scale[0]), ${Pe}(scale[1])); }`};r.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${F}`,inputDependencies:Q},getRunData:()=>({outputs:[{dims:g,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:Y}),getShaderSource:ie},{inputs:[s[0],S]})},rh=(r,s)=>{s.format==="NHWC"?nh(r,r.inputs,s):r.compute(eh(r.inputs,s))}}),ih,sh,oh,a_=c(()=>{Pn(),Mn(),Vn(),ih=r=>{if(!r||r.length<2)throw new Error("layerNorm requires at least 2 inputs.")},sh=(r,s,u)=>{let f=s.simplified,g=r[0].dims,w=r[1],m=!f&&r[2],P=g,F=mt.normalizeAxis(s.axis,g.length),O=mt.sizeToDimension(g,F),Y=mt.sizeFromDimension(g,F),Q=mt.size(w.dims),S=m?mt.size(m.dims):0;if(Q!==Y||m&&S!==Y)throw new Error(`Size of X.shape()[axis:] == ${Y}. Size of scale and bias (if provided) must match this. Got scale size of ${Q} and bias size of ${S}`);let ie=[];for(let Ge=0;Ge1,be=u>2,We=Ge=>{let zt=lr(r[0].dataType),It=[Bt("x",r[0].dataType,r[0].dims,ce),Bt("scale",w.dataType,w.dims,ce)];m&&It.push(Bt("bias",m.dataType,m.dims,ce)),It.push(vn("output",r[0].dataType,P,ce)),Pe&&It.push(vn("mean_data_output",1,ie)),be&&It.push(vn("inv_std_output",1,ie));let Ht=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${Ge.registerUniforms(Ht).declareVariables(...It)} ${Ge.mainStart()} ${Ge.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${_r("f32",ce)}; var mean_square_vector = ${_r("f32",ce)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Fr(zt,ce,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Fi("mean_vector",ce)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Fi("mean_square_vector",ce)} / uniforms.norm_size ${f?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Fr(zt,ce,"x[j + offset]")}; let f32scale = ${Fr(zt,ce,"scale[j]")}; output[j + offset] = ${It[0].type.value}((f32input ${f?"":"- mean"}) * inv_std_dev * f32scale ${m?`+ ${Fr(zt,ce,"bias[j]")}`:""} ); } ${Pe?"mean_data_output[global_idx] = mean":""}; ${be?"inv_std_output[global_idx] = inv_std_dev":""}; }`},ze=[{dims:P,dataType:r[0].dataType}];return Pe&&ze.push({dims:ie,dataType:1}),be&&ze.push({dims:ie,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${ce};${u};${f}`,inputDependencies:pe},getRunData:()=>({outputs:ze,dispatchGroup:{x:Math.ceil(O/64)},programUniforms:ke}),getShaderSource:We}},oh=(r,s)=>{ih(r.inputs),r.compute(sh(r.inputs,s,r.outputCount))}}),Jn,ah,hi,vi,Ri=c(()=>{Pn(),Mn(),Bn(),Vn(),Jn=(r,s)=>{if(r.length<3||r.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let u=r[0],f=u.dims.length;if(u.dims[f-1]!==s.k)throw new Error("The last dim of input shape does not match the k value");let g=Math.floor((s.k+s.blockSize-1)/s.blockSize),w=s.blockSize/8*s.bits,m=r[1];if(!mt.areEqual(m.dims,[s.n,g,w]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let P=r[2].dims;if(mt.size(P)!==s.n*g)throw new Error("scales input size error.");if(r.length===4){let F=r[3].dims,O=s.bits>4?s.n*g:s.n*Math.floor((g+1)/2);if(mt.size(F)!==O)throw new Error("zeroPoints input size error.")}},ah=(r,s)=>{let u=r[0].dims,f=u.length,g=u[f-2],w=s.k,m=s.n,P=u.slice(0,f-2),F=mt.size(P),O=r[1].dims[2]/4,Y=r[0].dataType,Q=nr(s.k),S=nr(O),ie=nr(m),ce=P.concat([g,m]),pe=g>1&&m/ie%2===0?2:1,ke=mt.size(ce)/ie/pe,Pe=64,be=[],We=[F,g,w/Q],ze=mt.convertShape(r[1].dims).slice();ze.splice(-1,1,O/S),be.push(...sn(We)),be.push(...sn(ze)),be.push(...sn(r[2].dims)),r.length===4&&be.push(...sn(mt.convertShape(r[3].dims)));let Ge=[F,g,m/ie];be.push(...sn(Ge));let zt=It=>{let Ht=We.length,pn=Bt("a",r[0].dataType,Ht,Q),wn=Bt("b",12,ze.length,S),Xn=Bt("scales",r[2].dataType,r[2].dims.length),ar=[pn,wn,Xn],Dn=r.length===4?Bt("zero_points",12,r[3].dims.length):void 0;Dn&&ar.push(Dn);let Cr=Ge.length,Vr=vn("output",r[0].dataType,Cr,ie),fr=lr(r[0].dataType),Or=(()=>{switch(Q){case 1:return`array<${fr}, 8>`;case 2:return`mat4x2<${fr}>`;case 4:return`mat2x4<${fr}>`;default:throw new Error(`${Q}-component is not supported.`)}})(),Fn=()=>{let Ft=` // reuse a data var input_offset = ${pn.indicesToOffset(`${pn.type.indices}(batch, row, word_offset)`)}; var a_data: ${Or}; for (var j: u32 = 0; j < ${8/Q}; j++) { a_data[j] = ${pn.getByOffset("input_offset")}; input_offset++; } `;for(let an=0;an> 4) & b_mask); b_quantized_values = ${Or}(${Array.from({length:4},(Nn,Pr)=>`${fr}(b_value_lower[${Pr}]), ${fr}(b_value_upper[${Pr}])`).join(", ")}); b_dequantized_values = ${Q===1?`${Or}(${Array.from({length:8},(Nn,Pr)=>`(b_quantized_values[${Pr}] - ${Dn?`zero_point${an}`:"zero_point"}) * scale${an}`).join(", ")});`:`(b_quantized_values - ${Or}(${Array(8).fill(`${Dn?`zero_point${an}`:"zero_point"}`).join(",")})) * scale${an};`}; workgroup_shared[local_id.x * ${pe} + ${Math.floor(an/ie)}]${ie>1?`[${an%ie}]`:""} += ${Array.from({length:8/Q},(Nn,Pr)=>`${Q===1?`a_data[${Pr}] * b_dequantized_values[${Pr}]`:`dot(a_data[${Pr}], b_dequantized_values[${Pr}])`}`).join(" + ")}; `;return Ft},sr=()=>{let Ft=` var col_index = col * ${ie}; ${Dn?` let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; var zero_point_byte_count: u32; var zero_point_word_index: u32; var zero_point_byte_offset: u32; let zero_point_nibble_offset: u32 = block & 0x1u; var zero_point_bits_offset: u32; var zero_point_word: u32;`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${fr}(8);`} `;for(let an=0;an> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${Dn.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${an} = ${fr}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return Ft},vr=()=>{let Ft=`col_index = col * ${ie};`;for(let an=0;an; var b_value_upper: vec4; var b_quantized_values: ${Or}; var b_dequantized_values: ${Or};`,Ft};return` var workgroup_shared: array<${Vr.type.value}, ${pe*Pe}>; ${It.declareVariables(...ar,Vr)} ${It.mainStart([Pe,1,1])} let output_indices = ${Vr.offsetToIndices(`(global_idx / ${Pe}) * ${pe}`)}; let col = output_indices[2]; let row = output_indices[1]; let batch = output_indices[0]; let nBlocksPerCol = uniforms.b_shape[1]; for (var block = local_id.x; block < nBlocksPerCol; block += ${Pe}) { //process one block var word_offset: u32 = block * ${s.blockSize/Q}; ${sr()} for (var word: u32 = 0; word < ${O}; word += ${S}) { ${vr()} for (var i: u32 = 0; i < ${S}; i++) { ${Fn()} word_offset += ${8/Q}; } } } workgroupBarrier(); if (local_id.x < ${pe}) { var output_value: ${Vr.type.value} = ${Vr.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${Pe}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${pe}; } ${Vr.setByIndices(`${Vr.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${s.blockSize};${s.bits};${Q};${S};${ie};${pe};${Pe}`,inputDependencies:Array(r.length).fill("rank")},getRunData:()=>({outputs:[{dims:ce,dataType:Y}],dispatchGroup:{x:ke},programUniforms:be}),getShaderSource:zt}},hi=(r,s)=>{Jn(r.inputs,s),r.compute(ah(r.inputs,s))},vi=r=>bn(r)}),Xo,Hp,lh,uh,H,X,de,De,kt,At=c(()=>{Pn(),Mn(),Vn(),Xo=r=>{if(!r||r.length<1)throw new Error("Too few inputs");if(r[0].dataType!==1&&r[0].dataType!==10)throw new Error("Input type must be float or float16.");if(r.length>=2){let s=r[0].dims.length*2===r[1].dims[0];if(r.length===4&&(s=r[3].dims[0]*2===r[1].dims[0]),!s)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Hp=(r,s,u)=>{let f="";for(let g=s-1;g>=0;--g)f+=` k = i32(${r.indicesGet("indices",g)}) - ${gn("uniforms.pads",g,u)}; if (k < 0) { break; } if (k >= i32(${gn("uniforms.x_shape",g,s)})) { break; } offset += k * i32(${gn("uniforms.x_strides",g,s)}); `;return` value = ${r.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${f} value = x[offset]; } `},lh=(r,s,u)=>{let f="";for(let g=s-1;g>=0;--g)f+=` k = i32(${r.indicesGet("indices",g)}) - ${gn("uniforms.pads",g,u)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${gn("uniforms.x_shape",g,s)}) - 1); k = k % _2n_1; if(k >= i32(${gn("uniforms.x_shape",g,s)})) { k = _2n_1 - k; } } offset += k * i32(${gn("uniforms.x_strides",g,s)}); `;return` var offset = 0; var k = 0; ${f} value = x[offset]; `},uh=(r,s,u)=>{let f="";for(let g=s-1;g>=0;--g)f+=` k = i32(${r.indicesGet("indices",g)}) - ${gn("uniforms.pads",g,u)}; if (k < 0) { k = 0; } if (k >= i32(${gn("uniforms.x_shape",g,s)})) { k = i32(${gn("uniforms.x_shape",g,s)}) - 1; } offset += k * i32(${gn("uniforms.x_strides",g,s)}); `;return` var offset = 0; var k = 0; ${f} value = x[offset]; `},H=(r,s,u)=>{let f="";for(let g=s-1;g>=0;--g)f+=` k = i32(${r.indicesGet("indices",g)}) - ${gn("uniforms.pads",g,u)}; if (k < 0) { k += i32(${gn("uniforms.x_shape",g,s)}]); } if (k >= i32(${gn("uniforms.x_shape",g,s)})) { k -= i32(${gn("uniforms.x_shape",g,s)}); } offset += k * i32(${gn("uniforms.x_strides",g,s)}); `;return` var offset = 0; var k = 0; ${f} value = x[offset]; `},X=(r,s,u)=>{switch(u.mode){case 0:return Hp(r,s,u.pads.length);case 1:return lh(r,s,u.pads.length);case 2:return uh(r,s,u.pads.length);case 3:return H(r,s,u.pads.length);default:throw new Error("Invalid mode")}},de=(r,s)=>{let u=mt.padShape(r[0].dims.slice(),s.pads),f=r[0].dims,g=mt.size(u),w=[{type:12,data:g},{type:6,data:s.pads}],m=r.length>=3&&r[2].data;s.mode===0&&w.push({type:m?r[2].dataType:1,data:s.value}),w.push(...sn(r[0].dims,u));let P=["rank"],F=O=>{let Y=vn("output",r[0].dataType,u.length),Q=Bt("x",r[0].dataType,f.length),S=Q.type.value,ie=X(Y,f.length,s),ce=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:s.pads.length}];return s.mode===0&&ce.push({name:"constant_value",type:m?S:"f32"}),` ${O.registerUniforms(ce).declareVariables(Q,Y)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${Y.offsetToIndices("global_idx")}; var value = ${S}(0); ${ie} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${s.mode}${m}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(mt.size(u)/64)},programUniforms:w}),getShaderSource:F}},De=(r,s)=>{if(r.length>1){let u=r[1].getBigInt64Array(),f=r.length>=3&&r[2].data?r[2].dataType===10?r[2].getUint16Array()[0]:r[2].getFloat32Array()[0]:0,g=r[0].dims.length,w=new Int32Array(2*g).fill(0);if(r.length>=4){let P=r[3].getBigInt64Array();for(let F=0;Fw[Number(F)]=Number(P));let m=[];return w.forEach(P=>m.push(P)),{mode:s.mode,value:f,pads:m}}else return s},kt=(r,s)=>{Xo(r.inputs);let u=De(r.inputs,s);r.compute(de(r.inputs,u),{inputs:[0]})}}),Vt,un,Cn,Kn,rr,Tr,ir,cr,er,or,dr,Er,Gi,qi,Ls,Li,oi,Mi,Tc,Mc=c(()=>{jt(),Pn(),Mn(),Vn(),Vt=r=>{if(j.webgpu.validateInputContent&&(!r||r.length!==1))throw new Error("Pool ops requires 1 input.")},un=(r,s,u)=>{let f=s.format==="NHWC",g=r.dims.slice();f&&g.splice(1,0,g.pop());let w=Object.hasOwnProperty.call(s,"dilations"),m=s.kernelShape.slice(),P=s.strides.slice(),F=w?s.dilations.slice():[],O=s.pads.slice();jr.adjustPoolAttributes(u,g,m,P,F,O);let Y=jr.computePoolOutputShape(u,g,P,F,m,O,s.autoPad),Q=Object.assign({},s);w?Object.assign(Q,{kernelShape:m,strides:P,pads:O,dilations:F,cacheKey:s.cacheKey}):Object.assign(Q,{kernelShape:m,strides:P,pads:O,cacheKey:s.cacheKey});let S=Y.slice();return S.push(S.splice(1,1)[0]),[Q,f?S:Y]},Cn=(r,s)=>{let u=s.format==="NHWC",f=mt.size(r),g=mt.size(s.kernelShape),w=[{type:12,data:f},{type:12,data:g}],m=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(s.kernelShape.length<=2){let P=s.kernelShape[s.kernelShape.length-1],F=s.strides[s.strides.length-1],O=s.pads[s.pads.length/2-1],Y=s.pads[s.pads.length-1],Q=!!(O+Y);w.push({type:12,data:P},{type:12,data:F},{type:12,data:O},{type:12,data:Y}),m.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let S=!1;if(s.kernelShape.length===2){let ie=s.kernelShape[s.kernelShape.length-2],ce=s.strides[s.strides.length-2],pe=s.pads[s.pads.length/2-2],ke=s.pads[s.pads.length-2];S=!!(pe+ke),w.push({type:12,data:ie},{type:12,data:ce},{type:12,data:pe},{type:12,data:ke}),m.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[w,m,!0,Q,S]}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let P=mt.computeStrides(s.kernelShape);w.push({type:12,data:P},{type:12,data:s.pads},{type:12,data:s.strides}),m.push({name:"kernelStrides",type:"u32",length:P.length},{name:"pads",type:"u32",length:s.pads.length},{name:"strides",type:"u32",length:s.strides.length});let F=s.pads.reduce((O,Y)=>O+Y);return[w,m,!!F,!1,!1]}},Kn=(r,s,u,f,g,w,m,P,F,O,Y,Q)=>{let S=g.format==="NHWC",ie=s.type.value,ce=vn("output",s.type.tensor,f);if(g.kernelShape.length<=2){let pe="",ke="",Pe="",be=u-(S?2:1);if(Y?pe=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${be}] = indices[${be}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${be}] < 0 || xIndices[${be}] >= uniforms.x_shape[${be}]) { pad++; continue; } let x_val = x[${s.indicesToOffset("xIndices")}]; ${w} }`:pe=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${be}] = indices[${be}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${s.indicesToOffset("xIndices")}]; ${w} }`,g.kernelShape.length===2){let We=u-(S?3:2);Q?ke=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${We}] = indices[${We}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${We}] < 0 || xIndices[${We}] >= uniforms.x_shape[${We}]) { pad += i32(uniforms.kw); continue; } `:ke=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${We}] = indices[${We}] * uniforms.sh - uniforms.phStart + j; `,Pe=` } `}return` ${r.registerUniforms(F).declareVariables(s,ce)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${ce.offsetToIndices("global_idx")}; var xIndices = ${ce.offsetToIndices("global_idx")}; var value = ${ie}(${P}); var pad = 0; ${ke} ${pe} ${Pe} ${m} output[global_idx] = value; }`}else{if(S)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let pe=g.kernelShape.length,ke=g.pads.length,Pe="";return O?Pe=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${s.indicesToOffset("xIndices")}]; ${w} }`:Pe=` } let x_val = x[${s.indicesToOffset("xIndices")}]; ${w} `,` ${r.registerUniforms(F).declareVariables(s,ce)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${ce.offsetToIndices("global_idx")}; var xIndices = ${ce.offsetToIndices("global_idx")}; var offsets: array; var value = ${ie}(${P}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${pe-1}u; j++) { offsets[j] = offset / ${gn("uniforms.kernelStrides","j",pe)}; offset -= offsets[j] * ${gn("uniforms.kernelStrides","j",pe)}; } offsets[${pe-1}] = offset; isPad = false; for (var j = ${u-pe}u; j < ${u}u; j++) { xIndices[j] = indices[j] * ${gn("uniforms.strides",`j - ${u-pe}u`,pe)} + offsets[j - ${u-pe}u] - ${gn("uniforms.pads","j - 2u",ke)}; ${Pe} } ${m} output[global_idx] = value; }`}},rr=r=>`${r.format};${r.ceilMode};${r.autoPad};${r.kernelShape.length}`,Tr=r=>`${rr(r)};${r.countIncludePad}`,ir=r=>`${rr(r)};${r.storageOrder};${r.dilations}`,cr=r=>({format:r.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][r.auto_pad],ceilMode:r.ceil_mode,kernelShape:r.kernel_shape,strides:r.strides,pads:r.pads}),er=(r,s,u,f)=>{let[g,w]=un(s,f,u),m=Bt("x",s.dataType,s.dims.length),P=m.type.value,F="value += x_val;",O="";g.countIncludePad?O+=`value /= ${P}(uniforms.kernelSize);`:O+=`value /= ${P}(i32(uniforms.kernelSize) - pad);`;let[Y,Q,S,ie,ce]=Cn(w,g);Y.push(...sn(s.dims,w));let pe=["rank"];return{name:r,shaderCache:{hint:`${f.cacheKey};${S};${ie};${ce}`,inputDependencies:pe},getRunData:()=>({outputs:[{dims:w,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(mt.size(w)/64)},programUniforms:Y}),getShaderSource:ke=>Kn(ke,m,s.dims.length,w.length,g,F,O,0,Q,S,ie,ce)}},or=r=>{let s=r.count_include_pad!==0,u=cr(r);if(u.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let f={countIncludePad:s,...u,cacheKey:""};return{...f,cacheKey:Tr(f)}},dr=(r,s)=>{Vt(r.inputs),r.compute(er("AveragePool",r.inputs[0],!1,s))},Er={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Gi=r=>{let s=r.format;return{format:s,...Er,cacheKey:s}},qi=(r,s)=>{Vt(r.inputs),r.compute(er("GlobalAveragePool",r.inputs[0],!0,s))},Ls=(r,s,u,f)=>{let[g,w]=un(s,f,u),m=` value = max(x_val, value); `,P="",F=Bt("x",s.dataType,s.dims.length),O=["rank"],[Y,Q,S,ie,ce]=Cn(w,g);return Y.push(...sn(s.dims,w)),{name:r,shaderCache:{hint:`${f.cacheKey};${S};${ie};${ce}`,inputDependencies:O},getRunData:()=>({outputs:[{dims:w,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(mt.size(w)/64)},programUniforms:Y}),getShaderSource:pe=>Kn(pe,F,s.dims.length,w.length,g,m,P,s.dataType===10?-65504:-1e5,Q,S,ie,ce)}},Li=(r,s)=>{Vt(r.inputs),r.compute(Ls("MaxPool",r.inputs[0],!1,s))},oi=r=>{let s=r.storage_order,u=r.dilations,f=cr(r);if(s!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(f.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let g={storageOrder:s,dilations:u,...f,cacheKey:""};return{...g,cacheKey:ir(g)}},Mi=r=>{let s=r.format;return{format:s,...Er,cacheKey:s}},Tc=(r,s)=>{Vt(r.inputs),r.compute(Ls("GlobalMaxPool",r.inputs[0],!0,s))}}),kc,l_,Bs,Ma,u_=c(()=>{Pn(),Mn(),Bn(),Vn(),kc=(r,s)=>{if(r.length<2||r.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(r.length===3&&r[1].dims===r[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(r.length===3&&r[0].dataType!==r[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(r[0].dataType===6&&r.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(r[1].dims.length!==0&&r[1].dims.length!==1&&r[1].dims.length!==r[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(r.length>2){if(r[0].dataType!==r[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(r[1].dims.length!==r[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!r[1].dims.map((u,f)=>u===r[2].dims[f]).reduce((u,f)=>u&&f,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(s.blockSize>0){if(r[1].dims.length===0||r[1].dims.length===1&&r[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!r[1].dims.map((g,w)=>w===s.axis||g===r[0].dims[w]).reduce((g,w)=>g&&w,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(r[1].dims.length!==r[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let u=r[0].dims[s.axis],f=r[1].dims[s.axis];if(s.blockSizeMath.ceil(u/(f-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},l_=(r,s)=>{let u=mt.normalizeAxis(s.axis,r[0].dims.length),f=r[0].dataType,g=f===3,w=r[0].dims,m=r[1].dataType,P=mt.size(w),F=f===3||f===2,O=F?[Math.ceil(mt.size(r[0].dims)/4)]:r[0].dims,Y=r[1].dims,Q=r.length>2?r[2]:void 0,S=Q?F?[Math.ceil(mt.size(Q.dims)/4)]:Q.dims:void 0,ie=Y.length===0||Y.length===1&&Y[0]===1,ce=ie===!1&&Y.length===1,pe=nr(P),ke=ie&&(!F||pe===4),Pe=ke?pe:1,be=ke&&!F?pe:1,We=Bt("input",F?12:f,O.length,be),ze=Bt("scale",m,Y.length),Ge=Q?Bt("zero_point",F?12:f,S.length):void 0,zt=vn("output",m,w.length,Pe),It=[We,ze];Ge&&It.push(Ge);let Ht=[O,Y];Q&&Ht.push(S);let pn=[{type:12,data:P/Pe},{type:12,data:u},{type:12,data:s.blockSize},...sn(...Ht,w)],wn=Xn=>{let ar=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${Xn.registerUniforms(ar).declareVariables(...It,zt)} ${Xn.mainStart()} ${Xn.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${zt.offsetToIndices("global_idx")}; // Set input x ${F?` let input = ${We.getByOffset("global_idx / 4")}; let x_vec = ${g?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${Pe===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${We.getByOffset("global_idx")};`}; // Set scale input ${ie?`let scale_value= ${ze.getByOffset("0")}`:ce?` let scale_index = ${zt.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${ze.getByOffset("scale_index")};`:` var scale_indices: ${ze.type.indices} = output_indices; let index = ${ze.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${ze.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${ze.getByIndices("scale_indices")};`}; // Set zero-point input ${Ge?ie?F?` let zero_point_input = ${Ge.getByOffset("0")}; let zero_point_vec = ${g?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Ge.getByOffset("0")}`:ce?F?` let zero_point_index = ${zt.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${Ge.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${g?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${zt.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${Ge.getByOffset("zero_point_index")};`:F?` let zero_point_offset = ${ze.indicesToOffset("scale_indices")}; let zero_point_input = ${Ge.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${g?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Ge.getByIndices("scale_indices")};`:`let zero_point_value = ${F?g?"i32":"u32":We.type.value}(0);`}; // Compute and write output ${zt.setByOffset("global_idx",`${zt.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:s.cacheKey,inputDependencies:Ge?["rank","rank","rank"]:["rank","rank"]},getShaderSource:wn,getRunData:()=>({outputs:[{dims:w,dataType:m}],dispatchGroup:{x:Math.ceil(P/Pe/64),y:1,z:1},programUniforms:pn})}},Bs=(r,s)=>{kc(r.inputs,s),r.compute(l_(r.inputs,s))},Ma=r=>bn({axis:r.axis,blockSize:r.blockSize})}),Kp,Xp,ch,tC=c(()=>{jt(),Pn(),Vn(),Kp=(r,s,u)=>{let f=r===s,g=rs&&u>0;if(f||g||w)throw new Error("Range these inputs' contents are invalid.")},Xp=(r,s,u,f)=>{let g=Math.abs(Math.ceil((s-r)/u)),w=[g],m=g,P=[{type:12,data:m},{type:f,data:r},{type:f,data:u},...sn(w)],F=O=>{let Y=vn("output",f,w.length),Q=Y.type.value,S=[{name:"outputSize",type:"u32"},{name:"start",type:Q},{name:"delta",type:Q}];return` ${O.registerUniforms(S).declareVariables(Y)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${Q}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${f}`},getShaderSource:F,getRunData:()=>({outputs:[{dims:w,dataType:f}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:P})}},ch=r=>{let s=0,u=0,f=0;r.inputs[0].dataType===6?(s=r.inputs[0].getInt32Array()[0],u=r.inputs[1].getInt32Array()[0],f=r.inputs[2].getInt32Array()[0]):r.inputs[0].dataType===1&&(s=r.inputs[0].getFloat32Array()[0],u=r.inputs[1].getFloat32Array()[0],f=r.inputs[2].getFloat32Array()[0]),j.webgpu.validateInputContent&&Kp(s,u,f),r.compute(Xp(s,u,f,r.inputs[0].dataType),{inputs:[]})}}),_w,yw,vw,ww,bw,xw,Tw,Mw,kw,Sw,Ew,c_,Cw,Pw,Aw,$w,Iw,Fw,Ow,nC=c(()=>{Pn(),Mn(),Bn(),Vn(),_w=(r,s)=>{if(r.every(u=>u>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),r.length>0){if(s.mode==="linear"){if(!(r.length===2||r.length===3||r.length===4&&r[0]===1&&r[1]===1||r.length===4&&r[0]===1&&r[3]===1||r.length===5&&r[0]===1&&r[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(s.mode==="cubic"&&!(r.length===2||r.length===4&&r[0]===1&&r[1]===1||r.length===4&&r[0]===1&&r[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},yw=(r,s,u)=>{s.every(g=>g>=0&&g{throw new Error("Resize requires axes input values to be positive and less than rank")}));let f=new Array(u).fill(1);return s.forEach((g,w)=>f[g]=r[w]),f},vw=(r,s,u,f,g,w)=>{let[m,P,F]=u>10?[1,2,3]:[-1,r.length>1?1:-1,-1],O=r[0].dims.length;if(m>0&&r.length>m&&r[m].dims.length>0)r[m].getFloat32Array().forEach(Y=>w.push(Y));else if(s.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(P>0&&r.length>P&&r[P].dims.length>0){if(r[P].getFloat32Array().forEach(Y=>f.push(Y)),f.length!==0&&f.length!==O&&u>=18&&f.length!==s.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");_w(f,s),s.axes.length>0&&yw(f,s.axes,O).forEach((Y,Q)=>f[Q]=Y)}if(F>0&&r.length>F&&(r[F].getBigInt64Array().forEach(Y=>g.push(Number(Y))),g.length!==O||u>=18&&g.length===s.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(s.axes.length>0){if(f.length!==s.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(g.length!==s.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof f<"u"&&typeof g<"u"&&f.length>0&&g.length>O)throw new Error("Resize requires only of scales or sizes to be specified")},ww=(r,s)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${s} { `+(()=>{switch(r){case"asymmetric":return`return ${s}(xResized) / ${s}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${s}(xResized) + 0.5) / ${s}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${s}(xResized) + 0.5) / ${s}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${s}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${s}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${s}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${s}(roiStart) * ${s}(lengthOriginal - 1) + (${s}(xResized) * ${s}(roiEnd - roiStart) * ${s}(lengthOriginal - 1)) / ${s}(lengthResized - 1); } else { return 0.5 * ${s}(roiStart + roiEnd) * ${s}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${s}xScale * ${s}(lengthResized); const adjustment = ${s}(lengthResized) / outputWidth; const center = ${s}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${s}(xResized) + 0.5) / ${s}(xScale)) - 0.5;`;case"half_pixel":return`return ((${s}(xResized) + 0.5) / ${s}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${r} is not supported`)}})()+"}",bw=(r,s,u)=>`fn getNearestPixelFromOriginal(xOriginal: ${u}, isDownSample: bool) -> ${u} {`+(()=>{switch(r){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(s<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${r} is not supported`)}})()+"}",xw=(r,s,u)=>{let f=new Array(u).fill(0).concat(new Array(u).fill(1)),g=r.length===0?f:r.slice();return s.length>0?(s.forEach((w,m)=>{f[w]=g[m],f[m+u]=g[s.length+m]}),f):g},Tw=(r,s,u,f)=>{let g=[];if(u.length>0)if(f.length>0){if(r.forEach(w=>g.push(w)),Math.max(...f)>r.length)throw new Error("axes is out of bound");f.forEach((w,m)=>g[w]=u[m])}else u.forEach(w=>g.push(w));else{if(s.length===0)throw new Error("Resize requires either scales or sizes.");g=r.map((w,m)=>Math.round(w*s[m]))}return g},Mw=(r,s,u)=>{let f=(()=>{switch(u.keepAspectRatioPolicy){case"not_larger":return u.axes.length>0?Math.min(...u.axes.map(w=>s[w]),Number.MAX_VALUE):Math.min(...s,Number.MAX_VALUE);case"not_smaller":return u.axes.length>0?Math.max(...u.axes.map(w=>s[w]),Number.MIN_VALUE):Math.max(...s,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${u.keepAspectRatioPolicy} is not supported`)}})();s.fill(1,0,s.length);let g=r.slice();return u.axes.length>0?(u.axes.forEach(w=>s[w]=f),u.axes.forEach(w=>g[w]=Math.round(r[w]*s[w]))):(s.fill(f,0,s.length),g.forEach((w,m)=>g[m]=Math.round(w*s[m]))),g},kw=(r,s,u,f,g)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> array<${r.type.value}, ${u.length}> { var original_indices: array<${r.type.value}, ${u.length}>; for (var i:u32 = 0; i < ${u.length}; i++) { var output_index = ${r.indicesGet("output_indices","i")}; var scale = ${gn("uniforms.scales","i",f)}; var roi_low = ${gn("uniforms.roi","i",g)}; var roi_hi = ${gn("uniforms.roi",`i + ${s.length}`,g)}; if (scale == 1.0) { original_indices[i] = ${r.type.value}(output_index); } else { var input_shape_i = ${gn("uniforms.input_shape","i",s.length)}; var output_shape_i = ${gn("uniforms.output_shape","i",u.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,Sw=(r,s,u,f,g,w,m)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${s.type.indices}) -> ${r.type.indices} { var input_indices: ${r.type.indices}; for (var i:u32 = 0; i < ${f.length}; i++) { var output_index = ${s.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${gn("uniforms.scales","i",g)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${gn("uniforms.roi","i",w)}; var roi_hi = ${gn("uniforms.roi",`i + ${u.length}`,w)}; var input_shape_i = ${gn("uniforms.input_shape","i",u.length)}; var output_shape_i = ${gn("uniforms.output_shape","i",f.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${m} || (original_idx >= 0 && original_idx < ${s.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${s.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${r.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,Ew=(r,s)=>` fn checkInputIndices(input_indices: ${r.type.indices}) -> bool { for (var i:u32 = 0; i < ${s.length}; i++) { var input_index = ${r.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${gn("uniforms.input_shape","i",s.length)}) { return false; } } return true; }`,c_=(r,s,u,f)=>r.rank>f?` ${r.indicesSet("input_indices",s,"channel")}; ${r.indicesSet("input_indices",u,"batch")}; `:"",Cw=(r,s,u,f,g)=>{let[w,m,P,F]=u.length===2?[-1,0,1,-1]:[0,2,3,1],O=r.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${O} { var input_indices: ${r.type.indices}; ${r.indicesSet("input_indices",m,`max(0, min(row, ${u[m]} - 1))`)}; ${r.indicesSet("input_indices",P,`max(0, min(col, ${u[P]} - 1))`)}; ${c_(r,F,w,2)} return ${r.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${s.type.indices}) -> ${O} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${O} = originalIndices[${m}]; var col:${O} = originalIndices[${P}]; ${f?`if (row < 0 || row > (${u[m]} - 1) || col < 0 || col > (${u[P]} - 1)) { return ${g}; }`:""}; row = max(0, min(row, ${u[m]} - 1)); col = max(0, min(col, ${u[P]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${u.length>2?`u32(originalIndices[${F}])`:"0"}; var batch: u32 = ${u.length>2?`u32(originalIndices[${w}])`:"0"}; var x11: ${O} = getInputValue(batch, channel, row1, col1); var x12: ${O} = getInputValue(batch, channel, row1, col2); var x21: ${O} = getInputValue(batch, channel, row2, col1); var x22: ${O} = getInputValue(batch, channel, row2, col2); var dx1: ${O} = abs(row - ${O}(row1)); var dx2: ${O} = abs(${O}(row2) - row); var dy1: ${O} = abs(col - ${O}(col1)); var dy2: ${O} = abs(${O}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},Pw=(r,s,u,f,g,w,m,P,F,O)=>{let Y=u.length===2,[Q,S]=Y?[0,1]:[2,3],ie=r.type.value,ce=pe=>{let ke=pe===Q?"row":"col";return` fn ${ke}CubicInterpolation(input_indices: ${r.type.indices}, output_indices: ${s.type.indices}) -> ${ie} { var output_index = ${s.indicesGet("output_indices",pe)}; var originalIdx: ${ie} = getOriginalCoordinateFromResizedCoordinate(output_index, ${g[pe]}, ${f[pe]}, ${u[pe]}, ${w[pe]}, ${w[pe]} + ${u.length}); var fractOriginalIdx: ${ie} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${P} && (originalIdx < 0 || originalIdx > (${u[pe]} - 1))) { return ${F}; } var data: array<${ie}, 4> = array<${ie}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${ke}: ${ie} = originalIdx + ${ie}(i); if (${ke} < 0 || ${ke} >= ${u[pe]}) { ${O?`coefs[i + 1] = 0.0; continue;`:P?`return ${F};`:`${ke} = max(0, min(${ke}, ${u[pe]} - 1));`}; } var input_indices_copy: ${r.type.indices} = input_indices; ${r.indicesSet("input_indices_copy",pe,`u32(${ke})`)}; data[i + 1] = ${pe===Q?r.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${ce(Q)}; ${ce(S)}; fn getCubicInterpolationCoefs(s: ${ie}) -> array<${ie}, 4> { var absS = abs(s); var coeffs: array<${ie}, 4> = array<${ie}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${ie} = 1.0 - absS; var twoMinusAbsS: ${ie} = 2.0 - absS; var onePlusAbsS: ${ie} = 1.0 + absS; coeffs[0] = ((${m} * onePlusAbsS - 5 * ${m}) * onePlusAbsS + 8 * ${m}) * onePlusAbsS - 4 * ${m}; coeffs[1] = ((${m} + 2) * absS - (${m} + 3)) * absS * absS + 1; coeffs[2] = ((${m} + 2) * oneMinusAbsS - (${m} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${m} * twoMinusAbsS - 5 * ${m}) * twoMinusAbsS + 8 * ${m}) * twoMinusAbsS - 4 * ${m}; return coeffs; } fn cubicInterpolation1D(x: array<${ie}, 4>, coefs: array<${ie}, 4>) -> ${ie} { var coefsSum: ${ie} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${s.type.indices}) -> ${ie} { var input_indices: ${r.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},Aw=(r,s,u,f,g)=>{let[w,m,P,F,O]=u.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],Y=r.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${Y} { var input_indices: ${r.type.indices}; ${r.indicesSet("input_indices",m,`max(0, min(depth, ${u[m]} - 1))`)}; ${r.indicesSet("input_indices",P,`max(0, min(height, ${u[P]} - 1))`)}; ${r.indicesSet("input_indices",F,`max(0, min(width, ${u[F]} - 1))`)}; ${c_(r,O,w,3)} return ${r.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${s.type.indices}) -> ${Y} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${Y} = originalIndices[${m}]; var height:${Y} = originalIndices[${P}]; var width:${Y} = originalIndices[${F}]; ${f?`if (depth < 0 || depth > (${u[m]} - 1) || height < 0 || height > (${u[P]} - 1) || width < 0 || (width > ${u[F]} - 1)) { return ${g}; }`:""}; depth = max(0, min(depth, ${u[m]} - 1)); height = max(0, min(height, ${u[P]} - 1)); width = max(0, min(width, ${u[F]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${u.length>3?`u32(originalIndices[${O}])`:"0"}; var batch: u32 = ${u.length>3?`u32(originalIndices[${w}])`:"0"}; var x111: ${Y} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${Y} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${Y} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${Y} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${Y} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${Y} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${Y} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${Y} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${Y} = abs(depth - ${Y}(depth1)); var dx2: ${Y} = abs(${Y}(depth2) - depth); var dy1: ${Y} = abs(height - ${Y}(height1)); var dy2: ${Y} = abs(${Y}(height2) - height); var dz1: ${Y} = abs(width - ${Y}(width1)); var dz2: ${Y} = abs(${Y}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},$w=(r,s,u,f,g,w)=>{let m=r.dims,P=xw(w,s.axes,m.length),F=Tw(m,f,g,s.axes),O=f.slice();f.length===0&&(O=m.map((be,We)=>be===0?1:F[We]/be),s.keepAspectRatioPolicy!=="stretch"&&(F=Mw(m,O,s)));let Y=vn("output",r.dataType,F.length),Q=Bt("input",r.dataType,m.length),S=mt.size(F),ie=m.length===F.length&&m.every((be,We)=>be===F[We]),ce=s.coordinateTransformMode==="tf_crop_and_resize",pe=s.extrapolationValue,ke=Q.type.value,Pe=be=>` ${ie?"":` ${ww(s.coordinateTransformMode,ke)}; ${(()=>{switch(s.mode){case"nearest":return` ${Ew(Q,m)}; ${bw(s.nearestMode,u,ke)}; ${Sw(Q,Y,m,F,O.length,P.length,ce)}; `;case"linear":return` ${kw(Y,m,F,O.length,P.length)}; ${(()=>{if(m.length===2||m.length===4)return`${Cw(Q,Y,m,ce,pe)}`;if(m.length===3||m.length===5)return`${Aw(Q,Y,m,ce,pe)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(m.length===2||m.length===4)return`${Pw(Q,Y,m,F,O,P,s.cubicCoeffA,ce,s.extrapolationValue,s.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${be.registerUniform("output_size","u32").registerUniform("scales","f32",O.length).registerUniform("roi","f32",P.length).declareVariables(Q,Y)} ${be.mainStart()} ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${ie?"output[global_idx] = input[global_idx];":` let output_indices = ${Y.offsetToIndices("global_idx")}; var input_indices: ${Q.type.indices}; ${(()=>{switch(s.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${Q.getByIndices("input_indices")}; } else { output[global_idx] = ${s.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${m.length===2||m.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${s.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${s.cacheKey}|${u}|${O.length>0?O:""}|${g.length>0?g:""}|${P.length>0?P:""}|${ie}|${m}`,inputDependencies:["rank"]},getShaderSource:Pe,getRunData:()=>({outputs:[{dims:F,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},{type:1,data:O},{type:1,data:P},...sn(m,F)]})}},Iw=r=>{let s=r.customDataBuffer;return new Uint32Array(s,s.byteOffset,1)[0]},Fw=(r,s)=>{let u=[],f=[],g=[],w=Iw(r);if(s.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");vw(r.inputs,s,w,u,f,g),r.compute($w(r.inputs[0],s,w,u,f,g),{inputs:[0]})},Ow=r=>{let s=r.antialias,u=r.axes,f=r.coordinateTransformMode,g=r.cubicCoeffA,w=r.excludeOutside!==0,m=r.extrapolationValue,P=r.keepAspectRatioPolicy,F=r.mode,O=r.nearestMode===""?"simple":r.nearestMode;return bn({antialias:s,axes:u,coordinateTransformMode:f,cubicCoeffA:g,excludeOutside:w,extrapolationValue:m,keepAspectRatioPolicy:P,mode:F,nearestMode:O})}}),Dw,zw,Rw,rC=c(()=>{Pn(),Mn(),Bn(),Vn(),Dw=(r,s)=>{let[u,f,g,w]=r,{numHeads:m,rotaryEmbeddingDim:P}=s;if(u.dims.length!==3&&u.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${u.dims.length}`);if(!mt.areEqual(f.dims,[])&&!mt.areEqual(f.dims,[1])&&f.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${f.dims.length}`);if(g.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${g.dims.length}`);if(w.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${w.dims.length}`);if(!mt.areEqual(g.dims,w.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(P>0&&m===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let F=u.dims[0],O=u.dims[u.dims.length-2],Y=g.dims[0],Q=mt.sizeFromDimension(u.dims,1)/O,S=P===0?g.dims[1]*2:Q/m;if(P>S)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(f.dims.length===2){if(F!==f.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${f.dims[0]}`);if(O!==f.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${f.dims[1]}`)}if(S/2!==g.dims[1]&&P/2!==g.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${g.dims[1]}`);if(O>Y)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},zw=(r,s)=>{let{interleaved:u,numHeads:f,rotaryEmbeddingDim:g,scale:w}=s,m=r[0].dims[0],P=mt.sizeFromDimension(r[0].dims,1),F=r[0].dims[r[0].dims.length-2],O=P/F,Y=r[2].dims[1],Q=g===0?Y*2:O/f,S=new Array(m,F,O/Q,Q-Y),ie=mt.computeStrides(S),ce=[{type:1,data:w},{type:12,data:S},{type:12,data:ie},...r[0].dims.length===3?new Array({type:12,data:[P,O,Q,1]}):[],...r[0].dims.length===4?new Array({type:12,data:[P,Q,F*Q,1]}):[],...sn(r[0].dims,r[1].dims,r[2].dims,r[3].dims,r[0].dims)],pe=ke=>{let Pe=Bt("input",r[0].dataType,r[0].dims.length),be=Bt("position_ids",r[1].dataType,r[1].dims.length),We=Bt("cos_cache",r[2].dataType,r[2].dims.length),ze=Bt("sin_cache",r[3].dataType,r[3].dims.length),Ge=vn("output",r[0].dataType,r[0].dims.length);return ke.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:S.length},{name:"global_strides",type:"u32",length:ie.length},{name:"input_output_strides",type:"u32",length:ie.length}]),` ${ke.declareVariables(Pe,be,We,ze,Ge)} ${ke.mainStart(Ii)} let half_rotary_emb_dim = uniforms.${We.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${ke.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${be.broadcastedIndicesToOffset("bsnh.xy",vn("",be.type.tensor,2))}; let position_id = u32(${be.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${u}); let j = i + select(half_rotary_emb_dim, 1, ${u}); let re = ${Pe.getByOffset("i")} * ${We.get("position_id","bsnh[3]")} - ${Pe.getByOffset("j")} * ${ze.get("position_id","bsnh[3]")}; ${Ge.setByOffset("i","re")} let im = ${Pe.getByOffset("i")} * ${ze.get("position_id","bsnh[3]")} + ${Pe.getByOffset("j")} * ${We.get("position_id","bsnh[3]")}; ${Ge.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${Ge.setByOffset("k",Pe.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:bn({interleaved:u}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:pe,getRunData:()=>({outputs:[{dims:r[0].dims,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(mt.size(S)/Ii)},programUniforms:ce})}},Rw=(r,s)=>{Dw(r.inputs,s),r.compute(zw(r.inputs,s))}}),Lw,Bw,Nw,iC=c(()=>{Pn(),Mn(),Vn(),Lw=r=>{if(!r||r.length<3)throw new Error("layerNorm requires at least 3 inputs.");let s=r[0],u=r[1],f=r[2];if(s.dataType!==u.dataType||s.dataType!==f.dataType)throw new Error("All inputs must have the same data type");if(s.dims.length!==3&&s.dims.length!==2)throw new Error("Input must be 2D or 3D");if(u.dims.length!==3&&u.dims.length!==2)throw new Error("Skip must be 2D or 3D");let g=s.dims[s.dims.length-1],w=s.dims[s.dims.length-2];if(u.dims[u.dims.length-1]!==g)throw new Error("Skip must have the same hidden size as input");if(u.dims[u.dims.length-2]!==w)throw new Error("Skip must have the same sequence length as input");if(f.dims.length!==1)throw new Error("Gamma must be 1D");if(f.dims[f.dims.length-1]!==g)throw new Error("Gamma must have the same hidden size as input");if(r.length>3){let m=r[3];if(m.dims.length!==1)throw new Error("Beta must be 1D");if(m.dims[m.dims.length-1]!==g)throw new Error("Beta must have the same hidden size as input")}if(r.length>4){let m=r[4];if(m.dims.length!==1)throw new Error("Bias must be 1D");if(m.dims[m.dims.length-1]!==g)throw new Error("Bias must have the same hidden size as input")}},Bw=(r,s,u,f)=>{let g=s.simplified,w=r[0].dims,m=mt.size(w),P=w,F=m,O=w.slice(-1)[0],Y=f?w.slice(0,-1).concat(1):[],Q=!g&&r.length>3,S=r.length>4,ie=f&&u>1,ce=f&&u>2,pe=u>3,ke=64,Pe=nr(O),be=[{type:12,data:F},{type:12,data:Pe},{type:12,data:O},{type:1,data:s.epsilon}],We=Ge=>{let zt=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],It=[Bt("x",r[0].dataType,r[0].dims,Pe),Bt("skip",r[1].dataType,r[1].dims,Pe),Bt("gamma",r[2].dataType,r[2].dims,Pe)];Q&&It.push(Bt("beta",r[3].dataType,r[3].dims,Pe)),S&&It.push(Bt("bias",r[4].dataType,r[4].dims,Pe)),It.push(vn("output",r[0].dataType,P,Pe)),ie&&It.push(vn("mean_output",1,Y)),ce&&It.push(vn("inv_std_output",1,Y)),pe&&It.push(vn("input_skip_bias_sum",r[0].dataType,P,Pe));let Ht=lr(r[0].dataType),pn=lr(1,Pe);return` ${Ge.registerUniforms(zt).declareVariables(...It)} var sum_shared : array<${pn}, ${ke}>; var sum_squared_shared : array<${pn}, ${ke}>; ${Ge.mainStart([ke,1,1])} let ix = local_id.x; let iy = global_id.x / ${ke}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${ke}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${ke-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${S?"bias[offset1d + i]":Ht+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${pe?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Fr(Ht,Pe,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${ke}; for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { reduce_size = curr_size + (reduce_size & 1); if (ix < curr_size) { sum_shared[ix] += sum_shared[ix + reduce_size]; sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; } workgroupBarrier(); } let sum = sum_shared[0]; let square_sum = sum_squared_shared[0]; let mean = ${Fi("sum",Pe)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Fi("square_sum",Pe)} / f32(uniforms.hidden_size) ${g?"":"- mean * mean"} + uniforms.epsilon); ${ie?"mean_output[global_idx] = mean;":""} ${ce?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${g?"":`- ${Ht}(mean)`}) * ${Ht}(inv_std_dev) * gamma[offset1d + i] ${Q?"+ beta[offset1d + i]":""}; } }`},ze=[{dims:P,dataType:r[0].dataType}];return u>1&&ze.push({dims:Y,dataType:1}),u>2&&ze.push({dims:Y,dataType:1}),u>3&&ze.push({dims:w,dataType:r[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${Pe};${ie};${ce};${pe}`,inputDependencies:r.map((Ge,zt)=>"type")},getShaderSource:We,getRunData:()=>({outputs:ze,dispatchGroup:{x:Math.ceil(F/O)},programUniforms:be})}},Nw=(r,s)=>{Lw(r.inputs);let u=[0];r.outputCount>1&&u.push(-3),r.outputCount>2&&u.push(-3),r.outputCount>3&&u.push(3),r.compute(Bw(r.inputs,s,r.outputCount,!1),{outputs:u})}}),jw,dh,Vw,d_,Uw,Ww,Gw,qw,sC=c(()=>{Pn(),Mn(),Bn(),Vn(),jw=(r,s)=>{if(!r||r.length<1)throw new Error("too few inputs");if(s.axes.length!==0){if(s.axes.length!==s.starts.length||s.axes.length!==s.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(s.starts.length!==s.ends.length)throw new Error("starts and ends must have the same length");r.slice(1).forEach((u,f)=>{if(r[f+1].dataType!==6&&r[f+1].dataType!==7)throw new Error(`Input ${f} must be an array of int32 or int64`)})},dh=(r,s)=>{let u=[];if(r.length>s)if(r[s].dataType===7)r[s].getBigInt64Array().forEach(f=>u.push(Number(f)));else if(r[s].dataType===6)r[s].getInt32Array().forEach(f=>u.push(Number(f)));else throw new Error(`Input ${s} must be an array of int32 or int64`);return u},Vw=(r,s)=>{if(r.length>1){let u=dh(r,1),f=dh(r,2),g=dh(r,3);return g.length===0&&(g=[...Array(r[0].dims.length).keys()]),bn({starts:u,ends:f,axes:g})}else return s},d_=(r,s,u,f,g)=>{let w=r;return r<0&&(w+=u[f[s]]),g[s]<0?Math.max(0,Math.min(w,u[f[s]]-1)):Math.max(0,Math.min(w,u[f[s]]))},Uw=(r,s,u)=>`fn calculateInputIndices(output_indices: ${s.type.indices}) -> ${r.type.indices} { var input_indices: ${r.type.indices}; var carry = 0u; for (var i = ${u.length}; i >= 0; i--) { let input_shape_i = ${gn("uniforms.input_shape","i",u.length)}; let steps_i = ${gn("uniforms.steps","i",u.length)}; let signs_i = ${gn("uniforms.signs","i",u.length)}; let starts_i = ${gn("uniforms.starts","i",u.length)}; var output_index = ${s.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${r.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,Ww=(r,s)=>{let u=r[0].dims,f=mt.size(u),g=s.axes.length>0?mt.normalizeAxes(s.axes,u.length):[...Array(u.length).keys()],w=dh(r,4);w.forEach(Pe=>Pe!==0||(()=>{throw new Error("step cannot be 0")})),w.length===0&&(w=Array(g.length).fill(1));let m=s.starts.map((Pe,be)=>d_(Pe,be,u,g,w)),P=s.ends.map((Pe,be)=>d_(Pe,be,u,g,w));if(g.length!==m.length||g.length!==P.length)throw new Error("start, ends and axes should have the same number of elements");if(g.length!==u.length)for(let Pe=0;PeMath.sign(Pe));w.forEach((Pe,be,We)=>{if(Pe<0){let ze=(P[be]-m[be])/Pe,Ge=m[be],zt=Ge+ze*w[be];m[be]=zt,P[be]=Ge,We[be]=-Pe}});let O=u.slice(0);g.forEach((Pe,be)=>{O[Pe]=Math.ceil((P[Pe]-m[Pe])/w[Pe])});let Y={dims:O,dataType:r[0].dataType},Q=vn("output",r[0].dataType,O.length),S=Bt("input",r[0].dataType,r[0].dims.length),ie=mt.size(O),ce=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:m.length},{name:"signs",type:"i32",length:F.length},{name:"steps",type:"u32",length:w.length}],pe=[{type:12,data:ie},{type:12,data:m},{type:6,data:F},{type:12,data:w},...sn(r[0].dims,O)],ke=Pe=>` ${Pe.registerUniforms(ce).declareVariables(S,Q)} ${Uw(S,Q,u)} ${Pe.mainStart()} ${Pe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${Q.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${Q.setByOffset("global_idx",S.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${F.length}_${m.length}_${w.length}`,inputDependencies:["rank"]},getShaderSource:ke,getRunData:()=>({outputs:[Y],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:pe})}},Gw=(r,s)=>{jw(r.inputs,s);let u=Vw(r.inputs,s);r.compute(Ww(r.inputs,u),{inputs:[0]})},qw=r=>{let s=r.starts,u=r.ends,f=r.axes;return bn({starts:s,ends:u,axes:f})}}),Hw,Kw,Xw,Qw,oC=c(()=>{Pn(),Mn(),Bn(),Vn(),Hw=r=>{if(!r||r.length!==1)throw new Error("Softmax op requires 1 input.")},Kw=(r,s)=>{let u=r.dims,f=mt.size(u),g=64,w=s.axis;if(w<0&&(w=u.length+w),wPe===4?`max(max(${ke}.x, ${ke}.y), max(${ke}.z, ${ke}.w))`:Pe===2?`max(${ke}.x, ${ke}.y)`:Pe===3?`max(max(${ke}.x, ${ke}.y), ${ke}.z)`:ke,Q=Bt("x",r.dataType,r.dims,F),S=vn("result",r.dataType,r.dims,F),ie=Q.type.value,ce=lr(r.dataType)==="f32"?`var threadMax = ${ie}(-3.402823e+38f);`:`var threadMax = ${ie}(-65504.0h);`,pe=ke=>` var rowMaxShared : ${ie}; var rowSumShared : ${ie}; var threadShared : array<${ie}, ${g}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${ie} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${ie}) { let index = row * row_stride + col; result[index] = value; } ${ke.registerUniform("packedCols","i32").declareVariables(Q,S)} ${ke.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${g}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${ce} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${ie}(${Y("threadShared[0]",F)}); } workgroupBarrier(); // find the rows sum var threadSum = ${ie}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; } threadShared[lindex] = threadSum; workgroupBarrier(); for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { if (lindex < currSize) { threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; } workgroupBarrier(); } if (lindex == 0) { rowSumShared = ${ie}(${Fi("threadShared[0]",F)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`;return{name:"Softmax",shaderCache:{hint:`${F}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:u,dataType:r.dataType}],dispatchGroup:{x:P},programUniforms:[{type:6,data:O}]}),getShaderSource:pe}},Xw=(r,s)=>{Hw(r.inputs),r.compute(Kw(r.inputs[0],s))},Qw=r=>bn({axis:r.axis})}),Yw,Zw,Jw,e1,t1,n1,r1,aC=c(()=>{Pn(),Mn(),Bn(),Vn(),Yw=r=>{if(!r||r.length<1)throw new Error("too few inputs")},Zw=(r,s)=>{let u=[],f=s.numOutputs;return r[1].dims[0]>0&&(r[1].getBigInt64Array().forEach(g=>u.push(Number(g))),f=u.length),bn({numOutputs:f,axis:s.axis,splitSizes:u})},Jw=r=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${r}u; i += 1u ) { if (index < ${gn("uniforms.size_in_split_axis","i",r)}) { return i; } } return ${r}u; }`,e1=r=>{let s=r.length,u=[];for(let f=0;f{let u=r[0].dims,f=mt.size(u),g=r[0].dataType,w=mt.normalizeAxis(s.axis,u.length),m=new Array(s.numOutputs),P=Bt("input",g,u.length),F=new Array(s.numOutputs),O=[],Y=[],Q=0,S=[{type:12,data:f}];for(let ce=0;ce` ${ce.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",F.length).declareVariables(P,...m)} ${Jw(F.length)} ${e1(m)} ${ce.mainStart()} ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${P.offsetToIndices("global_idx")}; var index = ${P.indicesGet("indices",w)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${gn("uniforms.size_in_split_axis","output_number - 1u",F.length)}; ${P.indicesSet("indices",w,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getShaderSource:ie,getRunData:()=>({outputs:O,dispatchGroup:{x:Math.ceil(f/64)},programUniforms:S})}},n1=(r,s)=>{Yw(r.inputs);let u=r.inputs.length===1?s:Zw(r.inputs,s);r.compute(t1(r.inputs,u),{inputs:[0]})},r1=r=>{let s=r.axis,u=r.splitSizes,f=r.numOutputs<0?u.length:r.numOutputs;if(f!==u.length)throw new Error("numOutputs and splitSizes lengh must be equal");return bn({axis:s,numOutputs:f,splitSizes:u})}}),i1,s1,o1,lC=c(()=>{Pn(),Mn(),Vn(),i1=(r,s,u,f,g)=>{let w=vn("output_data",g,u.length,4),m=Bt("a_data",s[1].dataType,s[1].dims.length,4),P=Bt("b_data",s[2].dataType,s[2].dims.length,4),F=Bt("c_data",s[0].dataType,s[0].dims.length,4),O,Y=(Q,S,ie)=>`select(${S}, ${Q}, ${ie})`;if(!f)O=w.setByOffset("global_idx",Y(m.getByOffset("global_idx"),P.getByOffset("global_idx"),F.getByOffset("global_idx")));else{let Q=(S,ie,ce="")=>{let pe=`a_data[index_a${ie}][component_a${ie}]`,ke=`b_data[index_b${ie}][component_b${ie}]`,Pe=`bool(c_data[index_c${ie}] & (0xffu << (component_c${ie} * 8)))`;return` let output_indices${ie} = ${w.offsetToIndices(`global_idx * 4u + ${ie}u`)}; let offset_a${ie} = ${m.broadcastedIndicesToOffset(`output_indices${ie}`,w)}; let offset_b${ie} = ${P.broadcastedIndicesToOffset(`output_indices${ie}`,w)}; let offset_c${ie} = ${F.broadcastedIndicesToOffset(`output_indices${ie}`,w)}; let index_a${ie} = offset_a${ie} / 4u; let index_b${ie} = offset_b${ie} / 4u; let index_c${ie} = offset_c${ie} / 4u; let component_a${ie} = offset_a${ie} % 4u; let component_b${ie} = offset_b${ie} % 4u; let component_c${ie} = offset_c${ie} % 4u; ${S}[${ie}] = ${ce}(${Y(pe,ke,Pe)}); `};g===9?O=` var data = vec4(0); ${Q("data",0,"u32")} ${Q("data",1,"u32")} ${Q("data",2,"u32")} ${Q("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:O=` ${Q("output_data[global_idx]",0)} ${Q("output_data[global_idx]",1)} ${Q("output_data[global_idx]",2)} ${Q("output_data[global_idx]",3)} `}return` ${r.registerUniform("vec_size","u32").declareVariables(F,m,P,w)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${O} }`},s1=r=>{let s=r[1].dims,u=r[2].dims,f=r[0].dims,g=r[1].dataType,w=!(mt.areEqual(s,u)&&mt.areEqual(u,f)),m=s,P=mt.size(s);if(w){let O=Qr.calcShape(Qr.calcShape(s,u,!1),f,!1);if(!O)throw new Error("Can't perform where op on the given tensors");m=O,P=mt.size(m)}let F=Math.ceil(P/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:O=>i1(O,r,m,w,g),getRunData:()=>({outputs:[{dims:m,dataType:g}],dispatchGroup:{x:Math.ceil(P/64/4)},programUniforms:[{type:12,data:F},...sn(f,s,u,m)]})}},o1=r=>{r.compute(s1(r.inputs))}}),a1,uC=c(()=>{y(),qe(),nt(),wt(),kp(),Sp(),Ep(),nc(),Fp(),Op(),Rp(),s_(),Bp(),Cf(),o_(),jp(),Vp(),Up(),Gp(),qp(),a_(),Ql(),Ri(),Gf(),At(),Mc(),u_(),tC(),qo(),nC(),rC(),iC(),sC(),oC(),aC(),Xf(),yo(),zu(),lC(),a1=new Map([["Abs",[Xt]],["Acos",[on]],["Acosh",[Kt]],["Add",[Lu]],["ArgMax",[nl,h]],["ArgMin",[Ss,h]],["Asin",[rn]],["Asinh",[ln]],["Atan",[qt]],["Atanh",[Un]],["Attention",[Qe]],["AveragePool",[dr,or]],["BatchNormalization",[Xe]],["BiasAdd",[yt]],["BiasSplitGelu",[Ru]],["Cast",[Qn,Gn]],["Ceil",[Hn]],["Clip",[Ui]],["Concat",[qd,Vu]],["Conv",[tc,Zu]],["ConvTranspose",[ac,oc]],["Cos",[ri]],["Cosh",[ii]],["CumSum",[lc,yf]],["DepthToSpace",[cc,dc]],["DequantizeLinear",[Bs,Ma]],["Div",[zd]],["Einsum",[Tf,xr]],["Elu",[si,Rs]],["Equal",[Rd]],["Erf",[Ho]],["Exp",[_d]],["Expand",[Sf]],["FastGelu",[mc]],["Floor",[yd]],["FusedConv",[tc,Zu]],["Gather",[Np,gc]],["GatherElements",[Lf,Rf]],["GatherBlockQuantized",[Ff,Of]],["Gelu",[vd]],["Gemm",[Vf,jf]],["GlobalAveragePool",[qi,Gi]],["GlobalMaxPool",[Tc,Mi]],["Greater",[Nu]],["GreaterOrEqual",[jd]],["GroupQueryAttention",[Jf,Yf]],["HardSigmoid",[Pu,Md]],["InstanceNormalization",[rh]],["LayerNormalization",[oh]],["LeakyRelu",[Eu,Rs]],["Less",[Nd]],["LessOrEqual",[ju]],["Log",[Pd]],["MatMul",[sf]],["MatMulNBits",[hi,vi]],["MaxPool",[Li,oi]],["Mul",[Bu]],["MultiHeadAttention",[Wf,_c]],["Neg",[bd]],["Not",[wd]],["Pad",[kt]],["Pow",[Ld]],["QuickGelu",[Gl,Rs]],["Range",[ch]],["Reciprocal",[xd]],["ReduceMin",[xi]],["ReduceMean",[Ul]],["ReduceMax",[Go]],["ReduceSum",[wa]],["ReduceProd",[Wl]],["ReduceL1",[Wo]],["ReduceL2",[rs]],["ReduceLogSum",[zs]],["ReduceLogSumExp",[Lr]],["ReduceSumSquare",[ba]],["Relu",[Cu]],["Resize",[Fw,Ow]],["RotaryEmbedding",[Rw]],["Sigmoid",[Td]],["Sin",[kd]],["Sinh",[Sd]],["Slice",[Gw,qw]],["SkipLayerNormalization",[Nw]],["Split",[n1,r1]],["Sqrt",[Au]],["Softmax",[Xw,Qw]],["Sub",[Bd]],["Tan",[Ed]],["Tanh",[Iu]],["ThresholdedRelu",[Cd,Rs]],["Tile",[Kf]],["Transpose",[zo,da]],["Where",[o1]]])}),l1,cC=c(()=>{jt(),_i(),Vn(),l1=class{constructor(r){this.backend=r,this.repo=new Map,this.attributesBound=!1}getArtifact(r){return this.repo.get(r)}setArtifact(r,s){this.repo.set(r,s)}run(r,s,u,f,g){xt(r.programInfo.name);let w=this.backend.device,m=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let P=[];for(let O of s)P.push({binding:P.length,resource:{buffer:O.buffer}});for(let O of u)P.push({binding:P.length,resource:{buffer:O.buffer}});g&&P.push({binding:P.length,resource:g});let F=w.createBindGroup({layout:r.computePipeline.getBindGroupLayout(0),entries:P,label:r.programInfo.name});if(this.backend.sessionStatus==="capturing"){let O={kernelId:this.backend.currentKernelId,computePipeline:r.computePipeline,bindGroup:F,dispatchGroup:f};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(O)}m.setPipeline(r.computePipeline),m.setBindGroup(0,F),m.dispatchWorkgroups(...f),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),z(r.programInfo.name)}dispose(){}build(r,s){xt(r.name);let u=this.backend.device,f=[];u.features.has("shader-f16")&&f.push("enable f16;");let g=Bl(s,this.backend.device.limits),w=r.getShaderSource(g),m=`${f.join(` `)} ${g.additionalImplementations} ${w}`,P=u.createShaderModule({code:m,label:r.name});kr("verbose",()=>`[WebGPU] ${r.name} shader code: ${m}`);let F=u.createComputePipeline({compute:{module:P,entryPoint:"main"},layout:"auto",label:r.name});return z(r.name),{programInfo:r,computePipeline:F,uniformVariablesInfo:g.variablesInfo}}normalizeDispatchGroupSize(r){let s=typeof r=="number"?r:r.x,u=typeof r=="number"?1:r.y||1,f=typeof r=="number"?1:r.z||1,g=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(s<=g&&u<=g&&f<=g)return[s,u,f];let w=s*u*f,m=Math.ceil(Math.sqrt(w));if(m>g){if(m=Math.ceil(Math.cbrt(w)),m>g)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[m,m,m]}else return[m,m,1]}}}),u1,c1,d1,f1,dC=c(()=>{jt(),Pn(),_i(),K(),Wn(),uC(),cC(),u1=(r,s)=>{if(s.length!==r.length)throw new Error(`inputDependencies length ${s.length} is not equal to inputTensors length ${r.length}.`);let u=[];for(let f=0;f{var g,w;let f=r.name;return(g=r.shaderCache)!=null&&g.hint&&(f+="["+r.shaderCache.hint+"]"),f+=":"+u+`:${u1(s,((w=r.shaderCache)==null?void 0:w.inputDependencies)??new Array(s.length).fill("dims"))}`,f},d1=class{constructor(r){r&&(this.architecture=r.architecture,this.vendor=r.vendor)}isArchitecture(r){return this.architecture===r}isVendor(r){return this.vendor===r}},f1=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let r=this.kernelCustomData.get(this.currentKernelId);return r||(r={},this.kernelCustomData.set(this.currentKernelId,r)),r}async initialize(r,s){this.env=r;let u=[],f={requiredLimits:{maxComputeWorkgroupStorageSize:s.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:s.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:s.limits.maxStorageBufferBindingSize,maxBufferSize:s.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:s.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:s.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:s.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:s.limits.maxComputeWorkgroupSizeZ},requiredFeatures:u};s.features.has("chromium-experimental-timestamp-query-inside-passes")?u.push("chromium-experimental-timestamp-query-inside-passes"):s.features.has("timestamp-query")&&u.push("timestamp-query"),s.features.has("shader-f16")&&u.push("shader-f16"),this.device=await s.requestDevice(f),this.adapterInfo=new d1(s.info||await s.requestAdapterInfo()),this.gpuDataManager=Rn(this),this.programManager=new l1(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ps(r.logLevel,!!r.debug),this.device.onuncapturederror=g=>{g.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${g.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:s,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let r=this.getCommandEncoder(),s={};this.queryType==="at-passes"&&(s.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=r.beginComputePass(s)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;xt(),this.endComputePass();let r;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),r=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(r,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,r,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&r.mapAsync(GPUMapMode.READ).then(()=>{var f;let s=new BigUint64Array(r.getMappedRange()),u=this.pendingQueries.get(r);for(let g=0;g"u"&&(this.queryTimeBase=ie);let pe=Number(ie-this.queryTimeBase),ke=Number(ce-this.queryTimeBase);if(!Number.isSafeInteger(pe)||!Number.isSafeInteger(ke))throw new RangeError("incorrect timestamp range");if((f=this.env.webgpu.profiling)!=null&&f.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:Q.map(Pe=>({dims:Pe.dims,dataType:Ai(Pe.dataType)})),outputsMetadata:S.map(Pe=>({dims:Pe.dims,dataType:Ai(Pe.dataType)})),kernelId:m,kernelType:F,kernelName:O,programName:Y,startTime:pe,endTime:ke});else{let Pe="";Q.forEach((We,ze)=>{Pe+=`input[${ze}]: [${We.dims}] | ${Ai(We.dataType)}, `});let be="";S.forEach((We,ze)=>{be+=`output[${ze}]: [${We.dims}] | ${Ai(We.dataType)}, `}),console.log(`[profiling] kernel "${m}|${F}|${O}|${Y}" ${Pe}${be}execution time: ${ke-pe} ns`)}rt("GPU",`${Y}::${ie}::${ce}`)}r.unmap(),this.pendingQueries.delete(r)}),z()}run(r,s,u,f,g,w){xt(r.name);let m=[];for(let be=0;beWe):u;if(Y.length!==P.length)throw new Error(`Output size ${Y.length} must be equal to ${P.length}.`);let Q=[],S=[];for(let be=0;be=w)throw new Error(`Invalid output index: ${Y[be]}`);if(Y[be]===-3)continue;let We=Y[be]===-1,ze=Y[be]===-2,Ge=We||ze?g(P[be].dataType,P[be].dims):f(Y[be],P[be].dataType,P[be].dims);if(Q.push(Ge),Ge.data===0)continue;let zt=this.gpuDataManager.get(Ge.data);if(!zt)throw new Error(`no GPU data for output: ${Ge.data}`);if(We&&this.temporaryData.push(zt),ze){let It=this.kernelPersistentData.get(this.currentKernelId);It||(It=[],this.kernelPersistentData.set(this.currentKernelId,It)),It.push(zt)}S.push(zt)}if(m.length!==s.length||S.length!==Q.length){if(S.length===0)return z(r.name),Q;throw new Error(`Program ${r.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let ie;if(O){let be=0,We=[];O.forEach(It=>{let Ht=typeof It.data=="number"?[It.data]:It.data;if(Ht.length===0)return;let pn=It.type===10?2:4,wn,Xn;It.type===10?(Xn=Ht.length>4?16:Ht.length>2?8:Ht.length*pn,wn=Ht.length>4?16:pn*Ht.length):(Xn=Ht.length<=2?Ht.length*pn:16,wn=16),be=Math.ceil(be/Xn)*Xn,We.push(be);let ar=It.type===10?8:4;be+=Ht.length>4?Math.ceil(Ht.length/ar)*wn:Ht.length*pn});let ze=16;be=Math.ceil(be/ze)*ze;let Ge=new ArrayBuffer(be);O.forEach((It,Ht)=>{let pn=We[Ht],wn=typeof It.data=="number"?[It.data]:It.data;if(It.type===6)new Int32Array(Ge,pn,wn.length).set(wn);else if(It.type===12)new Uint32Array(Ge,pn,wn.length).set(wn);else if(It.type===10)new Uint16Array(Ge,pn,wn.length).set(wn);else if(It.type===1)new Float32Array(Ge,pn,wn.length).set(wn);else throw new Error(`Unsupported uniform type: ${Ai(It.type)}`)});let zt=this.gpuDataManager.create(be,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(zt.buffer,0,Ge,0,be),this.gpuDataManager.release(zt.id),ie={offset:0,size:be,buffer:zt.buffer}}let ce=this.programManager.normalizeDispatchGroupSize(F),pe=ce[1]===1&&ce[2]===1,ke=c1(r,s,pe),Pe=this.programManager.getArtifact(ke);if(Pe||(Pe=this.programManager.build(r,ce),this.programManager.setArtifact(ke,Pe),kr("info",()=>`[artifact] key: ${ke}, programName: ${r.name}`)),O&&Pe.uniformVariablesInfo){if(O.length!==Pe.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${Pe.uniformVariablesInfo.length}, got ${O.length} in program "${Pe.programInfo.name}".`);for(let be=0;be`[ProgramManager] run "${r.name}" (key=${ke}) with ${ce[0]}x${ce[1]}x${ce[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let be={kernelId:this.currentKernelId,programName:Pe.programInfo.name,inputTensorViews:s,outputTensorViews:Q};this.pendingKernels.push(be),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(be)}return this.programManager.run(Pe,m,S,ce,ie),z(r.name),Q}upload(r,s){this.gpuDataManager.upload(r,s)}memcpy(r,s){this.gpuDataManager.memcpy(r,s)}async download(r,s){await this.gpuDataManager.download(r,s)}alloc(r){return this.gpuDataManager.create(r).id}free(r){return this.gpuDataManager.release(r)}createKernel(r,s,u,f){let g=a1.get(r);if(!g)throw new Error(`kernel not implemented: ${r}`);let w={kernelType:r,kernelName:f,kernelEntry:g[0],attributes:[g[1],u]};this.kernels.set(s,w)}releaseKernel(r){let s=this.kernelPersistentData.get(r);if(s){for(let u of s)this.gpuDataManager.release(u.id);this.kernelPersistentData.delete(r)}this.kernelCustomData.delete(r),this.kernels.delete(r)}computeKernel(r,s,u){let f=this.kernels.get(r);if(!f)throw new Error(`kernel not created: ${r}`);let g=f.kernelType,w=f.kernelName,m=f.kernelEntry,P=f.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${g}] ${w}" is not allowed to be called recursively`);this.currentKernelId=r,P[0]&&(P[1]=P[0](P[1]),P[0]=void 0),kr("info",()=>`[WebGPU] Start to run kernel "[${g}] ${w}"...`);let F=this.env.debug;this.temporaryData=[];try{return F&&this.device.pushErrorScope("validation"),m(s,P[1]),0}catch(O){return u.push(Promise.resolve(`[WebGPU] Kernel "[${g}] ${w}" failed. ${O}`)),1}finally{F&&u.push(this.device.popErrorScope().then(O=>O?`GPU validation error for kernel "[${g}] ${w}": ${O.message}`:null));for(let O of this.temporaryData)this.gpuDataManager.release(O.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(r,s,u,f){let g=this.sessionExternalDataMapping.get(r);g||(g=new Map,this.sessionExternalDataMapping.set(r,g));let w=g.get(s),m=this.gpuDataManager.registerExternalBuffer(u,f,w==null?void 0:w[1]);return g.set(s,[m,u]),m}unregisterBuffers(r){let s=this.sessionExternalDataMapping.get(r);s&&(s.forEach(u=>this.gpuDataManager.unregisterExternalBuffer(u[1])),this.sessionExternalDataMapping.delete(r))}getBuffer(r){let s=this.gpuDataManager.get(r);if(!s)throw new Error(`no GPU data for buffer: ${r}`);return s.buffer}createDownloader(r,s,u){return async()=>{let f=await Jt(this,r,s);return it(f.buffer,u)}}writeTimestamp(r){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,r)}setQueryType(){var r;this.queryType="none",(((r=this.env.webgpu.profiling)==null?void 0:r.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){kr("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){kr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){kr("info","replay"),this.sessionStatus="replaying";let r=this.capturedCommandList.get(this.currentSessionId),s=this.capturedPendingKernels.get(this.currentSessionId),u=r.length;this.pendingKernels=[];for(let f=0;f=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(r){this.unregisterBuffers(r),this.capturedCommandList.has(r)&&this.capturedCommandList.delete(r),this.capturedPendingKernels.has(r)&&this.capturedPendingKernels.delete(r),this.gpuDataManager.onReleaseSession(r)}onRunStart(r){this.currentSessionId=r,this.setQueryType()}}}),h1={};p(h1,{init:()=>m1});var Qp,p1,m1,fC=c(()=>{Pn(),dC(),_i(),Mn(),Qp=class gS{constructor(s,u,f,g){this.module=s,this.dataType=u,this.data=f,this.dims=g}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let s=mt.size(this.dims);return s===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,s)}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let s=mt.size(this.dims);return s===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,s)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let s=mt.size(this.dims);return s===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,s)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let s=mt.size(this.dims);return s===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,s)}reshape(s){if(mt.size(s)!==mt.size(this.dims))throw new Error("Invalid new shape");return new gS(this.module,this.dataType,this.data,s)}},p1=class{constructor(r,s,u){this.module=r,this.backend=s,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=s.adapterInfo;let f=r.HEAPU32,g=u>>>2;this.opKernelContext=f[g++];let w=f[g++];this.outputCount=f[g++],this.customDataOffset=f[g++],this.customDataSize=f[g++];let m=[];for(let P=0;Ptypeof P=="number"?this.inputs[P]:P))??this.inputs,f=(s==null?void 0:s.outputs)??[],g=(P,F,O)=>new Qp(this.module,F,this.output(P,O),O),w=(P,F)=>{let O=hs(P,F);if(!O)throw new Error(`Unsupported data type: ${P}`);let Y=O>0?this.backend.gpuDataManager.create(O).id:0;return new Qp(this.module,P,Y,F)};return this.backend.run(r,u,f,g,w,this.outputCount)}output(r,s){let u=this.module.stackSave();try{let f=this.module.stackAlloc((1+s.length)*4),g=f>>2;this.module.HEAPU32[g++]=s.length;for(let w=0;w{let g=s.jsepInit;if(!g)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(r==="webgpu"){let w=new f1;await w.initialize(u,f),g("webgpu",[w,m=>w.alloc(m),m=>w.free(m),(m,P,F,O=!1)=>{if(O)kr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${m}, dst=${P}, size=${F}`),w.memcpy(m,P);else{kr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${m}, gpuDataId=${P}, size=${F}`);let Y=s.HEAPU8.subarray(m>>>0,(m>>>0)+F);w.upload(P,Y)}},async(m,P,F)=>{kr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${m}, dataOffset=${P}, size=${F}`),await w.download(m,()=>s.HEAPU8.subarray(P>>>0,(P>>>0)+F))},(m,P,F)=>w.createKernel(m,P,F,s.UTF8ToString(s._JsepGetNodeName(P))),m=>w.releaseKernel(m),(m,P,F,O)=>{kr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${F}, kernel=${m}, contextDataOffset=${P}`);let Y=new p1(s,w,P);return w.computeKernel(m,Y,O)},()=>w.captureBegin(),()=>w.captureEnd(),()=>w.replay()])}else g("webnn")}}),g1,f_,h_,ol,_1,Yp,p_,m_,g_,__,y_,v_,y1=c(()=>{fs(),Io(),Pn(),Nr(),gi(),ho(),g1=(r,s)=>{gr()._OrtInit(r,s)!==0&&wr("Can't initialize onnxruntime.")},f_=async r=>{g1(r.wasm.numThreads,$i(r.logLevel))},h_=async(r,s)=>{{let u=(fC(),_(h1)).init;if(s==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let f=r.webgpu.adapter;if(f){if(typeof f.limits!="object"||typeof f.features!="object"||typeof f.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let g=r.webgpu.powerPreference;if(g!==void 0&&g!=="low-power"&&g!=="high-performance")throw new Error(`Invalid powerPreference setting: "${g}"`);let w=r.webgpu.forceFallbackAdapter;if(w!==void 0&&typeof w!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${w}"`);if(f=await navigator.gpu.requestAdapter({powerPreference:g,forceFallbackAdapter:w}),!f)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await u("webgpu",gr(),r,f)}if(s==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await u("webnn",gr(),r)}}},ol=new Map,_1=r=>{let s=gr(),u=s.stackSave();try{let f=s.stackAlloc(8);return s._OrtGetInputOutputCount(r,f,f+4)!==0&&wr("Can't get session input/output count."),[s.HEAP32[f/4],s.HEAP32[f/4+1]]}finally{s.stackRestore(u)}},Yp=r=>{let s=gr(),u=s._malloc(r.byteLength);if(u===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${r.byteLength}.`);return s.HEAPU8.set(r,u),[u,r.byteLength]},p_=async(r,s)=>{var Q,S;let u,f,g=gr();Array.isArray(r)?[u,f]=r:r.buffer===g.HEAPU8.buffer?[u,f]=[r.byteOffset,r.byteLength]:[u,f]=Yp(r);let w=0,m=0,P=0,F=[],O=[],Y=[];try{if([m,F]=ui(s),(s==null?void 0:s.externalData)&&g.mountExternalData){let ze=[];for(let Ge of s.externalData){let zt=typeof Ge=="string"?Ge:Ge.path;ze.push(Zn(typeof Ge=="string"?Ge:Ge.data).then(It=>{g.mountExternalData(zt,It)}))}await Promise.all(ze)}for(let ze of(s==null?void 0:s.executionProviders)??[])if((typeof ze=="string"?ze:ze.name)==="webnn"){if(g.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof ze!="string"){let Ge=ze,zt=Ge==null?void 0:Ge.context,It=Ge==null?void 0:Ge.gpuDevice,Ht=Ge==null?void 0:Ge.deviceType,pn=Ge==null?void 0:Ge.numThreads,wn=Ge==null?void 0:Ge.powerPreference;zt?g.currentContext=zt:It?g.currentContext=await navigator.ml.createContext(It):g.currentContext=await navigator.ml.createContext({deviceType:Ht,numThreads:pn,powerPreference:wn})}else g.currentContext=await navigator.ml.createContext();break}w=await g._OrtCreateSession(u,f,m),w===0&&wr("Can't create a session."),g.currentContext&&(g.currentContext=void 0);let[ie,ce]=_1(w),pe=!!(s!=null&&s.enableGraphCapture),ke=[],Pe=[],be=[];for(let ze=0;zeze==="gpu-buffer")&&(P=g._OrtCreateBinding(w),P===0&&wr("Can't create IO binding."),We={handle:P,outputPreferredLocations:be,outputPreferredLocationsEncoded:be.map(ze=>Ts(ze))}),ol.set(w,[w,O,Y,We,pe,!1]),[w,ke,Pe]}catch(ie){throw O.forEach(ce=>g._OrtFree(ce)),Y.forEach(ce=>g._OrtFree(ce)),P!==0&&g._OrtReleaseBinding(P),w!==0&&g._OrtReleaseSession(w),ie}finally{g._free(u),m!==0&&g._OrtReleaseSessionOptions(m),F.forEach(ie=>g._free(ie)),(S=g.unmountExternalData)==null||S.call(g)}},m_=r=>{var F;let s=gr(),u=ol.get(r);if(!u)throw new Error(`cannot release session. invalid session id: ${r}`);let[f,g,w,m,P]=u;m&&(P&&s._OrtClearBoundOutputs(m.handle),s._OrtReleaseBinding(m.handle)),(F=s.jsepOnReleaseSession)==null||F.call(s,r),g.forEach(O=>s._OrtFree(O)),w.forEach(O=>s._OrtFree(O)),s._OrtReleaseSession(f),ol.delete(r)},g_=(r,s,u,f,g,w=!1)=>{if(!r){s.push(0);return}let m=gr(),P=r[0],F=r[1],O=r[3],Y,Q;if(P==="string"&&O==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(w&&O!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${g} when enableGraphCapture is true.`);if(O==="gpu-buffer"){let ce=r[2].gpuBuffer;Q=hs(es(P),F);let pe=m.jsepRegisterBuffer;if(!pe)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Y=pe(f,g,ce,Q)}else{let ce=r[2];if(Array.isArray(ce)){Q=4*ce.length,Y=m._malloc(Q),u.push(Y);let pe=Y/4;for(let ke=0;kem.HEAP32[ce++]=ke);let pe=m._OrtCreateTensor(es(P),Y,Q,ie,F.length,Ts(O));pe===0&&wr(`Can't create tensor for input/output. session=${f}, index=${g}.`),s.push(pe)}finally{m.stackRestore(S)}},__=async(r,s,u,f,g,w)=>{var wn,Xn;let m=gr(),P=ol.get(r);if(!P)throw new Error(`cannot run inference. invalid session id: ${r}`);let F=P[0],O=P[1],Y=P[2],Q=P[3],S=P[4],ie=P[5],ce=s.length,pe=f.length,ke=0,Pe=[],be=[],We=[],ze=[],Ge=m.stackSave(),zt=m.stackAlloc(ce*4),It=m.stackAlloc(ce*4),Ht=m.stackAlloc(pe*4),pn=m.stackAlloc(pe*4);try{[ke,Pe]=ds(w);for(let Fn=0;FnKi*_s,1);Nn=Ai(ki);let ph=Q==null?void 0:Q.outputPreferredLocations[f[Fn]];if(Nn==="string"){if(ph==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ki=[],_s=Pr/4;for(let eo=0;eo0){let Ki=m.jsepGetBuffer;if(!Ki)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let _s=Ki(Pr),eo=hs(ki,Hi);if(eo===void 0||!Qs(Nn))throw new Error(`Unsupported data type: ${Nn}`);an=!0,Or.push([Nn,Ns,{gpuBuffer:_s,download:m.jsepCreateDownloader(_s,eo,Nn),dispose:()=>{m._OrtReleaseTensor(sr)}},"gpu-buffer"])}else{let Ki=ts(Nn),_s=new Ki(Hi);new Uint8Array(_s.buffer,_s.byteOffset,_s.byteLength).set(m.HEAPU8.subarray(Pr,Pr+_s.byteLength)),Or.push([Nn,Ns,_s,"cpu"])}}finally{m.stackRestore(vr),Nn==="string"&&Pr&&m._free(Pr),an||m._OrtReleaseTensor(sr)}}return Q&&!S&&(m._OrtClearBoundOutputs(Q.handle),ol.set(r,[F,O,Y,Q,S,!1])),Or}finally{m.stackRestore(Ge),be.forEach(ar=>m._OrtReleaseTensor(ar)),We.forEach(ar=>m._OrtReleaseTensor(ar)),ze.forEach(ar=>m._free(ar)),ke!==0&&m._OrtReleaseRunOptions(ke),Pe.forEach(ar=>m._free(ar))}},y_=r=>{let s=gr(),u=ol.get(r);if(!u)throw new Error("invalid session id");let f=u[0],g=s._OrtEndProfiling(f);g===0&&wr("Can't get an profile file name."),s._OrtFree(g)},v_=r=>{let s=[];for(let u of r){let f=u[2];!Array.isArray(f)&&"buffer"in f&&s.push(f.buffer)}return s}}),al,Cs,Sc,fh,hh,Zp,w_,Jp,nu,ru,v1,w1,b1,x1,T1,M1,k1,S1,E1=c(()=>{jt(),y1(),Nr(),zn(),al=()=>!!j.wasm.proxy&&typeof document<"u",Sc=!1,fh=!1,hh=!1,Jp=new Map,nu=(r,s)=>{let u=Jp.get(r);u?u.push(s):Jp.set(r,[s])},ru=()=>{if(Sc||!fh||hh||!Cs)throw new Error("worker not ready")},v1=r=>{switch(r.data.type){case"init-wasm":Sc=!1,r.data.err?(hh=!0,w_[1](r.data.err)):(fh=!0,w_[0]()),Zp&&(URL.revokeObjectURL(Zp),Zp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let s=Jp.get(r.data.type);r.data.err?s.shift()[1](r.data.err):s.shift()[0](r.data.out);break}}},w1=async()=>{if(!fh){if(Sc)throw new Error("multiple calls to 'initWasm()' detected.");if(hh)throw new Error("previous call to 'initWasm()' failed.");if(Sc=!0,al())return new Promise((r,s)=>{Cs==null||Cs.terminate(),yn().then(([u,f])=>{try{Cs=f,Cs.onerror=w=>s(w),Cs.onmessage=v1,w_=[r,s];let g={type:"init-wasm",in:j};Cs.postMessage(g),Zp=u}catch(g){s(g)}},s)});try{await xs(j.wasm),await f_(j),fh=!0}catch(r){throw hh=!0,r}finally{Sc=!1}}},b1=async r=>{if(al())return ru(),new Promise((s,u)=>{nu("init-ep",[s,u]);let f={type:"init-ep",in:{epName:r,env:j}};Cs.postMessage(f)});await h_(j,r)},x1=async r=>al()?(ru(),new Promise((s,u)=>{nu("copy-from",[s,u]);let f={type:"copy-from",in:{buffer:r}};Cs.postMessage(f,[r.buffer])})):Yp(r),T1=async(r,s)=>{if(al()){if(s!=null&&s.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ru(),new Promise((u,f)=>{nu("create",[u,f]);let g={type:"create",in:{model:r,options:{...s}}},w=[];r instanceof Uint8Array&&w.push(r.buffer),Cs.postMessage(g,w)})}else return p_(r,s)},M1=async r=>{if(al())return ru(),new Promise((s,u)=>{nu("release",[s,u]);let f={type:"release",in:r};Cs.postMessage(f)});m_(r)},k1=async(r,s,u,f,g,w)=>{if(al()){if(u.some(m=>m[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(g.some(m=>m))throw new Error("pre-allocated output tensor is not supported for proxy.");return ru(),new Promise((m,P)=>{nu("run",[m,P]);let F=u,O={type:"run",in:{sessionId:r,inputIndices:s,inputs:F,outputIndices:f,options:w}};Cs.postMessage(O,v_(F))})}else return __(r,s,u,f,g,w)},S1=async r=>{if(al())return ru(),new Promise((s,u)=>{nu("end-profiling",[s,u]);let f={type:"end-profiling",in:r};Cs.postMessage(f)});y_(r)}}),b_,C1,P1,hC=c(()=>{jt(),E1(),Pn(),ht(),ho(),b_=(r,s)=>{switch(r.location){case"cpu":return[r.type,r.dims,r.data,"cpu"];case"gpu-buffer":return[r.type,r.dims,{gpuBuffer:r.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${r.location} for ${s()}`)}},C1=r=>{switch(r[3]){case"cpu":return new je(r[0],r[2],r[1]);case"gpu-buffer":{let s=r[0];if(!Qs(s))throw new Error(`not supported data type: ${s} for deserializing GPU tensor`);let{gpuBuffer:u,download:f,dispose:g}=r[2];return je.fromGpuBuffer(u,{dataType:s,dims:r[1],download:f,dispose:g})}default:throw new Error(`invalid data location: ${r[3]}`)}},P1=class{async fetchModelAndCopyToWasmMemory(r){return x1(await Zn(r))}async loadModel(r,s){xt();let u;typeof r=="string"?u=await this.fetchModelAndCopyToWasmMemory(r):u=r,[this.sessionId,this.inputNames,this.outputNames]=await T1(u,s),z()}async dispose(){return M1(this.sessionId)}async run(r,s,u){xt();let f=[],g=[];Object.entries(r).forEach(Q=>{let S=Q[0],ie=Q[1],ce=this.inputNames.indexOf(S);if(ce===-1)throw new Error(`invalid input '${S}'`);f.push(ie),g.push(ce)});let w=[],m=[];Object.entries(s).forEach(Q=>{let S=Q[0],ie=Q[1],ce=this.outputNames.indexOf(S);if(ce===-1)throw new Error(`invalid output '${S}'`);w.push(ie),m.push(ce)});let P=f.map((Q,S)=>b_(Q,()=>`input "${this.inputNames[g[S]]}"`)),F=w.map((Q,S)=>Q?b_(Q,()=>`output "${this.outputNames[m[S]]}"`):null),O=await k1(this.sessionId,g,P,m,F,u),Y={};for(let Q=0;Q{jt(),E1(),hC(),zn(),A1=()=>{if((typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0),j.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let r=typeof navigator>"u"?d("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},$1=class{async init(r){A1(),await w1(),await b1(r)}async createInferenceSessionHandler(r,s){let u=new P1;return await u.loadModel(r,s),Promise.resolve(u)}}}),I1={};p(I1,{wasmBackend:()=>F1});var F1,mC=c(()=>{pC(),F1=new $1});jt(),jt(),jt();var gC="1.20.0-dev.20240827-1d059b8702",_C=Nt;{let r=(mC(),_(I1)).wasmBackend;I("webgpu",r,5),I("webnn",r,5),I("cpu",r,10),I("wasm",r,10)}Object.defineProperty(j.versions,"web",{value:gC,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */},"./src/backends/onnx.js":(e,t,n)=>{var i;n.r(t),n.d(t,{Tensor:()=>d.Tensor,createInferenceSession:()=>C,deviceToExecutionProviders:()=>M,isONNXProxy:()=>k,isONNXTensor:()=>E});var o=n("./src/env.js"),a=n("?2ce3"),l=n("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),d=n("./node_modules/onnxruntime-common/dist/esm/index.js");const c=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),p=[];let v,_;if(o.apis.IS_NODE_ENV){switch(_=a??(i||(i=n.t(a,2))),process.platform){case"win32":p.push("dml");break;case"linux":process.arch==="x64"&&p.push("cuda");break}p.push("cpu"),v=["cpu"]}else _=l,o.apis.IS_WEBNN_AVAILABLE&&p.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&p.push("webgpu"),p.push("wasm"),v=["wasm"];const T=_.InferenceSession;function M(A=null){if(!A)return v;switch(A){case"auto":return p;case"gpu":return p.filter(N=>["webgpu","cuda","dml","webnn-gpu"].includes(N))}if(p.includes(A))return[c[A]??A];throw new Error(`Unsupported device: "${A}". Should be one of: ${p.join(", ")}.`)}let I=null;async function C(A,N){I&&await I;const R=T.create(A,N);return I??(I=R),await R}function E(A){return A instanceof _.Tensor}const x=_==null?void 0:_.env;x!=null&&x.wasm&&(x.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`,x.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(x.wasm.numThreads=1)),x!=null&&x.webgpu&&(x.webgpu.powerPreference="high-performance");function k(){var A;return(A=x==null?void 0:x.wasm)==null?void 0:A.proxy}o.env.backends.onnx=x},"./src/configs.js":(e,t,n)=>{n.r(t),n.d(t,{AutoConfig:()=>p,PretrainedConfig:()=>c,getKeyValueShapes:()=>d});var i=n("./src/utils/core.js"),o=n("./src/utils/hub.js");async function a(v,_){return await(0,o.getModelJSON)(v,"config.json",!0,_)}function l(v){const _={};let T={};switch(v.model_type){case"llava":case"paligemma":case"florence2":T=l(v.text_config);break;case"moondream1":T=l(v.phi_config);break;case"musicgen":T=l(v.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":_.num_heads="n_head",_.num_layers="n_layer",_.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":_.num_heads="num_attention_heads",_.num_layers="num_hidden_layers",_.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":_.num_heads="num_key_value_heads",_.num_layers="num_hidden_layers",_.hidden_size="hidden_size",_.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":_.num_heads="num_key_value_heads",_.num_layers="num_hidden_layers",_.dim_kv="head_dim";break;case"openelm":_.num_heads="num_kv_heads",_.num_layers="num_transformer_layers",_.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":_.num_heads="num_heads",_.num_layers="num_layers",_.hidden_size="hidden_size";break;case"bloom":_.num_heads="n_head",_.num_layers="n_layer",_.hidden_size="hidden_size";break;case"mpt":_.num_heads="n_heads",_.num_layers="n_layers",_.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":_.num_decoder_layers="num_decoder_layers",_.num_decoder_heads="num_heads",_.decoder_dim_kv="d_kv",_.num_encoder_layers="num_layers",_.num_encoder_heads="num_heads",_.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":_.num_decoder_layers="decoder_layers",_.num_decoder_heads="decoder_attention_heads",_.decoder_hidden_size="d_model",_.num_encoder_layers="encoder_layers",_.num_encoder_heads="encoder_attention_heads",_.encoder_hidden_size="d_model";break;case"speecht5":_.num_decoder_layers="decoder_layers",_.num_decoder_heads="decoder_attention_heads",_.decoder_hidden_size="hidden_size",_.num_encoder_layers="encoder_layers",_.num_encoder_heads="encoder_attention_heads",_.encoder_hidden_size="hidden_size";break;case"trocr":_.num_encoder_layers=_.num_decoder_layers="decoder_layers",_.num_encoder_heads=_.num_decoder_heads="decoder_attention_heads",_.encoder_hidden_size=_.decoder_hidden_size="d_model";break;case"musicgen_decoder":_.num_encoder_layers=_.num_decoder_layers="num_hidden_layers",_.num_encoder_heads=_.num_decoder_heads="num_attention_heads",_.encoder_hidden_size=_.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const I=l(v.decoder),C="num_decoder_layers"in I,E=(0,i.pick)(v,["model_type","is_encoder_decoder"]);return C?(E.num_decoder_layers=I.num_decoder_layers,E.num_decoder_heads=I.num_decoder_heads,E.decoder_hidden_size=I.decoder_hidden_size,E.num_encoder_layers=I.num_encoder_layers,E.num_encoder_heads=I.num_encoder_heads,E.encoder_hidden_size=I.encoder_hidden_size):(E.num_layers=I.num_layers,E.num_heads=I.num_heads,E.hidden_size=I.hidden_size),E}const M={...T,...(0,i.pick)(v,["model_type","multi_query","is_encoder_decoder"])};for(const I in _)M[I]=v[_[I]];return M}function d(v,{prefix:_="past_key_values"}={}){const T={},M=v.normalized_config,I=1;if(M.is_encoder_decoder&&"num_encoder_heads"in M&&"num_decoder_heads"in M){const C=M.encoder_dim_kv??M.encoder_hidden_size/M.num_encoder_heads,E=M.decoder_dim_kv??M.decoder_hidden_size/M.num_decoder_heads,x=[I,M.num_encoder_heads,0,C],k=[I,M.num_decoder_heads,0,E];for(let A=0;A{var j;n.r(t),n.d(t,{apis:()=>E,env:()=>B});var i=n("?569f"),o=n("?3f59"),a=n("?154a");const l="3.0.0-alpha.13",d=typeof self<"u",c=d&&self.constructor.name==="DedicatedWorkerGlobalScope",p=d&&"caches"in self,v=typeof navigator<"u"&&"gpu"in navigator,_=typeof navigator<"u"&&"ml"in navigator,T=typeof process<"u",M=T&&((j=process==null?void 0:process.release)==null?void 0:j.name)==="node",I=!W(i),C=!W(o),E=Object.freeze({IS_BROWSER_ENV:d,IS_WEBWORKER_ENV:c,IS_WEB_CACHE_AVAILABLE:p,IS_WEBGPU_AVAILABLE:v,IS_WEBNN_AVAILABLE:_,IS_PROCESS_AVAILABLE:T,IS_NODE_ENV:M,IS_FS_AVAILABLE:I,IS_PATH_AVAILABLE:C}),x=I&&C,k=x?o.dirname(o.dirname(a.fileURLToPath(import.meta.url))):"./",A=x?o.join(k,"/.cache/"):null,N="/models/",R=x?o.join(k,N):N,B={version:l,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co./",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!d,localModelPath:R,useFS:I,useBrowserCache:p,useFSCache:I,cacheDir:A,useCustomCache:!1,customCache:null};function W(ae){return Object.keys(ae).length===0}},"./src/generation/configuration_utils.js":(e,t,n)=>{n.r(t),n.d(t,{GenerationConfig:()=>o});var i=n("./src/utils/core.js");class o{constructor(l){ft(this,"max_length",20);ft(this,"max_new_tokens",null);ft(this,"min_length",0);ft(this,"min_new_tokens",null);ft(this,"early_stopping",!1);ft(this,"max_time",null);ft(this,"do_sample",!1);ft(this,"num_beams",1);ft(this,"num_beam_groups",1);ft(this,"penalty_alpha",null);ft(this,"use_cache",!0);ft(this,"temperature",1);ft(this,"top_k",50);ft(this,"top_p",1);ft(this,"typical_p",1);ft(this,"epsilon_cutoff",0);ft(this,"eta_cutoff",0);ft(this,"diversity_penalty",0);ft(this,"repetition_penalty",1);ft(this,"encoder_repetition_penalty",1);ft(this,"length_penalty",1);ft(this,"no_repeat_ngram_size",0);ft(this,"bad_words_ids",null);ft(this,"force_words_ids",null);ft(this,"renormalize_logits",!1);ft(this,"constraints",null);ft(this,"forced_bos_token_id",null);ft(this,"forced_eos_token_id",null);ft(this,"remove_invalid_values",!1);ft(this,"exponential_decay_length_penalty",null);ft(this,"suppress_tokens",null);ft(this,"begin_suppress_tokens",null);ft(this,"forced_decoder_ids",null);ft(this,"guidance_scale",null);ft(this,"num_return_sequences",1);ft(this,"output_attentions",!1);ft(this,"output_hidden_states",!1);ft(this,"output_scores",!1);ft(this,"return_dict_in_generate",!1);ft(this,"pad_token_id",null);ft(this,"bos_token_id",null);ft(this,"eos_token_id",null);ft(this,"encoder_no_repeat_ngram_size",0);ft(this,"decoder_start_token_id",null);ft(this,"generation_kwargs",{});Object.assign(this,(0,i.pick)(l,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,t,n)=>{n.r(t),n.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>x,ForcedBOSTokenLogitsProcessor:()=>c,ForcedEOSTokenLogitsProcessor:()=>p,LogitsProcessor:()=>a,LogitsProcessorList:()=>d,LogitsWarper:()=>l,MinLengthLogitsProcessor:()=>I,MinNewTokensLengthLogitsProcessor:()=>C,NoBadWordsLogitsProcessor:()=>E,NoRepeatNGramLogitsProcessor:()=>T,RepetitionPenaltyLogitsProcessor:()=>M,SuppressTokensAtBeginLogitsProcessor:()=>v,TemperatureLogitsWarper:()=>k,TopKLogitsWarper:()=>N,TopPLogitsWarper:()=>A,WhisperTimeStampLogitsProcessor:()=>_});var i=n("./src/utils/generic.js");n("./src/utils/tensor.js");var o=n("./src/utils/maths.js");class a extends i.Callable{_call(B,W){throw Error("`_call` should be implemented in a subclass")}}class l extends i.Callable{_call(B,W){throw Error("`_call` should be implemented in a subclass")}}class d extends i.Callable{constructor(){super(),this.processors=[]}push(B){this.processors.push(B)}extend(B){this.processors.push(...B)}_call(B,W){let j=W;for(const ae of this.processors)j=ae(B,j);return j}[Symbol.iterator](){return this.processors.values()}}class c extends a{constructor(B){super(),this.bos_token_id=B}_call(B,W){for(let j=0;j=1&&ve[ve.length-1]>=this.timestamp_begin,oe=ve.length<2||ve[ve.length-2]>=this.timestamp_begin;if(Ne&&(oe?ae.subarray(this.timestamp_begin).fill(-1/0):ae.subarray(0,this.eos_token_id).fill(-1/0)),B[j].length===this.begin_index&&this.max_initial_timestamp_index!==null){const gt=this.timestamp_begin+this.max_initial_timestamp_index;ae.subarray(gt+1).fill(-1/0)}const Se=(0,o.log_softmax)(ae),G=Math.log(Se.subarray(this.timestamp_begin).map(Math.exp).reduce((gt,Me)=>gt+Me)),Ce=(0,o.max)(Se.subarray(0,this.timestamp_begin))[0];G>Ce&&ae.subarray(0,this.timestamp_begin).fill(-1/0)}return W}}class T extends a{constructor(B){super(),this.no_repeat_ngram_size=B}getNgrams(B){const W=B.length,j=[];for(let ve=0;ve1 to use the classifier free guidance processor, got guidance scale ${B}.`);this.guidance_scale=B}_call(B,W){if(W.dims[0]!==2*B.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 ${W.dims[0]} for the logits and ${B.length} for the input ids.`);const j=B.length,ae=W.slice([0,j],null),ve=W.slice([j,W.dims[0]],null);for(let Ne=0;Ne1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${B}`);if(!Number.isInteger(j)||j<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${j}`);this.top_p=B,this.filter_value=W,this.min_tokens_to_keep=j}}class N extends l{constructor(B,{filter_value:W=-1/0,min_tokens_to_keep:j=1}={}){if(super(),!Number.isInteger(B)||B<0)throw new Error(`\`top_k\` must be a positive integer, but is ${B}`);this.top_k=Math.max(B,j),this.filter_value=W}}},"./src/generation/logits_sampler.js":(e,t,n)=>{n.r(t),n.d(t,{LogitsSampler:()=>l});var i=n("./src/utils/generic.js"),o=n("./src/utils/tensor.js"),a=n("./src/utils/maths.js");n("./src/generation/configuration_utils.js");class l extends i.Callable{constructor(_){super(),this.generation_config=_}async _call(_){return this.sample(_)}async sample(_){throw Error("sample should be implemented in subclasses.")}getLogits(_,T){let M=_.dims.at(-1),I=_.data;if(T===-1)I=I.slice(-M);else{let C=T*M;I=I.slice(C,C+M)}return I}randomSelect(_){let T=0;for(let I=0;I<_.length;++I)T+=_[I];let M=Math.random()*T;for(let I=0;I<_.length;++I)if(M-=_[I],M<=0)return I;return 0}static getSampler(_){if(_.do_sample)return new c(_);if(_.num_beams>1)return new p(_);if(_.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${_.num_return_sequences}.`);return new d(_)}}class d extends l{async sample(_){const T=(0,a.max)(_.data)[1];return[[BigInt(T),0]]}}class c extends l{async sample(_){let T=_.dims.at(-1);this.generation_config.top_k>0&&(T=Math.min(this.generation_config.top_k,T));const[M,I]=await(0,o.topk)(_,T),C=(0,a.softmax)(M.data);return Array.from({length:this.generation_config.num_beams},()=>{const E=this.randomSelect(C);return[I.data[E],Math.log(C[E])]})}}class p extends l{async sample(_){let T=_.dims.at(-1);this.generation_config.top_k>0&&(T=Math.min(this.generation_config.top_k,T));const[M,I]=await(0,o.topk)(_,T),C=(0,a.softmax)(M.data);return Array.from({length:this.generation_config.num_beams},(E,x)=>[I.data[x],Math.log(C[x])])}}},"./src/generation/stopping_criteria.js":(e,t,n)=>{n.r(t),n.d(t,{EosTokenCriteria:()=>d,InterruptableStoppingCriteria:()=>c,MaxLengthCriteria:()=>l,StoppingCriteria:()=>o,StoppingCriteriaList:()=>a});var i=n("./src/utils/generic.js");class o extends i.Callable{_call(v,_){throw Error("StoppingCriteria needs to be subclassed")}}class a extends i.Callable{constructor(){super(),this.criteria=[]}push(v){this.criteria.push(v)}extend(v){v instanceof a?v=v.criteria:v instanceof o&&(v=[v]),this.criteria.push(...v)}_call(v,_){const T=new Array(v.length).fill(!1);for(const M of this.criteria){const I=M(v,_);for(let C=0;C_.length>=this.max_length)}}class d extends o{constructor(v){super(),Array.isArray(v)||(v=[v]),this.eos_token_id=v}_call(v,_){return v.map(T=>{const M=T.at(-1);return this.eos_token_id.some(I=>M==I)})}}class c extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(v,_){return new Array(v.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,t,n)=>{n.r(t),n.d(t,{BaseStreamer:()=>l,TextStreamer:()=>c,WhisperTextStreamer:()=>p});var i=n("./src/utils/core.js"),o=n("./src/tokenizers.js"),a=n("./src/env.js");class l{put(_){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const d=a.apis.IS_PROCESS_AVAILABLE?v=>process.stdout.write(v):v=>console.log(v);class c extends l{constructor(_,{skip_prompt:T=!1,callback_function:M=null,token_callback_function:I=null,decode_kwargs:C={},...E}={}){super(),this.tokenizer=_,this.skip_prompt=T,this.callback_function=M??d,this.token_callback_function=I,this.decode_kwargs={...C,...E},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(_){var C;if(_.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const T=_[0];(C=this.token_callback_function)==null||C.call(this,T),this.token_cache=(0,i.mergeArrays)(this.token_cache,T);const M=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let I;M.endsWith(` `)?(I=M.slice(this.print_len),this.token_cache=[],this.print_len=0):M.length>0&&(0,o.is_chinese_char)(M.charCodeAt(M.length-1))?(I=M.slice(this.print_len),this.print_len+=I.length):(I=M.slice(this.print_len,M.lastIndexOf(" ")+1),this.print_len+=I.length),this.on_finalized_text(I,!1)}end(){let _;this.token_cache.length>0?(_=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):_="",this.next_tokens_are_prompt=!0,this.on_finalized_text(_,!0)}on_finalized_text(_,T){var M,I;_.length>0&&((M=this.callback_function)==null||M.call(this,_)),T&&this.callback_function===d&&a.apis.IS_PROCESS_AVAILABLE&&((I=this.callback_function)==null||I.call(this,` `))}}class p extends c{constructor(_,{skip_prompt:T=!1,callback_function:M=null,token_callback_function:I=null,on_chunk_start:C=null,on_chunk_end:E=null,on_finalize:x=null,time_precision:k=.02,skip_special_tokens:A=!0,decode_kwargs:N={}}={}){super(_,{skip_prompt:T,callback_function:M,token_callback_function:I,decode_kwargs:{skip_special_tokens:A,...N}}),this.timestamp_begin=_.timestamp_begin,this.on_chunk_start=C,this.on_chunk_end=E,this.on_finalize=x,this.time_precision=k,this.waiting_for_timestamp=!1}put(_){var M,I;if(_.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const T=_[0];if(T.length===1){const C=Number(T[0])-this.timestamp_begin;if(C>=0){const E=C*this.time_precision;this.waiting_for_timestamp?(M=this.on_chunk_end)==null||M.call(this,E):(I=this.on_chunk_start)==null||I.call(this,E),this.waiting_for_timestamp=!this.waiting_for_timestamp,_=[[]]}}return super.put(_)}end(){var _;super.end(),(_=this.on_finalize)==null||_.call(this)}}},"./src/models.js":(e,t,n)=>{n.r(t),n.d(t,{ASTForAudioClassification:()=>ua,ASTModel:()=>gn,ASTPreTrainedModel:()=>Fi,AlbertForMaskedLM:()=>Pn,AlbertForQuestionAnswering:()=>Ts,AlbertForSequenceClassification:()=>Qs,AlbertModel:()=>$i,AlbertPreTrainedModel:()=>ts,AutoModel:()=>_c,AutoModelForAudioClassification:()=>Gp,AutoModelForAudioFrameClassification:()=>th,AutoModelForCTC:()=>Jf,AutoModelForCausalLM:()=>qf,AutoModelForDepthEstimation:()=>ih,AutoModelForDocumentQuestionAnswering:()=>nh,AutoModelForImageClassification:()=>Xf,AutoModelForImageFeatureExtraction:()=>oh,AutoModelForImageMatting:()=>rh,AutoModelForImageSegmentation:()=>Qf,AutoModelForImageToImage:()=>qp,AutoModelForMaskGeneration:()=>xc,AutoModelForMaskedLM:()=>Hf,AutoModelForNormalEstimation:()=>sh,AutoModelForObjectDetection:()=>Yf,AutoModelForQuestionAnswering:()=>wc,AutoModelForSemanticSegmentation:()=>bc,AutoModelForSeq2SeqLM:()=>sl,AutoModelForSequenceClassification:()=>yc,AutoModelForSpeechSeq2Seq:()=>Wf,AutoModelForTextToSpectrogram:()=>Gf,AutoModelForTextToWaveform:()=>vc,AutoModelForTokenClassification:()=>Uf,AutoModelForVision2Seq:()=>Kf,AutoModelForXVector:()=>eh,AutoModelForZeroShotObjectDetection:()=>Zf,BartForConditionalGeneration:()=>K,BartForSequenceClassification:()=>ye,BartModel:()=>it,BartPretrainedModel:()=>_i,BaseModelOutput:()=>pt,BeitForImageClassification:()=>Ui,BeitModel:()=>Yn,BeitPreTrainedModel:()=>Qn,BertForMaskedLM:()=>ct,BertForQuestionAnswering:()=>je,BertForSequenceClassification:()=>Et,BertForTokenClassification:()=>Rt,BertModel:()=>et,BertPreTrainedModel:()=>Ye,BlenderbotForConditionalGeneration:()=>fn,BlenderbotModel:()=>Jt,BlenderbotPreTrainedModel:()=>Lt,BlenderbotSmallForConditionalGeneration:()=>On,BlenderbotSmallModel:()=>Wn,BlenderbotSmallPreTrainedModel:()=>Rn,BloomForCausalLM:()=>$,BloomModel:()=>y,BloomPreTrainedModel:()=>h,CLIPModel:()=>Do,CLIPPreTrainedModel:()=>_o,CLIPSegForImageSegmentation:()=>vo,CLIPSegModel:()=>fi,CLIPSegPreTrainedModel:()=>Lo,CLIPTextModelWithProjection:()=>Oi,CLIPVisionModelWithProjection:()=>zo,CamembertForMaskedLM:()=>_e,CamembertForQuestionAnswering:()=>Je,CamembertForSequenceClassification:()=>Be,CamembertForTokenClassification:()=>st,CamembertModel:()=>ht,CamembertPreTrainedModel:()=>jt,CausalLMOutput:()=>Xo,CausalLMOutputWithPast:()=>Hp,ChineseCLIPModel:()=>pa,ChineseCLIPPreTrainedModel:()=>ha,ClapAudioModelWithProjection:()=>pf,ClapModel:()=>ff,ClapPreTrainedModel:()=>ic,ClapTextModelWithProjection:()=>hf,CodeGenForCausalLM:()=>Xa,CodeGenModel:()=>ns,CodeGenPreTrainedModel:()=>bo,CohereForCausalLM:()=>ya,CohereModel:()=>el,CoherePreTrainedModel:()=>Ja,ConvBertForMaskedLM:()=>q,ConvBertForQuestionAnswering:()=>me,ConvBertForSequenceClassification:()=>re,ConvBertForTokenClassification:()=>V,ConvBertModel:()=>Ee,ConvBertPreTrainedModel:()=>ue,ConvNextForImageClassification:()=>Rd,ConvNextModel:()=>zd,ConvNextPreTrainedModel:()=>Lu,ConvNextV2ForImageClassification:()=>Bd,ConvNextV2Model:()=>Ld,ConvNextV2PreTrainedModel:()=>Bu,DPTForDepthEstimation:()=>Pd,DPTModel:()=>Cd,DPTPreTrainedModel:()=>Du,DebertaForMaskedLM:()=>Wt,DebertaForQuestionAnswering:()=>Gt,DebertaForSequenceClassification:()=>ot,DebertaForTokenClassification:()=>nn,DebertaModel:()=>$t,DebertaPreTrainedModel:()=>_t,DebertaV2ForMaskedLM:()=>hn,DebertaV2ForQuestionAnswering:()=>yn,DebertaV2ForSequenceClassification:()=>Sn,DebertaV2ForTokenClassification:()=>Tn,DebertaV2Model:()=>mn,DebertaV2PreTrainedModel:()=>Mt,DeiTForImageClassification:()=>Md,DeiTModel:()=>Td,DeiTPreTrainedModel:()=>Cu,DepthAnythingForDepthEstimation:()=>$d,DepthAnythingPreTrainedModel:()=>Ad,DetrForObjectDetection:()=>ii,DetrForSegmentation:()=>Rs,DetrModel:()=>ri,DetrObjectDetectionOutput:()=>si,DetrPreTrainedModel:()=>Hn,DetrSegmentationOutput:()=>gs,Dinov2ForImageClassification:()=>jd,Dinov2Model:()=>Nd,Dinov2PreTrainedModel:()=>Nu,DistilBertForMaskedLM:()=>Qt,DistilBertForQuestionAnswering:()=>Pt,DistilBertForSequenceClassification:()=>zn,DistilBertForTokenClassification:()=>kn,DistilBertModel:()=>$n,DistilBertPreTrainedModel:()=>En,DonutSwinModel:()=>Es,DonutSwinPreTrainedModel:()=>Dd,EfficientNetForImageClassification:()=>Op,EfficientNetModel:()=>yf,EfficientNetPreTrainedModel:()=>lc,ElectraForMaskedLM:()=>Ze,ElectraForQuestionAnswering:()=>Nt,ElectraForSequenceClassification:()=>Dt,ElectraForTokenClassification:()=>Tt,ElectraModel:()=>$e,ElectraPreTrainedModel:()=>ge,EsmForMaskedLM:()=>Ci,EsmForSequenceClassification:()=>xs,EsmForTokenClassification:()=>gr,EsmModel:()=>Ar,EsmPreTrainedModel:()=>dn,FalconForCausalLM:()=>rc,FalconModel:()=>df,FalconPreTrainedModel:()=>cf,FastViTForImageClassification:()=>nt,FastViTModel:()=>Xe,FastViTPreTrainedModel:()=>lt,Florence2ForConditionalGeneration:()=>Oo,Florence2PreTrainedModel:()=>ca,GLPNForDepthEstimation:()=>Od,GLPNModel:()=>kp,GLPNPreTrainedModel:()=>Ru,GPT2LMHeadModel:()=>Bo,GPT2Model:()=>qa,GPT2PreTrainedModel:()=>Zs,GPTBigCodeForCausalLM:()=>wo,GPTBigCodeModel:()=>jl,GPTBigCodePreTrainedModel:()=>yi,GPTJForCausalLM:()=>Ka,GPTJModel:()=>Nl,GPTJPreTrainedModel:()=>_a,GPTNeoForCausalLM:()=>ma,GPTNeoModel:()=>Ds,GPTNeoPreTrainedModel:()=>jo,GPTNeoXForCausalLM:()=>ga,GPTNeoXModel:()=>Uo,GPTNeoXPreTrainedModel:()=>Vo,Gemma2ForCausalLM:()=>Wo,Gemma2Model:()=>Ul,Gemma2PreTrainedModel:()=>Vi,GemmaForCausalLM:()=>Vl,GemmaModel:()=>tl,GemmaPreTrainedModel:()=>va,HubertForCTC:()=>tf,HubertForSequenceClassification:()=>Ap,HubertModel:()=>ef,HubertPreTrainedModel:()=>Pp,ImageMattingOutput:()=>lh,JAISLMHeadModel:()=>No,JAISModel:()=>Ha,JAISPreTrainedModel:()=>Di,LlamaForCausalLM:()=>Za,LlamaModel:()=>Ya,LlamaPreTrainedModel:()=>Qa,LlavaForConditionalGeneration:()=>go,LlavaPreTrainedModel:()=>Bl,LongT5ForConditionalGeneration:()=>Ms,LongT5Model:()=>br,LongT5PreTrainedModel:()=>Ys,M2M100ForConditionalGeneration:()=>Uu,M2M100Model:()=>To,M2M100PreTrainedModel:()=>Js,MBartForCausalLM:()=>Zt,MBartForConditionalGeneration:()=>He,MBartForSequenceClassification:()=>St,MBartModel:()=>Ve,MBartPreTrainedModel:()=>Oe,MPNetForMaskedLM:()=>fo,MPNetForQuestionAnswering:()=>Ji,MPNetForSequenceClassification:()=>Xs,MPNetForTokenClassification:()=>$r,MPNetModel:()=>fs,MPNetPreTrainedModel:()=>ds,MT5ForConditionalGeneration:()=>kr,MT5Model:()=>ms,MT5PreTrainedModel:()=>ps,MarianMTModel:()=>xo,MarianModel:()=>Ep,MarianPreTrainedModel:()=>Vu,MaskedLMOutput:()=>vi,MistralForCausalLM:()=>tc,MistralModel:()=>af,MistralPreTrainedModel:()=>ec,MobileBertForMaskedLM:()=>Pi,MobileBertForQuestionAnswering:()=>gi,MobileBertForSequenceClassification:()=>wr,MobileBertModel:()=>yr,MobileBertPreTrainedModel:()=>Nr,MobileNetV1ForImageClassification:()=>eu,MobileNetV1Model:()=>Rp,MobileNetV1PreTrainedModel:()=>dc,MobileNetV2ForImageClassification:()=>vf,MobileNetV2Model:()=>fc,MobileNetV2PreTrainedModel:()=>Ta,MobileNetV3ForImageClassification:()=>bf,MobileNetV3Model:()=>wf,MobileNetV3PreTrainedModel:()=>hc,MobileNetV4ForImageClassification:()=>Tf,MobileNetV4Model:()=>xf,MobileNetV4PreTrainedModel:()=>tu,MobileViTForImageClassification:()=>bt,MobileViTModel:()=>wt,MobileViTPreTrainedModel:()=>yt,MobileViTV2ForImageClassification:()=>on,MobileViTV2Model:()=>Xt,MobileViTV2PreTrainedModel:()=>vt,ModelOutput:()=>xe,Moondream1ForConditionalGeneration:()=>Vn,MptForCausalLM:()=>le,MptModel:()=>Z,MptPreTrainedModel:()=>U,MusicgenForCausalLM:()=>zp,MusicgenForConditionalGeneration:()=>cc,MusicgenModel:()=>Dp,MusicgenPreTrainedModel:()=>uc,NomicBertModel:()=>rt,NomicBertPreTrainedModel:()=>Ie,OPTForCausalLM:()=>Qe,OPTModel:()=>Le,OPTPreTrainedModel:()=>Te,OpenELMForCausalLM:()=>Go,OpenELMModel:()=>Lr,OpenELMPreTrainedModel:()=>rs,OwlViTForObjectDetection:()=>ln,OwlViTModel:()=>rn,OwlViTPreTrainedModel:()=>Kt,Owlv2ForObjectDetection:()=>Gn,Owlv2Model:()=>Un,Owlv2PreTrainedModel:()=>qt,Phi3ForCausalLM:()=>nl,Phi3Model:()=>Ss,Phi3PreTrainedModel:()=>ks,PhiForCausalLM:()=>qo,PhiModel:()=>zs,PhiPreTrainedModel:()=>ba,PreTrainedModel:()=>ne,PretrainedMixin:()=>xr,PyAnnoteForAudioFrameClassification:()=>Kd,PyAnnoteModel:()=>Hd,PyAnnotePreTrainedModel:()=>qu,QuestionAnsweringModelOutput:()=>Ri,Qwen2ForCausalLM:()=>wa,Qwen2Model:()=>Wl,Qwen2PreTrainedModel:()=>xi,RTDetrForObjectDetection:()=>yd,RTDetrModel:()=>_d,RTDetrObjectDetectionOutput:()=>vd,RTDetrPreTrainedModel:()=>Ho,ResNetForImageClassification:()=>Sd,ResNetModel:()=>kd,ResNetPreTrainedModel:()=>Pu,RoFormerForMaskedLM:()=>z,RoFormerForQuestionAnswering:()=>he,RoFormerForSequenceClassification:()=>Fe,RoFormerForTokenClassification:()=>Re,RoFormerModel:()=>xt,RoFormerPreTrainedModel:()=>dt,RobertaForMaskedLM:()=>ci,RobertaForQuestionAnswering:()=>jr,RobertaForSequenceClassification:()=>Qr,RobertaForTokenClassification:()=>mt,RobertaModel:()=>Bn,RobertaPreTrainedModel:()=>bn,SamImageSegmentationOutput:()=>qd,SamModel:()=>Gd,SamPreTrainedModel:()=>Wd,SapiensForDepthEstimation:()=>Id,SapiensForNormalEstimation:()=>Fd,SapiensForSemanticSegmentation:()=>zu,SapiensPreTrainedModel:()=>Gl,SegformerForImageClassification:()=>mf,SegformerForSemanticSegmentation:()=>gf,SegformerModel:()=>Ip,SegformerPreTrainedModel:()=>Jl,Seq2SeqLMOutput:()=>a_,SequenceClassifierOutput:()=>Jn,SiglipModel:()=>yo,SiglipPreTrainedModel:()=>da,SiglipTextModel:()=>Ro,SiglipVisionModel:()=>fa,SpeechT5ForSpeechToText:()=>Yl,SpeechT5ForTextToSpeech:()=>of,SpeechT5HifiGan:()=>Zl,SpeechT5Model:()=>Yu,SpeechT5PreTrainedModel:()=>Ql,SqueezeBertForMaskedLM:()=>es,SqueezeBertForQuestionAnswering:()=>hs,SqueezeBertForSequenceClassification:()=>Ai,SqueezeBertModel:()=>Io,SqueezeBertPreTrainedModel:()=>ui,StableLmForCausalLM:()=>_f,StableLmModel:()=>Fp,StableLmPreTrainedModel:()=>ac,Starcoder2ForCausalLM:()=>uf,Starcoder2Model:()=>lf,Starcoder2PreTrainedModel:()=>nc,Swin2SRForImageSuperResolution:()=>Ou,Swin2SRModel:()=>Fu,Swin2SRPreTrainedModel:()=>Iu,SwinForImageClassification:()=>$u,SwinModel:()=>Ed,SwinPreTrainedModel:()=>Au,T5ForConditionalGeneration:()=>po,T5Model:()=>ho,T5PreTrainedModel:()=>Zn,TableTransformerForObjectDetection:()=>bd,TableTransformerModel:()=>wd,TableTransformerObjectDetectionOutput:()=>xd,TableTransformerPreTrainedModel:()=>Eu,TokenClassifierOutput:()=>hi,TrOCRForCausalLM:()=>Ju,TrOCRPreTrainedModel:()=>Zu,UniSpeechForCTC:()=>Xd,UniSpeechForSequenceClassification:()=>Ku,UniSpeechModel:()=>Xl,UniSpeechPreTrainedModel:()=>Kl,UniSpeechSatForAudioFrameClassification:()=>Zd,UniSpeechSatForCTC:()=>Yd,UniSpeechSatForSequenceClassification:()=>Cp,UniSpeechSatModel:()=>Qd,UniSpeechSatPreTrainedModel:()=>Ko,ViTForImageClassification:()=>Ue,ViTModel:()=>at,ViTPreTrainedModel:()=>qe,VisionEncoderDecoderModel:()=>Fo,VitMatteForImageMatting:()=>tt,VitMattePreTrainedModel:()=>ut,VitsModel:()=>oc,VitsModelOutput:()=>uh,VitsPreTrainedModel:()=>sc,Wav2Vec2BertForCTC:()=>Jd,Wav2Vec2BertForSequenceClassification:()=>Xu,Wav2Vec2BertModel:()=>il,Wav2Vec2BertPreTrainedModel:()=>rl,Wav2Vec2ForAudioFrameClassification:()=>Gu,Wav2Vec2ForCTC:()=>Wu,Wav2Vec2ForSequenceClassification:()=>ql,Wav2Vec2Model:()=>Ti,Wav2Vec2PreTrainedModel:()=>Wi,WavLMForAudioFrameClassification:()=>sf,WavLMForCTC:()=>$p,WavLMForSequenceClassification:()=>Qu,WavLMForXVector:()=>rf,WavLMModel:()=>nf,WavLMPreTrainedModel:()=>xa,WeSpeakerResNetModel:()=>Hu,WeSpeakerResNetPreTrainedModel:()=>Hl,WhisperForConditionalGeneration:()=>mo,WhisperModel:()=>vn,WhisperPreTrainedModel:()=>Bt,XLMForQuestionAnswering:()=>Ir,XLMForSequenceClassification:()=>Mn,XLMForTokenClassification:()=>Ii,XLMModel:()=>Rr,XLMPreTrainedModel:()=>tr,XLMRobertaForMaskedLM:()=>sn,XLMRobertaForQuestionAnswering:()=>Fr,XLMRobertaForSequenceClassification:()=>nr,XLMRobertaForTokenClassification:()=>_r,XLMRobertaModel:()=>ur,XLMRobertaPreTrainedModel:()=>lr,XLMWithLMHeadModel:()=>di,XVectorOutput:()=>ah,YolosForObjectDetection:()=>Vd,YolosModel:()=>Sp,YolosObjectDetectionOutput:()=>Ud,YolosPreTrainedModel:()=>ju});var i=n("./src/configs.js"),o=n("./src/backends/onnx.js"),a=n("./src/utils/dtypes.js"),l=n("./src/utils/generic.js"),d=n("./src/utils/core.js"),c=n("./src/utils/hub.js"),p=n("./src/generation/logits_process.js"),v=n("./src/generation/configuration_utils.js"),_=n("./src/utils/tensor.js"),T=n("./src/utils/maths.js"),M=n("./src/generation/stopping_criteria.js"),I=n("./src/generation/logits_sampler.js"),C=n("./src/env.js"),E=n("./src/models/whisper/generation_whisper.js"),x=n("./src/models/whisper/common_whisper.js");const k={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},A=new Map,N=new Map,R=new Map;async function B(H,X,de){let De=de.device;De&&typeof De!="string"&&(De.hasOwnProperty(X)?De=De[X]:(console.warn(`device not specified for "${X}". Using the default device.`),De=null));const kt=De??(C.apis.IS_NODE_ENV?"cpu":"wasm"),At=(0,o.deviceToExecutionProviders)(kt);let Vt=de.dtype;typeof Vt!="string"&&(Vt&&Vt.hasOwnProperty(X)?Vt=Vt[X]:(Vt=a.DEFAULT_DEVICE_DTYPE_MAPPING[kt]??a.DATA_TYPES.fp32,console.warn(`dtype not specified for "${X}". Using the default dtype (${Vt}) for this device (${kt}).`)));const un=Vt;if(a.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(un)){if(un===a.DATA_TYPES.fp16&&kt==="webgpu"&&!await(0,a.isWebGpuFp16Supported)())throw new Error(`The device (${kt}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${un}. Should be one of: ${Object.keys(a.DATA_TYPES).join(", ")}`);const Cn=a.DEFAULT_DTYPE_SUFFIX_MAPPING[un],Kn=`${de.subfolder??""}/${X}${Cn}.onnx`,rr={...de.session_options};rr.executionProviders??(rr.executionProviders=At);const Tr=(0,c.getModelFile)(H,Kn,!0,de);let ir=[];if(de.use_external_data_format&&(de.use_external_data_format===!0||typeof de.use_external_data_format=="object"&&de.use_external_data_format.hasOwnProperty(X)&&de.use_external_data_format[X]===!0)){if(C.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const er=`${X}${Cn}.onnx_data`,or=`${de.subfolder??""}/${er}`;ir.push(new Promise(async(dr,Er)=>{const Gi=await(0,c.getModelFile)(H,or,!0,de);dr({path:er,data:Gi})}))}else rr.externalData!==void 0&&(ir=rr.externalData.map(async er=>{if(typeof er.data=="string"){const or=await(0,c.getModelFile)(H,er.data,!0,de);return{...er,data:or}}return er}));if(ir.length>0&&(rr.externalData=await Promise.all(ir)),kt==="webgpu"){const er=(0,i.getKeyValueShapes)(de.config,{prefix:"present"});if(Object.keys(er).length>0&&!(0,o.isONNXProxy)()){const or={};for(const dr in er)or[dr]="gpu-buffer";rr.preferredOutputLocation=or}}return{buffer:await Tr,session_options:rr}}async function W(H,X,de){return Object.fromEntries(await Promise.all(Object.keys(X).map(async De=>{const{buffer:kt,session_options:At}=await B(H,X[De],de),Vt=await(0,o.createInferenceSession)(kt,At);return[De,Vt]})))}function j(H,X){const de=Object.create(null),De=[];for(const Vt of H.inputNames){const un=X[Vt];if(!(un instanceof _.Tensor)){De.push(Vt);continue}de[Vt]=(0,o.isONNXProxy)()?un.clone():un}if(De.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${De.join(", ")}.`);const kt=Object.keys(X).length,At=H.inputNames.length;if(kt>At){let Vt=Object.keys(X).filter(un=>!H.inputNames.includes(un));console.warn(`WARNING: Too many inputs were provided (${kt} > ${At}). The following inputs will be ignored: "${Vt.join(", ")}".`)}return de}async function ae(H,X){const de=j(H,X);try{const De=Object.fromEntries(Object.entries(de).map(([At,Vt])=>[At,Vt.ort_tensor]));let kt=await H.run(De);return kt=ve(kt),kt}catch(De){throw console.error(`An error occurred during model execution: "${De}".`),console.error("Inputs given to model:",de),De}}function ve(H){for(let X in H)(0,o.isONNXTensor)(H[X])?H[X]=new _.Tensor(H[X]):typeof H[X]=="object"&&ve(H[X]);return H}function Ne(H){if(H instanceof _.Tensor)return H;if(H.length===0)throw Error("items must be non-empty");if(Array.isArray(H[0])){if(H.some(X=>X.length!==H[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 _.Tensor("int64",BigInt64Array.from(H.flat().map(X=>BigInt(X))),[H.length,H[0].length])}else return new _.Tensor("int64",BigInt64Array.from(H.map(X=>BigInt(X))),[1,H.length])}function oe(H){return new _.Tensor("bool",[H],[1])}async function Se(H,X){let{encoder_outputs:de,input_ids:De,decoder_input_ids:kt,...At}=X;if(!de){const un=(0,d.pick)(X,H.sessions.model.inputNames);de=(await G(H,un)).last_hidden_state}return At.input_ids=kt,At.encoder_hidden_states=de,H.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(At.encoder_attention_mask=X.attention_mask),await Ce(H,At,!0)}async function G(H,X){const de=H.sessions.model,De=(0,d.pick)(X,de.inputNames);if(de.inputNames.includes("inputs_embeds")&&!De.inputs_embeds){if(!X.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");De.inputs_embeds=await H.encode_text({input_ids:X.input_ids})}return de.inputNames.includes("token_type_ids")&&!De.token_type_ids&&(De.token_type_ids=new _.Tensor("int64",new BigInt64Array(De.input_ids.data.length),De.input_ids.dims)),await ae(de,De)}async function Ce(H,X,de=!1){const De=H.sessions[de?"decoder_model_merged":"model"],{past_key_values:kt,...At}=X;De.inputNames.includes("use_cache_branch")&&(At.use_cache_branch=oe(!!kt)),De.inputNames.includes("position_ids")&&At.attention_mask&&!At.position_ids&&(At.position_ids=Me(At,kt)),H.addPastKeyValues(At,kt);const Vt=(0,d.pick)(At,De.inputNames);return await ae(De,Vt)}async function gt(H,{input_ids:X=null,attention_mask:de=null,pixel_values:De=null,position_ids:kt=null,inputs_embeds:At=null,past_key_values:Vt=null,generation_config:un=null,logits_processor:Cn=null,...Kn}){if(!At){if(At=await H.encode_text({input_ids:X}),De&&X.dims[1]!==1){const Tr=await H.encode_image({pixel_values:De});({inputs_embeds:At,attention_mask:de}=H._merge_input_ids_with_image_features({image_features:Tr,inputs_embeds:At,input_ids:X,attention_mask:de}))}else if(Vt&&De&&X.dims[1]===1){const Tr=X.dims[1],ir=Object.values(Vt)[0].dims.at(-2);de=(0,_.cat)([(0,_.ones)([X.dims[0],ir]),de.slice(null,[de.dims[1]-Tr,de.dims[1]])],1)}}return await Ce(H,{inputs_embeds:At,past_key_values:Vt,attention_mask:de,position_ids:kt,generation_config:un,logits_processor:Cn},!0)}function Me(H,X=null){const{input_ids:de,inputs_embeds:De,attention_mask:kt}=H,[At,Vt]=kt.dims,un=new BigInt64Array(kt.data.length);for(let Kn=0;KnAt.dims[1])){if(ktun==H.config.image_token_index)){const un=H.config.num_image_tokens;if(!un)throw new Error("`num_image_tokens` is missing in the model configuration.");const Cn=At.dims[1]-(kt-un);de.input_ids=At.slice(null,[-Cn,null]),de.attention_mask=(0,_.ones)([1,kt+Cn])}}}return de}function fe(H,X,de,De){return de.past_key_values&&(X=X.map(kt=>[kt.at(-1)])),{...de,decoder_input_ids:Ne(X)}}function Ae(H,...X){return H.config.is_encoder_decoder?fe(H,...X):te(H,...X)}class ne extends l.Callable{constructor(de,De){super();ft(this,"main_input_name","input_ids");ft(this,"forward_params",["input_ids","attention_mask"]);this.config=de,this.sessions=De;const kt=R.get(this.constructor),At=A.get(kt);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,At){case k.DecoderOnly:this.can_generate=!0,this._forward=Ce,this._prepare_inputs_for_generation=te;break;case k.Seq2Seq:case k.Vision2Seq:case k.Musicgen:this.can_generate=!0,this._forward=Se,this._prepare_inputs_for_generation=fe;break;case k.EncoderDecoder:this._forward=Se;break;case k.ImageTextToText:this.can_generate=!0,this._forward=gt,this._prepare_inputs_for_generation=Ae;break;default:this._forward=G;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var De;const de=[];for(const kt of Object.values(this.sessions))(De=kt==null?void 0:kt.handler)!=null&&De.dispose&&de.push(kt.handler.dispose());return await Promise.all(de)}static async from_pretrained(de,{progress_callback:De=null,config:kt=null,cache_dir:At=null,local_files_only:Vt=!1,revision:un="main",model_file_name:Cn=null,subfolder:Kn="onnx",device:rr=null,dtype:Tr=null,use_external_data_format:ir=null,session_options:cr={}}={}){let er={progress_callback:De,config:kt,cache_dir:At,local_files_only:Vt,revision:un,model_file_name:Cn,subfolder:Kn,device:rr,dtype:Tr,use_external_data_format:ir,session_options:cr};const or=R.get(this),dr=A.get(or);kt=er.config=await i.AutoConfig.from_pretrained(de,er);let Er;if(dr===k.DecoderOnly)Er=await Promise.all([W(de,{model:er.model_file_name??"model"},er),(0,c.getModelJSON)(de,"generation_config.json",!1,er)]);else if(dr===k.Seq2Seq||dr===k.Vision2Seq)Er=await Promise.all([W(de,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},er),(0,c.getModelJSON)(de,"generation_config.json",!1,er)]);else if(dr===k.MaskGeneration)Er=await Promise.all([W(de,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},er)]);else if(dr===k.EncoderDecoder)Er=await Promise.all([W(de,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},er)]);else if(dr===k.ImageTextToText){const Gi={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};kt.is_encoder_decoder&&(Gi.model="encoder_model"),Er=await Promise.all([W(de,Gi,er),(0,c.getModelJSON)(de,"generation_config.json",!1,er)])}else dr===k.Musicgen?Er=await Promise.all([W(de,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},er),(0,c.getModelJSON)(de,"generation_config.json",!1,er)]):(dr!==k.EncoderOnly&&console.warn(`Model type for '${or??(kt==null?void 0:kt.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),Er=await Promise.all([W(de,{model:er.model_file_name??"model"},er)]));return new this(kt,...Er)}async _call(de){return await this.forward(de)}async forward(de){return await this._forward(this,de)}_get_logits_warper(de){const De=new p.LogitsProcessorList;return de.temperature!==null&&de.temperature!==1&&De.push(new p.TemperatureLogitsWarper(de.temperature)),de.top_k!==null&&de.top_k!==0&&De.push(new p.TopKLogitsWarper(de.top_k)),de.top_p!==null&&de.top_p<1&&De.push(new p.TopPLogitsWarper(de.top_p)),De}_get_logits_processor(de,De,kt=null){const At=new p.LogitsProcessorList;if(de.repetition_penalty!==null&&de.repetition_penalty!==1&&At.push(new p.RepetitionPenaltyLogitsProcessor(de.repetition_penalty)),de.no_repeat_ngram_size!==null&&de.no_repeat_ngram_size>0&&At.push(new p.NoRepeatNGramLogitsProcessor(de.no_repeat_ngram_size)),de.bad_words_ids!==null&&At.push(new p.NoBadWordsLogitsProcessor(de.bad_words_ids,de.eos_token_id)),de.min_length!==null&&de.eos_token_id!==null&&de.min_length>0&&At.push(new p.MinLengthLogitsProcessor(de.min_length,de.eos_token_id)),de.min_new_tokens!==null&&de.eos_token_id!==null&&de.min_new_tokens>0&&At.push(new p.MinNewTokensLengthLogitsProcessor(De,de.min_new_tokens,de.eos_token_id)),de.forced_bos_token_id!==null&&At.push(new p.ForcedBOSTokenLogitsProcessor(de.forced_bos_token_id)),de.forced_eos_token_id!==null&&At.push(new p.ForcedEOSTokenLogitsProcessor(de.max_length,de.forced_eos_token_id)),de.begin_suppress_tokens!==null){const Vt=De>1||de.forced_bos_token_id===null?De:De+1;At.push(new p.SuppressTokensAtBeginLogitsProcessor(de.begin_suppress_tokens,Vt))}return de.guidance_scale!==null&&de.guidance_scale>1&&At.push(new p.ClassifierFreeGuidanceLogitsProcessor(de.guidance_scale)),kt!==null&&At.extend(kt),At}_prepare_generation_config(de,De,kt=v.GenerationConfig){const At={...this.config};for(const un of["decoder","generator","text_config"])un in At&&Object.assign(At,At[un]);const Vt=new kt(At);return"generation_config"in this&&Object.assign(Vt,this.generation_config),de&&Object.assign(Vt,de),De&&Object.assign(Vt,(0,d.pick)(De,Object.getOwnPropertyNames(Vt))),Vt}_get_stopping_criteria(de,De=null){const kt=new M.StoppingCriteriaList;return de.max_length!==null&&kt.push(new M.MaxLengthCriteria(de.max_length,this.config.max_position_embeddings??null)),de.eos_token_id!==null&&kt.push(new M.EosTokenCriteria(de.eos_token_id)),De&&kt.extend(De),kt}_validate_model_class(){if(!this.can_generate){const de=[Cf,gc,mc,pc],De=R.get(this.constructor),kt=new Set,At=this.config.model_type;for(const un of de){const Cn=un.get(At);Cn&&kt.add(Cn[0])}let Vt=`The current model class (${De}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw kt.size>0&&(Vt+=` Please use the following class instead: ${[...kt].join(", ")}`),Error(Vt)}}prepare_inputs_for_generation(...de){return this._prepare_inputs_for_generation(this,...de)}_update_model_kwargs_for_generation({generated_input_ids:de,outputs:De,model_inputs:kt,is_encoder_decoder:At}){return kt.past_key_values=this.getPastKeyValues(De,kt.past_key_values),kt.input_ids=new _.Tensor("int64",de.flat(),[de.length,1]),At||(kt.attention_mask=(0,_.cat)([kt.attention_mask,(0,_.ones)([kt.attention_mask.dims[0],1])],1)),kt.position_ids=null,kt}_prepare_model_inputs({inputs:de,bos_token_id:De,model_kwargs:kt}){const At=(0,d.pick)(kt,this.forward_params),Vt=this.main_input_name;if(Vt in At){if(de)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else At[Vt]=de;return{inputs_tensor:At[Vt],model_inputs:At,model_input_name:Vt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:de,model_inputs:De,model_input_name:kt,generation_config:At}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!De.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:un,pixel_values:Cn,attention_mask:Kn,...rr}=De,Tr=await this._prepare_inputs_embeds(De);De={...rr,...(0,d.pick)(Tr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Vt}=await G(this,De);if(At.guidance_scale!==null&&At.guidance_scale>1)Vt=(0,_.cat)([Vt,(0,_.full_like)(Vt,0)],0),"attention_mask"in De&&(De.attention_mask=(0,_.cat)([De.attention_mask,(0,_.zeros_like)(De.attention_mask)],0));else if(De.decoder_input_ids){const un=Ne(De.decoder_input_ids).dims[0];if(un!==Vt.dims[0]){if(Vt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Vt.dims[0]}) than the decoder inputs (${un}).`);Vt=(0,_.cat)(Array.from({length:un},()=>Vt),0)}}return De.encoder_outputs=Vt,De}_prepare_decoder_input_ids_for_generation({batch_size:de,model_input_name:De,model_kwargs:kt,decoder_start_token_id:At,bos_token_id:Vt,generation_config:un}){let{decoder_input_ids:Cn,...Kn}=kt;if(Cn)Array.isArray(Cn[0])||(Cn=Array.from({length:de},()=>Cn));else if(At??(At=Vt),this.config.model_type==="musicgen")Cn=Array.from({length:de*this.config.decoder.num_codebooks},()=>[At]);else if(Array.isArray(At)){if(At.length!==de)throw new Error(`\`decoder_start_token_id\` expcted to have length ${de} but got ${At.length}`);Cn=At}else Cn=Array.from({length:de},()=>[At]);return Cn=Ne(Cn),kt.decoder_attention_mask=(0,_.ones_like)(Cn),{input_ids:Cn,model_inputs:Kn}}async generate({inputs:de=null,generation_config:De=null,logits_processor:kt=null,stopping_criteria:At=null,streamer:Vt=null,...un}){this._validate_model_class(),De=this._prepare_generation_config(De,un);let{inputs_tensor:Cn,model_inputs:Kn,model_input_name:rr}=this._prepare_model_inputs({inputs:de,model_kwargs:un});const Tr=this.config.is_encoder_decoder;Tr&&("encoder_outputs"in Kn||(Kn=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Cn,model_inputs:Kn,model_input_name:rr,generation_config:De})));let ir;Tr?{input_ids:ir,model_inputs:Kn}=this._prepare_decoder_input_ids_for_generation({batch_size:Kn[rr].dims.at(0),model_input_name:rr,model_kwargs:Kn,decoder_start_token_id:De.decoder_start_token_id,bos_token_id:De.bos_token_id,generation_config:De}):ir=Kn[rr];let cr=ir.dims.at(-1);De.max_new_tokens!==null&&(De.max_length=cr+De.max_new_tokens);const er=this._get_logits_processor(De,cr,kt),or=this._get_stopping_criteria(De,At),dr=Kn[rr].dims.at(0),Er=I.LogitsSampler.getSampler(De),Gi=new Array(dr).fill(0),qi=ir.tolist();Vt&&Vt.put(qi);let Ls=null,Li={};for(;;){Kn=this.prepare_inputs_for_generation(qi,Kn,De);const Mi=await this.forward(Kn);if(De.output_attentions&&De.return_dict_in_generate){const Bs=this.getAttentions(Mi);for(const Ma in Bs)Ma in Li||(Li[Ma]=[]),Li[Ma].push(Bs[Ma])}const Tc=Mi.logits.slice(null,-1,null),Mc=er(qi,Tc),kc=[];for(let Bs=0;BsBs)){De.return_dict_in_generate&&(Ls=this.getPastKeyValues(Mi,Kn.past_key_values,!1));break}Kn=this._update_model_kwargs_for_generation({generated_input_ids:kc,outputs:Mi,model_inputs:Kn,is_encoder_decoder:Tr})}Vt&&Vt.end();const oi=new _.Tensor("int64",qi.flat(),[qi.length,qi[0].length]);return De.return_dict_in_generate?{sequences:oi,past_key_values:Ls,...Li}:oi}getPastKeyValues(de,De,kt=!0){const At=Object.create(null);for(const Vt in de)if(Vt.startsWith("present")){const un=Vt.replace("present","past_key_values");if(De&&Vt.includes("encoder"))At[un]=De[un];else{if(kt&&De){const Cn=De[un];Cn.location==="gpu-buffer"&&Cn.dispose()}At[un]=de[Vt]}}return At}getAttentions(de){const De={};for(const kt of["cross_attentions","encoder_attentions","decoder_attentions"])for(const At in de)At.startsWith(kt)&&(kt in De||(De[kt]=[]),De[kt].push(de[At]));return De}addPastKeyValues(de,De){if(De)Object.assign(de,De);else{const kt=this.custom_config.kv_cache_dtype??"float32",At=kt==="float16"?new Uint16Array:[],Vt=(0,i.getKeyValueShapes)(this.config);for(const un in Vt)de[un]=new _.Tensor(kt,At,Vt[un])}}async encode_image({pixel_values:de}){const De=(await ae(this.sessions.vision_encoder,{pixel_values:de})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${De.dims[1]}).`),this.config.num_image_tokens=De.dims[1]),De}async encode_text({input_ids:de}){return(await ae(this.sessions.embed_tokens,{input_ids:de})).inputs_embeds}}class xe{}class pt extends xe{constructor({last_hidden_state:X,hidden_states:de=null,attentions:De=null}){super(),this.last_hidden_state=X,this.hidden_states=de,this.attentions=De}}class Ye extends ne{}class et extends Ye{}class ct extends Ye{async _call(X){return new vi(await super._call(X))}}class Et extends Ye{async _call(X){return new Jn(await super._call(X))}}class Rt extends Ye{async _call(X){return new hi(await super._call(X))}}class je extends Ye{async _call(X){return new Ri(await super._call(X))}}class Ie extends ne{}class rt extends Ie{}class dt extends ne{}class xt extends dt{}class z extends dt{async _call(X){return new vi(await super._call(X))}}class Fe extends dt{async _call(X){return new Jn(await super._call(X))}}class Re extends dt{async _call(X){return new hi(await super._call(X))}}class he extends dt{async _call(X){return new Ri(await super._call(X))}}class ue extends ne{}class Ee extends ue{}class q extends ue{async _call(X){return new vi(await super._call(X))}}class re extends ue{async _call(X){return new Jn(await super._call(X))}}class V extends ue{async _call(X){return new hi(await super._call(X))}}class me extends ue{async _call(X){return new Ri(await super._call(X))}}class ge extends ne{}class $e extends ge{}class Ze extends ge{async _call(X){return new vi(await super._call(X))}}class Dt extends ge{async _call(X){return new Jn(await super._call(X))}}class Tt extends ge{async _call(X){return new hi(await super._call(X))}}class Nt extends ge{async _call(X){return new Ri(await super._call(X))}}class jt extends ne{}class ht extends jt{}class _e extends jt{async _call(X){return new vi(await super._call(X))}}class Be extends jt{async _call(X){return new Jn(await super._call(X))}}class st extends jt{async _call(X){return new hi(await super._call(X))}}class Je extends jt{async _call(X){return new Ri(await super._call(X))}}class _t extends ne{}class $t extends _t{}class Wt extends _t{async _call(X){return new vi(await super._call(X))}}class ot extends _t{async _call(X){return new Jn(await super._call(X))}}class nn extends _t{async _call(X){return new hi(await super._call(X))}}class Gt extends _t{async _call(X){return new Ri(await super._call(X))}}class Mt extends ne{}class mn extends Mt{}class hn extends Mt{async _call(X){return new vi(await super._call(X))}}class Sn extends Mt{async _call(X){return new Jn(await super._call(X))}}class Tn extends Mt{async _call(X){return new hi(await super._call(X))}}class yn extends Mt{async _call(X){return new Ri(await super._call(X))}}class En extends ne{}class $n extends En{}class zn extends En{async _call(X){return new Jn(await super._call(X))}}class kn extends En{async _call(X){return new hi(await super._call(X))}}class Pt extends En{async _call(X){return new Ri(await super._call(X))}}class Qt extends En{async _call(X){return new vi(await super._call(X))}}class dn extends ne{}class Ar extends dn{}class Ci extends dn{async _call(X){return new vi(await super._call(X))}}class xs extends dn{async _call(X){return new Jn(await super._call(X))}}class gr extends dn{async _call(X){return new hi(await super._call(X))}}class Nr extends ne{}class yr extends Nr{}class Pi extends Nr{async _call(X){return new vi(await super._call(X))}}class wr extends Nr{async _call(X){return new Jn(await super._call(X))}}class gi extends Nr{async _call(X){return new Ri(await super._call(X))}}class ds extends ne{}class fs extends ds{}class fo extends ds{async _call(X){return new vi(await super._call(X))}}class Xs extends ds{async _call(X){return new Jn(await super._call(X))}}class $r extends ds{async _call(X){return new hi(await super._call(X))}}class Ji extends ds{async _call(X){return new Ri(await super._call(X))}}class ui extends ne{}class Io extends ui{}class es extends ui{async _call(X){return new vi(await super._call(X))}}class Ai extends ui{async _call(X){return new Jn(await super._call(X))}}class hs extends ui{async _call(X){return new Ri(await super._call(X))}}class ts extends ne{}class $i extends ts{}class Qs extends ts{async _call(X){return new Jn(await super._call(X))}}class Ts extends ts{async _call(X){return new Ri(await super._call(X))}}class Pn extends ts{async _call(X){return new vi(await super._call(X))}}class Zn extends ne{constructor(de,De,kt){super(de,De);ft(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=kt}}class ho extends Zn{}class po extends Zn{}class Ys extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class br extends Ys{}class Ms extends Ys{}class ps extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class ms extends ps{}class kr extends ps{}class _i extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class it extends _i{}class K extends _i{}class ye extends _i{async _call(X){return new Jn(await super._call(X))}}class Oe extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class Ve extends Oe{}class He extends Oe{}class St extends Oe{async _call(X){return new Jn(await super._call(X))}}class Zt extends Oe{}class Lt extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class Jt extends Lt{}class fn extends Lt{}class Rn extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class Wn extends Rn{}class On extends Rn{}class bn extends ne{}class Bn extends bn{}class ci extends bn{async _call(X){return new vi(await super._call(X))}}class Qr extends bn{async _call(X){return new Jn(await super._call(X))}}class mt extends bn{async _call(X){return new hi(await super._call(X))}}class jr extends bn{async _call(X){return new Ri(await super._call(X))}}class tr extends ne{}class Rr extends tr{}class di extends tr{async _call(X){return new vi(await super._call(X))}}class Mn extends tr{async _call(X){return new Jn(await super._call(X))}}class Ii extends tr{async _call(X){return new hi(await super._call(X))}}class Ir extends tr{async _call(X){return new Ri(await super._call(X))}}class lr extends ne{}class ur extends lr{}class sn extends lr{async _call(X){return new vi(await super._call(X))}}class nr extends lr{async _call(X){return new Jn(await super._call(X))}}class _r extends lr{async _call(X){return new hi(await super._call(X))}}class Fr extends lr{async _call(X){return new Ri(await super._call(X))}}class Fi extends ne{}class gn extends Fi{}class ua extends Fi{}class Bt extends ne{constructor(de,De,kt){super(de,De);ft(this,"requires_attention_mask",!1);ft(this,"main_input_name","input_features");ft(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=kt}}class vn extends Bt{}class mo extends Bt{_prepare_generation_config(X,de){return super._prepare_generation_config(X,de,E.WhisperGenerationConfig)}_retrieve_init_tokens(X){const de=[X.decoder_start_token_id];let De=X.language;const kt=X.task;if(X.is_multilingual){De||(console.warn("No language specified - defaulting to English (en)."),De="en");const Vt=`<|${(0,x.whisper_language_to_code)(De)}|>`;de.push(X.lang_to_id[Vt]),de.push(X.task_to_id[kt??"transcribe"])}else if(De||kt)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!X.return_timestamps&&X.no_timestamps_token_id&&de.at(-1)!==X.no_timestamps_token_id?de.push(X.no_timestamps_token_id):X.return_timestamps&&de.at(-1)===X.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),de.pop()),de.filter(At=>At!=null)}async generate({inputs:X=null,generation_config:de=null,logits_processor:De=null,stopping_criteria:kt=null,...At}){de=this._prepare_generation_config(de,At);const Vt=At.decoder_input_ids??this._retrieve_init_tokens(de);if(de.return_timestamps&&(De??(De=new p.LogitsProcessorList),De.push(new p.WhisperTimeStampLogitsProcessor(de,Vt))),de.begin_suppress_tokens&&(De??(De=new p.LogitsProcessorList),De.push(new p.SuppressTokensAtBeginLogitsProcessor(de.begin_suppress_tokens,Vt.length))),de.return_token_timestamps){if(!de.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.");de.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),de.output_attentions=!0,de.return_dict_in_generate=!0}const un=await super.generate({inputs:X,generation_config:de,logits_processor:De,decoder_input_ids:Vt,...At});return de.return_token_timestamps&&(un.token_timestamps=this._extract_token_timestamps(un,de.alignment_heads,de.num_frames)),un}_extract_token_timestamps(X,de,De=null,kt=.02){if(!X.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`.");De==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let At=this.config.median_filter_width;At===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),At=7);const Vt=X.cross_attentions,un=Array.from({length:this.config.decoder_layers},(or,dr)=>(0,_.cat)(Vt.map(Er=>Er[dr]),2)),Cn=(0,_.stack)(de.map(([or,dr])=>{if(or>=un.length)throw new Error(`Layer index ${or} is out of bounds for cross attentions (length ${un.length}).`);return De?un[or].slice(null,dr,null,[0,De]):un[or].slice(null,dr)})).transpose(1,0,2,3),[Kn,rr]=(0,_.std_mean)(Cn,-2,0,!0),Tr=Cn.clone();for(let or=0;orEr[Mi+1]-Er[Mi]),Ls=(0,d.mergeArrays)([1],qi).map(oi=>!!oi),Li=[];for(let oi=0;oiir.findIndex(cr=>cr==At)),Cn=un.every(ir=>ir===-1),Kn=un.every(ir=>ir!==-1);if(!Cn&&!Kn)throw new Error("Every input should contain either 0 or 1 image token.");if(Cn)return{inputs_embeds:X,attention_mask:kt};const rr=[],Tr=[];for(let ir=0;irAt*Vt,1);X.input_labels=new _.Tensor("int64",new BigInt64Array(kt).fill(1n),De)}const de={image_embeddings:X.image_embeddings,image_positional_embeddings:X.image_positional_embeddings};return X.input_points&&(de.input_points=X.input_points),X.input_labels&&(de.input_labels=X.input_labels),X.input_boxes&&(de.input_boxes=X.input_boxes),await ae(this.sessions.prompt_encoder_mask_decoder,de)}async _call(X){return new qd(await super._call(X))}}class qd extends xe{constructor({iou_scores:X,pred_masks:de}){super(),this.iou_scores=X,this.pred_masks=de}}class Vu extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class Ep extends Vu{}class xo extends Vu{}class Js extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class To extends Js{}class Uu extends Js{}class Wi extends ne{}class Ti extends Wi{}class Wu extends Wi{async _call(X){return new Xo(await super._call(X))}}class ql extends Wi{async _call(X){return new Jn(await super._call(X))}}class Gu extends Wi{async _call(X){return new hi(await super._call(X))}}class qu extends ne{}class Hd extends qu{}class Kd extends qu{async _call(X){return new hi(await super._call(X))}}class Hl extends ne{}class Hu extends Hl{}class Kl extends ne{}class Xl extends Kl{}class Xd extends Kl{async _call(X){return new Xo(await super._call(X))}}class Ku extends Kl{async _call(X){return new Jn(await super._call(X))}}class Ko extends ne{}class Qd extends Ko{}class Yd extends Ko{async _call(X){return new Xo(await super._call(X))}}class Cp extends Ko{async _call(X){return new Jn(await super._call(X))}}class Zd extends Ko{async _call(X){return new hi(await super._call(X))}}class rl extends ne{}class il extends rl{}class Jd extends rl{async _call(X){return new Xo(await super._call(X))}}class Xu extends rl{async _call(X){return new Jn(await super._call(X))}}class Pp extends ne{}class ef extends Wi{}class tf extends Wi{async _call(X){return new Xo(await super._call(X))}}class Ap extends Wi{async _call(X){return new Jn(await super._call(X))}}class xa extends ne{}class nf extends xa{}class $p extends xa{async _call(X){return new Xo(await super._call(X))}}class Qu extends xa{async _call(X){return new Jn(await super._call(X))}}class rf extends xa{async _call(X){return new ah(await super._call(X))}}class sf extends xa{async _call(X){return new hi(await super._call(X))}}class Ql extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class Yu extends Ql{}class Yl extends Ql{}class of extends Ql{async generate_speech(X,de,{threshold:De=.5,minlenratio:kt=0,maxlenratio:At=20,vocoder:Vt=null}={}){const un={input_ids:X},{encoder_outputs:Cn,encoder_attention_mask:Kn}=await G(this,un),rr=Cn.dims[1]/this.config.reduction_factor,Tr=Math.floor(rr*At),ir=Math.floor(rr*kt),cr=this.config.num_mel_bins;let er=[],or=null,dr=null,Er=0;for(;;){++Er;const Ls=oe(!!dr);let Li;dr?Li=dr.output_sequence_out:Li=new _.Tensor("float32",new Float32Array(cr),[1,1,cr]);let oi={use_cache_branch:Ls,output_sequence:Li,encoder_attention_mask:Kn,speaker_embeddings:de,encoder_hidden_states:Cn};this.addPastKeyValues(oi,or),dr=await ae(this.sessions.decoder_model_merged,oi),or=this.getPastKeyValues(dr,or);const{prob:Mi,spectrum:Tc}=dr;if(er.push(Tc),Er>=ir&&(Array.from(Mi.data).filter(Mc=>Mc>=De).length>0||Er>=Tr))break}const Gi=(0,_.cat)(er),{waveform:qi}=await ae(Vt.sessions.model,{spectrogram:Gi});return{spectrogram:Gi,waveform:qi}}}class Zl extends ne{constructor(){super(...arguments);ft(this,"main_input_name","spectrogram")}}class Zu extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class Ju extends Zu{}class ec extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class af extends ec{}class tc extends ec{}class nc extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class lf extends nc{}class uf extends nc{}class cf extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class df extends cf{}class rc extends cf{}class ic extends ne{}class ff extends ic{}class hf extends ic{static async from_pretrained(X,de={}){return de.model_file_name??(de.model_file_name="text_model"),super.from_pretrained(X,de)}}class pf extends ic{static async from_pretrained(X,de={}){return de.model_file_name??(de.model_file_name="audio_model"),super.from_pretrained(X,de)}}class sc extends ne{}class oc extends sc{async _call(X){return new uh(await super._call(X))}}class Jl extends ne{}class Ip extends Jl{}class mf extends Jl{}class gf extends Jl{}class ac extends ne{constructor(X,de,De){super(X,de),this.generation_config=De}}class Fp extends ac{}class _f extends ac{}class lc extends ne{}class yf extends lc{}class Op extends lc{async _call(X){return new Jn(await super._call(X))}}class uc extends ne{}class Dp extends uc{}class zp extends uc{}class cc extends ne{constructor(de,De,kt){super(de,De);ft(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=kt}_apply_and_filter_by_delay_pattern_mask(de){const[De,kt]=de.dims,At=this.config.decoder.num_codebooks,Vt=kt-At;let un=0;for(let rr=0;rr0&&cr<=Vt&&(de.data[un++]=de.data[rr])}const Cn=Math.floor(De/At),Kn=un/(Cn*At);return new _.Tensor(de.type,de.data.slice(0,un),[Cn,At,Kn])}prepare_inputs_for_generation(de,De,kt){let At=structuredClone(de);for(let un=0;un=Cn&&(At[un][Cn]=BigInt(this.config.decoder.pad_token_id));return kt.guidance_scale!==null&&kt.guidance_scale>1&&(At=At.concat(At)),super.prepare_inputs_for_generation(At,De,kt)}async generate(de){const De=await super.generate(de),kt=this._apply_and_filter_by_delay_pattern_mask(De).unsqueeze_(0),{audio_values:At}=await ae(this.sessions.encodec_decode,{audio_codes:kt});return At}}class dc extends ne{}class Rp extends dc{}class eu extends dc{async _call(X){return new Jn(await super._call(X))}}class Ta extends ne{}class fc extends Ta{}class vf extends Ta{async _call(X){return new Jn(await super._call(X))}}class hc extends ne{}class wf extends hc{}class bf extends hc{async _call(X){return new Jn(await super._call(X))}}class tu extends ne{}class xf extends tu{}class Tf extends tu{async _call(X){return new Jn(await super._call(X))}}class xr{static async from_pretrained(X,{progress_callback:de=null,config:De=null,cache_dir:kt=null,local_files_only:At=!1,revision:Vt="main",model_file_name:un=null,subfolder:Cn="onnx",device:Kn=null,dtype:rr=null,use_external_data_format:Tr=null,session_options:ir={}}={}){let cr={progress_callback:de,config:De,cache_dir:kt,local_files_only:At,revision:Vt,model_file_name:un,subfolder:Cn,device:Kn,dtype:rr,use_external_data_format:Tr,session_options:ir};if(cr.config=await i.AutoConfig.from_pretrained(X,cr),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let er of this.MODEL_CLASS_MAPPINGS){const or=er.get(cr.config.model_type);if(or)return await or[1].from_pretrained(X,cr)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${cr.config.model_type}", attempting to construct from base class.`),await ne.from_pretrained(X,cr);throw Error(`Unsupported model type: ${cr.config.model_type}`)}}ft(xr,"MODEL_CLASS_MAPPINGS",null),ft(xr,"BASE_IF_FAIL",!1);const s_=new Map([["bert",["BertModel",et]],["nomic_bert",["NomicBertModel",rt]],["roformer",["RoFormerModel",xt]],["electra",["ElectraModel",$e]],["esm",["EsmModel",Ar]],["convbert",["ConvBertModel",Ee]],["camembert",["CamembertModel",ht]],["deberta",["DebertaModel",$t]],["deberta-v2",["DebertaV2Model",mn]],["mpnet",["MPNetModel",fs]],["albert",["AlbertModel",$i]],["distilbert",["DistilBertModel",$n]],["roberta",["RobertaModel",Bn]],["xlm",["XLMModel",Rr]],["xlm-roberta",["XLMRobertaModel",ur]],["clap",["ClapModel",ff]],["clip",["CLIPModel",Do]],["clipseg",["CLIPSegModel",fi]],["chinese_clip",["ChineseCLIPModel",pa]],["siglip",["SiglipModel",yo]],["mobilebert",["MobileBertModel",yr]],["squeezebert",["SqueezeBertModel",Io]],["wav2vec2",["Wav2Vec2Model",Ti]],["wav2vec2-bert",["Wav2Vec2BertModel",il]],["unispeech",["UniSpeechModel",Xl]],["unispeech-sat",["UniSpeechSatModel",Qd]],["hubert",["HubertModel",ef]],["wavlm",["WavLMModel",nf]],["audio-spectrogram-transformer",["ASTModel",gn]],["vits",["VitsModel",oc]],["pyannote",["PyAnnoteModel",Hd]],["wespeaker-resnet",["WeSpeakerResNetModel",Hu]],["detr",["DetrModel",ri]],["rt_detr",["RTDetrModel",_d]],["table-transformer",["TableTransformerModel",wd]],["vit",["ViTModel",at]],["fastvit",["FastViTModel",Xe]],["mobilevit",["MobileViTModel",wt]],["mobilevitv2",["MobileViTV2Model",Xt]],["owlvit",["OwlViTModel",rn]],["owlv2",["Owlv2Model",Un]],["beit",["BeitModel",Yn]],["deit",["DeiTModel",Td]],["convnext",["ConvNextModel",zd]],["convnextv2",["ConvNextV2Model",Ld]],["dinov2",["Dinov2Model",Nd]],["resnet",["ResNetModel",kd]],["swin",["SwinModel",Ed]],["swin2sr",["Swin2SRModel",Fu]],["donut-swin",["DonutSwinModel",Es]],["yolos",["YolosModel",Sp]],["dpt",["DPTModel",Cd]],["glpn",["GLPNModel",kp]],["hifigan",["SpeechT5HifiGan",Zl]],["efficientnet",["EfficientNetModel",yf]],["mobilenet_v1",["MobileNetV1Model",Rp]],["mobilenet_v2",["MobileNetV2Model",fc]],["mobilenet_v3",["MobileNetV3Model",wf]],["mobilenet_v4",["MobileNetV4Model",xf]]]),Lp=new Map([["t5",["T5Model",ho]],["longt5",["LongT5Model",br]],["mt5",["MT5Model",ms]],["bart",["BartModel",it]],["mbart",["MBartModel",Ve]],["marian",["MarianModel",Ep]],["whisper",["WhisperModel",vn]],["m2m_100",["M2M100Model",To]],["blenderbot",["BlenderbotModel",Jt]],["blenderbot-small",["BlenderbotSmallModel",Wn]]]),Mf=new Map([["bloom",["BloomModel",y]],["jais",["JAISModel",Ha]],["gpt2",["GPT2Model",qa]],["gptj",["GPTJModel",Nl]],["gpt_bigcode",["GPTBigCodeModel",jl]],["gpt_neo",["GPTNeoModel",Ds]],["gpt_neox",["GPTNeoXModel",Uo]],["codegen",["CodeGenModel",ns]],["llama",["LlamaModel",Ya]],["cohere",["CohereModel",el]],["gemma",["GemmaModel",tl]],["gemma2",["Gemma2Model",Ul]],["openelm",["OpenELMModel",Lr]],["qwen2",["Qwen2Model",Wl]],["phi",["PhiModel",zs]],["phi3",["Phi3Model",Ss]],["mpt",["MptModel",Z]],["opt",["OPTModel",Le]],["mistral",["MistralModel",af]],["starcoder2",["Starcoder2Model",lf]],["falcon",["FalconModel",df]],["stablelm",["StableLmModel",Fp]]]),pc=new Map([["speecht5",["SpeechT5ForSpeechToText",Yl]],["whisper",["WhisperForConditionalGeneration",mo]]]),kf=new Map([["speecht5",["SpeechT5ForTextToSpeech",of]]]),Sf=new Map([["vits",["VitsModel",oc]],["musicgen",["MusicgenForConditionalGeneration",cc]]]),Bp=new Map([["bert",["BertForSequenceClassification",Et]],["roformer",["RoFormerForSequenceClassification",Fe]],["electra",["ElectraForSequenceClassification",Dt]],["esm",["EsmForSequenceClassification",xs]],["convbert",["ConvBertForSequenceClassification",re]],["camembert",["CamembertForSequenceClassification",Be]],["deberta",["DebertaForSequenceClassification",ot]],["deberta-v2",["DebertaV2ForSequenceClassification",Sn]],["mpnet",["MPNetForSequenceClassification",Xs]],["albert",["AlbertForSequenceClassification",Qs]],["distilbert",["DistilBertForSequenceClassification",zn]],["roberta",["RobertaForSequenceClassification",Qr]],["xlm",["XLMForSequenceClassification",Mn]],["xlm-roberta",["XLMRobertaForSequenceClassification",nr]],["bart",["BartForSequenceClassification",ye]],["mbart",["MBartForSequenceClassification",St]],["mobilebert",["MobileBertForSequenceClassification",wr]],["squeezebert",["SqueezeBertForSequenceClassification",Ai]]]),Ef=new Map([["bert",["BertForTokenClassification",Rt]],["roformer",["RoFormerForTokenClassification",Re]],["electra",["ElectraForTokenClassification",Tt]],["esm",["EsmForTokenClassification",gr]],["convbert",["ConvBertForTokenClassification",V]],["camembert",["CamembertForTokenClassification",st]],["deberta",["DebertaForTokenClassification",nn]],["deberta-v2",["DebertaV2ForTokenClassification",Tn]],["mpnet",["MPNetForTokenClassification",$r]],["distilbert",["DistilBertForTokenClassification",kn]],["roberta",["RobertaForTokenClassification",mt]],["xlm",["XLMForTokenClassification",Ii]],["xlm-roberta",["XLMRobertaForTokenClassification",_r]]]),mc=new Map([["t5",["T5ForConditionalGeneration",po]],["longt5",["LongT5ForConditionalGeneration",Ms]],["mt5",["MT5ForConditionalGeneration",kr]],["bart",["BartForConditionalGeneration",K]],["mbart",["MBartForConditionalGeneration",He]],["marian",["MarianMTModel",xo]],["m2m_100",["M2M100ForConditionalGeneration",Uu]],["blenderbot",["BlenderbotForConditionalGeneration",fn]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",On]]]),Cf=new Map([["bloom",["BloomForCausalLM",$]],["gpt2",["GPT2LMHeadModel",Bo]],["jais",["JAISLMHeadModel",No]],["gptj",["GPTJForCausalLM",Ka]],["gpt_bigcode",["GPTBigCodeForCausalLM",wo]],["gpt_neo",["GPTNeoForCausalLM",ma]],["gpt_neox",["GPTNeoXForCausalLM",ga]],["codegen",["CodeGenForCausalLM",Xa]],["llama",["LlamaForCausalLM",Za]],["cohere",["CohereForCausalLM",ya]],["gemma",["GemmaForCausalLM",Vl]],["gemma2",["Gemma2ForCausalLM",Wo]],["openelm",["OpenELMForCausalLM",Go]],["qwen2",["Qwen2ForCausalLM",wa]],["phi",["PhiForCausalLM",qo]],["phi3",["Phi3ForCausalLM",nl]],["mpt",["MptForCausalLM",le]],["opt",["OPTForCausalLM",Qe]],["mbart",["MBartForCausalLM",Zt]],["mistral",["MistralForCausalLM",tc]],["starcoder2",["Starcoder2ForCausalLM",uf]],["falcon",["FalconForCausalLM",rc]],["trocr",["TrOCRForCausalLM",Ju]],["stablelm",["StableLmForCausalLM",_f]]]),Pf=new Map([["bert",["BertForMaskedLM",ct]],["roformer",["RoFormerForMaskedLM",z]],["electra",["ElectraForMaskedLM",Ze]],["esm",["EsmForMaskedLM",Ci]],["convbert",["ConvBertForMaskedLM",q]],["camembert",["CamembertForMaskedLM",_e]],["deberta",["DebertaForMaskedLM",Wt]],["deberta-v2",["DebertaV2ForMaskedLM",hn]],["mpnet",["MPNetForMaskedLM",fo]],["albert",["AlbertForMaskedLM",Pn]],["distilbert",["DistilBertForMaskedLM",Qt]],["roberta",["RobertaForMaskedLM",ci]],["xlm",["XLMWithLMHeadModel",di]],["xlm-roberta",["XLMRobertaForMaskedLM",sn]],["mobilebert",["MobileBertForMaskedLM",Pi]],["squeezebert",["SqueezeBertForMaskedLM",es]]]),Af=new Map([["bert",["BertForQuestionAnswering",je]],["roformer",["RoFormerForQuestionAnswering",he]],["electra",["ElectraForQuestionAnswering",Nt]],["convbert",["ConvBertForQuestionAnswering",me]],["camembert",["CamembertForQuestionAnswering",Je]],["deberta",["DebertaForQuestionAnswering",Gt]],["deberta-v2",["DebertaV2ForQuestionAnswering",yn]],["mpnet",["MPNetForQuestionAnswering",Ji]],["albert",["AlbertForQuestionAnswering",Ts]],["distilbert",["DistilBertForQuestionAnswering",Pt]],["roberta",["RobertaForQuestionAnswering",jr]],["xlm",["XLMForQuestionAnswering",Ir]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Fr]],["mobilebert",["MobileBertForQuestionAnswering",gi]],["squeezebert",["SqueezeBertForQuestionAnswering",hs]]]),gc=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Fo]]]),Np=new Map([["llava",["LlavaForConditionalGeneration",go]],["moondream1",["Moondream1ForConditionalGeneration",Vn]],["florence2",["Florence2ForConditionalGeneration",Oo]]]),o_=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Fo]]]),$f=new Map([["vit",["ViTForImageClassification",Ue]],["fastvit",["FastViTForImageClassification",nt]],["mobilevit",["MobileViTForImageClassification",bt]],["mobilevitv2",["MobileViTV2ForImageClassification",on]],["beit",["BeitForImageClassification",Ui]],["deit",["DeiTForImageClassification",Md]],["convnext",["ConvNextForImageClassification",Rd]],["convnextv2",["ConvNextV2ForImageClassification",Bd]],["dinov2",["Dinov2ForImageClassification",jd]],["resnet",["ResNetForImageClassification",Sd]],["swin",["SwinForImageClassification",$u]],["segformer",["SegformerForImageClassification",mf]],["efficientnet",["EfficientNetForImageClassification",Op]],["mobilenet_v1",["MobileNetV1ForImageClassification",eu]],["mobilenet_v2",["MobileNetV2ForImageClassification",vf]],["mobilenet_v3",["MobileNetV3ForImageClassification",bf]],["mobilenet_v4",["MobileNetV4ForImageClassification",Tf]]]),If=new Map([["detr",["DetrForObjectDetection",ii]],["rt_detr",["RTDetrForObjectDetection",yd]],["table-transformer",["TableTransformerForObjectDetection",bd]],["yolos",["YolosForObjectDetection",Vd]]]),Ff=new Map([["owlvit",["OwlViTForObjectDetection",ln]],["owlv2",["Owlv2ForObjectDetection",Gn]]]),Of=new Map([["detr",["DetrForSegmentation",Rs]],["clipseg",["CLIPSegForImageSegmentation",vo]]]),jp=new Map([["segformer",["SegformerForSemanticSegmentation",gf]],["sapiens",["SapiensForSemanticSegmentation",zu]]]),Df=new Map([["sam",["SamModel",Gd]]]),zf=new Map([["wav2vec2",["Wav2Vec2ForCTC",Wu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Jd]],["unispeech",["UniSpeechForCTC",Xd]],["unispeech-sat",["UniSpeechSatForCTC",Yd]],["wavlm",["WavLMForCTC",$p]],["hubert",["HubertForCTC",tf]]]),Rf=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",ql]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Xu]],["unispeech",["UniSpeechForSequenceClassification",Ku]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Cp]],["wavlm",["WavLMForSequenceClassification",Qu]],["hubert",["HubertForSequenceClassification",Ap]],["audio-spectrogram-transformer",["ASTForAudioClassification",ua]]]),Lf=new Map([["wavlm",["WavLMForXVector",rf]]]),Vp=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Zd]],["wavlm",["WavLMForAudioFrameClassification",sf]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Gu]],["pyannote",["PyAnnoteForAudioFrameClassification",Kd]]]),Bf=new Map([["vitmatte",["VitMatteForImageMatting",tt]]]),Nf=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ou]]]),jf=new Map([["dpt",["DPTForDepthEstimation",Pd]],["depth_anything",["DepthAnythingForDepthEstimation",$d]],["glpn",["GLPNForDepthEstimation",Od]],["sapiens",["SapiensForDepthEstimation",Id]]]),Vf=new Map([["sapiens",["SapiensForNormalEstimation",Fd]]]),Up=new Map([["clip",["CLIPVisionModelWithProjection",zo]],["siglip",["SiglipVisionModel",fa]]]),zi=[[s_,k.EncoderOnly],[Lp,k.EncoderDecoder],[Mf,k.DecoderOnly],[Bp,k.EncoderOnly],[Ef,k.EncoderOnly],[mc,k.Seq2Seq],[pc,k.Seq2Seq],[Cf,k.DecoderOnly],[Pf,k.EncoderOnly],[Af,k.EncoderOnly],[gc,k.Vision2Seq],[Np,k.ImageTextToText],[$f,k.EncoderOnly],[Of,k.EncoderOnly],[jp,k.EncoderOnly],[Bf,k.EncoderOnly],[Nf,k.EncoderOnly],[jf,k.EncoderOnly],[Vf,k.EncoderOnly],[If,k.EncoderOnly],[Ff,k.EncoderOnly],[Df,k.MaskGeneration],[zf,k.EncoderOnly],[Rf,k.EncoderOnly],[kf,k.Seq2Seq],[Sf,k.EncoderOnly],[Lf,k.EncoderOnly],[Vp,k.EncoderOnly],[Up,k.EncoderOnly]];for(const[H,X]of zi)for(const[de,De]of H.values())A.set(de,X),R.set(De,de),N.set(de,De);const Wp=[["MusicgenForConditionalGeneration",cc,k.Musicgen],["CLIPTextModelWithProjection",Oi,k.EncoderOnly],["SiglipTextModel",Ro,k.EncoderOnly],["ClapTextModelWithProjection",hf,k.EncoderOnly],["ClapAudioModelWithProjection",pf,k.EncoderOnly]];for(const[H,X,de]of Wp)A.set(H,de),R.set(X,H),N.set(H,X);class _c extends xr{}ft(_c,"MODEL_CLASS_MAPPINGS",zi.map(X=>X[0])),ft(_c,"BASE_IF_FAIL",!0);class yc extends xr{}ft(yc,"MODEL_CLASS_MAPPINGS",[Bp]);class Uf extends xr{}ft(Uf,"MODEL_CLASS_MAPPINGS",[Ef]);class sl extends xr{}ft(sl,"MODEL_CLASS_MAPPINGS",[mc]);class Wf extends xr{}ft(Wf,"MODEL_CLASS_MAPPINGS",[pc]);class Gf extends xr{}ft(Gf,"MODEL_CLASS_MAPPINGS",[kf]);class vc extends xr{}ft(vc,"MODEL_CLASS_MAPPINGS",[Sf]);class qf extends xr{}ft(qf,"MODEL_CLASS_MAPPINGS",[Cf]);class Hf extends xr{}ft(Hf,"MODEL_CLASS_MAPPINGS",[Pf]);class wc extends xr{}ft(wc,"MODEL_CLASS_MAPPINGS",[Af]);class Kf extends xr{}ft(Kf,"MODEL_CLASS_MAPPINGS",[gc]);class Xf extends xr{}ft(Xf,"MODEL_CLASS_MAPPINGS",[$f]);class Qf extends xr{}ft(Qf,"MODEL_CLASS_MAPPINGS",[Of]);class bc extends xr{}ft(bc,"MODEL_CLASS_MAPPINGS",[jp]);class Yf extends xr{}ft(Yf,"MODEL_CLASS_MAPPINGS",[If]);class Zf extends xr{}ft(Zf,"MODEL_CLASS_MAPPINGS",[Ff]);class xc extends xr{}ft(xc,"MODEL_CLASS_MAPPINGS",[Df]);class Jf extends xr{}ft(Jf,"MODEL_CLASS_MAPPINGS",[zf]);class Gp extends xr{}ft(Gp,"MODEL_CLASS_MAPPINGS",[Rf]);class eh extends xr{}ft(eh,"MODEL_CLASS_MAPPINGS",[Lf]);class th extends xr{}ft(th,"MODEL_CLASS_MAPPINGS",[Vp]);class nh extends xr{}ft(nh,"MODEL_CLASS_MAPPINGS",[o_]);class rh extends xr{}ft(rh,"MODEL_CLASS_MAPPINGS",[Bf]);class qp extends xr{}ft(qp,"MODEL_CLASS_MAPPINGS",[Nf]);class ih extends xr{}ft(ih,"MODEL_CLASS_MAPPINGS",[jf]);class sh extends xr{}ft(sh,"MODEL_CLASS_MAPPINGS",[Vf]);class oh extends xr{}ft(oh,"MODEL_CLASS_MAPPINGS",[Up]);class a_ extends xe{constructor({logits:X,past_key_values:de,encoder_outputs:De,decoder_attentions:kt=null,cross_attentions:At=null}){super(),this.logits=X,this.past_key_values=de,this.encoder_outputs=De,this.decoder_attentions=kt,this.cross_attentions=At}}class Jn extends xe{constructor({logits:X}){super(),this.logits=X}}class ah extends xe{constructor({logits:X,embeddings:de}){super(),this.logits=X,this.embeddings=de}}class hi extends xe{constructor({logits:X}){super(),this.logits=X}}class vi extends xe{constructor({logits:X}){super(),this.logits=X}}class Ri extends xe{constructor({start_logits:X,end_logits:de}){super(),this.start_logits=X,this.end_logits=de}}class Xo extends xe{constructor({logits:X}){super(),this.logits=X}}class Hp extends xe{constructor({logits:X,past_key_values:de}){super(),this.logits=X,this.past_key_values=de}}class lh extends xe{constructor({alphas:X}){super(),this.alphas=X}}class uh extends xe{constructor({waveform:X,spectrogram:de}){super(),this.waveform=X,this.spectrogram=de}}},"./src/models/whisper/common_whisper.js":(e,t,n)=>{n.r(t),n.d(t,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>a,whisper_language_to_code:()=>l});const i=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],o=new Map(i),a=new Map([...i.map(([d,c])=>[c,d]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function l(d){d=d.toLowerCase();let c=a.get(d);if(c===void 0)if(o.has(d))c=d;else{const v=d.length===2?o.keys():o.values();throw new Error(`Language "${d}" is not supported. Must be one of: ${JSON.stringify(v)}`)}return c}},"./src/models/whisper/generation_whisper.js":(e,t,n)=>{n.r(t),n.d(t,{WhisperGenerationConfig:()=>o});var i=n("./src/generation/configuration_utils.js");class o extends i.GenerationConfig{constructor(){super(...arguments);ft(this,"return_timestamps",null);ft(this,"return_token_timestamps",null);ft(this,"num_frames",null);ft(this,"alignment_heads",null);ft(this,"task",null);ft(this,"language",null);ft(this,"no_timestamps_token_id",null);ft(this,"prompt_ids",null);ft(this,"is_multilingual",null);ft(this,"lang_to_id",null);ft(this,"task_to_id",null);ft(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(e,t,n)=>{n.r(t),n.d(t,{TensorOpRegistry:()=>l});var i=n("./src/backends/onnx.js"),o=n("./src/utils/tensor.js");const a=async(d,c,p)=>{const v=await(0,i.createInferenceSession)(new Uint8Array(d),c);return async _=>{const T=Object.fromEntries(Object.entries(_).map(([I,C])=>[I,C.ort_tensor])),M=await v.run(T);return Array.isArray(p)?p.map(I=>new o.Tensor(M[I])):new o.Tensor(M[p])}};class l{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([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=a([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=a([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=a([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=a([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=a([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}}ft(l,"session_options",{})},"./src/pipelines.js":(e,t,n)=>{n.r(t),n.d(t,{AudioClassificationPipeline:()=>oe,AutomaticSpeechRecognitionPipeline:()=>G,DepthEstimationPipeline:()=>Ye,DocumentQuestionAnsweringPipeline:()=>ne,FeatureExtractionPipeline:()=>ve,FillMaskPipeline:()=>A,ImageClassificationPipeline:()=>gt,ImageFeatureExtractionPipeline:()=>Ne,ImageSegmentationPipeline:()=>Me,ImageToImagePipeline:()=>pt,ImageToTextPipeline:()=>Ce,ObjectDetectionPipeline:()=>fe,Pipeline:()=>C,QuestionAnsweringPipeline:()=>k,SummarizationPipeline:()=>R,Text2TextGenerationPipeline:()=>N,TextClassificationPipeline:()=>E,TextGenerationPipeline:()=>j,TextToAudioPipeline:()=>xe,TokenClassificationPipeline:()=>x,TranslationPipeline:()=>B,ZeroShotAudioClassificationPipeline:()=>Se,ZeroShotClassificationPipeline:()=>ae,ZeroShotImageClassificationPipeline:()=>te,ZeroShotObjectDetectionPipeline:()=>Ae,pipeline:()=>Et});var i=n("./src/tokenizers.js"),o=n("./src/models.js"),a=n("./src/processors.js"),l=n("./src/utils/generic.js"),d=n("./src/utils/core.js"),c=n("./src/utils/maths.js"),p=n("./src/utils/audio.js"),v=n("./src/utils/tensor.js"),_=n("./src/utils/image.js");async function T(je){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(Ie=>_.RawImage.read(Ie)))}async function M(je,Ie){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(rt=>typeof rt=="string"||rt instanceof URL?(0,p.read_audio)(rt,Ie):rt instanceof Float64Array?new Float32Array(rt):rt))}function I(je,Ie){Ie&&(je=je.map(Fe=>Fe|0));const[rt,dt,xt,z]=je;return{xmin:rt,ymin:dt,xmax:xt,ymax:z}}class C extends l.Callable{constructor({task:Ie,model:rt,tokenizer:dt=null,processor:xt=null}){super(),this.task=Ie,this.model=rt,this.tokenizer=dt,this.processor=xt}async dispose(){await this.model.dispose()}}class E extends C{constructor(Ie){super(Ie)}async _call(Ie,{top_k:rt=1}={}){const dt=this.tokenizer(Ie,{padding:!0,truncation:!0}),xt=await this.model(dt),z=this.model.config.problem_type==="multi_label_classification"?he=>he.sigmoid():he=>new v.Tensor("float32",(0,c.softmax)(he.data),he.dims),Fe=this.model.config.id2label,Re=[];for(const he of xt.logits){const ue=z(he),Ee=await(0,v.topk)(ue,rt),q=Ee[0].tolist(),V=Ee[1].tolist().map((me,ge)=>({label:Fe?Fe[me]:`LABEL_${me}`,score:q[ge]}));rt===1?Re.push(...V):Re.push(V)}return Array.isArray(Ie)||rt===1?Re:Re[0]}}class x extends C{constructor(Ie){super(Ie)}async _call(Ie,{ignore_labels:rt=["O"]}={}){const dt=Array.isArray(Ie),xt=this.tokenizer(dt?Ie:[Ie],{padding:!0,truncation:!0}),Fe=(await this.model(xt)).logits,Re=this.model.config.id2label,he=[];for(let ue=0;ueTt==this.tokenizer.sep_token_id);he[q].map((Tt,Nt)=>Tt==1&&(Nt===0||Nt>V&&ue.findIndex(jt=>jt==re[Nt])===-1));const me=z[q].tolist(),ge=Fe[q].tolist();for(let Tt=1;TtNt==re[Tt])!==-1)&&(me[Tt]=-1/0,ge[Tt]=-1/0);const $e=(0,c.softmax)(me).map((Tt,Nt)=>[Tt,Nt]),Ze=(0,c.softmax)(ge).map((Tt,Nt)=>[Tt,Nt]);$e[0][0]=0,Ze[0][0]=0;const Dt=(0,d.product)($e,Ze).filter(Tt=>Tt[0][1]<=Tt[1][1]).map(Tt=>[Tt[0][1],Tt[1][1],Tt[0][0]*Tt[1][0]]).sort((Tt,Nt)=>Nt[2]-Tt[2]);for(let Tt=0;Ttme==this.tokenizer.mask_token_id);if(ue===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ee=xt[Re][ue],q=await(0,v.topk)(new v.Tensor("float32",(0,c.softmax)(Ee.data),Ee.dims),rt),re=q[0].tolist(),V=q[1].tolist();z.push(V.map((me,ge)=>{const $e=he.slice();return $e[ue]=me,{score:re[ge],token:Number(me),token_str:this.tokenizer.model.vocab[me],sequence:this.tokenizer.decode($e,{skip_special_tokens:!0})}}))}return Array.isArray(Ie)?z:z[0]}}class N extends C{constructor(rt){super(rt);ft(this,"_key","generated_text")}async _call(rt,dt={}){Array.isArray(rt)||(rt=[rt]),this.model.config.prefix&&(rt=rt.map(ue=>this.model.config.prefix+ue));const xt=this.model.config.task_specific_params;xt&&xt[this.task]&&xt[this.task].prefix&&(rt=rt.map(ue=>xt[this.task].prefix+ue));const z=this.tokenizer,Fe={padding:!0,truncation:!0};let Re;this instanceof B&&"_build_translation_inputs"in z?Re=z._build_translation_inputs(rt,Fe,dt):Re=z(rt,Fe);const he=await this.model.generate({...Re,...dt});return z.batch_decode(he,{skip_special_tokens:!0}).map(ue=>({[this._key]:ue}))}}class R extends N{constructor(rt){super(rt);ft(this,"_key","summary_text")}}class B extends N{constructor(rt){super(rt);ft(this,"_key","translation_text")}}function W(je){return Array.isArray(je)&&je.every(Ie=>"role"in Ie&&"content"in Ie)}class j extends C{constructor(Ie){super(Ie)}async _call(Ie,rt={}){let dt=!1,xt=!1,z;if(typeof Ie=="string")z=Ie=[Ie];else if(Array.isArray(Ie)&&Ie.every(V=>typeof V=="string"))dt=!0,z=Ie;else{if(W(Ie))Ie=[Ie];else if(Array.isArray(Ie)&&Ie.every(W))dt=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");xt=!0,z=Ie.map(V=>this.tokenizer.apply_chat_template(V,{tokenize:!1,add_generation_prompt:!0}))}const Fe=rt.add_special_tokens??!1,Re=xt?!1:rt.return_full_text??!0;this.tokenizer.padding_side="left";const he=this.tokenizer(z,{add_special_tokens:Fe,padding:!0,truncation:!0}),ue=await this.model.generate({...he,...rt}),Ee=this.tokenizer.batch_decode(ue,{skip_special_tokens:!0});let q;!Re&&he.input_ids.dims.at(-1)>0&&(q=this.tokenizer.batch_decode(he.input_ids,{skip_special_tokens:!0}).map(V=>V.length));const re=Array.from({length:Ie.length},V=>[]);for(let V=0;V[rt.toLowerCase(),dt])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(Ie,rt,{hypothesis_template:dt="This example is {}.",multi_label:xt=!1}={}){const z=Array.isArray(Ie);z||(Ie=[Ie]),Array.isArray(rt)||(rt=[rt]);const Fe=rt.map(ue=>dt.replace("{}",ue)),Re=xt||rt.length===1,he=[];for(const ue of Ie){const Ee=[];for(const V of Fe){const me=this.tokenizer(ue,{text_pair:V,padding:!0,truncation:!0}),ge=await this.model(me);Re?Ee.push([ge.logits.data[this.contradiction_id],ge.logits.data[this.entailment_id]]):Ee.push(ge.logits.data[this.entailment_id])}const re=(Re?Ee.map(V=>(0,c.softmax)(V)[1]):(0,c.softmax)(Ee)).map((V,me)=>[V,me]).sort((V,me)=>me[0]-V[0]);he.push({sequence:ue,labels:re.map(V=>rt[V[1]]),scores:re.map(V=>V[0])})}return z?he:he[0]}}class ve extends C{constructor(Ie){super(Ie)}async _call(Ie,{pooling:rt="none",normalize:dt=!1,quantize:xt=!1,precision:z="binary"}={}){const Fe=this.tokenizer(Ie,{padding:!0,truncation:!0}),Re=await this.model(Fe);let he=Re.last_hidden_state??Re.logits??Re.token_embeddings;if(rt!=="none")if(rt==="mean")he=(0,v.mean_pooling)(he,Fe.attention_mask);else if(rt==="cls")he=he.slice(null,0);else throw Error(`Pooling method '${rt}' not supported.`);return dt&&(he=he.normalize(2,-1)),xt&&(he=(0,v.quantize_embeddings)(he,z)),he}}class Ne extends C{constructor(Ie){super(Ie)}async _call(Ie,{pool:rt=null}={}){const dt=await T(Ie),{pixel_values:xt}=await this.processor(dt),z=await this.model({pixel_values:xt});let Fe;if(rt){if(!("pooler_output"in z))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Fe=z.pooler_output}else Fe=z.last_hidden_state??z.logits??z.image_embeds;return Fe}}class oe extends C{constructor(Ie){super(Ie)}async _call(Ie,{top_k:rt=5}={}){const dt=this.processor.feature_extractor.config.sampling_rate,xt=await M(Ie,dt),z=this.model.config.id2label,Fe=[];for(const Re of xt){const he=await this.processor(Re),Ee=(await this.model(he)).logits[0],q=await(0,v.topk)(new v.Tensor("float32",(0,c.softmax)(Ee.data),Ee.dims),rt),re=q[0].tolist(),me=q[1].tolist().map((ge,$e)=>({label:z?z[ge]:`LABEL_${ge}`,score:re[$e]}));Fe.push(me)}return Array.isArray(Ie)?Fe:Fe[0]}}class Se extends C{constructor(Ie){super(Ie)}async _call(Ie,rt,{hypothesis_template:dt="This is a sound of {}."}={}){const xt=!Array.isArray(Ie);xt&&(Ie=[Ie]);const z=rt.map(Ee=>dt.replace("{}",Ee)),Fe=this.tokenizer(z,{padding:!0,truncation:!0}),Re=this.processor.feature_extractor.config.sampling_rate,he=await M(Ie,Re),ue=[];for(const Ee of he){const q=await this.processor(Ee),re=await this.model({...Fe,...q}),V=(0,c.softmax)(re.logits_per_audio.data);ue.push([...V].map((me,ge)=>({score:me,label:rt[ge]})))}return xt?ue[0]:ue}}class G extends C{constructor(Ie){super(Ie)}async _call(Ie,rt={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(Ie,rt);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(Ie,rt);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Ie,rt){rt.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),rt.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const dt=!Array.isArray(Ie);dt&&(Ie=[Ie]);const xt=this.processor.feature_extractor.config.sampling_rate,z=await M(Ie,xt),Fe=[];for(const Re of z){const he=await this.processor(Re),Ee=(await this.model(he)).logits[0],q=[];for(const V of Ee)q.push((0,c.max)(V.data)[1]);const re=this.tokenizer.decode(q);Fe.push({text:re})}return dt?Fe[0]:Fe}async _call_whisper(Ie,rt){const dt=rt.return_timestamps??!1,xt=rt.chunk_length_s??0,z=rt.force_full_sequences??!1;let Fe=rt.stride_length_s??null;const Re={...rt};dt==="word"&&(Re.return_token_timestamps=!0,Re.return_timestamps=!1);const he=!Array.isArray(Ie);he&&(Ie=[Ie]);const ue=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ee=this.processor.feature_extractor.config.hop_length,q=this.processor.feature_extractor.config.sampling_rate,re=await M(Ie,q),V=[];for(const me of re){let ge=[];if(xt>0){if(Fe===null)Fe=xt/6;else if(xt<=Fe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Dt=q*xt,Tt=q*Fe,Nt=Dt-2*Tt;let jt=0;for(;;){const ht=jt+Dt,_e=me.subarray(jt,ht),Be=await this.processor(_e),st=jt===0,Je=ht>=me.length;if(ge.push({stride:[_e.length,st?0:Tt,Je?0:Tt],input_features:Be.input_features,is_last:Je}),Je)break;jt+=Nt}}else ge=[{stride:[me.length,0,0],input_features:(await this.processor(me)).input_features,is_last:!0}];for(const Dt of ge){Re.num_frames=Math.floor(Dt.stride[0]/Ee);const Tt=await this.model.generate({inputs:Dt.input_features,...Re});dt==="word"?(Dt.tokens=Tt.sequences.tolist()[0],Dt.token_timestamps=Tt.token_timestamps.tolist()[0].map(Nt=>(0,c.round)(Nt,2))):Dt.tokens=Tt[0].tolist(),Dt.stride=Dt.stride.map(Nt=>Nt/q)}const[$e,Ze]=this.tokenizer._decode_asr(ge,{time_precision:ue,return_timestamps:dt,force_full_sequences:z});V.push({text:$e,...Ze})}return he?V[0]:V}}class Ce extends C{constructor(Ie){super(Ie)}async _call(Ie,rt={}){const dt=Array.isArray(Ie),xt=await T(Ie),{pixel_values:z}=await this.processor(xt),Fe=[];for(const Re of z){Re.dims=[1,...Re.dims];const he=await this.model.generate({inputs:Re,...rt}),ue=this.tokenizer.batch_decode(he,{skip_special_tokens:!0}).map(Ee=>({generated_text:Ee.trim()}));Fe.push(ue)}return dt?Fe:Fe[0]}}class gt extends C{constructor(Ie){super(Ie)}async _call(Ie,{top_k:rt=5}={}){const dt=await T(Ie),{pixel_values:xt}=await this.processor(dt),z=await this.model({pixel_values:xt}),Fe=this.model.config.id2label,Re=[];for(const he of z.logits){const ue=await(0,v.topk)(new v.Tensor("float32",(0,c.softmax)(he.data),he.dims),rt),Ee=ue[0].tolist(),re=ue[1].tolist().map((V,me)=>({label:Fe?Fe[V]:`LABEL_${V}`,score:Ee[me]}));Re.push(re)}return Array.isArray(Ie)?Re:Re[0]}}class Me extends C{constructor(Ie){super(Ie),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Ie,{threshold:rt=.5,mask_threshold:dt=.5,overlap_mask_area_threshold:xt=.8,label_ids_to_fuse:z=null,target_sizes:Fe=null,subtask:Re=null}={}){if(Array.isArray(Ie)&&Ie.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ue=await T(Ie),Ee=ue.map(Ze=>[Ze.height,Ze.width]),{pixel_values:q,pixel_mask:re}=await this.processor(ue),V=await this.model({pixel_values:q,pixel_mask:re});let me=null;if(Re!==null)me=this.subtasks_mapping[Re];else for(let[Ze,Dt]of Object.entries(this.subtasks_mapping))if(Dt in this.processor.feature_extractor){me=this.processor.feature_extractor[Dt].bind(this.processor.feature_extractor),Re=Ze;break}const ge=this.model.config.id2label,$e=[];if(Re==="panoptic"||Re==="instance"){const Ze=me(V,rt,dt,xt,z,Fe??Ee)[0],Dt=Ze.segmentation;for(const Tt of Ze.segments_info){const Nt=new Uint8ClampedArray(Dt.data.length);for(let ht=0;htdt.replace("{}",re)),Re=this.tokenizer(Fe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:he}=await this.processor(z),ue=await this.model({...Re,pixel_values:he}),Ee=this.model.config.model_type==="siglip"?re=>re.sigmoid().data:re=>(0,c.softmax)(re.data),q=[];for(const re of ue.logits_per_image){const me=[...Ee(re)].map((ge,$e)=>({score:ge,label:rt[$e]}));me.sort((ge,$e)=>$e.score-ge.score),q.push(me)}return xt?q:q[0]}}class fe extends C{constructor(Ie){super(Ie)}async _call(Ie,{threshold:rt=.9,percentage:dt=!1}={}){const xt=Array.isArray(Ie);if(xt&&Ie.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const z=await T(Ie),Fe=dt?null:z.map(V=>[V.height,V.width]),{pixel_values:Re,pixel_mask:he}=await this.processor(z),ue=await this.model({pixel_values:Re,pixel_mask:he}),Ee=this.processor.feature_extractor.post_process_object_detection(ue,rt,Fe),q=this.model.config.id2label,re=Ee.map(V=>V.boxes.map((me,ge)=>({score:V.scores[ge],label:q[V.classes[ge]],box:I(me,!dt)})));return xt?re:re[0]}}class Ae extends C{constructor(Ie){super(Ie)}async _call(Ie,rt,{threshold:dt=.1,top_k:xt=null,percentage:z=!1}={}){const Fe=Array.isArray(Ie),Re=await T(Ie),he=this.tokenizer(rt,{padding:!0,truncation:!0}),ue=await this.processor(Re),Ee=[];for(let q=0;q({score:$e.scores[Tt],label:rt[$e.classes[Tt]],box:I(Dt,!z)})).sort((Dt,Tt)=>Tt.score-Dt.score);xt!==null&&(Ze=Ze.slice(0,xt)),Ee.push(Ze)}return Fe?Ee:Ee[0]}}class ne extends C{constructor(Ie){super(Ie)}async _call(Ie,rt,dt={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class xe extends C{constructor(rt){super(rt);ft(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=rt.vocoder??null}async _call(rt,{speaker_embeddings:dt=null}={}){return this.processor?this._call_text_to_spectrogram(rt,{speaker_embeddings:dt}):this._call_text_to_waveform(rt)}async _call_text_to_waveform(rt){const dt=this.tokenizer(rt,{padding:!0,truncation:!0}),{waveform:xt}=await this.model(dt),z=this.model.config.sampling_rate;return{audio:xt.data,sampling_rate:z}}async _call_text_to_spectrogram(rt,{speaker_embeddings:dt}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof dt=="string"||dt instanceof URL)&&(dt=new Float32Array(await(await fetch(dt)).arrayBuffer())),dt instanceof Float32Array)dt=new v.Tensor("float32",dt,[1,dt.length]);else if(!(dt instanceof v.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:xt}=this.tokenizer(rt,{padding:!0,truncation:!0}),{waveform:z}=await this.model.generate_speech(xt,dt,{vocoder:this.vocoder}),Fe=this.processor.feature_extractor.config.sampling_rate;return{audio:z.data,sampling_rate:Fe}}}class pt extends C{constructor(Ie){super(Ie)}async _call(Ie){const rt=await T(Ie),dt=await this.processor(rt),xt=await this.model(dt),z=[];for(const Fe of xt.reconstruction){const Re=Fe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");z.push(_.RawImage.fromTensor(Re))}return z.length>1?z:z[0]}}class Ye extends C{constructor(Ie){super(Ie)}async _call(Ie){const rt=await T(Ie),dt=await this.processor(rt),{predicted_depth:xt}=await this.model(dt),z=[];for(let Fe=0;Fe1?z:z[0]}}const et=Object.freeze({"text-classification":{tokenizer:i.AutoTokenizer,pipeline:E,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:i.AutoTokenizer,pipeline:x,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:i.AutoTokenizer,pipeline:k,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:i.AutoTokenizer,pipeline:A,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:i.AutoTokenizer,pipeline:R,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:i.AutoTokenizer,pipeline:B,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:i.AutoTokenizer,pipeline:N,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:i.AutoTokenizer,pipeline:j,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:i.AutoTokenizer,pipeline:ae,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:oe,model:o.AutoModelForAudioClassification,processor:a.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:i.AutoTokenizer,pipeline:Se,model:o.AutoModel,processor:a.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:i.AutoTokenizer,pipeline:G,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:a.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:i.AutoTokenizer,pipeline:xe,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[a.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:i.AutoTokenizer,pipeline:Ce,model:o.AutoModelForVision2Seq,processor:a.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:gt,model:o.AutoModelForImageClassification,processor:a.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Me,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation],processor:a.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:i.AutoTokenizer,pipeline:te,model:o.AutoModel,processor:a.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:fe,model:o.AutoModelForObjectDetection,processor:a.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:i.AutoTokenizer,pipeline:Ae,model:o.AutoModelForZeroShotObjectDetection,processor:a.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:i.AutoTokenizer,pipeline:ne,model:o.AutoModelForDocumentQuestionAnswering,processor:a.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:pt,model:o.AutoModelForImageToImage,processor:a.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ye,model:o.AutoModelForDepthEstimation,processor:a.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:i.AutoTokenizer,pipeline:ve,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:a.AutoProcessor,pipeline:Ne,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ct=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Et(je,Ie=null,{progress_callback:rt=null,config:dt=null,cache_dir:xt=null,local_files_only:z=!1,revision:Fe="main",device:Re=null,dtype:he=null,model_file_name:ue=null,session_options:Ee={}}={}){je=ct[je]??je;const q=et[je.split("_",1)[0]];if(!q)throw Error(`Unsupported pipeline: ${je}. Must be one of [${Object.keys(et)}]`);Ie||(Ie=q.default.model,console.log(`No model specified. Using default model: "${Ie}".`));const re={progress_callback:rt,config:dt,cache_dir:xt,local_files_only:z,revision:Fe,device:Re,dtype:he,model_file_name:ue,session_options:Ee},V=new Map([["tokenizer",q.tokenizer],["model",q.model],["processor",q.processor]]),me=await Rt(V,Ie,re);me.task=je,(0,d.dispatchCallback)(rt,{status:"ready",task:je,model:Ie});const ge=q.pipeline;return new ge(me)}async function Rt(je,Ie,rt){const dt=Object.create(null),xt=[];for(let[z,Fe]of je.entries()){if(!Fe)continue;let Re;Array.isArray(Fe)?Re=new Promise(async(he,ue)=>{var q,re;let Ee;for(let V of Fe){if(V===null){he(null);return}try{he(await V.from_pretrained(Ie,rt));return}catch(me){if((q=me.message)!=null&&q.includes("Unsupported model type"))Ee=me;else if((re=me.message)!=null&&re.includes("Could not locate file"))Ee=me;else{ue(me);return}}}ue(Ee)}):Re=Fe.from_pretrained(Ie,rt),dt[z]=Re,xt.push(Re)}await Promise.all(xt);for(let[z,Fe]of Object.entries(dt))dt[z]=await Fe;return dt}},"./src/processors.js":(e,t,n)=>{n.r(t),n.d(t,{ASTFeatureExtractor:()=>he,AutoProcessor:()=>jt,BeitFeatureExtractor:()=>ct,BitImageProcessor:()=>R,CLIPFeatureExtractor:()=>W,CLIPImageProcessor:()=>j,ChineseCLIPFeatureExtractor:()=>ae,ClapFeatureExtractor:()=>ue,ConvNextFeatureExtractor:()=>Ne,ConvNextImageProcessor:()=>oe,DPTFeatureExtractor:()=>A,DPTImageProcessor:()=>N,DeiTFeatureExtractor:()=>et,DetrFeatureExtractor:()=>je,DonutFeatureExtractor:()=>Et,EfficientNetImageProcessor:()=>Ce,FeatureExtractor:()=>C,Florence2Processor:()=>Nt,GLPNFeatureExtractor:()=>B,ImageFeatureExtractor:()=>E,MobileNetV1FeatureExtractor:()=>gt,MobileNetV2FeatureExtractor:()=>Me,MobileNetV3FeatureExtractor:()=>te,MobileNetV4FeatureExtractor:()=>fe,MobileViTFeatureExtractor:()=>Ae,MobileViTImageProcessor:()=>ne,NougatImageProcessor:()=>Rt,OwlViTFeatureExtractor:()=>xe,OwlViTProcessor:()=>Tt,Owlv2ImageProcessor:()=>pt,Processor:()=>V,PyAnnoteFeatureExtractor:()=>Ee,PyAnnoteProcessor:()=>Ze,RTDetrImageProcessor:()=>Ye,SamImageProcessor:()=>rt,SamProcessor:()=>me,SapiensFeatureExtractor:()=>x,SeamlessM4TFeatureExtractor:()=>Re,SegformerFeatureExtractor:()=>k,SiglipImageProcessor:()=>ve,SpeechT5FeatureExtractor:()=>re,SpeechT5Processor:()=>Dt,Swin2SRImageProcessor:()=>dt,ViTFeatureExtractor:()=>Se,ViTImageProcessor:()=>G,VitMatteImageProcessor:()=>xt,Wav2Vec2FeatureExtractor:()=>Fe,Wav2Vec2ProcessorWithLM:()=>$e,WeSpeakerFeatureExtractor:()=>q,WhisperFeatureExtractor:()=>z,WhisperProcessor:()=>ge,YolosFeatureExtractor:()=>Ie});var i=n("./src/utils/generic.js"),o=n("./src/utils/core.js"),a=n("./src/utils/hub.js"),l=n("./src/utils/maths.js"),d=n("./src/utils/tensor.js");n("./src/utils/image.js");var c=n("./src/utils/audio.js");function p([ht,_e,Be,st]){return[ht-Be/2,_e-st/2,ht+Be/2,_e+st/2]}function v(ht,_e=.5,Be=null,st=!1){const Je=ht.logits,_t=ht.pred_boxes,[$t,Wt,ot]=Je.dims;if(Be!==null&&Be.length!==$t)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let nn=[];for(let Gt=0;Gt<$t;++Gt){let Mt=Be!==null?Be[Gt]:null,mn={boxes:[],classes:[],scores:[]},hn=Je[Gt],Sn=_t[Gt];for(let Tn=0;Tn_e&&En.push(zn)}else{let zn=(0,l.max)(yn.data)[1];if(zn===ot-1||($n=(0,l.softmax)(yn.data),$n[zn]<_e))continue;En.push(zn)}for(const zn of En){let kn=Sn[Tn].data;kn=p(kn),Mt!==null&&(kn=kn.map((Pt,Qt)=>Pt*Mt[(Qt+1)%2])),mn.boxes.push(kn),mn.classes.push(zn),mn.scores.push($n[zn])}}nn.push(mn)}return nn}function _(ht,_e=null){const Be=ht.logits,st=Be.dims[0];if(_e!==null&&_e.length!==st)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Je=[];for(let _t=0;_tMt[$n]&&(Mt[$n]=En[$n],mn[$n]=yn)}const hn=new Array(Wt.dims[0]),Sn=Gt.data;for(let yn=0;ynyn!==void 0);Je.push({segmentation:Gt,labels:Tn})}return Je}function T(ht,_e){var Be;if(!(ht instanceof Float32Array||ht instanceof Float64Array))throw new Error(`${_e} expects input to be a Float32Array or a Float64Array, but got ${((Be=ht==null?void 0:ht.constructor)==null?void 0:Be.name)??typeof ht} 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.`)}function M(ht,_e,Be=0,st=null){const Je=ht/_e;let _t=(0,l.bankers_round)(Je)*_e;return st!==null&&_t>st&&(_t=Math.floor(Je)*_e),_t_t?nn=Math.floor(_t*ot/Je):_t>Je&&(ot=Math.floor(Je*nn/_t)),await _e.resize(nn,ot,{resample:st}))}async crop_margin(_e,Be=200){const st=_e.clone().grayscale(),Je=(0,l.min)(st.data)[0],$t=(0,l.max)(st.data)[0]-Je;if($t===0)return _e;const Wt=Be/255;let ot=st.width,nn=st.height,Gt=0,Mt=0;const mn=st.data;for(let hn=0;hnthis.preprocess(_t)));return{pixel_values:(0,d.stack)(st.map(_t=>_t.pixel_values),0),original_sizes:st.map(_t=>_t.original_size),reshaped_input_sizes:st.map(_t=>_t.reshaped_input_size)}}}class x extends E{post_process_semantic_segmentation(..._e){return _(..._e)}}class k extends E{post_process_semantic_segmentation(..._e){return _(..._e)}}class A extends E{}class N extends A{}class R extends E{}class B extends E{}class W extends E{}class j extends W{}class ae extends E{}class ve extends E{}class Ne extends E{constructor(_e){super(_e),this.crop_pct=this.config.crop_pct??224/256}async resize(_e){var st;const Be=(st=this.size)==null?void 0:st.shortest_edge;if(Be===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(Be<384){const Je=Math.floor(Be/this.crop_pct),[_t,$t]=this.get_resize_output_image_size(_e,{shortest_edge:Je});_e=await _e.resize(_t,$t,{resample:this.resample}),_e=await _e.center_crop(Be,Be)}else _e=await _e.resize(Be,Be,{resample:this.resample});return _e}}class oe extends Ne{}class Se extends E{}class G extends E{}class Ce extends E{constructor(_e){super(_e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(Be=>Be*Be))}}class gt extends E{}class Me extends E{}class te extends E{}class fe extends E{}class Ae extends E{}class ne extends Ae{}class xe extends E{post_process_object_detection(..._e){return v(..._e)}}class pt extends xe{}class Ye extends E{post_process_object_detection(..._e){return v(..._e)}}class et extends E{}class ct extends E{}class Et extends E{pad_image(_e,Be,st,Je={}){const[_t,$t,Wt]=Be;let ot=this.image_mean;Array.isArray(this.image_mean)||(ot=new Array(Wt).fill(ot));let nn=this.image_std;Array.isArray(nn)||(nn=new Array(Wt).fill(ot));const Gt=ot.map((Mt,mn)=>-Mt/nn[mn]);return super.pad_image(_e,Be,st,{center:!0,constant_values:Gt,...Je})}}class Rt extends Et{}class je extends E{async _call(_e){const Be=await super._call(_e),st=[Be.pixel_values.dims[0],64,64],Je=new d.Tensor("int64",new BigInt64Array(st.reduce((_t,$t)=>_t*$t)).fill(1n),st);return{...Be,pixel_mask:Je}}post_process_object_detection(..._e){return v(..._e)}remove_low_and_no_objects(_e,Be,st,Je){let _t=[],$t=[],Wt=[];for(let ot=0;ot<_e.dims[0];++ot){let nn=_e[ot],Gt=Be[ot],Mt=(0,l.max)(nn.data)[1];if(Mt===Je)continue;let hn=(0,l.softmax)(nn.data)[Mt];hn>st&&(_t.push(Gt),$t.push(hn),Wt.push(Mt))}return[_t,$t,Wt]}check_segment_validity(_e,Be,st,Je=.5,_t=.8){let $t=[],Wt=0,ot=0;const nn=Be[st].data;for(let Mt=0;Mt<_e.length;++Mt)_e[Mt]===st&&($t.push(Mt),++Wt),nn[Mt]>=Je&&++ot;let Gt=Wt>0&&ot>0;return Gt&&(Gt=Wt/ot>_t),[Gt,$t]}compute_segments(_e,Be,st,Je,_t,$t=null,Wt=null){let[ot,nn]=Wt??_e[0].dims,Gt=new d.Tensor("int32",new Int32Array(ot*nn),[ot,nn]),Mt=[];if(Wt!==null)for(let yn=0;yn<_e.length;++yn)_e[yn]=(0,d.interpolate)(_e[yn],Wt,"bilinear",!1);let mn=new Int32Array(_e[0].data.length),hn=new Float32Array(_e[0].data.length);for(let yn=0;yn<_e.length;++yn){let En=Be[yn];const $n=_e[yn].data;for(let zn=0;zn<$n.length;++zn)$n[zn]*=En,$n[zn]>hn[zn]&&(mn[zn]=yn,hn[zn]=$n[zn])}let Sn=0;const Tn=Gt.data;for(let yn=0;ynJe!==Be.dims[_t]))throw Error(`The first ${st.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new d.Tensor("int64",_e.flat(1/0).map(BigInt),st)}async _call(_e,{input_points:Be=null,input_labels:st=null,input_boxes:Je=null}={}){const _t=await super._call(_e);if(Be&&(_t.input_points=this.reshape_input_points(Be,_t.original_sizes,_t.reshaped_input_sizes)),st){if(!_t.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");_t.input_labels=this.add_input_labels(st,_t.input_points)}return Je&&(_t.input_boxes=this.reshape_input_points(Je,_t.original_sizes,_t.reshaped_input_sizes,!0)),_t}async post_process_masks(_e,Be,st,{mask_threshold:Je=0,binarize:_t=!0,pad_size:$t=null}={}){const Wt=[];$t=$t??this.pad_size;const ot=[$t.height,$t.width];for(let nn=0;nnJe&&(Sn[Tn]=1);mn=new d.Tensor("bool",Sn,mn.dims)}Wt.push(mn)}return Wt}generate_crop_boxes(_e,Be,{crop_n_layers:st=0,overlap_ratio:Je=512/1500,points_per_crop:_t=32,crop_n_points_downscale_factor:$t=1}={}){}}class dt extends E{pad_image(_e,Be,st,Je={}){const[_t,$t,Wt]=Be;return super.pad_image(_e,Be,{width:$t+(st-$t%st)%st,height:_t+(st-_t%st)%st},{mode:"symmetric",center:!1,constant_values:-1,...Je})}}class xt extends E{async _call(_e,Be){Array.isArray(_e)||(_e=[_e]),Array.isArray(Be)||(Be=[Be]);const st=await Promise.all(_e.map($t=>this.preprocess($t))),Je=await Promise.all(Be.map($t=>this.preprocess($t,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,d.stack)(st.map(($t,Wt)=>(0,d.cat)([$t.pixel_values,Je[Wt].pixel_values],0)),0),original_sizes:st.map($t=>$t.original_size),reshaped_input_sizes:st.map($t=>$t.reshaped_input_size)}}}class z extends C{constructor(_e){var Be;super(_e),(Be=this.config).mel_filters??(Be.mel_filters=(0,c.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,c.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(_e){const Be=await(0,c.spectrogram)(_e,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),st=Be.data,Je=(0,l.max)(st)[0];for(let _t=0;_tthis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),Be=_e.slice(0,this.config.n_samples)):(Be=new Float32Array(this.config.n_samples),Be.set(_e)),{input_features:(await this._extract_fbank_features(Be)).unsqueeze_(0)}}}class Fe extends C{_zero_mean_unit_var_norm(_e){const st=_e.reduce((_t,$t)=>_t+$t,0)/_e.length,Je=_e.reduce((_t,$t)=>_t+($t-st)**2,0)/_e.length;return _e.map(_t=>(_t-st)/Math.sqrt(Je+1e-7))}async _call(_e){T(_e,"Wav2Vec2FeatureExtractor"),_e instanceof Float64Array&&(_e=new Float32Array(_e));let Be=_e;this.config.do_normalize&&(Be=this._zero_mean_unit_var_norm(Be));const st=[1,Be.length];return{input_values:new d.Tensor("float32",Be,st),attention_mask:new d.Tensor("int64",new BigInt64Array(Be.length).fill(1n),st)}}}class Re extends C{constructor(_e){super(_e);const Be=this.config.sampling_rate,st=(0,c.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(Be/2),Be,null,"kaldi",!0);for(let Je=0;Jest*32768),(0,c.spectrogram)(_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:Be,transpose:!0})}async _call(_e,{padding:Be=!0,pad_to_multiple_of:st=2,do_normalize_per_mel_bins:Je=!0,return_attention_mask:_t=!0}={}){T(_e,"SeamlessM4TFeatureExtractor");let $t=await this._extract_fbank_features(_e,this.config.max_length);if(Je){const[Sn,Tn]=$t.dims,yn=$t.data;for(let En=0;En0){const $n=new Float32Array(Tn*(Sn+En));$n.set(yn),$n.fill(this.config.padding_value,yn.length);const zn=Sn+En;$t=new d.Tensor($t.type,$n,[zn,Tn]),_t&&(Wt=new d.Tensor("int64",new BigInt64Array(zn),[1,zn]),Wt.data.fill(1n,0,Sn))}}const[ot,nn]=$t.dims,Gt=this.config.stride;if(ot%Gt!==0)throw new Error(`The number of frames (${ot}) must be a multiple of the stride (${Gt}).`);const mn=$t.view(1,Math.floor(ot/Gt),nn*Gt),hn={input_features:mn};if(_t){const Sn=mn.dims[1],Tn=new BigInt64Array(Sn);if(Wt){const yn=Wt.data;for(let En=1,$n=0;En0)if(st==="rand_trunc"){const Wt=Math.floor(Math.random()*($t+1));_e=_e.subarray(Wt,Wt+Be),_t=await this._extract_fbank_features(_e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${st}" not implemented`);else{if($t<0){let Wt=new Float64Array(Be);if(Wt.set(_e),Je==="repeat")for(let ot=_e.length;ot({id:ot,start:nn*st,end:Gt*st,confidence:Mt/(Gt-nn)})))}return Je}}class q extends C{constructor(_e){super(_e);const Be=this.config.sampling_rate,st=(0,c.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(Be/2),Be,null,"kaldi",!0);for(let Je=0;JeBe*32768),(0,c.spectrogram)(_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){T(_e,"WeSpeakerFeatureExtractor");const Be=(await this._extract_fbank_features(_e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const st=Be.mean(1).data,Je=Be.data,[_t,$t,Wt]=Be.dims;for(let ot=0;ot<_t;++ot){const nn=ot*$t*Wt,Gt=ot*Wt;for(let Mt=0;Mt<$t;++Mt){const mn=nn+Mt*Wt;for(let hn=0;hn/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(_e){typeof _e=="string"&&(_e=[_e]);const Be=[];for(const st of _e)if(this.task_prompts_without_inputs.has(st))Be.push(this.task_prompts_without_inputs.get(st));else{for(const[Je,_t]of this.task_prompts_with_input)if(st.includes(Je)){Be.push(_t.replaceAll("{input}",st).replaceAll(Je,""));break}Be.length!==_e.length&&Be.push(st)}return Be}post_process_generation(_e,Be,st){const Je=this.tasks_answer_post_processing_type.get(Be)??"pure_text";_e=_e.replaceAll("","").replaceAll("","");let _t;switch(Je){case"pure_text":_t=_e;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const $t=Je==="ocr"?"quad_boxes":"bboxes",Wt=_e.matchAll(this.regexes[$t]),ot=[],nn=[];for(const[Gt,Mt,...mn]of Wt)ot.push(Mt?Mt.trim():ot.at(-1)??""),nn.push(mn.map((hn,Sn)=>(Number(hn)+.5)/this.size_per_bin*st[Sn%2]));_t={labels:ot,[$t]:nn};break;default:throw new Error(`Task "${Be}" (of type "${Je}") not yet implemented.`)}return{[Be]:_t}}}class jt{static async from_pretrained(_e,{progress_callback:Be=null,config:st=null,cache_dir:Je=null,local_files_only:_t=!1,revision:$t="main"}={}){let Wt=st??await(0,a.getModelJSON)(_e,"preprocessor_config.json",!0,{progress_callback:Be,config:st,cache_dir:Je,local_files_only:_t,revision:$t}),ot=Wt.feature_extractor_type??Wt.image_processor_type,nn=this.FEATURE_EXTRACTOR_CLASS_MAPPING[ot];if(!nn)if(Wt.size!==void 0)console.warn(`Feature extractor type "${ot}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),nn=E;else throw new Error(`Unknown Feature Extractor type: ${ot}`);let Gt=this.PROCESSOR_CLASS_MAPPING[Wt.processor_class]??V,Mt=new nn(Wt);return new Gt(Mt)}}ft(jt,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:E,WhisperFeatureExtractor:z,ViTFeatureExtractor:Se,MobileViTFeatureExtractor:Ae,MobileViTImageProcessor:ne,MobileNetV1FeatureExtractor:gt,MobileNetV2FeatureExtractor:Me,MobileNetV3FeatureExtractor:te,MobileNetV4FeatureExtractor:fe,OwlViTFeatureExtractor:xe,Owlv2ImageProcessor:pt,CLIPFeatureExtractor:W,CLIPImageProcessor:j,Florence2Processor:Nt,ChineseCLIPFeatureExtractor:ae,SiglipImageProcessor:ve,ConvNextFeatureExtractor:Ne,ConvNextImageProcessor:oe,SegformerFeatureExtractor:k,SapiensFeatureExtractor:x,BitImageProcessor:R,DPTImageProcessor:N,DPTFeatureExtractor:A,GLPNFeatureExtractor:B,BeitFeatureExtractor:ct,DeiTFeatureExtractor:et,DetrFeatureExtractor:je,RTDetrImageProcessor:Ye,YolosFeatureExtractor:Ie,DonutFeatureExtractor:Et,NougatImageProcessor:Rt,EfficientNetImageProcessor:Ce,ViTImageProcessor:G,VitMatteImageProcessor:xt,SamImageProcessor:rt,Swin2SRImageProcessor:dt,Wav2Vec2FeatureExtractor:Fe,SeamlessM4TFeatureExtractor:Re,SpeechT5FeatureExtractor:re,ASTFeatureExtractor:he,ClapFeatureExtractor:ue,PyAnnoteFeatureExtractor:Ee,WeSpeakerFeatureExtractor:q}),ft(jt,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:ge,Wav2Vec2ProcessorWithLM:$e,PyAnnoteProcessor:Ze,SamProcessor:me,SpeechT5Processor:Dt,OwlViTProcessor:Tt,Florence2Processor:Nt})},"./src/tokenizers.js":(e,t,n)=>{n.r(t),n.d(t,{AlbertTokenizer:()=>hn,AutoTokenizer:()=>_i,BartTokenizer:()=>gr,BertTokenizer:()=>mn,BlenderbotSmallTokenizer:()=>br,BlenderbotTokenizer:()=>Ys,BloomTokenizer:()=>wr,CLIPTokenizer:()=>Pn,CamembertTokenizer:()=>Qt,CodeGenTokenizer:()=>Ts,CodeLlamaTokenizer:()=>fs,CohereTokenizer:()=>kr,ConvBertTokenizer:()=>zn,DebertaTokenizer:()=>yn,DebertaV2Tokenizer:()=>En,DistilBertTokenizer:()=>Pt,ElectraTokenizer:()=>Ar,EsmTokenizer:()=>ui,FalconTokenizer:()=>$r,GPT2Tokenizer:()=>xs,GPTNeoXTokenizer:()=>Ji,GemmaTokenizer:()=>es,Grok1Tokenizer:()=>Ai,HerbertTokenizer:()=>$n,LlamaTokenizer:()=>ds,M2M100Tokenizer:()=>$i,MBart50Tokenizer:()=>yr,MBartTokenizer:()=>Nr,MPNetTokenizer:()=>Xs,MarianTokenizer:()=>ho,MobileBertTokenizer:()=>Sn,NllbTokenizer:()=>ts,NougatTokenizer:()=>ps,PreTrainedTokenizer:()=>Mt,Qwen2Tokenizer:()=>Io,RoFormerTokenizer:()=>kn,RobertaTokenizer:()=>Pi,SiglipTokenizer:()=>Zn,SpeechT5Tokenizer:()=>Ms,SqueezeBertTokenizer:()=>Tn,T5Tokenizer:()=>Ci,TokenizerModel:()=>Ne,VitsTokenizer:()=>ms,Wav2Vec2CTCTokenizer:()=>po,WhisperTokenizer:()=>Qs,XLMRobertaTokenizer:()=>fo,XLMTokenizer:()=>dn,is_chinese_char:()=>N});var i=n("./src/utils/generic.js"),o=n("./src/utils/core.js"),a=n("./src/utils/hub.js"),l=n("./src/utils/maths.js"),d=n("./src/utils/tensor.js"),c=n("./src/utils/data-structures.js"),p=n("./node_modules/@huggingface/jinja/dist/index.js"),v=n("./src/models/whisper/common_whisper.js"),_=n("./src/utils/constants.js");async function T(it,K){const ye=await Promise.all([(0,a.getModelJSON)(it,"tokenizer.json",!0,K),(0,a.getModelJSON)(it,"tokenizer_config.json",!0,K)]);return K.legacy!==null&&(ye[1].legacy=K.legacy),ye}function M(it,K){const ye=[];let Oe=0;for(const Ve of it.matchAll(K)){const He=Ve[0];Oe0&&ye.push(He),Oe=Ve.index+He.length}return Oe=19968&&it<=40959||it>=13312&&it<=19903||it>=131072&&it<=173791||it>=173824&&it<=177983||it>=177984&&it<=178207||it>=178208&&it<=183983||it>=63744&&it<=64255||it>=194560&&it<=195103}function R(it,K,ye){const Oe=[];let Ve=0;for(;Vethis.tokens_to_ids.get(ye)??this.unk_token_id)}convert_ids_to_tokens(K){return K.map(ye=>this.vocab[ye]??this.unk_token)}}class oe extends Ne{constructor(K){super(K),this.tokens_to_ids=C(K.vocab),this.unk_token_id=this.tokens_to_ids.get(K.unk_token),this.unk_token=K.unk_token,this.max_input_chars_per_word=K.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[ye,Oe]of this.tokens_to_ids)this.vocab[Oe]=ye}encode(K){const ye=[];for(const Oe of K){const Ve=[...Oe];if(Ve.length>this.max_input_chars_per_word){ye.push(this.unk_token);continue}let He=!1,St=0;const Zt=[];for(;St0&&(fn=this.config.continuing_subword_prefix+fn),this.tokens_to_ids.has(fn)){Jt=fn;break}--Lt}if(Jt===null){He=!0;break}Zt.push(Jt),St=Lt}He?ye.push(this.unk_token):ye.push(...Zt)}return ye}}class Se extends Ne{constructor(K,ye){super(K);const Oe=K.vocab.length;this.vocab=new Array(Oe),this.scores=new Array(Oe);for(let Ve=0;Ve[Ve,He])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=ye.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,l.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new c.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(K){const ye=K.sentence,Oe=ye.length;let Ve=0;for(;Ve{const it=[...Array.from({length:94},(Ve,He)=>He+33),...Array.from({length:12},(Ve,He)=>He+161),...Array.from({length:82},(Ve,He)=>He+174)],K=it.slice();let ye=0;for(let Ve=0;Ve<256;++Ve)it.includes(Ve)||(it.push(Ve),K.push(256+ye),ye+=1);const Oe=K.map(Ve=>String.fromCharCode(Ve));return Object.fromEntries(it.map((Ve,He)=>[Ve,Oe[He]]))})(),Ce=(0,o.reverseDictionary)(G);class gt extends Ne{constructor(K){super(K),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=C(K.vocab),this.unk_token_id=this.tokens_to_ids.get(K.unk_token),this.unk_token=K.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ye,Oe]of this.tokens_to_ids)this.vocab[Oe]=ye;this.bpe_ranks=new Map(K.merges.map((ye,Oe)=>[ye,Oe])),this.merges=K.merges.map(ye=>ye.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=K.end_of_word_suffix,this.continuing_subword_suffix=K.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.cache=new Map}bpe(K){if(K.length===0)return[];const ye=this.cache.get(K);if(ye!==void 0)return ye;const Oe=Array.from(K);this.end_of_word_suffix&&(Oe[Oe.length-1]+=this.end_of_word_suffix);let Ve=[];if(Oe.length>1){const He=new c.PriorityQueue((Lt,Jt)=>Lt.score`<0x${St.toString(16).toUpperCase().padStart(2,"0")}>`)):ye.push(this.unk_token)}return ye}}class Me extends Ne{constructor(K,ye){super(K),this.tokens_to_ids=C(ye.target_lang?K.vocab[ye.target_lang]:K.vocab),this.bos_token=ye.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=ye.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=ye.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=ye.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[Oe,Ve]of this.tokens_to_ids)this.vocab[Ve]=Oe}encode(K){return K}}class te extends i.Callable{constructor(K){super(),this.config=K}static fromConfig(K){if(K===null)return null;switch(K.type){case"BertNormalizer":return new Rt(K);case"Precompiled":return new st(K);case"Sequence":return new Et(K);case"Replace":return new fe(K);case"NFC":return new Ae(K);case"NFKC":return new ne(K);case"NFKD":return new xe(K);case"Strip":return new pt(K);case"StripAccents":return new Ye(K);case"Lowercase":return new et(K);case"Prepend":return new ct(K);default:throw new Error(`Unknown Normalizer type: ${K.type}`)}}normalize(K){throw Error("normalize should be implemented in subclass.")}_call(K){return this.normalize(K)}}class fe extends te{normalize(K){const ye=I(this.config.pattern);return ye===null?K:K.replaceAll(ye,this.config.content)}}class Ae extends te{normalize(K){return K=K.normalize("NFC"),K}}class ne extends te{normalize(K){return K=K.normalize("NFKC"),K}}class xe extends te{normalize(K){return K=K.normalize("NFKD"),K}}class pt extends te{normalize(K){return this.config.strip_left&&this.config.strip_right?K=K.trim():(this.config.strip_left&&(K=K.trimStart()),this.config.strip_right&&(K=K.trimEnd())),K}}class Ye extends te{normalize(K){return K=k(K),K}}class et extends te{normalize(K){return K=K.toLowerCase(),K}}class ct extends te{normalize(K){return K=this.config.prepend+K,K}}class Et extends te{constructor(K){super(K),this.normalizers=K.normalizers.map(ye=>te.fromConfig(ye))}normalize(K){return this.normalizers.reduce((ye,Oe)=>Oe.normalize(ye),K)}}class Rt extends te{_tokenize_chinese_chars(K){const ye=[];for(let Oe=0;Oethis.pre_tokenize_text(Oe,ye)):this.pre_tokenize_text(K,ye)).flat()}_call(K,ye){return this.pre_tokenize(K,ye)}}class Ie extends je{constructor(K){super(),this.pattern=new RegExp(`[^\\s${W}]+|[${W}]`,"gu")}pre_tokenize_text(K,ye){return K.trim().match(this.pattern)||[]}}class rt extends je{constructor(K){super(),this.config=K,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,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=G,this.text_encoder=new TextEncoder}pre_tokenize_text(K,ye){return this.add_prefix_space&&!K.startsWith(" ")&&(K=" "+K),(this.use_regex?K.match(this.pattern)||[]:[K]).map(Ve=>Array.from(this.text_encoder.encode(Ve),He=>this.byte_encoder[He]).join(""))}}class dt extends je{constructor(K){super(),this.config=K,this.pattern=I(this.config.pattern,this.config.invert)}pre_tokenize_text(K,ye){return this.pattern===null?[]:this.config.invert?K.match(this.pattern)||[]:M(K,this.pattern)}}class xt extends je{constructor(K){super(),this.config=K,this.pattern=new RegExp(`[^${W}]+|[${W}]+`,"gu")}pre_tokenize_text(K,ye){return K.match(this.pattern)||[]}}class z extends je{constructor(K){super(),this.config=K;const ye=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(ye,"gu")}pre_tokenize_text(K,ye){return K.match(this.pattern)||[]}}class Fe extends i.Callable{constructor(K){super(),this.config=K}static fromConfig(K){if(K===null)return null;switch(K.type){case"TemplateProcessing":return new ue(K);case"ByteLevel":return new Ee(K);case"RobertaProcessing":return new he(K);case"BertProcessing":return new Re(K);case"Sequence":return new q(K);default:throw new Error(`Unknown PostProcessor type: ${K.type}`)}}post_process(K,...ye){throw Error("post_process should be implemented in subclass.")}_call(K,...ye){return this.post_process(K,...ye)}}class Re extends Fe{constructor(K){super(K),this.cls=K.cls[0],this.sep=K.sep[0]}post_process(K,ye=null,{add_special_tokens:Oe=!0}={}){Oe&&(K=(0,o.mergeArrays)([this.cls],K,[this.sep]));let Ve=new Array(K.length).fill(0);if(ye!==null){const He=Oe&&this instanceof he?[this.sep]:[],St=Oe?[this.sep]:[];K=(0,o.mergeArrays)(K,He,ye,St),Ve=(0,o.mergeArrays)(Ve,new Array(ye.length+He.length+St.length).fill(1))}return{tokens:K,token_type_ids:Ve}}}class he extends Re{}class ue extends Fe{constructor(K){super(K),this.single=K.single,this.pair=K.pair}post_process(K,ye=null,{add_special_tokens:Oe=!0}={}){const Ve=ye===null?this.single:this.pair;let He=[],St=[];for(const Zt of Ve)"SpecialToken"in Zt?Oe&&(He.push(Zt.SpecialToken.id),St.push(Zt.SpecialToken.type_id)):"Sequence"in Zt&&(Zt.Sequence.id==="A"?(He=(0,o.mergeArrays)(He,K),St=(0,o.mergeArrays)(St,new Array(K.length).fill(Zt.Sequence.type_id))):Zt.Sequence.id==="B"&&(He=(0,o.mergeArrays)(He,ye),St=(0,o.mergeArrays)(St,new Array(ye.length).fill(Zt.Sequence.type_id))));return{tokens:He,token_type_ids:St}}}class Ee extends Fe{post_process(K,ye=null){return ye&&(K=(0,o.mergeArrays)(K,ye)),{tokens:K}}}class q extends Fe{constructor(K){super(K),this.processors=K.processors.map(ye=>Fe.fromConfig(ye))}post_process(K,ye=null,Oe={}){let Ve;for(const He of this.processors)if(He instanceof Ee)K=He.post_process(K).tokens,ye&&(ye=He.post_process(ye).tokens);else{const St=He.post_process(K,ye,Oe);K=St.tokens,Ve=St.token_type_ids}return{tokens:K,token_type_ids:Ve}}}class re extends i.Callable{constructor(K){super(),this.config=K,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=K.trim_offsets}static fromConfig(K){if(K===null)return null;switch(K.type){case"WordPiece":return new Ze(K);case"Metaspace":return new Be(K);case"ByteLevel":return new Dt(K);case"Replace":return new V(K);case"ByteFallback":return new me(K);case"Fuse":return new ge(K);case"Strip":return new $e(K);case"Sequence":return new Nt(K);case"CTC":return new Tt(K);case"BPEDecoder":return new jt(K);default:throw new Error(`Unknown Decoder type: ${K.type}`)}}_call(K){return this.decode(K)}decode(K){return this.decode_chain(K).join("")}decode_chain(K){throw Error("`decode_chain` should be implemented in subclass.")}}class V extends re{decode_chain(K){const ye=I(this.config.pattern);return ye===null?K:K.map(Oe=>Oe.replaceAll(ye,this.config.content))}}class me extends re{constructor(K){super(K),this.text_decoder=new TextDecoder}decode_chain(K){const ye=[];let Oe=[];for(const Ve of K){let He=null;if(Ve.length===6&&Ve.startsWith("<0x")&&Ve.endsWith(">")){const St=parseInt(Ve.slice(3,5),16);isNaN(St)||(He=St)}if(He!==null)Oe.push(He);else{if(Oe.length>0){const St=this.text_decoder.decode(Uint8Array.from(Oe));ye.push(St),Oe=[]}ye.push(Ve)}}if(Oe.length>0){const Ve=this.text_decoder.decode(Uint8Array.from(Oe));ye.push(Ve),Oe=[]}return ye}}class ge extends re{decode_chain(K){return[K.join("")]}}class $e extends re{constructor(K){super(K),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(K){return K.map(ye=>{let Oe=0;for(let He=0;He(Oe!==0&&(ye.startsWith(this.config.prefix)?ye=ye.replace(this.config.prefix,""):ye=" "+ye),this.cleanup&&(ye=x(ye)),ye))}}class Dt extends re{constructor(K){super(K),this.byte_decoder=Ce,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(K){const ye=K.join(""),Oe=new Uint8Array([...ye].map(He=>this.byte_decoder[He]));return this.text_decoder.decode(Oe)}decode_chain(K){const ye=[];let Oe=[];for(const Ve of K)this.added_tokens.find(He=>He.content===Ve)!==void 0?(Oe.length>0&&(ye.push(this.convert_tokens_to_string(Oe)),Oe=[]),ye.push(Ve)):Oe.push(Ve);return Oe.length>0&&ye.push(this.convert_tokens_to_string(Oe)),ye}}class Tt extends re{constructor(K){super(K),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(K){if(K.length===0)return"";const ye=[K[0]];for(let He=1;HeHe!==this.pad_token).join("");return this.cleanup&&(Ve=x(Ve).replaceAll(this.word_delimiter_token," ").trim()),Ve}decode_chain(K){return[this.convert_tokens_to_string(K)]}}class Nt extends re{constructor(K){super(K),this.decoders=K.decoders.map(ye=>re.fromConfig(ye))}decode_chain(K){return this.decoders.reduce((ye,Oe)=>Oe.decode_chain(ye),K)}}class jt extends re{constructor(K){super(K),this.suffix=this.config.suffix}decode_chain(K){return K.map((ye,Oe)=>ye.replaceAll(this.suffix,Oe===K.length-1?"":" "))}}class ht extends re{decode_chain(K){let ye="";for(let Oe=1;OeOe.normalize("NFKC")).join("~"):K=K.normalize("NFKC"),K}}class Je extends je{constructor(K){super(),this.tokenizers=K.pretokenizers.map(ye=>je.fromConfig(ye))}pre_tokenize_text(K,ye){return this.tokenizers.reduce((Oe,Ve)=>Ve.pre_tokenize(Oe,ye),[K])}}class _t extends je{constructor(K){super()}pre_tokenize_text(K,ye){return K.match(/\w+|[^\w\s]+/g)||[]}}class $t extends je{constructor(K){super()}pre_tokenize_text(K,ye){return B(K)}}class Wt extends je{constructor(K){super(),this.config=K,this.pattern=I(this.config.pattern),this.content=this.config.content}pre_tokenize_text(K,ye){return this.pattern===null?[K]:[K.replaceAll(this.pattern,this.config.content)]}}const ot=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function nn(it,K,ye,Oe){for(const Ve of Object.keys(it)){const He=K-it[Ve].length,St=ye(Ve),Zt=new Array(He).fill(St);it[Ve]=Oe==="right"?(0,o.mergeArrays)(it[Ve],Zt):(0,o.mergeArrays)(Zt,it[Ve])}}function Gt(it,K){for(const ye of Object.keys(it))it[ye].length=K}class Mt extends i.Callable{constructor(ye,Oe){super();ft(this,"return_token_type_ids",!1);ft(this,"padding_side","right");this._tokenizer_config=Oe,this.normalizer=te.fromConfig(ye.normalizer),this.pre_tokenizer=je.fromConfig(ye.pre_tokenizer),this.model=Ne.fromConfig(ye.model,Oe),this.post_processor=Fe.fromConfig(ye.post_processor),this.decoder=re.fromConfig(ye.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Ve of ye.added_tokens){const He=new ve(Ve);this.added_tokens.push(He),this.model.tokens_to_ids.set(He.content,He.id),this.model.vocab[He.id]=He.content,He.special&&(this.special_tokens.push(He.content),this.all_special_ids.push(He.id))}if(this.additional_special_tokens=Oe.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.toSorted((Ve,He)=>He.content.length-Ve.content.length).map(Ve=>`${Ve.lstrip?"\\s*":""}(${(0,o.escapeRegExp)(Ve.content)})${Ve.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=Oe.model_max_length,this.remove_space=Oe.remove_space,this.clean_up_tokenization_spaces=Oe.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Oe.do_lowercase_and_remove_accent??!1,Oe.padding_side&&(this.padding_side=Oe.padding_side),this.legacy=!1,this.chat_template=Oe.chat_template??null,Array.isArray(this.chat_template)){const Ve=Object.create(null);for(const{name:He,template:St}of this.chat_template){if(typeof He!="string"||typeof St!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Ve[He]=St}this.chat_template=Ve}this._compiled_template_cache=new Map}getToken(...ye){for(const Oe of ye){const Ve=this._tokenizer_config[Oe];if(Ve)if(typeof Ve=="object"){if(Ve.__type==="AddedToken")return Ve.content;throw Error(`Unknown token: ${Ve}`)}else return Ve}return null}static async from_pretrained(ye,{progress_callback:Oe=null,config:Ve=null,cache_dir:He=null,local_files_only:St=!1,revision:Zt="main",legacy:Lt=null}={}){const Jt=await T(ye,{progress_callback:Oe,config:Ve,cache_dir:He,local_files_only:St,revision:Zt,legacy:Lt});return new this(...Jt)}_call(ye,{text_pair:Oe=null,add_special_tokens:Ve=!0,padding:He=!1,truncation:St=null,max_length:Zt=null,return_tensor:Lt=!0,return_token_type_ids:Jt=null}={}){const fn=Array.isArray(ye);let Rn;if(fn){if(ye.length===0)throw Error("text array must be non-empty");if(Oe!==null){if(Array.isArray(Oe)){if(ye.length!==Oe.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Rn=ye.map((On,bn)=>this._encode_plus(On,{text_pair:Oe[bn],add_special_tokens:Ve,return_token_type_ids:Jt}))}else Rn=ye.map(On=>this._encode_plus(On,{add_special_tokens:Ve,return_token_type_ids:Jt}))}else{if(ye==null)throw Error("text may not be null or undefined");if(Array.isArray(Oe))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Rn=[this._encode_plus(ye,{text_pair:Oe,add_special_tokens:Ve,return_token_type_ids:Jt})]}if(Zt===null?He==="max_length"?Zt=this.model_max_length:Zt=(0,l.max)(Rn.map(On=>On.input_ids.length))[0]:St||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),Zt=Math.min(Zt,this.model_max_length??1/0),He||St)for(let On=0;OnZt?St&&Gt(Rn[On],Zt):He&&nn(Rn[On],Zt,bn=>bn==="input_ids"?this.pad_token_id:0,this.padding_side));const Wn={};if(Lt){if(!(He&&St)&&Rn.some(bn=>{var Bn;for(const ci of Object.keys(bn))if(bn[ci].length!==((Bn=Rn[0][ci])==null?void 0:Bn.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 On=[Rn.length,Rn[0].input_ids.length];for(const bn of Object.keys(Rn[0]))Wn[bn]=new d.Tensor("int64",BigInt64Array.from(Rn.flatMap(Bn=>Bn[bn]).map(BigInt)),On)}else{for(const On of Object.keys(Rn[0]))Wn[On]=Rn.map(bn=>bn[On]);if(!fn)for(const On of Object.keys(Wn))Wn[On]=Wn[On][0]}return Wn}_encode_text(ye){return ye===null?null:(this.added_tokens_regex?ye.split(this.added_tokens_regex).filter(He=>He):[ye]).map((He,St)=>{if(this.added_tokens.find(Lt=>Lt.content===He)!==void 0)return He;{if(this.remove_space===!0&&(He=He.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(He=A(He)),this.normalizer!==null&&(He=this.normalizer(He)),He.length===0)return[];const Lt=this.pre_tokenizer!==null?this.pre_tokenizer(He,{section_index:St}):[He];return this.model(Lt)}}).flat()}_encode_plus(ye,{text_pair:Oe=null,add_special_tokens:Ve=!0,return_token_type_ids:He=null}={}){const{tokens:St,token_type_ids:Zt}=this._tokenize_helper(ye,{pair:Oe,add_special_tokens:Ve}),Lt=this.model.convert_tokens_to_ids(St),Jt={input_ids:Lt,attention_mask:new Array(Lt.length).fill(1)};return(He??this.return_token_type_ids)&&Zt&&(Jt.token_type_ids=Zt),Jt}_tokenize_helper(ye,{pair:Oe=null,add_special_tokens:Ve=!1}={}){const He=this._encode_text(ye),St=this._encode_text(Oe);return this.post_processor?this.post_processor(He,St,{add_special_tokens:Ve}):{tokens:(0,o.mergeArrays)(He??[],St??[])}}tokenize(ye,{pair:Oe=null,add_special_tokens:Ve=!1}={}){return this._tokenize_helper(ye,{pair:Oe,add_special_tokens:Ve}).tokens}encode(ye,{text_pair:Oe=null,add_special_tokens:Ve=!0,return_token_type_ids:He=null}={}){return this._encode_plus(ye,{text_pair:Oe,add_special_tokens:Ve,return_token_type_ids:He}).input_ids}batch_decode(ye,Oe={}){return ye instanceof d.Tensor&&(ye=ye.tolist()),ye.map(Ve=>this.decode(Ve,Oe))}decode(ye,Oe={}){if(ye instanceof d.Tensor&&(ye=E(ye)),!Array.isArray(ye)||ye.length===0||!(0,o.isIntegralNumber)(ye[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(ye,Oe)}decode_single(ye,{skip_special_tokens:Oe=!1,clean_up_tokenization_spaces:Ve=null}){let He=this.model.convert_ids_to_tokens(ye);Oe&&(He=He.filter(Zt=>!this.special_tokens.includes(Zt)));let St=this.decoder?this.decoder(He):He.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(St=St.replaceAll(this.decoder.end_of_word_suffix," "),Oe&&(St=St.trim())),(Ve??this.clean_up_tokenization_spaces)&&(St=x(St)),St}apply_chat_template(ye,{tools:Oe=null,documents:Ve=null,chat_template:He=null,add_generation_prompt:St=!1,tokenize:Zt=!0,padding:Lt=!1,truncation:Jt=!1,max_length:fn=null,return_tensor:Rn=!0,return_dict:Wn=!1,tokenizer_kwargs:On={},...bn}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const mt=this.chat_template;if(He!==null&&Object.hasOwn(mt,He))He=mt[He];else if(He===null&&"default"in mt)He=mt.default;else if(He===null)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(mt).sort()}.`)}else if(this.chat_template)He=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");if(typeof He!="string")throw Error(`chat_template must be a string, but got ${typeof He}`);let Bn=this._compiled_template_cache.get(He);Bn===void 0&&(Bn=new p.Template(He),this._compiled_template_cache.set(He,Bn));const ci=Object.create(null);for(const mt of ot){const jr=this.getToken(mt);jr&&(ci[mt]=jr)}const Qr=Bn.render({messages:ye,add_generation_prompt:St,tools:Oe,documents:Ve,...ci,...bn});if(Zt){const mt=this._call(Qr,{add_special_tokens:!1,padding:Lt,truncation:Jt,max_length:fn,return_tensor:Rn,...On});return Wn?mt:mt.input_ids}return Qr}}class mn extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class hn extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class Sn extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class Tn extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class yn extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class En extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class $n extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class zn extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class kn extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class Pt extends Mt{}class Qt extends Mt{}class dn extends Mt{constructor(ye,Oe){super(ye,Oe);ft(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Ar extends Mt{constructor(){super(...arguments);ft(this,"return_token_type_ids",!0)}}class Ci extends Mt{}class xs extends Mt{}class gr extends Mt{}class Nr extends Mt{constructor(K,ye){super(K,ye),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Oe=>this.languageRegex.test(Oe)),this.lang_to_token=Oe=>Oe}_build_translation_inputs(K,ye,Oe){return hs(this,K,ye,Oe)}}class yr extends Nr{}class Pi extends Mt{}class wr extends Mt{constructor(K,ye){var He,St;const Oe=".,!?…。,、।۔،",Ve=(St=(He=K.pre_tokenizer)==null?void 0:He.pretokenizers[0])==null?void 0:St.pattern;Ve&&Ve.Regex===` ?[^(\\s|[${Oe}])]+`&&(Ve.Regex=` ?[^\\s${Oe}]+`),super(K,ye)}}const gi="▁";class ds extends Mt{constructor(ye,Oe){super(ye,Oe);ft(this,"padding_side","left");this.legacy=Oe.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new _e({replacement:gi,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(ye){if(ye===null)return null;if(this.legacy||ye.length===0)return super._encode_text(ye);let Oe=super._encode_text(gi+ye.replaceAll(gi," "));return Oe.length>1&&Oe[0]===gi&&this.special_tokens.includes(Oe[1])&&(Oe=Oe.slice(1)),Oe}}class fs extends Mt{}class fo extends Mt{}class Xs extends Mt{}class $r extends Mt{}class Ji extends Mt{}class ui extends Mt{}class Io extends Mt{}class es extends Mt{}class Ai extends Mt{}function hs(it,K,ye,Oe){if(!("language_codes"in it)||!Array.isArray(it.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in it)||!(it.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in it)||typeof it.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const Ve=Oe.src_lang,He=Oe.tgt_lang;if(!it.language_codes.includes(He))throw new Error(`Target language code "${He}" is not valid. Must be one of: {${it.language_codes.join(", ")}}`);if(Ve!==void 0){if(!it.language_codes.includes(Ve))throw new Error(`Source language code "${Ve}" is not valid. Must be one of: {${it.language_codes.join(", ")}}`);for(const St of it.post_processor.config.single)if("SpecialToken"in St&&it.languageRegex.test(St.SpecialToken.id)){St.SpecialToken.id=it.lang_to_token(Ve);break}}return Oe.forced_bos_token_id=it.model.convert_tokens_to_ids([it.lang_to_token(He)])[0],it._call(K,ye)}class ts extends Mt{constructor(K,ye){super(K,ye),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Oe=>this.languageRegex.test(Oe)),this.lang_to_token=Oe=>Oe}_build_translation_inputs(K,ye,Oe){return hs(this,K,ye,Oe)}}class $i extends Mt{constructor(K,ye){super(K,ye),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Oe=>this.languageRegex.test(Oe)).map(Oe=>Oe.slice(2,-2)),this.lang_to_token=Oe=>`__${Oe}__`}_build_translation_inputs(K,ye,Oe){return hs(this,K,ye,Oe)}}class Qs extends Mt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(K,{return_timestamps:ye=!1,return_language:Oe=!1,time_precision:Ve=null,force_full_sequences:He=!0}={}){if(Ve===null)throw Error("Must specify time_precision");let St=null;const Zt=ye==="word";function Lt(){return{language:St,timestamp:[null,null],text:""}}const Jt=[];let fn=Lt(),Rn=0;const Wn=this.timestamp_begin;let On=[],bn=[],Bn=!1,ci=null;const Qr=new Set(this.all_special_ids);for(const tr of K){const Rr=tr.tokens,di=Zt?tr.token_timestamps:null;let Mn=null,Ii=Wn;if("stride"in tr){const[ur,sn,nr]=tr.stride;if(Rn-=sn,ci=ur-nr,sn&&(Ii=sn/Ve+Wn),nr)for(let _r=Rr.length-1;_r>=0;--_r){const Fr=Number(Rr[_r]);if(Fr>=Wn){if(Mn!==null&&(Fr-Wn)*Ve=Wn){const nr=(sn-Wn)*Ve+Rn,_r=(0,l.round)(nr,2);if(Mn!==null&&sn>=Mn)Bn=!0;else if(Bn||On.length>0&&sn0?(On.push(Ir),Zt&&bn.push(lr)):On.every(ur=>ur.length===0)&&(fn=Lt(),On=[],Ir=[],bn=[],lr=[])}if(On.length>0){if(He&&ye)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[tr,Rr]=this.findLongestCommonSequence(On,bn),di=this.decode(tr);fn.text=di,Zt&&(fn.words=this.collateWordTimestamps(tr,Rr,St)),Jt.push(fn)}let mt=Object.create(null);const jr=Jt.map(tr=>tr.text).join("");if(ye||Oe){for(let tr=0;tr0;let Zt=St?[]:null,Lt=St?ye[0]:null;for(let Jt=1;Jt_r===lr[Fr]&&Lt[Rr+Fr]<=ye[Jt][Ii+Fr]).length:ur=Mn.filter((_r,Fr)=>_r===lr[Fr]).length;const sn=tr/1e4,nr=ur/tr+sn;ur>1&&nr>Rn&&(Rn=nr,Wn=[Rr,di,Ii,Ir])}const[bn,Bn,ci,Qr]=Wn,mt=Math.floor((Bn+bn)/2),jr=Math.floor((Qr+ci)/2);He.push(...Oe.slice(0,mt)),Oe=fn.slice(jr),Ve=Oe.length,St&&(Zt.push(...Lt.slice(0,mt)),Lt=ye[Jt].slice(jr))}return He.push(...Oe),St?(Zt.push(...Lt),[He,Zt]):[He,[]]}collateWordTimestamps(K,ye,Oe){const[Ve,He,St]=this.combineTokensIntoWords(K,Oe),Zt=[];for(let Lt=0;Lt=Ve){const Zt=((St-Ve)*Oe).toFixed(2);He.push(`<|${Zt}|>`),He.push([])}else He[He.length-1].push(St);return He=He.map(St=>typeof St=="string"?St:super.decode(St,ye)),He.join("")}splitTokensOnUnicode(K){const ye=this.decode(K,{decode_with_timestamps:!0}),Oe="�",Ve=[],He=[],St=[];let Zt=[],Lt=[],Jt=0;for(let fn=0;fn=this.model.tokens_to_ids.get("<|endoftext|>"),bn=fn.startsWith(" "),Bn=fn.trim(),ci=Lt.test(Bn);if(On||bn||ci||He.length===0)He.push(fn),St.push(Rn),Zt.push(Wn);else{const Qr=He.length-1;He[Qr]+=fn,St[Qr].push(...Rn),Zt[Qr].push(...Wn)}}return[He,St,Zt]}mergePunctuations(K,ye,Oe,Ve,He){const St=structuredClone(K),Zt=structuredClone(ye),Lt=structuredClone(Oe);let Jt=St.length-2,fn=St.length-1;for(;Jt>=0;)St[Jt].startsWith(" ")&&Ve.includes(St[Jt].trim())?(St[fn]=St[Jt]+St[fn],Zt[fn]=(0,o.mergeArrays)(Zt[Jt],Zt[fn]),Lt[fn]=(0,o.mergeArrays)(Lt[Jt],Lt[fn]),St[Jt]="",Zt[Jt]=[],Lt[Jt]=[]):fn=Jt,--Jt;for(Jt=0,fn=1;fnRn),Zt.filter(Rn=>Rn.length>0),Lt.filter(Rn=>Rn.length>0)]}get_decoder_prompt_ids({language:K=null,task:ye=null,no_timestamps:Oe=!0}={}){const Ve=[];if(K){const He=(0,v.whisper_language_to_code)(K),St=this.model.tokens_to_ids.get(`<|${He}|>`);if(St===void 0)throw new Error(`Unable to find language "${He}" in model vocabulary. Please report this issue at ${_.GITHUB_ISSUE_URL}.`);Ve.push(St)}else Ve.push(null);if(ye){if(ye=ye.toLowerCase(),ye!=="transcribe"&&ye!=="translate")throw new Error(`Task "${ye}" is not supported. Must be one of: ["transcribe", "translate"]`);const He=this.model.tokens_to_ids.get(`<|${ye}|>`);if(He===void 0)throw new Error(`Unable to find task "${ye}" in model vocabulary. Please report this issue at ${_.GITHUB_ISSUE_URL}.`);Ve.push(He)}else Ve.push(null);if(Oe){const He=this.model.tokens_to_ids.get("<|notimestamps|>");if(He===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${_.GITHUB_ISSUE_URL}.`);Ve.push(He)}return Ve.map((He,St)=>[St+1,He]).filter(He=>He[1]!==null)}}class Ts extends Mt{}class Pn extends Mt{}class Zn extends Mt{}class ho extends Mt{constructor(K,ye){super(K,ye),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Oe=>this.languageRegex.test(Oe)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(K){if(K===null)return null;const[ye,...Oe]=K.trim().split(this.languageRegex);if(Oe.length===0)return super._encode_text(ye);if(Oe.length===2){const[Ve,He]=Oe;return this.supported_language_codes.includes(Ve)||console.warn(`Unsupported language code "${Ve}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([Ve],super._encode_text(He))}}}class po extends Mt{}class Ys extends Mt{}class br extends Mt{}class Ms extends Mt{}class ps extends Mt{}class ms extends Mt{constructor(K,ye){super(K,ye),this.decoder=new ht({})}}class kr extends Mt{}class _i{static async from_pretrained(K,{progress_callback:ye=null,config:Oe=null,cache_dir:Ve=null,local_files_only:He=!1,revision:St="main",legacy:Zt=null}={}){var Wn;const[Lt,Jt]=await T(K,{progress_callback:ye,config:Oe,cache_dir:Ve,local_files_only:He,revision:St,legacy:Zt}),fn=((Wn=Jt.tokenizer_class)==null?void 0:Wn.replace(/Fast$/,""))??"PreTrainedTokenizer";let Rn=this.TOKENIZER_CLASS_MAPPING[fn];return Rn||(console.warn(`Unknown tokenizer class "${fn}", attempting to construct from base class.`),Rn=Mt),new Rn(Lt,Jt)}}ft(_i,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Ci,DistilBertTokenizer:Pt,CamembertTokenizer:Qt,DebertaTokenizer:yn,DebertaV2Tokenizer:En,BertTokenizer:mn,HerbertTokenizer:$n,ConvBertTokenizer:zn,RoFormerTokenizer:kn,XLMTokenizer:dn,ElectraTokenizer:Ar,MobileBertTokenizer:Sn,SqueezeBertTokenizer:Tn,AlbertTokenizer:hn,GPT2Tokenizer:xs,BartTokenizer:gr,MBartTokenizer:Nr,MBart50Tokenizer:yr,RobertaTokenizer:Pi,WhisperTokenizer:Qs,CodeGenTokenizer:Ts,CLIPTokenizer:Pn,SiglipTokenizer:Zn,MarianTokenizer:ho,BloomTokenizer:wr,NllbTokenizer:ts,M2M100Tokenizer:$i,LlamaTokenizer:ds,CodeLlamaTokenizer:fs,XLMRobertaTokenizer:fo,MPNetTokenizer:Xs,FalconTokenizer:$r,GPTNeoXTokenizer:Ji,EsmTokenizer:ui,Wav2Vec2CTCTokenizer:po,BlenderbotTokenizer:Ys,BlenderbotSmallTokenizer:br,SpeechT5Tokenizer:Ms,NougatTokenizer:ps,VitsTokenizer:ms,Qwen2Tokenizer:Io,GemmaTokenizer:es,Grok1Tokenizer:Ai,CohereTokenizer:kr,PreTrainedTokenizer:Mt})},"./src/utils/audio.js":(e,t,n)=>{n.r(t),n.d(t,{hamming:()=>v,hanning:()=>p,mel_filter_bank:()=>x,read_audio:()=>d,spectrogram:()=>B,window_function:()=>W});var i=n("./src/utils/hub.js"),o=n("./src/utils/maths.js"),a=n("./src/utils/core.js"),l=n("./src/utils/tensor.js");async function d(j,ae){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 ve=await(await(0,i.getFile)(j)).arrayBuffer(),Ne=new AudioContext({sampleRate:ae});typeof ae>"u"&&console.warn(`No sampling rate provided, using default of ${Ne.sampleRate}Hz.`);const oe=await Ne.decodeAudioData(ve);let Se;if(oe.numberOfChannels===2){const G=Math.sqrt(2),Ce=oe.getChannelData(0),gt=oe.getChannelData(1);Se=new Float32Array(Ce.length);for(let Me=0;Me2595*Math.log10(1+j/700),kaldi:j=>1127*Math.log(1+j/700),slaney:(j,ae=1e3,ve=15,Ne=27/Math.log(6.4))=>j>=ae?ve+Math.log(j/ae)*Ne:3*j/200};function T(j,ae="htk"){const ve=_[ae];if(!ve)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?ve(j):j.map(Ne=>ve(Ne))}const M={htk:j=>700*(10**(j/2595)-1),kaldi:j=>700*(Math.exp(j/1127)-1),slaney:(j,ae=1e3,ve=15,Ne=Math.log(6.4)/27)=>j>=ve?ae*Math.exp(Ne*(j-ve)):200*j/3};function I(j,ae="htk"){const ve=M[ae];if(!ve)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?ve(j):j.map(Ne=>ve(Ne))}function C(j,ae){const ve=Float64Array.from({length:ae.length-1},(G,Ce)=>ae[Ce+1]-ae[Ce]),Ne=Array.from({length:j.length},()=>new Array(ae.length));for(let G=0;Gnew Array(j.length));for(let G=0;Gj+Ne*Se)}function x(j,ae,ve,Ne,oe,Se=null,G="htk",Ce=!1){if(Se!==null&&Se!=="slaney")throw new Error('norm must be one of null or "slaney"');const gt=T(ve,G),Me=T(Ne,G),te=E(gt,Me,ae+2);let fe=I(te,G),Ae;if(Ce){const xe=oe/(j*2);Ae=T(Float64Array.from({length:j},(pt,Ye)=>Ye*xe),G),fe=te}else Ae=E(0,Math.floor(oe/2),j);const ne=C(Ae,fe);if(Se!==null&&Se==="slaney")for(let xe=0;xeoe)throw Error(`frame_length (${ve}) may not be larger than fft_length (${oe})`);if(je!==ve)throw new Error(`Length of the window (${je}) must equal frame_length (${ve})`);if(Ne<=0)throw new Error("hop_length must be greater than zero");if(Se===null&&te!==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){if(Ce!=="reflect")throw new Error(`pad_mode="${Ce}" not implemented yet.`);const re=Math.floor((oe-1)/2)+1;j=k(j,re,re)}let Ie=Math.floor(1+Math.floor((j.length-ve)/Ne));et!==null&&IeIe?Et&&(xt=ct):xt=dt=ct);const z=new o.FFT(oe),Fe=new Float64Array(oe),Re=new Float64Array(z.outputBufferSize),he=new Float32Array(rt*xt);for(let re=0;re=1;--ge)Fe[ge]-=Me*Fe[ge-1];Fe[0]*=1-Me}for(let ge=0;geMath.pow(Ce,.85));break;default:throw new Error(`Unknown window type ${ae}.`)}if(ve&&(G=G.subarray(0,j)),Ne===null)return G;if(j>Ne)throw new Error(`Length of the window (${j}) may not be larger than frame_length (${Ne})`);return G}},"./src/utils/constants.js":(e,t,n)=>{n.r(t),n.d(t,{GITHUB_ISSUE_URL:()=>i});const i="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(e,t,n)=>{n.r(t),n.d(t,{calculateDimensions:()=>c,calculateReflectOffset:()=>T,dispatchCallback:()=>i,escapeRegExp:()=>a,isIntegralNumber:()=>d,isTypedArray:()=>l,mergeArrays:()=>v,pick:()=>M,pop:()=>p,product:()=>_,reverseDictionary:()=>o});function i(I,C){I&&I(C)}function o(I){return Object.fromEntries(Object.entries(I).map(([C,E])=>[E,C]))}function a(I){return I.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function l(I){var C,E,x;return((x=(E=(C=I==null?void 0:I.prototype)==null?void 0:C.__proto__)==null?void 0:E.constructor)==null?void 0:x.name)==="TypedArray"}function d(I){return Number.isInteger(I)||typeof I=="bigint"}function c(I){const C=[];let E=I;for(;Array.isArray(E);)C.push(E.length),E=E[0];return C}function p(I,C,E=void 0){const x=I[C];if(x!==void 0)return delete I[C],x;if(E===void 0)throw Error(`Key ${C} does not exist in object.`);return E}function v(...I){return Array.prototype.concat.apply([],I)}function _(...I){return I.reduce((C,E)=>C.flatMap(x=>E.map(k=>[x,k])))}function T(I,C){return Math.abs((I+C)%(2*C)-C)}function M(I,C){return Object.assign({},...C.map(E=>{if(I[E]!==void 0)return{[E]:I[E]}}))}},"./src/utils/data-structures.js":(e,t,n)=>{n.r(t),n.d(t,{CharTrie:()=>o,PriorityQueue:()=>i,TokenLattice:()=>l});class i{constructor(p=(_,T)=>_>T,v=1/0){this._heap=[],this._comparator=p,this._maxSize=v}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...p){return this.extend(p)}extend(p){for(const v of p)if(this.size0&&this._swap(0,v),this._heap.pop(),this._siftDown(),p}replace(p){const v=this.peek();return this._heap[0]=p,this._siftDown(),v}_parent(p){return(p+1>>>1)-1}_left(p){return(p<<1)+1}_right(p){return p+1<<1}_greater(p,v){return this._comparator(this._heap[p],this._heap[v])}_swap(p,v){const _=this._heap[p];this._heap[p]=this._heap[v],this._heap[v]=_}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(p){for(;p>0&&this._greater(p,this._parent(p));)this._swap(p,this._parent(p)),p=this._parent(p)}_siftDown(){let p=0;for(;this._left(p)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const T=new d(this.bosTokenId,0,0,0,0),M=new d(this.eosTokenId,1,this.len,0,0);this.nodes.push(T.clone()),this.nodes.push(M.clone()),this.beginNodes[this.len].push(M),this.endNodes[0].push(T)}insert(p,v,_,T){const M=this.nodes.length,I=new d(T,M,p,v,_);this.beginNodes[p].push(I),this.endNodes[p+v].push(I),this.nodes.push(I)}viterbi(){const p=this.len;let v=0;for(;v<=p;){if(this.beginNodes[v].length==0)return[];for(let C of this.beginNodes[v]){C.prev=null;let E=0,x=null;for(let k of this.endNodes[v]){const A=k.backtraceScore+C.score;(x===null||A>E)&&(x=k.clone(),E=A)}if(x!==null)C.prev=x,C.backtraceScore=E;else return[]}++v}const _=[],M=this.beginNodes[p][0].prev;if(M===null)return[];let I=M.clone();for(;I.prev!==null;)_.push(I.clone()),I=I.clone().prev.clone();return _.reverse(),_}piece(p){return this.sentence.slice(p.pos,p.pos+p.length)}tokens(){return this.viterbi().map(v=>this.piece(v))}tokenIds(){return this.viterbi().map(v=>v.tokenId)}}class d{constructor(p,v,_,T,M){this.tokenId=p,this.nodeId=v,this.pos=_,this.length=T,this.score=M,this.prev=null,this.backtraceScore=0}clone(){const p=new d(this.tokenId,this.nodeId,this.pos,this.length,this.score);return p.prev=this.prev,p.backtraceScore=this.backtraceScore,p}}},"./src/utils/devices.js":(e,t,n)=>{n.r(t),n.d(t,{DEVICE_TYPES:()=>i});const i=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,t,n)=>{n.r(t),n.d(t,{DATA_TYPES:()=>l,DEFAULT_DEVICE_DTYPE_MAPPING:()=>d,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>c,isWebGpuFp16Supported:()=>a});var i=n("./src/env.js"),o=n("./src/utils/devices.js");const a=function(){let p;return async function(){if(p===void 0)if(!i.apis.IS_WEBGPU_AVAILABLE)p=!1;else try{p=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{p=!1}return p}}(),l=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),d=Object.freeze({[o.DEVICE_TYPES.wasm]:l.q8}),c=Object.freeze({[l.fp32]:"",[l.fp16]:"_fp16",[l.int8]:"_int8",[l.uint8]:"_uint8",[l.q8]:"_quantized",[l.q4]:"_q4",[l.q4f16]:"_q4f16",[l.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,t,n)=>{n.r(t),n.d(t,{Callable:()=>i});const i=class{constructor(){let o=function(...a){return o._call(...a)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,t,n)=>{n.r(t),n.d(t,{getFile:()=>v,getModelFile:()=>C,getModelJSON:()=>E});var i=n("?7a2c"),o=n("?a42a"),a=n("./src/env.js"),l=n("./src/utils/core.js");const d={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"};class c{constructor(N){if(this.filePath=N,this.headers=new Headers,this.exists=i.existsSync(N),this.exists){this.status=200,this.statusText="OK";let R=i.statSync(N);this.headers.set("content-length",R.size.toString()),this.updateContentType();let B=this;this.body=new ReadableStream({start(W){B.arrayBuffer().then(j=>{W.enqueue(new Uint8Array(j)),W.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const N=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",d[N]??"application/octet-stream")}clone(){let N=new c(this.filePath);return N.exists=this.exists,N.status=this.status,N.statusText=this.statusText,N.headers=new Headers(this.headers),N}async arrayBuffer(){return(await i.promises.readFile(this.filePath)).buffer}async blob(){const N=await i.promises.readFile(this.filePath);return new Blob([N],{type:this.headers.get("content-type")})}async text(){return await i.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(A,N=null,R=null){let B;try{B=new URL(A)}catch{return!1}return!(N&&!N.includes(B.protocol)||R&&!R.includes(B.hostname))}async function v(A){var N;if(a.env.useFS&&!p(A,["http:","https:","blob:"]))return new c(A);if(typeof process<"u"&&((N=process==null?void 0:process.release)==null?void 0:N.name)==="node"){const R=!!(Ea!=null&&Ea.TESTING_REMOTELY),B=a.env.version,W=new Headers;if(W.set("User-Agent",`transformers.js/${B}; is_ci/${R};`),p(A,["http:","https:"],["huggingface.co","hf.co"])){const ae=(Ea==null?void 0:Ea.HF_TOKEN)??(Ea==null?void 0:Ea.HF_ACCESS_TOKEN);ae&&W.set("Authorization",`Bearer ${ae}`)}return fetch(A,{headers:W})}else return fetch(A)}const _={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"};function T(A,N,R){if(!R)return null;const B=_[A]??`Error (${A}) occurred while trying to load file`;throw Error(`${B}: "${N}".`)}class M{constructor(N){this.path=N}async match(N){let R=o.join(this.path,N),B=new c(R);if(B.exists)return B}async put(N,R){const B=Buffer.from(await R.arrayBuffer());let W=o.join(this.path,N);try{await i.promises.mkdir(o.dirname(W),{recursive:!0}),await i.promises.writeFile(W,B)}catch(j){console.warn("An error occurred while writing the file to cache:",j)}}}async function I(A,...N){for(let R of N)try{let B=await A.match(R);if(B)return B}catch{continue}}async function C(A,N,R=!0,B={}){if(!a.env.allowLocalModels){if(B.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(!a.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,l.dispatchCallback)(B.progress_callback,{status:"initiate",name:A,file:N});let W;if(!W&&a.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{W=await caches.open("transformers-cache")}catch(Ae){console.warn("An error occurred while opening the browser cache:",Ae)}}if(!W&&a.env.useFSCache&&(W=new M(B.cache_dir??a.env.cacheDir)),!W&&a.env.useCustomCache){if(!a.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!a.env.customCache.match||!a.env.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");W=a.env.customCache}const j=B.revision??"main";let ae=k(A,N),ve=k(a.env.localModelPath,ae),Ne=k(a.env.remoteHost,a.env.remotePathTemplate.replaceAll("{model}",A).replaceAll("{revision}",encodeURIComponent(j)),N),oe=j==="main"?ae:k(A,j,N),Se,G=W instanceof M?oe:Ne,Ce=!1,gt;W&&(gt=await I(W,ve,G));const Me=gt!==void 0;if(gt===void 0){if(a.env.allowLocalModels)if(p(ae,["http:","https:"])){if(B.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ae}.`);if(!a.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ae}.`)}else try{gt=await v(ve),Se=ve}catch(ne){console.warn(`Unable to load from local path "${ve}": "${ne}"`)}if(gt===void 0||gt.status===404){if(B.local_files_only||!a.env.allowRemoteModels){if(R)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ve}".`);return null}if(gt=await v(Ne),gt.status!==200)return T(gt.status,Ne,R);Se=G}Ce=W&&typeof Response<"u"&> instanceof Response&>.status===200}(0,l.dispatchCallback)(B.progress_callback,{status:"download",name:A,file:N});const te={status:"progress",name:A,file:N};let fe;return B.progress_callback?Me&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(fe=new Uint8Array(await gt.arrayBuffer()),(0,l.dispatchCallback)(B.progress_callback,{...te,progress:100,loaded:fe.length,total:fe.length})):fe=await x(gt,Ae=>{(0,l.dispatchCallback)(B.progress_callback,{...te,...Ae})}):fe=new Uint8Array(await gt.arrayBuffer()),Ce&&Se&&await W.match(Se)===void 0&&await W.put(Se,new Response(fe,{headers:gt.headers})).catch(Ae=>{console.warn(`Unable to add response to browser cache: ${Ae}.`)}),(0,l.dispatchCallback)(B.progress_callback,{status:"done",name:A,file:N}),fe}async function E(A,N,R=!0,B={}){let W=await C(A,N,R,B);if(W===null)return{};let ae=new TextDecoder("utf-8").decode(W);return JSON.parse(ae)}async function x(A,N){const R=A.headers.get("Content-Length");R===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let B=parseInt(R??"0"),W=new Uint8Array(B),j=0;const ae=A.body.getReader();async function ve(){const{done:Ne,value:oe}=await ae.read();if(Ne)return;let Se=j+oe.length;if(Se>B){B=Se;let Ce=new Uint8Array(B);Ce.set(W),W=Ce}W.set(oe,j),j=Se;const G=j/B*100;return N({progress:G,loaded:j,total:B}),ve()}return await ve(),W}function k(...A){return A=A.map((N,R)=>(R&&(N=N.replace(new RegExp("^/"),"")),R!==A.length-1&&(N=N.replace(new RegExp("/$"),"")),N)),A.join("/")}},"./src/utils/image.js":(e,t,n)=>{n.r(t),n.d(t,{RawImage:()=>I});var i=n("./src/utils/hub.js"),o=n("./src/env.js"),a=n("./src/utils/tensor.js"),l=n("?2b25");const d=typeof self<"u",c=d&&self.constructor.name==="DedicatedWorkerGlobalScope";let p,v,_;if(d)p=(C,E)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(C,E)},_=self.createImageBitmap,v=self.ImageData;else if(l)_=async C=>{const x=(await C.metadata()).channels,{data:k,info:A}=await C.rotate().raw().toBuffer({resolveWithObject:!0}),N=new I(new Uint8ClampedArray(k),A.width,A.height,A.channels);return x!==void 0&&x!==A.channels&&N.convert(x),N};else throw new Error("Unable to load image processing library.");const T={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},M=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class I{constructor(E,x,k,A){this.data=E,this.width=x,this.height=k,this.channels=A}get size(){return[this.width,this.height]}static async read(E){if(E instanceof I)return E;if(typeof E=="string"||E instanceof URL)return await this.fromURL(E);throw new Error(`Unsupported input type: ${typeof E}`)}static fromCanvas(E){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const k=E.getContext("2d").getImageData(0,0,E.width,E.height).data;return new I(k,E.width,E.height,4)}static async fromURL(E){const x=await(0,i.getFile)(E);if(x.status!==200)throw new Error(`Unable to read image from "${E}" (${x.status} ${x.statusText})`);const k=await x.blob();return this.fromBlob(k)}static async fromBlob(E){if(d){const x=await _(E),k=p(x.width,x.height).getContext("2d");return k.drawImage(x,0,0),new this(k.getImageData(0,0,x.width,x.height).data,x.width,x.height,4)}else{const x=l(await E.arrayBuffer());return await _(x)}}static fromTensor(E,x="CHW"){if(E.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${E.dims.length} dimensions.`);if(x==="CHW")E=E.transpose(1,2,0);else if(x!=="HWC")throw new Error(`Unsupported channel format: ${x}`);if(!(E.data instanceof Uint8ClampedArray||E.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${E.type}`);switch(E.dims[2]){case 1:case 2:case 3:case 4:return new I(E.data,E.dims[1],E.dims[0],E.dims[2]);default:throw new Error(`Unsupported number of channels: ${E.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const E=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let x=0,k=0;x=0?W=k:ae=-k,A>=0?j=A:ve=-A,B.drawImage(R,W,j,E,x,ae,ve,E,x),new I(B.getImageData(0,0,E,x).data,E,x,4).convert(N)}else{let N=this.toSharp();if(k>=0&&A>=0)N=N.extract({left:Math.floor(k),top:Math.floor(A),width:E,height:x});else if(k<=0&&A<=0){const R=Math.floor(-A),B=Math.floor(-k);N=N.extend({top:R,left:B,right:E-this.width-B,bottom:x-this.height-R})}else{let R=[0,0],B=0;A<0?(R[0]=Math.floor(-A),R[1]=x-this.height-R[0]):B=Math.floor(A);let W=[0,0],j=0;k<0?(W[0]=Math.floor(-k),W[1]=E-this.width-W[0]):j=Math.floor(k),N=N.extend({top:R[0],bottom:R[1],left:W[0],right:W[1]}).extract({left:j,top:B,width:E,height:x})}return await _(N)}}async toBlob(E="image/png",x=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:E,quality:x})}toTensor(E="CHW"){let x=new a.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(E!=="HWC")if(E==="CHW")x=x.permute(2,0,1);else throw new Error(`Unsupported channel format: ${E}`);return x}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const E=this.clone().rgba(),x=p(E.width,E.height),k=new v(E.data,E.width,E.height);return x.getContext("2d").putImageData(k,0,0),x}_update(E,x,k,A=null){return this.data=E,this.width=x,this.height=k,A!==null&&(this.channels=A),this}clone(){return new I(this.data.slice(),this.width,this.height,this.channels)}convert(E){if(this.channels===E)return this;switch(E){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(E){if(d){if(c)throw new Error("Unable to save an image from a Web Worker.");const x=E.split(".").pop().toLowerCase(),k=M.get(x)??"image/png",A=await this.toBlob(k),N=URL.createObjectURL(A),R=document.createElement("a");R.href=N,R.download=E,R.click(),R.remove()}else{if(o.env.useFS)return await this.toSharp().toFile(E);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)throw new Error("toSharp() is only supported in server-side environments.");return l(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(e,t,n)=>{n.r(t),n.d(t,{FFT:()=>C,bankers_round:()=>k,cos_sim:()=>c,dot:()=>d,dynamic_time_warping:()=>A,interpolate_data:()=>i,log_softmax:()=>l,magnitude:()=>p,max:()=>_,medianFilter:()=>E,min:()=>v,permute_data:()=>o,round:()=>x,softmax:()=>a});function i(N,[R,B,W],[j,ae],ve="bilinear",Ne=!1){const oe=ae/W,Se=j/B,G=new N.constructor(j*ae*R),Ce=B*W,gt=j*ae;for(let Me=0;Me=0;--Ne)j[Ne]=oe,W[Ne]=R[B[Ne]],oe*=W[Ne];const ae=B.map((Ne,oe)=>j[B.indexOf(oe)]),ve=new N.constructor(N.length);for(let Ne=0;Ne=0;--Se)oe+=G%R[Se]*ae[Se],G=Math.floor(G/R[Se]);ve[oe]=N[Ne]}return[ve,W]}function a(N){const R=_(N)[0],B=N.map(ae=>Math.exp(ae-R)),W=B.reduce((ae,ve)=>ae+ve,0);return B.map(ae=>ae/W)}function l(N){return a(N).map(W=>Math.log(W))}function d(N,R){let B=0;for(let W=0;WR+B*B,0))}function v(N){if(N.length===0)throw Error("Array must not be empty");let R=N[0],B=0;for(let W=1;WR&&(R=N[W],B=W);return[Number(R),B]}function T(N){return N>0&&(N&N-1)===0}class M{constructor(R){if(this.size=R|0,this.size<=1||!T(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=R<<1,this.table=new Float64Array(this.size*2);for(let W=0;WW;W<<=1)++B;this._width=B%2===0?B-1:B,this._bitrev=new Int32Array(1<>>j&3)<>>1);for(let j=0;j>>1]=R[j];return W}toComplexArray(R,B){const W=B||this.createComplexArray();for(let j=0;j>>1],W[j+1]=0;return W}transform(R,B){if(R===B)throw new Error("Input and output buffers must be different");this._transform4(R,B,1)}realTransform(R,B){if(R===B)throw new Error("Input and output buffers must be different");this._realTransform4(R,B,1)}inverseTransform(R,B){if(R===B)throw new Error("Input and output buffers must be different");this._transform4(R,B,-1);for(let W=0;W>=2;ve>=2;ve>>=2){Ne=j/ve<<1;const gt=Ne>>>2;for(oe=0;oe>>1,ve>>>1)}else for(oe=0,Se=0;oe>>1,ve>>>1,W)}const Ce=this.table;for(ve>>=2;ve>=2;ve>>=2){Ne=j/ve<<1;const Me=Ne>>>1,te=Me>>>1,fe=te>>>1;for(oe=0;oe>>1;for(let Me=2;Me>1;++G){const Ce=(G+1-R)**2/2,gt=Math.sqrt(oe**2+Se**2)**Ce,Me=Ce*Math.atan2(Se,oe),te=2*G;ae[te]=gt*Math.cos(Me),ae[te+1]=gt*Math.sin(Me),ve[te]=ae[te],ve[te+1]=-ae[te+1]}this._slicedChirpBuffer=ae.subarray(B,W),this._f=new M(j>>1),this._f.transform(this._chirpBuffer,ve)}_transform(R,B,W){const j=this._buffer1,ae=this._buffer2,ve=this._outBuffer1,Ne=this._outBuffer2,oe=this._chirpBuffer,Se=this._slicedChirpBuffer,G=this._a;if(W)for(let Ce=0;Ce>1,te=B[Me];j[Ce]=te*Se[Ce],j[gt]=te*Se[gt]}else for(let Ce=0;Ce=N.length&&(oe=2*(N.length-1)-oe),W[ve++]=N[oe]}W.sort(),B[ae]=W[j]}return B}function x(N,R){const B=Math.pow(10,R);return Math.round(N*B)/B}function k(N){const R=Math.round(N);return Math.abs(N)%1===.5?R%2===0?R:R-1:R}function A(N){const R=N.length,B=N[0].length,W=[R+1,B+1],j=Array.from({length:W[0]},()=>Array(W[1]).fill(1/0));j[0][0]=0;const ae=Array.from({length:W[0]},()=>Array(W[1]).fill(-1));for(let G=1;G0||Ne>0;)switch(oe.push(ve-1),Se.push(Ne-1),ae[ve][Ne]){case 0:--ve,--Ne;break;case 1:--ve;break;case 2:--Ne;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ve}, ${Ne}]. Please file a bug report.`)}return oe.reverse(),Se.reverse(),[oe,Se]}},"./src/utils/tensor.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>d,cat:()=>N,full:()=>ve,full_like:()=>Ne,interpolate:()=>v,interpolate_4d:()=>_,layer_norm:()=>E,matmul:()=>T,mean:()=>W,mean_pooling:()=>C,ones:()=>oe,ones_like:()=>Se,permute:()=>p,quantize_embeddings:()=>gt,rfft:()=>M,stack:()=>R,std_mean:()=>B,topk:()=>I,zeros:()=>G,zeros_like:()=>Ce});var i=n("./src/utils/maths.js"),o=n("./src/backends/onnx.js"),a=n("./src/ops/registry.js");const l=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class d{constructor(...te){ft(this,"ort_tensor");return(0,o.isONNXTensor)(te[0])?this.ort_tensor=te[0]:this.ort_tensor=new o.Tensor(te[0],te[1],te[2]),new Proxy(this,{get:(fe,Ae)=>{if(typeof Ae=="string"){let ne=Number(Ae);if(Number.isInteger(ne))return fe._getitem(ne)}return fe[Ae]},set:(fe,Ae,ne)=>fe[Ae]=ne})}get dims(){return this.ort_tensor.dims}set dims(te){this.ort_tensor.dims=te}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[te,...fe]=this.dims;if(fe.length>0){const Ae=fe.reduce((ne,xe)=>ne*xe);for(let ne=0;ne0){const ne=Ae.reduce((xe,pt)=>xe*pt);return this._subarray(te,ne,Ae)}else return new d(this.type,[this.data[te]],Ae)}indexOf(te){const fe=this.data;for(let Ae=0;Aeje)throw new Error(`Invalid slice: ${Et}`);const Ie=[Math.max(Rt,0),Math.min(je,this.dims[ct])];Ae.push(Ie),fe.push(Ie[1]-Ie[0])}else throw new Error(`Invalid slice: ${Et}`)}const ne=Ae.map(([ct,Et])=>Et-ct),xe=ne.reduce((ct,Et)=>ct*Et),pt=this.data,Ye=new pt.constructor(xe),et=this.stride();for(let ct=0;ct=0;--Rt){const Ie=ne[Rt];Et+=(je%Ie+Ae[Rt][0])*et[Rt],je=Math.floor(je/Ie)}Ye[ct]=pt[Et]}return new d(this.type,Ye,fe)}permute(...te){return p(this,te)}transpose(...te){return this.permute(...te)}sum(te=null,fe=!1){return this.norm(1,te,fe)}norm(te="fro",fe=null,Ae=!1){if(te==="fro")te=2;else if(typeof te=="string")throw Error(`Unsupported norm: ${te}`);const ne=this.data;if(fe===null){let Ye=ne.reduce((et,ct)=>et+ct**te,0)**(1/te);return new d(this.type,[Ye],[])}fe=A(fe,this.dims.length);const xe=this.dims.slice();xe[fe]=1;const pt=new ne.constructor(ne.length/this.dims[fe]);for(let Ye=0;Ye=0;--ct){const je=this.dims[ct];if(ct!==fe){const Ie=Et%je;et+=Ie*Rt,Rt*=xe[ct]}Et=Math.floor(Et/je)}pt[et]+=ne[Ye]**te}if(te!==1)for(let Ye=0;Ye=0;--et){const Rt=this.dims[et];if(et!==fe){const je=ct%Rt;Ye+=je*Et,Et*=this.dims[et]}ct=Math.floor(ct/Rt)}ne[pt]/=xe[Ye]}return this}normalize(te=2,fe=1){return this.clone().normalize_(te,fe)}stride(){return j(this.dims)}squeeze(te=null){return new d(this.type,this.data,x(this.dims,te))}squeeze_(te=null){return this.dims=x(this.dims,te),this}unsqueeze(te=null){return new d(this.type,this.data,k(this.dims,te))}unsqueeze_(te=null){return this.dims=k(this.dims,te),this}flatten_(te=0,fe=-1){fe=(fe+this.dims.length)%this.dims.length;let Ae=this.dims.slice(0,te),ne=this.dims.slice(te,fe+1),xe=this.dims.slice(fe+1);return this.dims=[...Ae,ne.reduce((pt,Ye)=>pt*Ye,1),...xe],this}flatten(te=0,fe=-1){return this.clone().flatten_(te,fe)}view(...te){let fe=-1;for(let ne=0;neYe!==fe?xe*pt:xe,1);te[fe]=Ae.length/ne}return new d(this.type,Ae,te)}neg_(){const te=this.data;for(let fe=0;fexe*pt);if(fe!==Ae)throw Error(`cannot reshape array of size ${fe} into shape (${te})`);let ne=Me;for(let xe=te.length-1;xe>=0;xe--)ne=ne.reduce((pt,Ye)=>{let et=pt[pt.length-1];return et.lengthfe!==1):typeof te=="number"?Me[te]===1&&Me.splice(te,1):Array.isArray(te)&&(Me=Me.filter((fe,Ae)=>fe!==1||!te.includes(Ae))),Me}function k(Me,te){return te=A(te,Me.length+1),Me=Me.slice(),Me.splice(te,0,1),Me}function A(Me,te,fe=null,Ae=!0){if(Ae&&(Me<-te||Me>=te))throw new Error(`IndexError: index ${Me} is out of bounds for dimension${fe===null?"":" "+fe} with size ${te}`);return Me<0&&(Me=(Me%te+te)%te),Me}function N(Me,te=0){te=A(te,Me[0].dims.length);const fe=Me[0].dims.slice();fe[te]=Me.reduce((pt,Ye)=>pt+Ye.dims[te],0);const Ae=fe.reduce((pt,Ye)=>pt*Ye,1),ne=new Me[0].data.constructor(Ae),xe=Me[0].type;if(te===0){let pt=0;for(const Ye of Me){const et=Ye.data;ne.set(et,pt),pt+=et.length}}else{let pt=0;for(let Ye=0;Ye=0;--je){const dt=ct[je];let xt=Ie%dt;je===te&&(xt+=pt),Rt+=xt*rt,rt*=fe[je],Ie=Math.floor(Ie/dt)}ne[Rt]=et[Et]}pt+=ct[te]}}return new d(xe,ne,fe)}function R(Me,te=0){return N(Me.map(fe=>fe.unsqueeze(te)),te)}function B(Me,te=null,fe=1,Ae=!1){const ne=Me.data,xe=Me.dims;if(te===null){const je=ne.reduce((xt,z)=>xt+z,0)/ne.length,Ie=Math.sqrt(ne.reduce((xt,z)=>xt+(z-je)**2,0)/(ne.length-fe)),rt=new d(Me.type,[je],[]);return[new d(Me.type,[Ie],[]),rt]}te=A(te,xe.length);const pt=W(Me,te,Ae),Ye=pt.data,et=xe.slice();et[te]=1;const ct=new ne.constructor(ne.length/xe[te]);for(let Rt=0;Rt=0;--Ie){const xt=xe[Ie];if(Ie!==te){const z=rt%xt;je+=z*dt,dt*=et[Ie]}rt=Math.floor(rt/xt)}ct[je]+=(ne[Rt]-Ye[je])**2}for(let Rt=0;Rtet+ct,0);return new d(Me.type,[Ye/Ae.length],[])}const ne=Me.dims;te=A(te,ne.length);const xe=ne.slice();xe[te]=1;const pt=new Ae.constructor(Ae.length/ne[te]);for(let Ye=0;Ye=0;--ct){const je=ne[ct];if(ct!==te){const Ie=Et%je;et+=Ie*Rt,Rt*=xe[ct]}Et=Math.floor(Et/je)}pt[et]+=Ae[Ye]}if(ne[te]!==1)for(let Ye=0;Ye=0;--fe)te[fe]=Ae,Ae*=Me[fe];return te}function ae(Me,te,fe,Ae){const ne=Me.reduce((xe,pt)=>xe*pt,1);return new d(fe,new Ae(ne).fill(te),Me)}function ve(Me,te){let fe,Ae;if(typeof te=="number")fe="float32",Ae=Float32Array;else if(typeof te=="bigint")fe="int64",Ae=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof te}`);return ae(Me,te,fe,Ae)}function Ne(Me,te){return ve(Me.dims,te)}function oe(Me){return ae(Me,1n,"int64",BigInt64Array)}function Se(Me){return oe(Me.dims)}function G(Me){return ae(Me,0n,"int64",BigInt64Array)}function Ce(Me){return G(Me.dims)}function gt(Me,te){if(Me.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(Me.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(te))throw new Error("The precision must be either 'binary' or 'ubinary'");const fe=te==="binary",Ae=fe?"int8":"uint8",ne=fe?Int8Array:Uint8Array,xe=Me.data,pt=new ne(xe.length/8);for(let Ye=0;Ye0?1:0,ct=Math.floor(Ye/8),Et=Ye%8;pt[ct]|=et<<7-Et,fe&&Et===0&&(pt[ct]-=128)}return new d(Ae,pt,[Me.dims[0],Me.dims[1]/8])}}},v2={};function Gr(e){var t=v2[e];if(t!==void 0)return t.exports;var n=v2[e]={exports:{}};return hS[e](n,n.exports,Gr),n.exports}Gr.m=hS;(()=>{var e=Object.getPrototypeOf?n=>Object.getPrototypeOf(n):n=>n.__proto__,t;Gr.t=function(n,i){if(i&1&&(n=this(n)),i&8||typeof n=="object"&&n&&(i&4&&n.__esModule||i&16&&typeof n.then=="function"))return n;var o=Object.create(null);Gr.r(o);var a={};t=t||[null,e({}),e([]),e(e)];for(var l=i&2&&n;typeof l=="object"&&!~t.indexOf(l);l=e(l))Object.getOwnPropertyNames(l).forEach(d=>a[d]=()=>n[d]);return a.default=()=>n,Gr.d(o,a),o}})();Gr.d=(e,t)=>{for(var n in t)Gr.o(t,n)&&!Gr.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})};Gr.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);Gr.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};(()=>{var e;if(typeof import.meta.url=="string"&&(e=import.meta.url),!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Gr.p=e})();Gr.b=new URL("./",import.meta.url);var D={};/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/Gr.r(D);Gr.d(D,{ASTFeatureExtractor:()=>Ln.ASTFeatureExtractor,ASTForAudioClassification:()=>ee.ASTForAudioClassification,ASTModel:()=>ee.ASTModel,ASTPreTrainedModel:()=>ee.ASTPreTrainedModel,AlbertForMaskedLM:()=>ee.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>ee.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>ee.AlbertForSequenceClassification,AlbertModel:()=>ee.AlbertModel,AlbertPreTrainedModel:()=>ee.AlbertPreTrainedModel,AlbertTokenizer:()=>qn.AlbertTokenizer,AudioClassificationPipeline:()=>Ur.AudioClassificationPipeline,AutoConfig:()=>yy.AutoConfig,AutoModel:()=>ee.AutoModel,AutoModelForAudioClassification:()=>ee.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>ee.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>ee.AutoModelForCTC,AutoModelForCausalLM:()=>ee.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>ee.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>ee.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>ee.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>ee.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>ee.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>ee.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>ee.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>ee.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>ee.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>ee.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>ee.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>ee.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>ee.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>ee.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>ee.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>ee.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>ee.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>ee.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>ee.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>ee.AutoModelForVision2Seq,AutoModelForXVector:()=>ee.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>ee.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Ln.AutoProcessor,AutoTokenizer:()=>qn.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>Ur.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>ee.BartForConditionalGeneration,BartForSequenceClassification:()=>ee.BartForSequenceClassification,BartModel:()=>ee.BartModel,BartPretrainedModel:()=>ee.BartPretrainedModel,BartTokenizer:()=>qn.BartTokenizer,BaseModelOutput:()=>ee.BaseModelOutput,BaseStreamer:()=>vy.BaseStreamer,BeitFeatureExtractor:()=>Ln.BeitFeatureExtractor,BeitForImageClassification:()=>ee.BeitForImageClassification,BeitModel:()=>ee.BeitModel,BeitPreTrainedModel:()=>ee.BeitPreTrainedModel,BertForMaskedLM:()=>ee.BertForMaskedLM,BertForQuestionAnswering:()=>ee.BertForQuestionAnswering,BertForSequenceClassification:()=>ee.BertForSequenceClassification,BertForTokenClassification:()=>ee.BertForTokenClassification,BertModel:()=>ee.BertModel,BertPreTrainedModel:()=>ee.BertPreTrainedModel,BertTokenizer:()=>qn.BertTokenizer,BitImageProcessor:()=>Ln.BitImageProcessor,BlenderbotForConditionalGeneration:()=>ee.BlenderbotForConditionalGeneration,BlenderbotModel:()=>ee.BlenderbotModel,BlenderbotPreTrainedModel:()=>ee.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>ee.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>ee.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>ee.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>qn.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>qn.BlenderbotTokenizer,BloomForCausalLM:()=>ee.BloomForCausalLM,BloomModel:()=>ee.BloomModel,BloomPreTrainedModel:()=>ee.BloomPreTrainedModel,BloomTokenizer:()=>qn.BloomTokenizer,CLIPFeatureExtractor:()=>Ln.CLIPFeatureExtractor,CLIPImageProcessor:()=>Ln.CLIPImageProcessor,CLIPModel:()=>ee.CLIPModel,CLIPPreTrainedModel:()=>ee.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>ee.CLIPSegForImageSegmentation,CLIPSegModel:()=>ee.CLIPSegModel,CLIPSegPreTrainedModel:()=>ee.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>ee.CLIPTextModelWithProjection,CLIPTokenizer:()=>qn.CLIPTokenizer,CLIPVisionModelWithProjection:()=>ee.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>ee.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>ee.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>ee.CamembertForSequenceClassification,CamembertForTokenClassification:()=>ee.CamembertForTokenClassification,CamembertModel:()=>ee.CamembertModel,CamembertPreTrainedModel:()=>ee.CamembertPreTrainedModel,CamembertTokenizer:()=>qn.CamembertTokenizer,CausalLMOutput:()=>ee.CausalLMOutput,CausalLMOutputWithPast:()=>ee.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Ln.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>ee.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>ee.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>ee.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Ln.ClapFeatureExtractor,ClapModel:()=>ee.ClapModel,ClapPreTrainedModel:()=>ee.ClapPreTrainedModel,ClapTextModelWithProjection:()=>ee.ClapTextModelWithProjection,CodeGenForCausalLM:()=>ee.CodeGenForCausalLM,CodeGenModel:()=>ee.CodeGenModel,CodeGenPreTrainedModel:()=>ee.CodeGenPreTrainedModel,CodeGenTokenizer:()=>qn.CodeGenTokenizer,CodeLlamaTokenizer:()=>qn.CodeLlamaTokenizer,CohereForCausalLM:()=>ee.CohereForCausalLM,CohereModel:()=>ee.CohereModel,CoherePreTrainedModel:()=>ee.CoherePreTrainedModel,CohereTokenizer:()=>qn.CohereTokenizer,ConvBertForMaskedLM:()=>ee.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>ee.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>ee.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>ee.ConvBertForTokenClassification,ConvBertModel:()=>ee.ConvBertModel,ConvBertPreTrainedModel:()=>ee.ConvBertPreTrainedModel,ConvBertTokenizer:()=>qn.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Ln.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>ee.ConvNextForImageClassification,ConvNextImageProcessor:()=>Ln.ConvNextImageProcessor,ConvNextModel:()=>ee.ConvNextModel,ConvNextPreTrainedModel:()=>ee.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>ee.ConvNextV2ForImageClassification,ConvNextV2Model:()=>ee.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>ee.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Ln.DPTFeatureExtractor,DPTForDepthEstimation:()=>ee.DPTForDepthEstimation,DPTImageProcessor:()=>Ln.DPTImageProcessor,DPTModel:()=>ee.DPTModel,DPTPreTrainedModel:()=>ee.DPTPreTrainedModel,DebertaForMaskedLM:()=>ee.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>ee.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>ee.DebertaForSequenceClassification,DebertaForTokenClassification:()=>ee.DebertaForTokenClassification,DebertaModel:()=>ee.DebertaModel,DebertaPreTrainedModel:()=>ee.DebertaPreTrainedModel,DebertaTokenizer:()=>qn.DebertaTokenizer,DebertaV2ForMaskedLM:()=>ee.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>ee.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>ee.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>ee.DebertaV2ForTokenClassification,DebertaV2Model:()=>ee.DebertaV2Model,DebertaV2PreTrainedModel:()=>ee.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>qn.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>Ln.DeiTFeatureExtractor,DeiTForImageClassification:()=>ee.DeiTForImageClassification,DeiTModel:()=>ee.DeiTModel,DeiTPreTrainedModel:()=>ee.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>ee.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>ee.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>Ur.DepthEstimationPipeline,DetrFeatureExtractor:()=>Ln.DetrFeatureExtractor,DetrForObjectDetection:()=>ee.DetrForObjectDetection,DetrForSegmentation:()=>ee.DetrForSegmentation,DetrModel:()=>ee.DetrModel,DetrObjectDetectionOutput:()=>ee.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>ee.DetrPreTrainedModel,DetrSegmentationOutput:()=>ee.DetrSegmentationOutput,Dinov2ForImageClassification:()=>ee.Dinov2ForImageClassification,Dinov2Model:()=>ee.Dinov2Model,Dinov2PreTrainedModel:()=>ee.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>ee.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>ee.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>ee.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>ee.DistilBertForTokenClassification,DistilBertModel:()=>ee.DistilBertModel,DistilBertPreTrainedModel:()=>ee.DistilBertPreTrainedModel,DistilBertTokenizer:()=>qn.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>Ur.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Ln.DonutFeatureExtractor,DonutSwinModel:()=>ee.DonutSwinModel,DonutSwinPreTrainedModel:()=>ee.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>ee.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Ln.EfficientNetImageProcessor,EfficientNetModel:()=>ee.EfficientNetModel,EfficientNetPreTrainedModel:()=>ee.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>ee.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>ee.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>ee.ElectraForSequenceClassification,ElectraForTokenClassification:()=>ee.ElectraForTokenClassification,ElectraModel:()=>ee.ElectraModel,ElectraPreTrainedModel:()=>ee.ElectraPreTrainedModel,ElectraTokenizer:()=>qn.ElectraTokenizer,EosTokenCriteria:()=>Mh.EosTokenCriteria,EsmForMaskedLM:()=>ee.EsmForMaskedLM,EsmForSequenceClassification:()=>ee.EsmForSequenceClassification,EsmForTokenClassification:()=>ee.EsmForTokenClassification,EsmModel:()=>ee.EsmModel,EsmPreTrainedModel:()=>ee.EsmPreTrainedModel,EsmTokenizer:()=>qn.EsmTokenizer,FFT:()=>Ps.FFT,FalconForCausalLM:()=>ee.FalconForCausalLM,FalconModel:()=>ee.FalconModel,FalconPreTrainedModel:()=>ee.FalconPreTrainedModel,FalconTokenizer:()=>qn.FalconTokenizer,FastViTForImageClassification:()=>ee.FastViTForImageClassification,FastViTModel:()=>ee.FastViTModel,FastViTPreTrainedModel:()=>ee.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>Ur.FeatureExtractionPipeline,FeatureExtractor:()=>Ln.FeatureExtractor,FillMaskPipeline:()=>Ur.FillMaskPipeline,Florence2ForConditionalGeneration:()=>ee.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>ee.Florence2PreTrainedModel,Florence2Processor:()=>Ln.Florence2Processor,GLPNFeatureExtractor:()=>Ln.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>ee.GLPNForDepthEstimation,GLPNModel:()=>ee.GLPNModel,GLPNPreTrainedModel:()=>ee.GLPNPreTrainedModel,GPT2LMHeadModel:()=>ee.GPT2LMHeadModel,GPT2Model:()=>ee.GPT2Model,GPT2PreTrainedModel:()=>ee.GPT2PreTrainedModel,GPT2Tokenizer:()=>qn.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>ee.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>ee.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>ee.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>ee.GPTJForCausalLM,GPTJModel:()=>ee.GPTJModel,GPTJPreTrainedModel:()=>ee.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>ee.GPTNeoForCausalLM,GPTNeoModel:()=>ee.GPTNeoModel,GPTNeoPreTrainedModel:()=>ee.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>ee.GPTNeoXForCausalLM,GPTNeoXModel:()=>ee.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>ee.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>qn.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>ee.Gemma2ForCausalLM,Gemma2Model:()=>ee.Gemma2Model,Gemma2PreTrainedModel:()=>ee.Gemma2PreTrainedModel,GemmaForCausalLM:()=>ee.GemmaForCausalLM,GemmaModel:()=>ee.GemmaModel,GemmaPreTrainedModel:()=>ee.GemmaPreTrainedModel,GemmaTokenizer:()=>qn.GemmaTokenizer,Grok1Tokenizer:()=>qn.Grok1Tokenizer,HerbertTokenizer:()=>qn.HerbertTokenizer,HubertForCTC:()=>ee.HubertForCTC,HubertForSequenceClassification:()=>ee.HubertForSequenceClassification,HubertModel:()=>ee.HubertModel,HubertPreTrainedModel:()=>ee.HubertPreTrainedModel,ImageClassificationPipeline:()=>Ur.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>Ur.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Ln.ImageFeatureExtractor,ImageMattingOutput:()=>ee.ImageMattingOutput,ImageSegmentationPipeline:()=>Ur.ImageSegmentationPipeline,ImageToImagePipeline:()=>Ur.ImageToImagePipeline,ImageToTextPipeline:()=>Ur.ImageToTextPipeline,InterruptableStoppingCriteria:()=>Mh.InterruptableStoppingCriteria,JAISLMHeadModel:()=>ee.JAISLMHeadModel,JAISModel:()=>ee.JAISModel,JAISPreTrainedModel:()=>ee.JAISPreTrainedModel,LlamaForCausalLM:()=>ee.LlamaForCausalLM,LlamaModel:()=>ee.LlamaModel,LlamaPreTrainedModel:()=>ee.LlamaPreTrainedModel,LlamaTokenizer:()=>qn.LlamaTokenizer,LlavaForConditionalGeneration:()=>ee.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>ee.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>ee.LongT5ForConditionalGeneration,LongT5Model:()=>ee.LongT5Model,LongT5PreTrainedModel:()=>ee.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>ee.M2M100ForConditionalGeneration,M2M100Model:()=>ee.M2M100Model,M2M100PreTrainedModel:()=>ee.M2M100PreTrainedModel,M2M100Tokenizer:()=>qn.M2M100Tokenizer,MBart50Tokenizer:()=>qn.MBart50Tokenizer,MBartForCausalLM:()=>ee.MBartForCausalLM,MBartForConditionalGeneration:()=>ee.MBartForConditionalGeneration,MBartForSequenceClassification:()=>ee.MBartForSequenceClassification,MBartModel:()=>ee.MBartModel,MBartPreTrainedModel:()=>ee.MBartPreTrainedModel,MBartTokenizer:()=>qn.MBartTokenizer,MPNetForMaskedLM:()=>ee.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>ee.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>ee.MPNetForSequenceClassification,MPNetForTokenClassification:()=>ee.MPNetForTokenClassification,MPNetModel:()=>ee.MPNetModel,MPNetPreTrainedModel:()=>ee.MPNetPreTrainedModel,MPNetTokenizer:()=>qn.MPNetTokenizer,MT5ForConditionalGeneration:()=>ee.MT5ForConditionalGeneration,MT5Model:()=>ee.MT5Model,MT5PreTrainedModel:()=>ee.MT5PreTrainedModel,MarianMTModel:()=>ee.MarianMTModel,MarianModel:()=>ee.MarianModel,MarianPreTrainedModel:()=>ee.MarianPreTrainedModel,MarianTokenizer:()=>qn.MarianTokenizer,MaskedLMOutput:()=>ee.MaskedLMOutput,MaxLengthCriteria:()=>Mh.MaxLengthCriteria,MistralForCausalLM:()=>ee.MistralForCausalLM,MistralModel:()=>ee.MistralModel,MistralPreTrainedModel:()=>ee.MistralPreTrainedModel,MobileBertForMaskedLM:()=>ee.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>ee.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>ee.MobileBertForSequenceClassification,MobileBertModel:()=>ee.MobileBertModel,MobileBertPreTrainedModel:()=>ee.MobileBertPreTrainedModel,MobileBertTokenizer:()=>qn.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>Ln.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>ee.MobileNetV1ForImageClassification,MobileNetV1Model:()=>ee.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>ee.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Ln.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>ee.MobileNetV2ForImageClassification,MobileNetV2Model:()=>ee.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>ee.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Ln.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>ee.MobileNetV3ForImageClassification,MobileNetV3Model:()=>ee.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>ee.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Ln.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>ee.MobileNetV4ForImageClassification,MobileNetV4Model:()=>ee.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>ee.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Ln.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>ee.MobileViTForImageClassification,MobileViTImageProcessor:()=>Ln.MobileViTImageProcessor,MobileViTModel:()=>ee.MobileViTModel,MobileViTPreTrainedModel:()=>ee.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>ee.MobileViTV2ForImageClassification,MobileViTV2Model:()=>ee.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>ee.MobileViTV2PreTrainedModel,ModelOutput:()=>ee.ModelOutput,Moondream1ForConditionalGeneration:()=>ee.Moondream1ForConditionalGeneration,MptForCausalLM:()=>ee.MptForCausalLM,MptModel:()=>ee.MptModel,MptPreTrainedModel:()=>ee.MptPreTrainedModel,MusicgenForCausalLM:()=>ee.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>ee.MusicgenForConditionalGeneration,MusicgenModel:()=>ee.MusicgenModel,MusicgenPreTrainedModel:()=>ee.MusicgenPreTrainedModel,NllbTokenizer:()=>qn.NllbTokenizer,NomicBertModel:()=>ee.NomicBertModel,NomicBertPreTrainedModel:()=>ee.NomicBertPreTrainedModel,NougatImageProcessor:()=>Ln.NougatImageProcessor,NougatTokenizer:()=>qn.NougatTokenizer,OPTForCausalLM:()=>ee.OPTForCausalLM,OPTModel:()=>ee.OPTModel,OPTPreTrainedModel:()=>ee.OPTPreTrainedModel,ObjectDetectionPipeline:()=>Ur.ObjectDetectionPipeline,OpenELMForCausalLM:()=>ee.OpenELMForCausalLM,OpenELMModel:()=>ee.OpenELMModel,OpenELMPreTrainedModel:()=>ee.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Ln.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>ee.OwlViTForObjectDetection,OwlViTModel:()=>ee.OwlViTModel,OwlViTPreTrainedModel:()=>ee.OwlViTPreTrainedModel,OwlViTProcessor:()=>Ln.OwlViTProcessor,Owlv2ForObjectDetection:()=>ee.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Ln.Owlv2ImageProcessor,Owlv2Model:()=>ee.Owlv2Model,Owlv2PreTrainedModel:()=>ee.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>ee.Phi3ForCausalLM,Phi3Model:()=>ee.Phi3Model,Phi3PreTrainedModel:()=>ee.Phi3PreTrainedModel,PhiForCausalLM:()=>ee.PhiForCausalLM,PhiModel:()=>ee.PhiModel,PhiPreTrainedModel:()=>ee.PhiPreTrainedModel,Pipeline:()=>Ur.Pipeline,PreTrainedModel:()=>ee.PreTrainedModel,PreTrainedTokenizer:()=>qn.PreTrainedTokenizer,PretrainedConfig:()=>yy.PretrainedConfig,PretrainedMixin:()=>ee.PretrainedMixin,Processor:()=>Ln.Processor,PyAnnoteFeatureExtractor:()=>Ln.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>ee.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>ee.PyAnnoteModel,PyAnnotePreTrainedModel:()=>ee.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Ln.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>ee.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>Ur.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>ee.Qwen2ForCausalLM,Qwen2Model:()=>ee.Qwen2Model,Qwen2PreTrainedModel:()=>ee.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>qn.Qwen2Tokenizer,RTDetrForObjectDetection:()=>ee.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Ln.RTDetrImageProcessor,RTDetrModel:()=>ee.RTDetrModel,RTDetrObjectDetectionOutput:()=>ee.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>ee.RTDetrPreTrainedModel,RawImage:()=>l3.RawImage,ResNetForImageClassification:()=>ee.ResNetForImageClassification,ResNetModel:()=>ee.ResNetModel,ResNetPreTrainedModel:()=>ee.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>ee.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>ee.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>ee.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>ee.RoFormerForTokenClassification,RoFormerModel:()=>ee.RoFormerModel,RoFormerPreTrainedModel:()=>ee.RoFormerPreTrainedModel,RoFormerTokenizer:()=>qn.RoFormerTokenizer,RobertaForMaskedLM:()=>ee.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>ee.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>ee.RobertaForSequenceClassification,RobertaForTokenClassification:()=>ee.RobertaForTokenClassification,RobertaModel:()=>ee.RobertaModel,RobertaPreTrainedModel:()=>ee.RobertaPreTrainedModel,RobertaTokenizer:()=>qn.RobertaTokenizer,SamImageProcessor:()=>Ln.SamImageProcessor,SamImageSegmentationOutput:()=>ee.SamImageSegmentationOutput,SamModel:()=>ee.SamModel,SamPreTrainedModel:()=>ee.SamPreTrainedModel,SamProcessor:()=>Ln.SamProcessor,SapiensFeatureExtractor:()=>Ln.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>ee.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>ee.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>ee.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>ee.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Ln.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Ln.SegformerFeatureExtractor,SegformerForImageClassification:()=>ee.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>ee.SegformerForSemanticSegmentation,SegformerModel:()=>ee.SegformerModel,SegformerPreTrainedModel:()=>ee.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>ee.Seq2SeqLMOutput,SequenceClassifierOutput:()=>ee.SequenceClassifierOutput,SiglipImageProcessor:()=>Ln.SiglipImageProcessor,SiglipModel:()=>ee.SiglipModel,SiglipPreTrainedModel:()=>ee.SiglipPreTrainedModel,SiglipTextModel:()=>ee.SiglipTextModel,SiglipTokenizer:()=>qn.SiglipTokenizer,SiglipVisionModel:()=>ee.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Ln.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>ee.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>ee.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>ee.SpeechT5HifiGan,SpeechT5Model:()=>ee.SpeechT5Model,SpeechT5PreTrainedModel:()=>ee.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Ln.SpeechT5Processor,SpeechT5Tokenizer:()=>qn.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>ee.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>ee.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>ee.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>ee.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>ee.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>qn.SqueezeBertTokenizer,StableLmForCausalLM:()=>ee.StableLmForCausalLM,StableLmModel:()=>ee.StableLmModel,StableLmPreTrainedModel:()=>ee.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>ee.Starcoder2ForCausalLM,Starcoder2Model:()=>ee.Starcoder2Model,Starcoder2PreTrainedModel:()=>ee.Starcoder2PreTrainedModel,StoppingCriteria:()=>Mh.StoppingCriteria,StoppingCriteriaList:()=>Mh.StoppingCriteriaList,SummarizationPipeline:()=>Ur.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>ee.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Ln.Swin2SRImageProcessor,Swin2SRModel:()=>ee.Swin2SRModel,Swin2SRPreTrainedModel:()=>ee.Swin2SRPreTrainedModel,SwinForImageClassification:()=>ee.SwinForImageClassification,SwinModel:()=>ee.SwinModel,SwinPreTrainedModel:()=>ee.SwinPreTrainedModel,T5ForConditionalGeneration:()=>ee.T5ForConditionalGeneration,T5Model:()=>ee.T5Model,T5PreTrainedModel:()=>ee.T5PreTrainedModel,T5Tokenizer:()=>qn.T5Tokenizer,TableTransformerForObjectDetection:()=>ee.TableTransformerForObjectDetection,TableTransformerModel:()=>ee.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>ee.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>ee.TableTransformerPreTrainedModel,Tensor:()=>wi.Tensor,Text2TextGenerationPipeline:()=>Ur.Text2TextGenerationPipeline,TextClassificationPipeline:()=>Ur.TextClassificationPipeline,TextGenerationPipeline:()=>Ur.TextGenerationPipeline,TextStreamer:()=>vy.TextStreamer,TextToAudioPipeline:()=>Ur.TextToAudioPipeline,TokenClassificationPipeline:()=>Ur.TokenClassificationPipeline,TokenClassifierOutput:()=>ee.TokenClassifierOutput,TokenizerModel:()=>qn.TokenizerModel,TrOCRForCausalLM:()=>ee.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>ee.TrOCRPreTrainedModel,TranslationPipeline:()=>Ur.TranslationPipeline,UniSpeechForCTC:()=>ee.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>ee.UniSpeechForSequenceClassification,UniSpeechModel:()=>ee.UniSpeechModel,UniSpeechPreTrainedModel:()=>ee.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>ee.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>ee.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>ee.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>ee.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>ee.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>Ln.ViTFeatureExtractor,ViTForImageClassification:()=>ee.ViTForImageClassification,ViTImageProcessor:()=>Ln.ViTImageProcessor,ViTModel:()=>ee.ViTModel,ViTPreTrainedModel:()=>ee.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>ee.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>ee.VitMatteForImageMatting,VitMatteImageProcessor:()=>Ln.VitMatteImageProcessor,VitMattePreTrainedModel:()=>ee.VitMattePreTrainedModel,VitsModel:()=>ee.VitsModel,VitsModelOutput:()=>ee.VitsModelOutput,VitsPreTrainedModel:()=>ee.VitsPreTrainedModel,VitsTokenizer:()=>qn.VitsTokenizer,Wav2Vec2BertForCTC:()=>ee.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>ee.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>ee.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>ee.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>qn.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Ln.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>ee.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>ee.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>ee.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>ee.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>ee.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Ln.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>ee.WavLMForAudioFrameClassification,WavLMForCTC:()=>ee.WavLMForCTC,WavLMForSequenceClassification:()=>ee.WavLMForSequenceClassification,WavLMForXVector:()=>ee.WavLMForXVector,WavLMModel:()=>ee.WavLMModel,WavLMPreTrainedModel:()=>ee.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Ln.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>ee.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>ee.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Ln.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>ee.WhisperForConditionalGeneration,WhisperModel:()=>ee.WhisperModel,WhisperPreTrainedModel:()=>ee.WhisperPreTrainedModel,WhisperProcessor:()=>Ln.WhisperProcessor,WhisperTextStreamer:()=>vy.WhisperTextStreamer,WhisperTokenizer:()=>qn.WhisperTokenizer,XLMForQuestionAnswering:()=>ee.XLMForQuestionAnswering,XLMForSequenceClassification:()=>ee.XLMForSequenceClassification,XLMForTokenClassification:()=>ee.XLMForTokenClassification,XLMModel:()=>ee.XLMModel,XLMPreTrainedModel:()=>ee.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>ee.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>ee.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>ee.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>ee.XLMRobertaForTokenClassification,XLMRobertaModel:()=>ee.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>ee.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>qn.XLMRobertaTokenizer,XLMTokenizer:()=>qn.XLMTokenizer,XLMWithLMHeadModel:()=>ee.XLMWithLMHeadModel,XVectorOutput:()=>ee.XVectorOutput,YolosFeatureExtractor:()=>Ln.YolosFeatureExtractor,YolosForObjectDetection:()=>ee.YolosForObjectDetection,YolosModel:()=>ee.YolosModel,YolosObjectDetectionOutput:()=>ee.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>ee.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>Ur.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>Ur.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>Ur.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>Ur.ZeroShotObjectDetectionPipeline,bankers_round:()=>Ps.bankers_round,cat:()=>wi.cat,cos_sim:()=>Ps.cos_sim,dot:()=>Ps.dot,dynamic_time_warping:()=>Ps.dynamic_time_warping,env:()=>a3.env,full:()=>wi.full,full_like:()=>wi.full_like,getKeyValueShapes:()=>yy.getKeyValueShapes,hamming:()=>Ic.hamming,hanning:()=>Ic.hanning,interpolate:()=>wi.interpolate,interpolate_4d:()=>wi.interpolate_4d,interpolate_data:()=>Ps.interpolate_data,is_chinese_char:()=>qn.is_chinese_char,layer_norm:()=>wi.layer_norm,log_softmax:()=>Ps.log_softmax,magnitude:()=>Ps.magnitude,matmul:()=>wi.matmul,max:()=>Ps.max,mean:()=>wi.mean,mean_pooling:()=>wi.mean_pooling,medianFilter:()=>Ps.medianFilter,mel_filter_bank:()=>Ic.mel_filter_bank,min:()=>Ps.min,ones:()=>wi.ones,ones_like:()=>wi.ones_like,permute:()=>wi.permute,permute_data:()=>Ps.permute_data,pipeline:()=>Ur.pipeline,quantize_embeddings:()=>wi.quantize_embeddings,read_audio:()=>Ic.read_audio,rfft:()=>wi.rfft,round:()=>Ps.round,softmax:()=>Ps.softmax,spectrogram:()=>Ic.spectrogram,stack:()=>wi.stack,std_mean:()=>wi.std_mean,topk:()=>wi.topk,window_function:()=>Ic.window_function,zeros:()=>wi.zeros,zeros_like:()=>wi.zeros_like});var a3=Gr("./src/env.js"),Ur=Gr("./src/pipelines.js"),ee=Gr("./src/models.js"),qn=Gr("./src/tokenizers.js"),Ln=Gr("./src/processors.js"),yy=Gr("./src/configs.js"),Ic=Gr("./src/utils/audio.js"),l3=Gr("./src/utils/image.js"),wi=Gr("./src/utils/tensor.js"),Ps=Gr("./src/utils/maths.js"),vy=Gr("./src/generation/streamers.js"),Mh=Gr("./src/generation/stopping_criteria.js");D.ASTFeatureExtractor;D.ASTForAudioClassification;D.ASTModel;D.ASTPreTrainedModel;D.AlbertForMaskedLM;D.AlbertForQuestionAnswering;D.AlbertForSequenceClassification;D.AlbertModel;D.AlbertPreTrainedModel;D.AlbertTokenizer;D.AudioClassificationPipeline;D.AutoConfig;var _S=D.AutoModel;D.AutoModelForAudioClassification;D.AutoModelForAudioFrameClassification;D.AutoModelForCTC;D.AutoModelForCausalLM;D.AutoModelForDepthEstimation;D.AutoModelForDocumentQuestionAnswering;D.AutoModelForImageClassification;D.AutoModelForImageFeatureExtraction;D.AutoModelForImageMatting;D.AutoModelForImageSegmentation;D.AutoModelForImageToImage;D.AutoModelForMaskGeneration;D.AutoModelForMaskedLM;D.AutoModelForNormalEstimation;D.AutoModelForObjectDetection;D.AutoModelForQuestionAnswering;D.AutoModelForSemanticSegmentation;D.AutoModelForSeq2SeqLM;D.AutoModelForSequenceClassification;D.AutoModelForSpeechSeq2Seq;D.AutoModelForTextToSpectrogram;D.AutoModelForTextToWaveform;D.AutoModelForTokenClassification;D.AutoModelForVision2Seq;D.AutoModelForXVector;D.AutoModelForZeroShotObjectDetection;var yS=D.AutoProcessor;D.AutoTokenizer;D.AutomaticSpeechRecognitionPipeline;D.BartForConditionalGeneration;D.BartForSequenceClassification;D.BartModel;D.BartPretrainedModel;D.BartTokenizer;D.BaseModelOutput;D.BaseStreamer;D.BeitFeatureExtractor;D.BeitForImageClassification;D.BeitModel;D.BeitPreTrainedModel;D.BertForMaskedLM;D.BertForQuestionAnswering;D.BertForSequenceClassification;D.BertForTokenClassification;D.BertModel;D.BertPreTrainedModel;D.BertTokenizer;D.BitImageProcessor;D.BlenderbotForConditionalGeneration;D.BlenderbotModel;D.BlenderbotPreTrainedModel;D.BlenderbotSmallForConditionalGeneration;D.BlenderbotSmallModel;D.BlenderbotSmallPreTrainedModel;D.BlenderbotSmallTokenizer;D.BlenderbotTokenizer;D.BloomForCausalLM;D.BloomModel;D.BloomPreTrainedModel;D.BloomTokenizer;D.CLIPFeatureExtractor;D.CLIPImageProcessor;D.CLIPModel;D.CLIPPreTrainedModel;D.CLIPSegForImageSegmentation;D.CLIPSegModel;D.CLIPSegPreTrainedModel;D.CLIPTextModelWithProjection;D.CLIPTokenizer;D.CLIPVisionModelWithProjection;D.CamembertForMaskedLM;D.CamembertForQuestionAnswering;D.CamembertForSequenceClassification;D.CamembertForTokenClassification;D.CamembertModel;D.CamembertPreTrainedModel;D.CamembertTokenizer;D.CausalLMOutput;D.CausalLMOutputWithPast;D.ChineseCLIPFeatureExtractor;D.ChineseCLIPModel;D.ChineseCLIPPreTrainedModel;D.ClapAudioModelWithProjection;D.ClapFeatureExtractor;D.ClapModel;D.ClapPreTrainedModel;D.ClapTextModelWithProjection;D.CodeGenForCausalLM;D.CodeGenModel;D.CodeGenPreTrainedModel;D.CodeGenTokenizer;D.CodeLlamaTokenizer;D.CohereForCausalLM;D.CohereModel;D.CoherePreTrainedModel;D.CohereTokenizer;D.ConvBertForMaskedLM;D.ConvBertForQuestionAnswering;D.ConvBertForSequenceClassification;D.ConvBertForTokenClassification;D.ConvBertModel;D.ConvBertPreTrainedModel;D.ConvBertTokenizer;D.ConvNextFeatureExtractor;D.ConvNextForImageClassification;D.ConvNextImageProcessor;D.ConvNextModel;D.ConvNextPreTrainedModel;D.ConvNextV2ForImageClassification;D.ConvNextV2Model;D.ConvNextV2PreTrainedModel;D.DPTFeatureExtractor;D.DPTForDepthEstimation;D.DPTImageProcessor;D.DPTModel;D.DPTPreTrainedModel;D.DebertaForMaskedLM;D.DebertaForQuestionAnswering;D.DebertaForSequenceClassification;D.DebertaForTokenClassification;D.DebertaModel;D.DebertaPreTrainedModel;D.DebertaTokenizer;D.DebertaV2ForMaskedLM;D.DebertaV2ForQuestionAnswering;D.DebertaV2ForSequenceClassification;D.DebertaV2ForTokenClassification;D.DebertaV2Model;D.DebertaV2PreTrainedModel;D.DebertaV2Tokenizer;D.DeiTFeatureExtractor;D.DeiTForImageClassification;D.DeiTModel;D.DeiTPreTrainedModel;D.DepthAnythingForDepthEstimation;D.DepthAnythingPreTrainedModel;D.DepthEstimationPipeline;D.DetrFeatureExtractor;D.DetrForObjectDetection;D.DetrForSegmentation;D.DetrModel;D.DetrObjectDetectionOutput;D.DetrPreTrainedModel;D.DetrSegmentationOutput;D.Dinov2ForImageClassification;D.Dinov2Model;D.Dinov2PreTrainedModel;D.DistilBertForMaskedLM;D.DistilBertForQuestionAnswering;D.DistilBertForSequenceClassification;D.DistilBertForTokenClassification;D.DistilBertModel;D.DistilBertPreTrainedModel;D.DistilBertTokenizer;D.DocumentQuestionAnsweringPipeline;D.DonutFeatureExtractor;D.DonutSwinModel;D.DonutSwinPreTrainedModel;D.EfficientNetForImageClassification;D.EfficientNetImageProcessor;D.EfficientNetModel;D.EfficientNetPreTrainedModel;D.ElectraForMaskedLM;D.ElectraForQuestionAnswering;D.ElectraForSequenceClassification;D.ElectraForTokenClassification;D.ElectraModel;D.ElectraPreTrainedModel;D.ElectraTokenizer;D.EosTokenCriteria;D.EsmForMaskedLM;D.EsmForSequenceClassification;D.EsmForTokenClassification;D.EsmModel;D.EsmPreTrainedModel;D.EsmTokenizer;D.FFT;D.FalconForCausalLM;D.FalconModel;D.FalconPreTrainedModel;D.FalconTokenizer;D.FastViTForImageClassification;D.FastViTModel;D.FastViTPreTrainedModel;D.FeatureExtractionPipeline;D.FeatureExtractor;D.FillMaskPipeline;D.Florence2ForConditionalGeneration;D.Florence2PreTrainedModel;D.Florence2Processor;D.GLPNFeatureExtractor;D.GLPNForDepthEstimation;D.GLPNModel;D.GLPNPreTrainedModel;D.GPT2LMHeadModel;D.GPT2Model;D.GPT2PreTrainedModel;D.GPT2Tokenizer;D.GPTBigCodeForCausalLM;D.GPTBigCodeModel;D.GPTBigCodePreTrainedModel;D.GPTJForCausalLM;D.GPTJModel;D.GPTJPreTrainedModel;D.GPTNeoForCausalLM;D.GPTNeoModel;D.GPTNeoPreTrainedModel;D.GPTNeoXForCausalLM;D.GPTNeoXModel;D.GPTNeoXPreTrainedModel;D.GPTNeoXTokenizer;D.Gemma2ForCausalLM;D.Gemma2Model;D.Gemma2PreTrainedModel;D.GemmaForCausalLM;D.GemmaModel;D.GemmaPreTrainedModel;D.GemmaTokenizer;D.Grok1Tokenizer;D.HerbertTokenizer;D.HubertForCTC;D.HubertForSequenceClassification;D.HubertModel;D.HubertPreTrainedModel;D.ImageClassificationPipeline;D.ImageFeatureExtractionPipeline;D.ImageFeatureExtractor;D.ImageMattingOutput;D.ImageSegmentationPipeline;D.ImageToImagePipeline;D.ImageToTextPipeline;D.InterruptableStoppingCriteria;D.JAISLMHeadModel;D.JAISModel;D.JAISPreTrainedModel;D.LlamaForCausalLM;D.LlamaModel;D.LlamaPreTrainedModel;D.LlamaTokenizer;D.LlavaForConditionalGeneration;D.LlavaPreTrainedModel;D.LongT5ForConditionalGeneration;D.LongT5Model;D.LongT5PreTrainedModel;D.M2M100ForConditionalGeneration;D.M2M100Model;D.M2M100PreTrainedModel;D.M2M100Tokenizer;D.MBart50Tokenizer;D.MBartForCausalLM;D.MBartForConditionalGeneration;D.MBartForSequenceClassification;D.MBartModel;D.MBartPreTrainedModel;D.MBartTokenizer;D.MPNetForMaskedLM;D.MPNetForQuestionAnswering;D.MPNetForSequenceClassification;D.MPNetForTokenClassification;D.MPNetModel;D.MPNetPreTrainedModel;D.MPNetTokenizer;D.MT5ForConditionalGeneration;D.MT5Model;D.MT5PreTrainedModel;D.MarianMTModel;D.MarianModel;D.MarianPreTrainedModel;D.MarianTokenizer;D.MaskedLMOutput;D.MaxLengthCriteria;D.MistralForCausalLM;D.MistralModel;D.MistralPreTrainedModel;D.MobileBertForMaskedLM;D.MobileBertForQuestionAnswering;D.MobileBertForSequenceClassification;D.MobileBertModel;D.MobileBertPreTrainedModel;D.MobileBertTokenizer;D.MobileNetV1FeatureExtractor;D.MobileNetV1ForImageClassification;D.MobileNetV1Model;D.MobileNetV1PreTrainedModel;D.MobileNetV2FeatureExtractor;D.MobileNetV2ForImageClassification;D.MobileNetV2Model;D.MobileNetV2PreTrainedModel;D.MobileNetV3FeatureExtractor;D.MobileNetV3ForImageClassification;D.MobileNetV3Model;D.MobileNetV3PreTrainedModel;D.MobileNetV4FeatureExtractor;D.MobileNetV4ForImageClassification;D.MobileNetV4Model;D.MobileNetV4PreTrainedModel;D.MobileViTFeatureExtractor;D.MobileViTForImageClassification;D.MobileViTImageProcessor;D.MobileViTModel;D.MobileViTPreTrainedModel;D.MobileViTV2ForImageClassification;D.MobileViTV2Model;D.MobileViTV2PreTrainedModel;D.ModelOutput;D.Moondream1ForConditionalGeneration;D.MptForCausalLM;D.MptModel;D.MptPreTrainedModel;D.MusicgenForCausalLM;D.MusicgenForConditionalGeneration;D.MusicgenModel;D.MusicgenPreTrainedModel;D.NllbTokenizer;D.NomicBertModel;D.NomicBertPreTrainedModel;D.NougatImageProcessor;D.NougatTokenizer;D.OPTForCausalLM;D.OPTModel;D.OPTPreTrainedModel;D.ObjectDetectionPipeline;D.OpenELMForCausalLM;D.OpenELMModel;D.OpenELMPreTrainedModel;D.OwlViTFeatureExtractor;D.OwlViTForObjectDetection;D.OwlViTModel;D.OwlViTPreTrainedModel;D.OwlViTProcessor;D.Owlv2ForObjectDetection;D.Owlv2ImageProcessor;D.Owlv2Model;D.Owlv2PreTrainedModel;D.Phi3ForCausalLM;D.Phi3Model;D.Phi3PreTrainedModel;D.PhiForCausalLM;D.PhiModel;D.PhiPreTrainedModel;D.Pipeline;D.PreTrainedModel;D.PreTrainedTokenizer;D.PretrainedConfig;D.PretrainedMixin;D.Processor;D.PyAnnoteFeatureExtractor;D.PyAnnoteForAudioFrameClassification;D.PyAnnoteModel;D.PyAnnotePreTrainedModel;D.PyAnnoteProcessor;D.QuestionAnsweringModelOutput;D.QuestionAnsweringPipeline;D.Qwen2ForCausalLM;D.Qwen2Model;D.Qwen2PreTrainedModel;D.Qwen2Tokenizer;D.RTDetrForObjectDetection;D.RTDetrImageProcessor;D.RTDetrModel;D.RTDetrObjectDetectionOutput;D.RTDetrPreTrainedModel;var w2=D.RawImage;D.ResNetForImageClassification;D.ResNetModel;D.ResNetPreTrainedModel;D.RoFormerForMaskedLM;D.RoFormerForQuestionAnswering;D.RoFormerForSequenceClassification;D.RoFormerForTokenClassification;D.RoFormerModel;D.RoFormerPreTrainedModel;D.RoFormerTokenizer;D.RobertaForMaskedLM;D.RobertaForQuestionAnswering;D.RobertaForSequenceClassification;D.RobertaForTokenClassification;D.RobertaModel;D.RobertaPreTrainedModel;D.RobertaTokenizer;D.SamImageProcessor;D.SamImageSegmentationOutput;D.SamModel;D.SamPreTrainedModel;D.SamProcessor;D.SapiensFeatureExtractor;D.SapiensForDepthEstimation;D.SapiensForNormalEstimation;D.SapiensForSemanticSegmentation;D.SapiensPreTrainedModel;D.SeamlessM4TFeatureExtractor;D.SegformerFeatureExtractor;D.SegformerForImageClassification;D.SegformerForSemanticSegmentation;D.SegformerModel;D.SegformerPreTrainedModel;D.Seq2SeqLMOutput;D.SequenceClassifierOutput;D.SiglipImageProcessor;D.SiglipModel;D.SiglipPreTrainedModel;D.SiglipTextModel;D.SiglipTokenizer;D.SiglipVisionModel;D.SpeechT5FeatureExtractor;D.SpeechT5ForSpeechToText;D.SpeechT5ForTextToSpeech;D.SpeechT5HifiGan;D.SpeechT5Model;D.SpeechT5PreTrainedModel;D.SpeechT5Processor;D.SpeechT5Tokenizer;D.SqueezeBertForMaskedLM;D.SqueezeBertForQuestionAnswering;D.SqueezeBertForSequenceClassification;D.SqueezeBertModel;D.SqueezeBertPreTrainedModel;D.SqueezeBertTokenizer;D.StableLmForCausalLM;D.StableLmModel;D.StableLmPreTrainedModel;D.Starcoder2ForCausalLM;D.Starcoder2Model;D.Starcoder2PreTrainedModel;D.StoppingCriteria;D.StoppingCriteriaList;D.SummarizationPipeline;D.Swin2SRForImageSuperResolution;D.Swin2SRImageProcessor;D.Swin2SRModel;D.Swin2SRPreTrainedModel;D.SwinForImageClassification;D.SwinModel;D.SwinPreTrainedModel;D.T5ForConditionalGeneration;D.T5Model;D.T5PreTrainedModel;D.T5Tokenizer;D.TableTransformerForObjectDetection;D.TableTransformerModel;D.TableTransformerObjectDetectionOutput;D.TableTransformerPreTrainedModel;D.Tensor;D.Text2TextGenerationPipeline;D.TextClassificationPipeline;D.TextGenerationPipeline;D.TextStreamer;D.TextToAudioPipeline;D.TokenClassificationPipeline;D.TokenClassifierOutput;D.TokenizerModel;D.TrOCRForCausalLM;D.TrOCRPreTrainedModel;D.TranslationPipeline;D.UniSpeechForCTC;D.UniSpeechForSequenceClassification;D.UniSpeechModel;D.UniSpeechPreTrainedModel;D.UniSpeechSatForAudioFrameClassification;D.UniSpeechSatForCTC;D.UniSpeechSatForSequenceClassification;D.UniSpeechSatModel;D.UniSpeechSatPreTrainedModel;D.ViTFeatureExtractor;D.ViTForImageClassification;D.ViTImageProcessor;D.ViTModel;D.ViTPreTrainedModel;D.VisionEncoderDecoderModel;D.VitMatteForImageMatting;D.VitMatteImageProcessor;D.VitMattePreTrainedModel;D.VitsModel;D.VitsModelOutput;D.VitsPreTrainedModel;D.VitsTokenizer;D.Wav2Vec2BertForCTC;D.Wav2Vec2BertForSequenceClassification;D.Wav2Vec2BertModel;D.Wav2Vec2BertPreTrainedModel;D.Wav2Vec2CTCTokenizer;D.Wav2Vec2FeatureExtractor;D.Wav2Vec2ForAudioFrameClassification;D.Wav2Vec2ForCTC;D.Wav2Vec2ForSequenceClassification;D.Wav2Vec2Model;D.Wav2Vec2PreTrainedModel;D.Wav2Vec2ProcessorWithLM;D.WavLMForAudioFrameClassification;D.WavLMForCTC;D.WavLMForSequenceClassification;D.WavLMForXVector;D.WavLMModel;D.WavLMPreTrainedModel;D.WeSpeakerFeatureExtractor;D.WeSpeakerResNetModel;D.WeSpeakerResNetPreTrainedModel;D.WhisperFeatureExtractor;D.WhisperForConditionalGeneration;D.WhisperModel;D.WhisperPreTrainedModel;D.WhisperProcessor;D.WhisperTextStreamer;D.WhisperTokenizer;D.XLMForQuestionAnswering;D.XLMForSequenceClassification;D.XLMForTokenClassification;D.XLMModel;D.XLMPreTrainedModel;D.XLMRobertaForMaskedLM;D.XLMRobertaForQuestionAnswering;D.XLMRobertaForSequenceClassification;D.XLMRobertaForTokenClassification;D.XLMRobertaModel;D.XLMRobertaPreTrainedModel;D.XLMRobertaTokenizer;D.XLMTokenizer;D.XLMWithLMHeadModel;D.XVectorOutput;D.YolosFeatureExtractor;D.YolosForObjectDetection;D.YolosModel;D.YolosObjectDetectionOutput;D.YolosPreTrainedModel;D.ZeroShotAudioClassificationPipeline;D.ZeroShotClassificationPipeline;D.ZeroShotImageClassificationPipeline;D.ZeroShotObjectDetectionPipeline;D.bankers_round;D.cat;D.cos_sim;D.dot;D.dynamic_time_warping;var $0=D.env;D.full;D.full_like;D.getKeyValueShapes;D.hamming;D.hanning;D.interpolate;D.interpolate_4d;D.interpolate_data;D.is_chinese_char;D.layer_norm;D.log_softmax;D.magnitude;D.matmul;D.max;D.mean;D.mean_pooling;D.medianFilter;D.mel_filter_bank;D.min;D.ones;D.ones_like;D.permute;D.permute_data;D.pipeline;D.quantize_embeddings;D.read_audio;D.rfft;D.round;D.softmax;D.spectrogram;D.stack;D.std_mean;D.topk;D.window_function;D.zeros;D.zeros_like;function Im(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var vS={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */(function(e,t){(function(n){e.exports=n()})(function(){return function n(i,o,a){function l(p,v){if(!o[p]){if(!i[p]){var _=typeof Im=="function"&ℑif(!v&&_)return _(p,!0);if(d)return d(p,!0);var T=new Error("Cannot find module '"+p+"'");throw T.code="MODULE_NOT_FOUND",T}var M=o[p]={exports:{}};i[p][0].call(M.exports,function(I){var C=i[p][1][I];return l(C||I)},M,M.exports,n,i,o,a)}return o[p].exports}for(var d=typeof Im=="function"&&Im,c=0;c>2,M=(3&p)<<4|v>>4,I=1>6:64,C=2>4,v=(15&T)<<4|(M=d.indexOf(c.charAt(C++)))>>2,_=(3&M)<<6|(I=d.indexOf(c.charAt(C++))),k[E++]=p,M!==64&&(k[E++]=v),I!==64&&(k[E++]=_);return k}},{"./support":30,"./utils":32}],2:[function(n,i,o){var a=n("./external"),l=n("./stream/DataWorker"),d=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function p(v,_,T,M,I){this.compressedSize=v,this.uncompressedSize=_,this.crc32=T,this.compression=M,this.compressedContent=I}p.prototype={getContentWorker:function(){var v=new l(a.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),_=this;return v.on("end",function(){if(this.streamInfo.data_length!==_.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),v},getCompressedWorker:function(){return new l(a.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},p.createWorkerFrom=function(v,_,T){return v.pipe(new d).pipe(new c("uncompressedSize")).pipe(_.compressWorker(T)).pipe(new c("compressedSize")).withStreamInfo("compression",_)},i.exports=p},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,i,o){var a=n("./stream/GenericWorker");o.STORE={magic:"\0\0",compressWorker:function(){return new a("STORE compression")},uncompressWorker:function(){return new a("STORE decompression")}},o.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,i,o){var a=n("./utils"),l=function(){for(var d,c=[],p=0;p<256;p++){d=p;for(var v=0;v<8;v++)d=1&d?3988292384^d>>>1:d>>>1;c[p]=d}return c}();i.exports=function(d,c){return d!==void 0&&d.length?a.getTypeOf(d)!=="string"?function(p,v,_,T){var M=l,I=T+_;p^=-1;for(var C=T;C>>8^M[255&(p^v[C])];return-1^p}(0|c,d,d.length,0):function(p,v,_,T){var M=l,I=T+_;p^=-1;for(var C=T;C>>8^M[255&(p^v.charCodeAt(C))];return-1^p}(0|c,d,d.length,0):0}},{"./utils":32}],5:[function(n,i,o){o.base64=!1,o.binary=!1,o.dir=!1,o.createFolders=!0,o.date=null,o.compression=null,o.compressionOptions=null,o.comment=null,o.unixPermissions=null,o.dosPermissions=null},{}],6:[function(n,i,o){var a=null;a=typeof Promise<"u"?Promise:n("lie"),i.exports={Promise:a}},{lie:37}],7:[function(n,i,o){var a=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),d=n("./utils"),c=n("./stream/GenericWorker"),p=a?"uint8array":"array";function v(_,T){c.call(this,"FlateWorker/"+_),this._pako=null,this._pakoAction=_,this._pakoOptions=T,this.meta={}}o.magic="\b\0",d.inherits(v,c),v.prototype.processChunk=function(_){this.meta=_.meta,this._pako===null&&this._createPako(),this._pako.push(d.transformTo(p,_.data),!1)},v.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},v.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},v.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var _=this;this._pako.onData=function(T){_.push({data:T,meta:_.meta})}},o.compressWorker=function(_){return new v("Deflate",_)},o.uncompressWorker=function(){return new v("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,i,o){function a(M,I){var C,E="";for(C=0;C>>=8;return E}function l(M,I,C,E,x,k){var A,N,R=M.file,B=M.compression,W=k!==p.utf8encode,j=d.transformTo("string",k(R.name)),ae=d.transformTo("string",p.utf8encode(R.name)),ve=R.comment,Ne=d.transformTo("string",k(ve)),oe=d.transformTo("string",p.utf8encode(ve)),Se=ae.length!==R.name.length,G=oe.length!==ve.length,Ce="",gt="",Me="",te=R.dir,fe=R.date,Ae={crc32:0,compressedSize:0,uncompressedSize:0};I&&!C||(Ae.crc32=M.crc32,Ae.compressedSize=M.compressedSize,Ae.uncompressedSize=M.uncompressedSize);var ne=0;I&&(ne|=8),W||!Se&&!G||(ne|=2048);var xe=0,pt=0;te&&(xe|=16),x==="UNIX"?(pt=798,xe|=function(et,ct){var Et=et;return et||(Et=ct?16893:33204),(65535&Et)<<16}(R.unixPermissions,te)):(pt=20,xe|=function(et){return 63&(et||0)}(R.dosPermissions)),A=fe.getUTCHours(),A<<=6,A|=fe.getUTCMinutes(),A<<=5,A|=fe.getUTCSeconds()/2,N=fe.getUTCFullYear()-1980,N<<=4,N|=fe.getUTCMonth()+1,N<<=5,N|=fe.getUTCDate(),Se&&(gt=a(1,1)+a(v(j),4)+ae,Ce+="up"+a(gt.length,2)+gt),G&&(Me=a(1,1)+a(v(Ne),4)+oe,Ce+="uc"+a(Me.length,2)+Me);var Ye="";return Ye+=` \0`,Ye+=a(ne,2),Ye+=B.magic,Ye+=a(A,2),Ye+=a(N,2),Ye+=a(Ae.crc32,4),Ye+=a(Ae.compressedSize,4),Ye+=a(Ae.uncompressedSize,4),Ye+=a(j.length,2),Ye+=a(Ce.length,2),{fileRecord:_.LOCAL_FILE_HEADER+Ye+j+Ce,dirRecord:_.CENTRAL_FILE_HEADER+a(pt,2)+Ye+a(Ne.length,2)+"\0\0\0\0"+a(xe,4)+a(E,4)+j+Ce+Ne}}var d=n("../utils"),c=n("../stream/GenericWorker"),p=n("../utf8"),v=n("../crc32"),_=n("../signature");function T(M,I,C,E){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=I,this.zipPlatform=C,this.encodeFileName=E,this.streamFiles=M,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}d.inherits(T,c),T.prototype.push=function(M){var I=M.meta.percent||0,C=this.entriesCount,E=this._sources.length;this.accumulate?this.contentBuffer.push(M):(this.bytesWritten+=M.data.length,c.prototype.push.call(this,{data:M.data,meta:{currentFile:this.currentFile,percent:C?(I+100*(C-E-1))/C:100}}))},T.prototype.openedSource=function(M){this.currentSourceOffset=this.bytesWritten,this.currentFile=M.file.name;var I=this.streamFiles&&!M.file.dir;if(I){var C=l(M,I,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:C.fileRecord,meta:{percent:0}})}else this.accumulate=!0},T.prototype.closedSource=function(M){this.accumulate=!1;var I=this.streamFiles&&!M.file.dir,C=l(M,I,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(C.dirRecord),I)this.push({data:function(E){return _.DATA_DESCRIPTOR+a(E.crc32,4)+a(E.compressedSize,4)+a(E.uncompressedSize,4)}(M),meta:{percent:100}});else for(this.push({data:C.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},T.prototype.flush=function(){for(var M=this.bytesWritten,I=0;I=this.index;c--)p=(p<<8)+this.byteAt(c);return this.index+=d,p},readString:function(d){return a.transformTo("string",this.readData(d))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var d=this.readInt(4);return new Date(Date.UTC(1980+(d>>25&127),(d>>21&15)-1,d>>16&31,d>>11&31,d>>5&63,(31&d)<<1))}},i.exports=l},{"../utils":32}],19:[function(n,i,o){var a=n("./Uint8ArrayReader");function l(d){a.call(this,d)}n("../utils").inherits(l,a),l.prototype.readData=function(d){this.checkOffset(d);var c=this.data.slice(this.zero+this.index,this.zero+this.index+d);return this.index+=d,c},i.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,i,o){var a=n("./DataReader");function l(d){a.call(this,d)}n("../utils").inherits(l,a),l.prototype.byteAt=function(d){return this.data.charCodeAt(this.zero+d)},l.prototype.lastIndexOfSignature=function(d){return this.data.lastIndexOf(d)-this.zero},l.prototype.readAndCheckSignature=function(d){return d===this.readData(4)},l.prototype.readData=function(d){this.checkOffset(d);var c=this.data.slice(this.zero+this.index,this.zero+this.index+d);return this.index+=d,c},i.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,i,o){var a=n("./ArrayReader");function l(d){a.call(this,d)}n("../utils").inherits(l,a),l.prototype.readData=function(d){if(this.checkOffset(d),d===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+d);return this.index+=d,c},i.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,i,o){var a=n("../utils"),l=n("../support"),d=n("./ArrayReader"),c=n("./StringReader"),p=n("./NodeBufferReader"),v=n("./Uint8ArrayReader");i.exports=function(_){var T=a.getTypeOf(_);return a.checkSupport(T),T!=="string"||l.uint8array?T==="nodebuffer"?new p(_):l.uint8array?new v(a.transformTo("uint8array",_)):new d(a.transformTo("array",_)):new c(_)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,i,o){o.LOCAL_FILE_HEADER="PK",o.CENTRAL_FILE_HEADER="PK",o.CENTRAL_DIRECTORY_END="PK",o.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",o.ZIP64_CENTRAL_DIRECTORY_END="PK",o.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,i,o){var a=n("./GenericWorker"),l=n("../utils");function d(c){a.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(d,a),d.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},i.exports=d},{"../utils":32,"./GenericWorker":28}],25:[function(n,i,o){var a=n("./GenericWorker"),l=n("../crc32");function d(){a.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(d,a),d.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},i.exports=d},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,i,o){var a=n("../utils"),l=n("./GenericWorker");function d(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}a.inherits(d,l),d.prototype.processChunk=function(c){if(c){var p=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=p+c.data.length}l.prototype.processChunk.call(this,c)},i.exports=d},{"../utils":32,"./GenericWorker":28}],27:[function(n,i,o){var a=n("../utils"),l=n("./GenericWorker");function d(c){l.call(this,"DataWorker");var p=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(v){p.dataIsReady=!0,p.data=v,p.max=v&&v.length||0,p.type=a.getTypeOf(v),p.isPaused||p._tickAndRepeat()},function(v){p.error(v)})}a.inherits(d,l),d.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},d.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,a.delay(this._tickAndRepeat,[],this)),!0)},d.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(a.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},d.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,p=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,p);break;case"uint8array":c=this.data.subarray(this.index,p);break;case"array":case"nodebuffer":c=this.data.slice(this.index,p)}return this.index=p,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},i.exports=d},{"../utils":32,"./GenericWorker":28}],28:[function(n,i,o){function a(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}a.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,d){return this._listeners[l].push(d),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,d){if(this._listeners[l])for(var c=0;c "+l:l}},i.exports=a},{}],29:[function(n,i,o){var a=n("../utils"),l=n("./ConvertWorker"),d=n("./GenericWorker"),c=n("../base64"),p=n("../support"),v=n("../external"),_=null;if(p.nodestream)try{_=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function T(I,C){return new v.Promise(function(E,x){var k=[],A=I._internalType,N=I._outputType,R=I._mimeType;I.on("data",function(B,W){k.push(B),C&&C(W)}).on("error",function(B){k=[],x(B)}).on("end",function(){try{var B=function(W,j,ae){switch(W){case"blob":return a.newBlob(a.transformTo("arraybuffer",j),ae);case"base64":return c.encode(j);default:return a.transformTo(W,j)}}(N,function(W,j){var ae,ve=0,Ne=null,oe=0;for(ae=0;ae"u")o.blob=!1;else{var a=new ArrayBuffer(0);try{o.blob=new Blob([a],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(a),o.blob=l.getBlob("application/zip").size===0}catch{o.blob=!1}}}try{o.nodestream=!!n("readable-stream").Readable}catch{o.nodestream=!1}},{"readable-stream":16}],31:[function(n,i,o){for(var a=n("./utils"),l=n("./support"),d=n("./nodejsUtils"),c=n("./stream/GenericWorker"),p=new Array(256),v=0;v<256;v++)p[v]=252<=v?6:248<=v?5:240<=v?4:224<=v?3:192<=v?2:1;p[254]=p[254]=1;function _(){c.call(this,"utf-8 decode"),this.leftOver=null}function T(){c.call(this,"utf-8 encode")}o.utf8encode=function(M){return l.nodebuffer?d.newBufferFrom(M,"utf-8"):function(I){var C,E,x,k,A,N=I.length,R=0;for(k=0;k>>6:(E<65536?C[A++]=224|E>>>12:(C[A++]=240|E>>>18,C[A++]=128|E>>>12&63),C[A++]=128|E>>>6&63),C[A++]=128|63&E);return C}(M)},o.utf8decode=function(M){return l.nodebuffer?a.transformTo("nodebuffer",M).toString("utf-8"):function(I){var C,E,x,k,A=I.length,N=new Array(2*A);for(C=E=0;C>10&1023,N[E++]=56320|1023&x)}return N.length!==E&&(N.subarray?N=N.subarray(0,E):N.length=E),a.applyFromCharCode(N)}(M=a.transformTo(l.uint8array?"uint8array":"array",M))},a.inherits(_,c),_.prototype.processChunk=function(M){var I=a.transformTo(l.uint8array?"uint8array":"array",M.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var C=I;(I=new Uint8Array(C.length+this.leftOver.length)).set(this.leftOver,0),I.set(C,this.leftOver.length)}else I=this.leftOver.concat(I);this.leftOver=null}var E=function(k,A){var N;for((A=A||k.length)>k.length&&(A=k.length),N=A-1;0<=N&&(192&k[N])==128;)N--;return N<0||N===0?A:N+p[k[N]]>A?N:A}(I),x=I;E!==I.length&&(l.uint8array?(x=I.subarray(0,E),this.leftOver=I.subarray(E,I.length)):(x=I.slice(0,E),this.leftOver=I.slice(E,I.length))),this.push({data:o.utf8decode(x),meta:M.meta})},_.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:o.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},o.Utf8DecodeWorker=_,a.inherits(T,c),T.prototype.processChunk=function(M){this.push({data:o.utf8encode(M.data),meta:M.meta})},o.Utf8EncodeWorker=T},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,i,o){var a=n("./support"),l=n("./base64"),d=n("./nodejsUtils"),c=n("./external");function p(C){return C}function v(C,E){for(var x=0;x>8;this.dir=!!(16&this.externalFileAttributes),M==0&&(this.dosPermissions=63&this.externalFileAttributes),M==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var M=a(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=M.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=M.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=M.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=M.readInt(4))}},readExtraFields:function(M){var I,C,E,x=M.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});M.index+4>>6:(M<65536?T[E++]=224|M>>>12:(T[E++]=240|M>>>18,T[E++]=128|M>>>12&63),T[E++]=128|M>>>6&63),T[E++]=128|63&M);return T},o.buf2binstring=function(_){return v(_,_.length)},o.binstring2buf=function(_){for(var T=new a.Buf8(_.length),M=0,I=T.length;M>10&1023,k[I++]=56320|1023&C)}return v(k,I)},o.utf8border=function(_,T){var M;for((T=T||_.length)>_.length&&(T=_.length),M=T-1;0<=M&&(192&_[M])==128;)M--;return M<0||M===0?T:M+c[_[M]]>T?M:T}},{"./common":41}],43:[function(n,i,o){i.exports=function(a,l,d,c){for(var p=65535&a|0,v=a>>>16&65535|0,_=0;d!==0;){for(d-=_=2e3>>1:l>>>1;d[c]=l}return d}();i.exports=function(l,d,c,p){var v=a,_=p+c;l^=-1;for(var T=p;T<_;T++)l=l>>>8^v[255&(l^d[T])];return-1^l}},{}],46:[function(n,i,o){var a,l=n("../utils/common"),d=n("./trees"),c=n("./adler32"),p=n("./crc32"),v=n("./messages"),_=0,T=4,M=0,I=-2,C=-1,E=4,x=2,k=8,A=9,N=286,R=30,B=19,W=2*N+1,j=15,ae=3,ve=258,Ne=ve+ae+1,oe=42,Se=113,G=1,Ce=2,gt=3,Me=4;function te(z,Fe){return z.msg=v[Fe],Fe}function fe(z){return(z<<1)-(4z.avail_out&&(Re=z.avail_out),Re!==0&&(l.arraySet(z.output,Fe.pending_buf,Fe.pending_out,Re,z.next_out),z.next_out+=Re,Fe.pending_out+=Re,z.total_out+=Re,z.avail_out-=Re,Fe.pending-=Re,Fe.pending===0&&(Fe.pending_out=0))}function xe(z,Fe){d._tr_flush_block(z,0<=z.block_start?z.block_start:-1,z.strstart-z.block_start,Fe),z.block_start=z.strstart,ne(z.strm)}function pt(z,Fe){z.pending_buf[z.pending++]=Fe}function Ye(z,Fe){z.pending_buf[z.pending++]=Fe>>>8&255,z.pending_buf[z.pending++]=255&Fe}function et(z,Fe){var Re,he,ue=z.max_chain_length,Ee=z.strstart,q=z.prev_length,re=z.nice_match,V=z.strstart>z.w_size-Ne?z.strstart-(z.w_size-Ne):0,me=z.window,ge=z.w_mask,$e=z.prev,Ze=z.strstart+ve,Dt=me[Ee+q-1],Tt=me[Ee+q];z.prev_length>=z.good_match&&(ue>>=2),re>z.lookahead&&(re=z.lookahead);do if(me[(Re=Fe)+q]===Tt&&me[Re+q-1]===Dt&&me[Re]===me[Ee]&&me[++Re]===me[Ee+1]){Ee+=2,Re++;do;while(me[++Ee]===me[++Re]&&me[++Ee]===me[++Re]&&me[++Ee]===me[++Re]&&me[++Ee]===me[++Re]&&me[++Ee]===me[++Re]&&me[++Ee]===me[++Re]&&me[++Ee]===me[++Re]&&me[++Ee]===me[++Re]&&EeV&&--ue!=0);return q<=z.lookahead?q:z.lookahead}function ct(z){var Fe,Re,he,ue,Ee,q,re,V,me,ge,$e=z.w_size;do{if(ue=z.window_size-z.lookahead-z.strstart,z.strstart>=$e+($e-Ne)){for(l.arraySet(z.window,z.window,$e,$e,0),z.match_start-=$e,z.strstart-=$e,z.block_start-=$e,Fe=Re=z.hash_size;he=z.head[--Fe],z.head[Fe]=$e<=he?he-$e:0,--Re;);for(Fe=Re=$e;he=z.prev[--Fe],z.prev[Fe]=$e<=he?he-$e:0,--Re;);ue+=$e}if(z.strm.avail_in===0)break;if(q=z.strm,re=z.window,V=z.strstart+z.lookahead,me=ue,ge=void 0,ge=q.avail_in,me=ae)for(Ee=z.strstart-z.insert,z.ins_h=z.window[Ee],z.ins_h=(z.ins_h<=ae&&(z.ins_h=(z.ins_h<=ae)if(he=d._tr_tally(z,z.strstart-z.match_start,z.match_length-ae),z.lookahead-=z.match_length,z.match_length<=z.max_lazy_match&&z.lookahead>=ae){for(z.match_length--;z.strstart++,z.ins_h=(z.ins_h<=ae&&(z.ins_h=(z.ins_h<=ae&&z.match_length<=z.prev_length){for(ue=z.strstart+z.lookahead-ae,he=d._tr_tally(z,z.strstart-1-z.prev_match,z.prev_length-ae),z.lookahead-=z.prev_length-1,z.prev_length-=2;++z.strstart<=ue&&(z.ins_h=(z.ins_h<z.pending_buf_size-5&&(Re=z.pending_buf_size-5);;){if(z.lookahead<=1){if(ct(z),z.lookahead===0&&Fe===_)return G;if(z.lookahead===0)break}z.strstart+=z.lookahead,z.lookahead=0;var he=z.block_start+Re;if((z.strstart===0||z.strstart>=he)&&(z.lookahead=z.strstart-he,z.strstart=he,xe(z,!1),z.strm.avail_out===0)||z.strstart-z.block_start>=z.w_size-Ne&&(xe(z,!1),z.strm.avail_out===0))return G}return z.insert=0,Fe===T?(xe(z,!0),z.strm.avail_out===0?gt:Me):(z.strstart>z.block_start&&(xe(z,!1),z.strm.avail_out),G)}),new je(4,4,8,4,Et),new je(4,5,16,8,Et),new je(4,6,32,32,Et),new je(4,4,16,16,Rt),new je(8,16,32,32,Rt),new je(8,16,128,128,Rt),new je(8,32,128,256,Rt),new je(32,128,258,1024,Rt),new je(32,258,258,4096,Rt)],o.deflateInit=function(z,Fe){return xt(z,Fe,k,15,8,0)},o.deflateInit2=xt,o.deflateReset=dt,o.deflateResetKeep=rt,o.deflateSetHeader=function(z,Fe){return z&&z.state?z.state.wrap!==2?I:(z.state.gzhead=Fe,M):I},o.deflate=function(z,Fe){var Re,he,ue,Ee;if(!z||!z.state||5>8&255),pt(he,he.gzhead.time>>16&255),pt(he,he.gzhead.time>>24&255),pt(he,he.level===9?2:2<=he.strategy||he.level<2?4:0),pt(he,255&he.gzhead.os),he.gzhead.extra&&he.gzhead.extra.length&&(pt(he,255&he.gzhead.extra.length),pt(he,he.gzhead.extra.length>>8&255)),he.gzhead.hcrc&&(z.adler=p(z.adler,he.pending_buf,he.pending,0)),he.gzindex=0,he.status=69):(pt(he,0),pt(he,0),pt(he,0),pt(he,0),pt(he,0),pt(he,he.level===9?2:2<=he.strategy||he.level<2?4:0),pt(he,3),he.status=Se);else{var q=k+(he.w_bits-8<<4)<<8;q|=(2<=he.strategy||he.level<2?0:he.level<6?1:he.level===6?2:3)<<6,he.strstart!==0&&(q|=32),q+=31-q%31,he.status=Se,Ye(he,q),he.strstart!==0&&(Ye(he,z.adler>>>16),Ye(he,65535&z.adler)),z.adler=1}if(he.status===69)if(he.gzhead.extra){for(ue=he.pending;he.gzindex<(65535&he.gzhead.extra.length)&&(he.pending!==he.pending_buf_size||(he.gzhead.hcrc&&he.pending>ue&&(z.adler=p(z.adler,he.pending_buf,he.pending-ue,ue)),ne(z),ue=he.pending,he.pending!==he.pending_buf_size));)pt(he,255&he.gzhead.extra[he.gzindex]),he.gzindex++;he.gzhead.hcrc&&he.pending>ue&&(z.adler=p(z.adler,he.pending_buf,he.pending-ue,ue)),he.gzindex===he.gzhead.extra.length&&(he.gzindex=0,he.status=73)}else he.status=73;if(he.status===73)if(he.gzhead.name){ue=he.pending;do{if(he.pending===he.pending_buf_size&&(he.gzhead.hcrc&&he.pending>ue&&(z.adler=p(z.adler,he.pending_buf,he.pending-ue,ue)),ne(z),ue=he.pending,he.pending===he.pending_buf_size)){Ee=1;break}Ee=he.gzindexue&&(z.adler=p(z.adler,he.pending_buf,he.pending-ue,ue)),Ee===0&&(he.gzindex=0,he.status=91)}else he.status=91;if(he.status===91)if(he.gzhead.comment){ue=he.pending;do{if(he.pending===he.pending_buf_size&&(he.gzhead.hcrc&&he.pending>ue&&(z.adler=p(z.adler,he.pending_buf,he.pending-ue,ue)),ne(z),ue=he.pending,he.pending===he.pending_buf_size)){Ee=1;break}Ee=he.gzindexue&&(z.adler=p(z.adler,he.pending_buf,he.pending-ue,ue)),Ee===0&&(he.status=103)}else he.status=103;if(he.status===103&&(he.gzhead.hcrc?(he.pending+2>he.pending_buf_size&&ne(z),he.pending+2<=he.pending_buf_size&&(pt(he,255&z.adler),pt(he,z.adler>>8&255),z.adler=0,he.status=Se)):he.status=Se),he.pending!==0){if(ne(z),z.avail_out===0)return he.last_flush=-1,M}else if(z.avail_in===0&&fe(Fe)<=fe(Re)&&Fe!==T)return te(z,-5);if(he.status===666&&z.avail_in!==0)return te(z,-5);if(z.avail_in!==0||he.lookahead!==0||Fe!==_&&he.status!==666){var re=he.strategy===2?function(V,me){for(var ge;;){if(V.lookahead===0&&(ct(V),V.lookahead===0)){if(me===_)return G;break}if(V.match_length=0,ge=d._tr_tally(V,0,V.window[V.strstart]),V.lookahead--,V.strstart++,ge&&(xe(V,!1),V.strm.avail_out===0))return G}return V.insert=0,me===T?(xe(V,!0),V.strm.avail_out===0?gt:Me):V.last_lit&&(xe(V,!1),V.strm.avail_out===0)?G:Ce}(he,Fe):he.strategy===3?function(V,me){for(var ge,$e,Ze,Dt,Tt=V.window;;){if(V.lookahead<=ve){if(ct(V),V.lookahead<=ve&&me===_)return G;if(V.lookahead===0)break}if(V.match_length=0,V.lookahead>=ae&&0V.lookahead&&(V.match_length=V.lookahead)}if(V.match_length>=ae?(ge=d._tr_tally(V,1,V.match_length-ae),V.lookahead-=V.match_length,V.strstart+=V.match_length,V.match_length=0):(ge=d._tr_tally(V,0,V.window[V.strstart]),V.lookahead--,V.strstart++),ge&&(xe(V,!1),V.strm.avail_out===0))return G}return V.insert=0,me===T?(xe(V,!0),V.strm.avail_out===0?gt:Me):V.last_lit&&(xe(V,!1),V.strm.avail_out===0)?G:Ce}(he,Fe):a[he.level].func(he,Fe);if(re!==gt&&re!==Me||(he.status=666),re===G||re===gt)return z.avail_out===0&&(he.last_flush=-1),M;if(re===Ce&&(Fe===1?d._tr_align(he):Fe!==5&&(d._tr_stored_block(he,0,0,!1),Fe===3&&(Ae(he.head),he.lookahead===0&&(he.strstart=0,he.block_start=0,he.insert=0))),ne(z),z.avail_out===0))return he.last_flush=-1,M}return Fe!==T?M:he.wrap<=0?1:(he.wrap===2?(pt(he,255&z.adler),pt(he,z.adler>>8&255),pt(he,z.adler>>16&255),pt(he,z.adler>>24&255),pt(he,255&z.total_in),pt(he,z.total_in>>8&255),pt(he,z.total_in>>16&255),pt(he,z.total_in>>24&255)):(Ye(he,z.adler>>>16),Ye(he,65535&z.adler)),ne(z),0=Re.w_size&&(Ee===0&&(Ae(Re.head),Re.strstart=0,Re.block_start=0,Re.insert=0),me=new l.Buf8(Re.w_size),l.arraySet(me,Fe,ge-Re.w_size,Re.w_size,0),Fe=me,ge=Re.w_size),q=z.avail_in,re=z.next_in,V=z.input,z.avail_in=ge,z.next_in=0,z.input=Fe,ct(Re);Re.lookahead>=ae;){for(he=Re.strstart,ue=Re.lookahead-(ae-1);Re.ins_h=(Re.ins_h<>>=ae=j>>>24,A-=ae,(ae=j>>>16&255)===0)Ce[v++]=65535&j;else{if(!(16&ae)){if(!(64&ae)){j=N[(65535&j)+(k&(1<>>=ae,A-=ae),A<15&&(k+=G[c++]<>>=ae=j>>>24,A-=ae,!(16&(ae=j>>>16&255))){if(!(64&ae)){j=R[(65535&j)+(k&(1<>>=ae,A-=ae,(ae=v-_)>3,k&=(1<<(A-=ve<<3))-1,a.next_in=c,a.next_out=v,a.avail_in=c>>24&255)+(oe>>>8&65280)+((65280&oe)<<8)+((255&oe)<<24)}function k(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new a.Buf16(320),this.work=new a.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function A(oe){var Se;return oe&&oe.state?(Se=oe.state,oe.total_in=oe.total_out=Se.total=0,oe.msg="",Se.wrap&&(oe.adler=1&Se.wrap),Se.mode=I,Se.last=0,Se.havedict=0,Se.dmax=32768,Se.head=null,Se.hold=0,Se.bits=0,Se.lencode=Se.lendyn=new a.Buf32(C),Se.distcode=Se.distdyn=new a.Buf32(E),Se.sane=1,Se.back=-1,T):M}function N(oe){var Se;return oe&&oe.state?((Se=oe.state).wsize=0,Se.whave=0,Se.wnext=0,A(oe)):M}function R(oe,Se){var G,Ce;return oe&&oe.state?(Ce=oe.state,Se<0?(G=0,Se=-Se):(G=1+(Se>>4),Se<48&&(Se&=15)),Se&&(Se<8||15=Me.wsize?(a.arraySet(Me.window,Se,G-Me.wsize,Me.wsize,0),Me.wnext=0,Me.whave=Me.wsize):(Ce<(gt=Me.wsize-Me.wnext)&&(gt=Ce),a.arraySet(Me.window,Se,G-Ce,gt,Me.wnext),(Ce-=gt)?(a.arraySet(Me.window,Se,G-Ce,Ce,0),Me.wnext=Ce,Me.whave=Me.wsize):(Me.wnext+=gt,Me.wnext===Me.wsize&&(Me.wnext=0),Me.whave>>8&255,G.check=d(G.check,Ee,2,0),xe=ne=0,G.mode=2;break}if(G.flags=0,G.head&&(G.head.done=!1),!(1&G.wrap)||(((255&ne)<<8)+(ne>>8))%31){oe.msg="incorrect header check",G.mode=30;break}if((15&ne)!=8){oe.msg="unknown compression method",G.mode=30;break}if(xe-=4,z=8+(15&(ne>>>=4)),G.wbits===0)G.wbits=z;else if(z>G.wbits){oe.msg="invalid window size",G.mode=30;break}G.dmax=1<>8&1),512&G.flags&&(Ee[0]=255&ne,Ee[1]=ne>>>8&255,G.check=d(G.check,Ee,2,0)),xe=ne=0,G.mode=3;case 3:for(;xe<32;){if(fe===0)break e;fe--,ne+=Ce[Me++]<>>8&255,Ee[2]=ne>>>16&255,Ee[3]=ne>>>24&255,G.check=d(G.check,Ee,4,0)),xe=ne=0,G.mode=4;case 4:for(;xe<16;){if(fe===0)break e;fe--,ne+=Ce[Me++]<>8),512&G.flags&&(Ee[0]=255&ne,Ee[1]=ne>>>8&255,G.check=d(G.check,Ee,2,0)),xe=ne=0,G.mode=5;case 5:if(1024&G.flags){for(;xe<16;){if(fe===0)break e;fe--,ne+=Ce[Me++]<>>8&255,G.check=d(G.check,Ee,2,0)),xe=ne=0}else G.head&&(G.head.extra=null);G.mode=6;case 6:if(1024&G.flags&&(fe<(et=G.length)&&(et=fe),et&&(G.head&&(z=G.head.extra_len-G.length,G.head.extra||(G.head.extra=new Array(G.head.extra_len)),a.arraySet(G.head.extra,Ce,Me,et,z)),512&G.flags&&(G.check=d(G.check,Ce,et,Me)),fe-=et,Me+=et,G.length-=et),G.length))break e;G.length=0,G.mode=7;case 7:if(2048&G.flags){if(fe===0)break e;for(et=0;z=Ce[Me+et++],G.head&&z&&G.length<65536&&(G.head.name+=String.fromCharCode(z)),z&&et>9&1,G.head.done=!0),oe.adler=G.check=0,G.mode=12;break;case 10:for(;xe<32;){if(fe===0)break e;fe--,ne+=Ce[Me++]<>>=7&xe,xe-=7&xe,G.mode=27;break}for(;xe<3;){if(fe===0)break e;fe--,ne+=Ce[Me++]<>>=1)){case 0:G.mode=14;break;case 1:if(ve(G),G.mode=20,Se!==6)break;ne>>>=2,xe-=2;break e;case 2:G.mode=17;break;case 3:oe.msg="invalid block type",G.mode=30}ne>>>=2,xe-=2;break;case 14:for(ne>>>=7&xe,xe-=7&xe;xe<32;){if(fe===0)break e;fe--,ne+=Ce[Me++]<>>16^65535)){oe.msg="invalid stored block lengths",G.mode=30;break}if(G.length=65535&ne,xe=ne=0,G.mode=15,Se===6)break e;case 15:G.mode=16;case 16:if(et=G.length){if(fe>>=5,xe-=5,G.ndist=1+(31&ne),ne>>>=5,xe-=5,G.ncode=4+(15&ne),ne>>>=4,xe-=4,286>>=3,xe-=3}for(;G.have<19;)G.lens[q[G.have++]]=0;if(G.lencode=G.lendyn,G.lenbits=7,Re={bits:G.lenbits},Fe=p(0,G.lens,0,19,G.lencode,0,G.work,Re),G.lenbits=Re.bits,Fe){oe.msg="invalid code lengths set",G.mode=30;break}G.have=0,G.mode=19;case 19:for(;G.have>>16&255,Ie=65535&ue,!((Rt=ue>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Me++]<>>=Rt,xe-=Rt,G.lens[G.have++]=Ie;else{if(Ie===16){for(he=Rt+2;xe>>=Rt,xe-=Rt,G.have===0){oe.msg="invalid bit length repeat",G.mode=30;break}z=G.lens[G.have-1],et=3+(3&ne),ne>>>=2,xe-=2}else if(Ie===17){for(he=Rt+3;xe>>=Rt)),ne>>>=3,xe-=3}else{for(he=Rt+7;xe>>=Rt)),ne>>>=7,xe-=7}if(G.have+et>G.nlen+G.ndist){oe.msg="invalid bit length repeat",G.mode=30;break}for(;et--;)G.lens[G.have++]=z}}if(G.mode===30)break;if(G.lens[256]===0){oe.msg="invalid code -- missing end-of-block",G.mode=30;break}if(G.lenbits=9,Re={bits:G.lenbits},Fe=p(v,G.lens,0,G.nlen,G.lencode,0,G.work,Re),G.lenbits=Re.bits,Fe){oe.msg="invalid literal/lengths set",G.mode=30;break}if(G.distbits=6,G.distcode=G.distdyn,Re={bits:G.distbits},Fe=p(_,G.lens,G.nlen,G.ndist,G.distcode,0,G.work,Re),G.distbits=Re.bits,Fe){oe.msg="invalid distances set",G.mode=30;break}if(G.mode=20,Se===6)break e;case 20:G.mode=21;case 21:if(6<=fe&&258<=Ae){oe.next_out=te,oe.avail_out=Ae,oe.next_in=Me,oe.avail_in=fe,G.hold=ne,G.bits=xe,c(oe,Ye),te=oe.next_out,gt=oe.output,Ae=oe.avail_out,Me=oe.next_in,Ce=oe.input,fe=oe.avail_in,ne=G.hold,xe=G.bits,G.mode===12&&(G.back=-1);break}for(G.back=0;je=(ue=G.lencode[ne&(1<>>16&255,Ie=65535&ue,!((Rt=ue>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Me++]<>rt)])>>>16&255,Ie=65535&ue,!(rt+(Rt=ue>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Me++]<>>=rt,xe-=rt,G.back+=rt}if(ne>>>=Rt,xe-=Rt,G.back+=Rt,G.length=Ie,je===0){G.mode=26;break}if(32&je){G.back=-1,G.mode=12;break}if(64&je){oe.msg="invalid literal/length code",G.mode=30;break}G.extra=15&je,G.mode=22;case 22:if(G.extra){for(he=G.extra;xe>>=G.extra,xe-=G.extra,G.back+=G.extra}G.was=G.length,G.mode=23;case 23:for(;je=(ue=G.distcode[ne&(1<>>16&255,Ie=65535&ue,!((Rt=ue>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Me++]<>rt)])>>>16&255,Ie=65535&ue,!(rt+(Rt=ue>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Me++]<>>=rt,xe-=rt,G.back+=rt}if(ne>>>=Rt,xe-=Rt,G.back+=Rt,64&je){oe.msg="invalid distance code",G.mode=30;break}G.offset=Ie,G.extra=15&je,G.mode=24;case 24:if(G.extra){for(he=G.extra;xe>>=G.extra,xe-=G.extra,G.back+=G.extra}if(G.offset>G.dmax){oe.msg="invalid distance too far back",G.mode=30;break}G.mode=25;case 25:if(Ae===0)break e;if(et=Ye-Ae,G.offset>et){if((et=G.offset-et)>G.whave&&G.sane){oe.msg="invalid distance too far back",G.mode=30;break}ct=et>G.wnext?(et-=G.wnext,G.wsize-et):G.wnext-et,et>G.length&&(et=G.length),Et=G.window}else Et=gt,ct=te-G.offset,et=G.length;for(AeW?(ae=ct[Et+E[Se]],xe[pt+E[Se]]):(ae=96,0),k=1<>te)+(A-=k)]=j<<24|ae<<16|ve|0,A!==0;);for(k=1<>=1;if(k!==0?(ne&=k-1,ne+=k):ne=0,Se++,--Ye[oe]==0){if(oe===Ce)break;oe=_[T+E[Se]]}if(gt>>7)]}function pt(ue,Ee){ue.pending_buf[ue.pending++]=255&Ee,ue.pending_buf[ue.pending++]=Ee>>>8&255}function Ye(ue,Ee,q){ue.bi_valid>x-q?(ue.bi_buf|=Ee<>x-ue.bi_valid,ue.bi_valid+=q-x):(ue.bi_buf|=Ee<>>=1,q<<=1,0<--Ee;);return q>>>1}function Et(ue,Ee,q){var re,V,me=new Array(E+1),ge=0;for(re=1;re<=E;re++)me[re]=ge=ge+q[re-1]<<1;for(V=0;V<=Ee;V++){var $e=ue[2*V+1];$e!==0&&(ue[2*V]=ct(me[$e]++,$e))}}function Rt(ue){var Ee;for(Ee=0;Ee>1;1<=q;q--)rt(ue,me,q);for(V=Ze;q=ue.heap[1],ue.heap[1]=ue.heap[ue.heap_len--],rt(ue,me,1),re=ue.heap[1],ue.heap[--ue.heap_max]=q,ue.heap[--ue.heap_max]=re,me[2*V]=me[2*q]+me[2*re],ue.depth[V]=(ue.depth[q]>=ue.depth[re]?ue.depth[q]:ue.depth[re])+1,me[2*q+1]=me[2*re+1]=V,ue.heap[1]=V++,rt(ue,me,1),2<=ue.heap_len;);ue.heap[--ue.heap_max]=ue.heap[1],function(Tt,Nt){var jt,ht,_e,Be,st,Je,_t=Nt.dyn_tree,$t=Nt.max_code,Wt=Nt.stat_desc.static_tree,ot=Nt.stat_desc.has_stree,nn=Nt.stat_desc.extra_bits,Gt=Nt.stat_desc.extra_base,Mt=Nt.stat_desc.max_length,mn=0;for(Be=0;Be<=E;Be++)Tt.bl_count[Be]=0;for(_t[2*Tt.heap[Tt.heap_max]+1]=0,jt=Tt.heap_max+1;jt>=7;V>>=1)if(1&Dt&&$e.dyn_ltree[2*Ze]!==0)return l;if($e.dyn_ltree[18]!==0||$e.dyn_ltree[20]!==0||$e.dyn_ltree[26]!==0)return d;for(Ze=32;Ze<_;Ze++)if($e.dyn_ltree[2*Ze]!==0)return d;return l}(ue)),xt(ue,ue.l_desc),xt(ue,ue.d_desc),ge=function($e){var Ze;for(z($e,$e.dyn_ltree,$e.l_desc.max_code),z($e,$e.dyn_dtree,$e.d_desc.max_code),xt($e,$e.bl_desc),Ze=I-1;3<=Ze&&$e.bl_tree[2*ve[Ze]+1]===0;Ze--);return $e.opt_len+=3*(Ze+1)+5+5+4,Ze}(ue),V=ue.opt_len+3+7>>>3,(me=ue.static_len+3+7>>>3)<=V&&(V=me)):V=me=q+5,q+4<=V&&Ee!==-1?he(ue,Ee,q,re):ue.strategy===4||me===V?(Ye(ue,2+(re?1:0),3),dt(ue,Ne,oe)):(Ye(ue,4+(re?1:0),3),function($e,Ze,Dt,Tt){var Nt;for(Ye($e,Ze-257,5),Ye($e,Dt-1,5),Ye($e,Tt-4,4),Nt=0;Nt>>8&255,ue.pending_buf[ue.d_buf+2*ue.last_lit+1]=255&Ee,ue.pending_buf[ue.l_buf+ue.last_lit]=255&q,ue.last_lit++,Ee===0?ue.dyn_ltree[2*q]++:(ue.matches++,Ee--,ue.dyn_ltree[2*(G[q]+_+1)]++,ue.dyn_dtree[2*xe(Ee)]++),ue.last_lit===ue.lit_bufsize-1},o._tr_align=function(ue){Ye(ue,2,3),et(ue,A,Ne),function(Ee){Ee.bi_valid===16?(pt(Ee,Ee.bi_buf),Ee.bi_buf=0,Ee.bi_valid=0):8<=Ee.bi_valid&&(Ee.pending_buf[Ee.pending++]=255&Ee.bi_buf,Ee.bi_buf>>=8,Ee.bi_valid-=8)}(ue)}},{"../utils/common":41}],53:[function(n,i,o){i.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,i,o){(function(a){(function(l,d){if(!l.setImmediate){var c,p,v,_,T=1,M={},I=!1,C=l.document,E=Object.getPrototypeOf&&Object.getPrototypeOf(l);E=E&&E.setTimeout?E:l,c={}.toString.call(l.process)==="[object process]"?function(N){process.nextTick(function(){k(N)})}:function(){if(l.postMessage&&!l.importScripts){var N=!0,R=l.onmessage;return l.onmessage=function(){N=!1},l.postMessage("","*"),l.onmessage=R,N}}()?(_="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",A,!1):l.attachEvent("onmessage",A),function(N){l.postMessage(_+N,"*")}):l.MessageChannel?((v=new MessageChannel).port1.onmessage=function(N){k(N.data)},function(N){v.port2.postMessage(N)}):C&&"onreadystatechange"in C.createElement("script")?(p=C.documentElement,function(N){var R=C.createElement("script");R.onreadystatechange=function(){k(N),R.onreadystatechange=null,p.removeChild(R),R=null},p.appendChild(R)}):function(N){setTimeout(k,0,N)},E.setImmediate=function(N){typeof N!="function"&&(N=new Function(""+N));for(var R=new Array(arguments.length-1),B=0;B"u"?a===void 0?this:a:self)}).call(this,typeof Co<"u"?Co:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(vS);var u3=vS.exports;const wS=Og(u3);var bS={exports:{}};(function(e,t){(function(n,i){i()})(Co,function(){function n(p,v){return typeof v>"u"?v={autoBom:!1}:typeof v!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),v={autoBom:!v}),v.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(p.type)?new Blob(["\uFEFF",p],{type:p.type}):p}function i(p,v,_){var T=new XMLHttpRequest;T.open("GET",p),T.responseType="blob",T.onload=function(){c(T.response,v,_)},T.onerror=function(){console.error("could not download file")},T.send()}function o(p){var v=new XMLHttpRequest;v.open("HEAD",p,!1);try{v.send()}catch{}return 200<=v.status&&299>=v.status}function a(p){try{p.dispatchEvent(new MouseEvent("click"))}catch{var v=document.createEvent("MouseEvents");v.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),p.dispatchEvent(v)}}var l=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof Co=="object"&&Co.global===Co?Co:void 0,d=l.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),c=l.saveAs||(typeof window!="object"||window!==l?function(){}:"download"in HTMLAnchorElement.prototype&&!d?function(p,v,_){var T=l.URL||l.webkitURL,M=document.createElement("a");v=v||p.name||"download",M.download=v,M.rel="noopener",typeof p=="string"?(M.href=p,M.origin===location.origin?a(M):o(M.href)?i(p,v,_):a(M,M.target="_blank")):(M.href=T.createObjectURL(p),setTimeout(function(){T.revokeObjectURL(M.href)},4e4),setTimeout(function(){a(M)},0))}:"msSaveOrOpenBlob"in navigator?function(p,v,_){if(v=v||p.name||"download",typeof p!="string")navigator.msSaveOrOpenBlob(n(p,_),v);else if(o(p))i(p,v,_);else{var T=document.createElement("a");T.href=p,T.target="_blank",setTimeout(function(){a(T)})}}:function(p,v,_,T){if(T=T||open("","_blank"),T&&(T.document.title=T.document.body.innerText="downloading..."),typeof p=="string")return i(p,v,_);var M=p.type==="application/octet-stream",I=/constructor/i.test(l.HTMLElement)||l.safari,C=/CriOS\/[\d]+/.test(navigator.userAgent);if((C||M&&I||d)&&typeof FileReader<"u"){var E=new FileReader;E.onloadend=function(){var A=E.result;A=C?A:A.replace(/^data:[^;]*;/,"data:attachment/file;"),T?T.location.href=A:location=A,T=null},E.readAsDataURL(p)}else{var x=l.URL||l.webkitURL,k=x.createObjectURL(p);T?T.location=k:location.href=k,T=null,setTimeout(function(){x.revokeObjectURL(k)},4e4)}});l.saveAs=c.saveAs=c,e.exports=c})})(bS);var xS=bS.exports,TS={exports:{}};(function(e,t){(function(n,i){e.exports=i()})(Co,function(){var n=function(h,y){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function($,U){$.__proto__=U}||function($,U){for(var Z in U)Object.prototype.hasOwnProperty.call(U,Z)&&($[Z]=U[Z])})(h,y)},i=function(){return(i=Object.assign||function(h){for(var y,$=1,U=arguments.length;$"u"||a.Promise||(a.Promise=Promise);var p=Object.getPrototypeOf,v={}.hasOwnProperty;function _(h,y){return v.call(h,y)}function T(h,y){typeof y=="function"&&(y=y(p(h))),(typeof Reflect>"u"?l:Reflect.ownKeys)(y).forEach(function($){I(h,$,y[$])})}var M=Object.defineProperty;function I(h,y,$,U){M(h,y,c($&&_($,"get")&&typeof $.get=="function"?{get:$.get,set:$.set,configurable:!0}:{value:$,configurable:!0,writable:!0},U))}function C(h){return{from:function(y){return h.prototype=Object.create(y.prototype),I(h.prototype,"constructor",h),{extend:T.bind(null,h.prototype)}}}}var E=Object.getOwnPropertyDescriptor,x=[].slice;function k(h,y,$){return x.call(h,y,$)}function A(h,y){return y(h)}function N(h){if(!h)throw new Error("Assertion Failed")}function R(h){a.setImmediate?setImmediate(h):setTimeout(h,0)}function B(h,y){if(typeof y=="string"&&_(h,y))return h[y];if(!y)return h;if(typeof y!="string"){for(var $=[],U=0,Z=y.length;U"u"?[]:function(){var h=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[h,p(h),h];var y=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[y,p(y),h]}(),$e=Ve[0],xi=Ve[1],Ve=Ve[2],xi=xi&&xi.then,Ze=$e&&$e.constructor,Dt=!!Ve,Tt=function(h,y){_t.push([h,y]),jt&&(queueMicrotask(Tn),jt=!1)},Nt=!0,jt=!0,ht=[],_e=[],Be=xt,st={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:dt,pgp:!1,env:{},finalize:dt},Je=st,_t=[],$t=0,Wt=[];function ot(h){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var y=this._PSD=Je;if(typeof h!="function"){if(h!==me)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&Mt(this,this._value))}this._state=null,this._value=null,++y.ref,function $(U,Z){try{Z(function(le){if(U._state===null){if(le===U)throw new TypeError("A promise cannot be resolved with itself.");var Te=U._lib&&yn();le&&typeof le.then=="function"?$(U,function(Le,Qe){le instanceof ot?le._then(Le,Qe):le.then(Le,Qe)}):(U._state=!0,U._value=le,mn(U)),Te&&En()}},Mt.bind(null,U))}catch(le){Mt(U,le)}}(this,h)}var nn={get:function(){var h=Je,y=Ci;function $(U,Z){var le=this,Te=!h.global&&(h!==Je||y!==Ci),Le=Te&&!yr(),Qe=new ot(function(qe,at){hn(le,new Gt(fo(U,h,Te,Le),fo(Z,h,Te,Le),qe,at,h))});return this._consoleTask&&(Qe._consoleTask=this._consoleTask),Qe}return $.prototype=me,$},set:function(h){I(this,"then",h&&h.prototype===me?nn:{get:function(){return h},set:nn.set})}};function Gt(h,y,$,U,Z){this.onFulfilled=typeof h=="function"?h:null,this.onRejected=typeof y=="function"?y:null,this.resolve=$,this.reject=U,this.psd=Z}function Mt(h,y){var $,U;_e.push(y),h._state===null&&($=h._lib&&yn(),y=Be(y),h._state=!1,h._value=y,U=h,ht.some(function(Z){return Z._value===U._value})||ht.push(U),mn(h),$&&En())}function mn(h){var y=h._listeners;h._listeners=[];for(var $=0,U=y.length;$.",Io="String expected.",es=[],Ai="__dbnames",hs="readonly",ts="readwrite";function $i(h,y){return h?y?function(){return h.apply(this,arguments)&&y.apply(this,arguments)}:h:y}var Qs={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Ts(h){return typeof h!="string"||/\./.test(h)?function(y){return y}:function(y){return y[h]===void 0&&h in y&&delete(y=Se(y))[h],y}}function Pn(){throw je.Type()}function Zn(h,y){try{var $=ho(h),U=ho(y);if($!==U)return $==="Array"?1:U==="Array"?-1:$==="binary"?1:U==="binary"?-1:$==="string"?1:U==="string"?-1:$==="Date"?1:U!=="Date"?NaN:-1;switch($){case"number":case"Date":case"string":return ybt+vt&&yt(bt+lt)})})}var wt=ms($)&&$.limit===1/0&&(typeof h!="function"||h===Jt)&&{index:$.index,range:$.range};return yt(0).then(function(){if(0=lt})).length!==0?(at.forEach(function(yt){ut.push(function(){var wt=tt,bt=yt._cfg.dbschema;zo(Ue,wt,nt),zo(Ue,bt,nt),tt=Ue._dbSchema=bt;var vt=ca(wt,bt);vt.add.forEach(function(ln){Oo(nt,ln[0],ln[1].primKey,ln[1].indexes)}),vt.change.forEach(function(ln){if(ln.recreate)throw new je.Upgrade("Not yet support for changing primary key");var qt=nt.objectStore(ln.name);ln.add.forEach(function(Un){return Do(qt,Un)}),ln.change.forEach(function(Un){qt.deleteIndex(Un.name),Do(qt,Un)}),ln.del.forEach(function(Un){return qt.deleteIndex(Un)})});var Xt=yt._cfg.contentUpgrade;if(Xt&&yt._cfg.version>lt){vn(Ue,nt),Xe._memoizedTables={};var on=j(bt);vt.del.forEach(function(ln){on[ln]=wt[ln]}),Fo(Ue,[Ue.Transaction.prototype]),mo(Ue,[Ue.Transaction.prototype],l(on),on),Xe.schema=on;var Kt,rn=ne(Xt);return rn&&Nr(),vt=ot.follow(function(){var ln;(Kt=Xt(Xe))&&rn&&(ln=yr.bind(null,null),Kt.then(ln,ln))}),Kt&&typeof Kt.then=="function"?ot.resolve(Kt):vt.then(function(){return Kt})}}),ut.push(function(wt){var bt,vt,Xt=yt._cfg.dbschema;bt=Xt,vt=wt,[].slice.call(vt.db.objectStoreNames).forEach(function(on){return bt[on]==null&&vt.db.deleteObjectStore(on)}),Fo(Ue,[Ue.Transaction.prototype]),mo(Ue,[Ue.Transaction.prototype],Ue._storeNames,Ue._dbSchema),Xe.schema=Ue._dbSchema}),ut.push(function(wt){Ue.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(Ue.idbdb.version/10)===yt._cfg.version?(Ue.idbdb.deleteObjectStore("$meta"),delete Ue._dbSchema.$meta,Ue._storeNames=Ue._storeNames.filter(function(bt){return bt!=="$meta"})):wt.objectStore("$meta").put(yt._cfg.version,"version"))})}),function yt(){return ut.length?ot.resolve(ut.shift()(Xe.idbtrans)).then(yt):ot.resolve()}().then(function(){_o(tt,nt)})):ot.resolve();var Ue,lt,Xe,nt,ut,tt}).catch(Te)):(l(Z).forEach(function(at){Oo($,at,Z[at].primKey,Z[at].indexes)}),vn(h,$),void ot.follow(function(){return h.on.populate.fire(le)}).catch(Te));var Qe,qe})}function Vn(h,y){_o(h._dbSchema,y),y.db.version%10!=0||y.objectStoreNames.contains("$meta")||y.db.createObjectStore("$meta").add(Math.ceil(y.db.version/10-1),"version");var $=Oi(0,h.idbdb,y);zo(h,h._dbSchema,y);for(var U=0,Z=ca($,h._dbSchema).change;UMath.pow(2,62)?0:tt.oldVersion,Ue=tt<1,h.idbdb=ut.result,le&&Vn(h,at),go(h,tt/10,at,Xe))},Xe),ut.onsuccess=kn(function(){at=null;var tt,yt,wt,bt,vt,Xt=h.idbdb=ut.result,on=k(Xt.objectStoreNames);if(0"u"?ot.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(lt){function Xe(){return indexedDB.databases().finally(lt)}Qe=setInterval(Xe,100),Xe()}).finally(function(){return clearInterval(Qe)}):Promise.resolve()).then(Le)]).then(function(){return Te(),y.onReadyBeingFired=[],ot.resolve(pa(function(){return h.on.ready.fire(h.vip)})).then(function lt(){if(0y.limit?lt.length=y.limit:h.length===y.limit&<.length=yt.limit&&(!yt.values||Xt.req.values)&&Vl(Xt.req.query.range,yt.query.range)}),!1,wt,bt];case"count":return vt=bt.find(function(Xt){return tl(Xt.req.query.range,yt.query.range)}),[vt,!!vt,wt,bt]}}(y,$,"query",le),at=qe[0],Ue=qe[1],lt=qe[2],Xe=qe[3];return at&&Ue?at.obsSet=le.obsSet:(Ue=U.query(le).then(function(nt){var ut=nt.result;if(at&&(at.res=ut),Te){for(var tt=0,yt=ut.length;tt=0)&&Object.prototype.propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}function g3(e,t){if(e==null)return{};var n={};for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){if(t.indexOf(i)>=0)continue;n[i]=e[i]}return n}function Sg(){return Sg=Object.assign?Object.assign.bind():function(e){for(var t=1;tVs.createElement(t.tag,Eg({key:n},t.attr),kS(t.child)))}function la(e){return t=>Vs.createElement(w3,Sg({attr:Eg({},e.attr)},t),kS(e.child))}function w3(e){var t=n=>{var{attr:i,size:o,title:a}=e,l=m3(e,p3),d=o||n.size||"1em",c;return n.className&&(c=n.className),e.className&&(c=(c?c+" ":"")+e.className),Vs.createElement("svg",Sg({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,i,l,{className:c,style:Eg(Eg({color:e.color||n.color},n.style),e.style),height:d,width:d,xmlns:"http://www.w3.org/2000/svg"}),a&&Vs.createElement("title",null,a),e.children)};return x2!==void 0?Vs.createElement(x2.Consumer,null,n=>t(n)):t(MS)}function b3(e){return la({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M504 256c0 136.967-111.033 248-248 248S8 392.967 8 256 119.033 8 256 8s248 111.033 248 248zM227.314 387.314l184-184c6.248-6.248 6.248-16.379 0-22.627l-22.627-22.627c-6.248-6.249-16.379-6.249-22.628 0L216 308.118l-70.059-70.059c-6.248-6.248-16.379-6.248-22.628 0l-22.627 22.627c-6.248 6.248-6.248 16.379 0 22.627l104 104c6.249 6.249 16.379 6.249 22.628.001z"},child:[]}]})(e)}function x3(e){return la({tag:"svg",attr:{viewBox:"0 0 640 512"},child:[{tag:"path",attr:{d:"M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zm-132.9 88.7L299.3 420.7c-6.2 6.2-16.4 6.2-22.6 0L171.3 315.3c-10.1-10.1-2.9-27.3 11.3-27.3H248V176c0-8.8 7.2-16 16-16h48c8.8 0 16 7.2 16 16v112h65.4c14.2 0 21.4 17.2 11.3 27.3z"},child:[]}]})(e)}function SS(e){return la({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M320 448v40c0 13.255-10.745 24-24 24H24c-13.255 0-24-10.745-24-24V120c0-13.255 10.745-24 24-24h72v296c0 30.879 25.121 56 56 56h168zm0-344V0H152c-13.255 0-24 10.745-24 24v368c0 13.255 10.745 24 24 24h272c13.255 0 24-10.745 24-24V128H344c-13.2 0-24-10.8-24-24zm120.971-31.029L375.029 7.029A24 24 0 0 0 358.059 0H352v96h96v-6.059a24 24 0 0 0-7.029-16.97z"},child:[]}]})(e)}function ES(e){return la({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M216 0h80c13.3 0 24 10.7 24 24v168h87.7c17.8 0 26.7 21.5 14.1 34.1L269.7 378.3c-7.5 7.5-19.8 7.5-27.3 0L90.1 226.1c-12.6-12.6-3.7-34.1 14.1-34.1H192V24c0-13.3 10.7-24 24-24zm296 376v112c0 13.3-10.7 24-24 24H24c-13.3 0-24-10.7-24-24V376c0-13.3 10.7-24 24-24h146.7l49 49c20.1 20.1 52.5 20.1 72.6 0l49-49H488c13.3 0 24 10.7 24 24zm-124 88c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20zm64 0c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20z"},child:[]}]})(e)}function T3(e){return la({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M283.211 512c78.962 0 151.079-35.925 198.857-94.792 7.068-8.708-.639-21.43-11.562-19.35-124.203 23.654-238.262-71.576-238.262-196.954 0-72.222 38.662-138.635 101.498-174.394 9.686-5.512 7.25-20.197-3.756-22.23A258.156 258.156 0 0 0 283.211 0c-141.309 0-256 114.511-256 256 0 141.309 114.511 256 256 256z"},child:[]}]})(e)}function M3(e){return la({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M256 160c-52.9 0-96 43.1-96 96s43.1 96 96 96 96-43.1 96-96-43.1-96-96-96zm246.4 80.5l-94.7-47.3 33.5-100.4c4.5-13.6-8.4-26.5-21.9-21.9l-100.4 33.5-47.4-94.8c-6.4-12.8-24.6-12.8-31 0l-47.3 94.7L92.7 70.8c-13.6-4.5-26.5 8.4-21.9 21.9l33.5 100.4-94.7 47.4c-12.8 6.4-12.8 24.6 0 31l94.7 47.3-33.5 100.5c-4.5 13.6 8.4 26.5 21.9 21.9l100.4-33.5 47.3 94.7c6.4 12.8 24.6 12.8 31 0l47.3-94.7 100.4 33.5c13.6 4.5 26.5-8.4 21.9-21.9l-33.5-100.4 94.7-47.3c13-6.5 13-24.7.2-31.1zm-155.9 106c-49.9 49.9-131.1 49.9-181 0-49.9-49.9-49.9-131.1 0-181 49.9-49.9 131.1-49.9 181 0 49.9 49.9 49.9 131.1 0 181z"},child:[]}]})(e)}function k3(e){return la({tag:"svg",attr:{viewBox:"0 0 352 512"},child:[{tag:"path",attr:{d:"M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"},child:[]}]})(e)}function S3(e){return la({tag:"svg",attr:{viewBox:"0 0 576 512"},child:[{tag:"path",attr:{d:"M384 64H192C85.961 64 0 149.961 0 256s85.961 192 192 192h192c106.039 0 192-85.961 192-192S490.039 64 384 64zM64 256c0-70.741 57.249-128 128-128 70.741 0 128 57.249 128 128 0 70.741-57.249 128-128 128-70.741 0-128-57.249-128-128zm320 128h-48.905c65.217-72.858 65.236-183.12 0-256H384c70.741 0 128 57.249 128 128 0 70.74-57.249 128-128 128z"},child:[]}]})(e)}function E3(e){return la({tag:"svg",attr:{viewBox:"0 0 576 512"},child:[{tag:"path",attr:{d:"M384 64H192C86 64 0 150 0 256s86 192 192 192h192c106 0 192-86 192-192S490 64 384 64zm0 320c-70.8 0-128-57.3-128-128 0-70.8 57.3-128 128-128 70.8 0 128 57.3 128 128 0 70.8-57.3 128-128 128z"},child:[]}]})(e)}function C3(e){return la({tag:"svg",attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z"},child:[]}]})(e)}function P3(e){if(typeof Proxy>"u")return e;const t=new Map,n=(...i)=>e(...i);return new Proxy(n,{get:(i,o)=>o==="create"?e:(t.has(o)||t.set(o,e(o)),t.get(o))})}function cp(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}const F0=e=>Array.isArray(e);function CS(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let i=0;i{t[0][i]=n.get(),t[1][i]=n.getVelocity()}),t}function Gv(e,t,n,i){if(typeof t=="function"){const[o,a]=M2(i);t=t(n!==void 0?n:e.custom,o,a)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[o,a]=M2(i);t=t(n!==void 0?n:e.custom,o,a)}return t}function Yg(e,t,n){const i=e.getProps();return Gv(i,t,n!==void 0?n:i.custom,e)}const qv=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Hv=["initial",...qv],bp=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Rl=new Set(bp),Da=e=>e*1e3,za=e=>e/1e3,A3={type:"spring",stiffness:500,damping:25,restSpeed:10},$3=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),I3={type:"keyframes",duration:.8},F3={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},O3=(e,{keyframes:t})=>t.length>2?I3:Rl.has(e)?e.startsWith("scale")?$3(t[1]):A3:F3;function D3({when:e,delay:t,delayChildren:n,staggerChildren:i,staggerDirection:o,repeat:a,repeatType:l,repeatDelay:d,from:c,elapsed:p,...v}){return!!Object.keys(v).length}function Kv(e,t){return e[t]||e.default||e}const z3={skipAnimations:!1,useManualTiming:!1},R3=e=>e!==null;function Zg(e,{repeat:t,repeatType:n="loop"},i){const o=e.filter(R3),a=t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const us=e=>e;function L3(e){let t=new Set,n=new Set,i=!1,o=!1;const a=new WeakSet;let l={delta:0,timestamp:0,isProcessing:!1};function d(p){a.has(p)&&(c.schedule(p),e()),p(l)}const c={schedule:(p,v=!1,_=!1)=>{const M=_&&i?t:n;return v&&a.add(p),M.has(p)||M.add(p),p},cancel:p=>{n.delete(p),a.delete(p)},process:p=>{if(l=p,i){o=!0;return}i=!0,[t,n]=[n,t],n.clear(),t.forEach(d),i=!1,o&&(o=!1,c.process(p))}};return c}const Fm=["read","resolveKeyframes","update","preRender","render","postRender"],B3=40;function PS(e,t){let n=!1,i=!0;const o={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,l=Fm.reduce((x,k)=>(x[k]=L3(a),x),{}),{read:d,resolveKeyframes:c,update:p,preRender:v,render:_,postRender:T}=l,M=()=>{const x=performance.now();n=!1,o.delta=i?1e3/60:Math.max(Math.min(x-o.timestamp,B3),1),o.timestamp=x,o.isProcessing=!0,d.process(o),c.process(o),p.process(o),v.process(o),_.process(o),T.process(o),o.isProcessing=!1,n&&t&&(i=!1,e(M))},I=()=>{n=!0,i=!0,o.isProcessing||e(M)};return{schedule:Fm.reduce((x,k)=>{const A=l[k];return x[k]=(N,R=!1,B=!1)=>(n||I(),A.schedule(N,R,B)),x},{}),cancel:x=>{for(let k=0;k/^0[^.\s]+$/u.test(e);function N3(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||AS(e):!0}let O0=us;const $S=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),IS=e=>t=>typeof t=="string"&&t.startsWith(e),FS=IS("--"),j3=IS("var(--"),Xv=e=>j3(e)?V3.test(e.split("/*")[0].trim()):!1,V3=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,U3=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function W3(e){const t=U3.exec(e);if(!t)return[,];const[,n,i,o]=t;return[`--${n??i}`,o]}function OS(e,t,n=1){const[i,o]=W3(e);if(!i)return;const a=window.getComputedStyle(t).getPropertyValue(i);if(a){const l=a.trim();return $S(l)?parseFloat(l):l}return Xv(o)?OS(o,t,n+1):o}const Il=(e,t,n)=>n>t?t:ntypeof e=="number",parse:parseFloat,transform:e=>e},Vh={...gd,transform:e=>Il(0,1,e)},Om={...gd,default:1},Uh=e=>Math.round(e*1e5)/1e5,Qv=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu,G3=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu,q3=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu;function xp(e){return typeof e=="string"}function H3(e){return e==null}const Tp=e=>({test:t=>xp(t)&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),ml=Tp("deg"),aa=Tp("%"),jn=Tp("px"),K3=Tp("vh"),X3=Tp("vw"),k2={...aa,parse:e=>aa.parse(e)/100,transform:e=>aa.transform(e*100)},Q3=new Set(["width","height","top","left","right","bottom","x","y","translateX","translateY"]),S2=e=>e===gd||e===jn,E2=(e,t)=>parseFloat(e.split(", ")[t]),C2=(e,t)=>(n,{transform:i})=>{if(i==="none"||!i)return 0;const o=i.match(/^matrix3d\((.+)\)$/u);if(o)return E2(o[1],t);{const a=i.match(/^matrix\((.+)\)$/u);return a?E2(a[1],e):0}},Y3=new Set(["x","y","z"]),Z3=bp.filter(e=>!Y3.has(e));function J3(e){const t=[];return Z3.forEach(n=>{const i=e.getValue(n);i!==void 0&&(t.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),t}const ud={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:C2(4,13),y:C2(5,14)};ud.translateX=ud.x;ud.translateY=ud.y;const DS=e=>t=>t.test(e),eF={test:e=>e==="auto",parse:e=>e},zS=[gd,jn,aa,ml,X3,K3,eF],P2=e=>zS.find(DS(e)),vu=new Set;let D0=!1,z0=!1;function RS(){if(z0){const e=Array.from(vu).filter(i=>i.needsMeasurement),t=new Set(e.map(i=>i.element)),n=new Map;t.forEach(i=>{const o=J3(i);o.length&&(n.set(i,o),i.render())}),e.forEach(i=>i.measureInitialState()),t.forEach(i=>{i.render();const o=n.get(i);o&&o.forEach(([a,l])=>{var d;(d=i.getValue(a))===null||d===void 0||d.set(l)})}),e.forEach(i=>i.measureEndState()),e.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}z0=!1,D0=!1,vu.forEach(e=>e.complete()),vu.clear()}function LS(){vu.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(z0=!0)})}function tF(){LS(),RS()}class Yv{constructor(t,n,i,o,a,l=!1){this.isComplete=!1,this.isAsync=!1,this.needsMeasurement=!1,this.isScheduled=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=i,this.motionValue=o,this.element=a,this.isAsync=l}scheduleResolve(){this.isScheduled=!0,this.isAsync?(vu.add(this),D0||(D0=!0,Dr.read(LS),Dr.resolveKeyframes(RS))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:i,motionValue:o}=this;for(let a=0;an=>!!(xp(n)&&q3.test(n)&&n.startsWith(e)||t&&!H3(n)&&Object.prototype.hasOwnProperty.call(n,t)),BS=(e,t,n)=>i=>{if(!xp(i))return i;const[o,a,l,d]=i.match(Qv);return{[e]:parseFloat(o),[t]:parseFloat(a),[n]:parseFloat(l),alpha:d!==void 0?parseFloat(d):1}},nF=e=>Il(0,255,e),by={...gd,transform:e=>Math.round(nF(e))},gu={test:Zv("rgb","red"),parse:BS("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:i=1})=>"rgba("+by.transform(e)+", "+by.transform(t)+", "+by.transform(n)+", "+Uh(Vh.transform(i))+")"};function rF(e){let t="",n="",i="",o="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),i=e.substring(5,7),o=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),i=e.substring(3,4),o=e.substring(4,5),t+=t,n+=n,i+=i,o+=o),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:o?parseInt(o,16)/255:1}}const R0={test:Zv("#"),parse:rF,transform:gu.transform},Gc={test:Zv("hsl","hue"),parse:BS("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:i=1})=>"hsla("+Math.round(e)+", "+aa.transform(Uh(t))+", "+aa.transform(Uh(n))+", "+Uh(Vh.transform(i))+")"},os={test:e=>gu.test(e)||R0.test(e)||Gc.test(e),parse:e=>gu.test(e)?gu.parse(e):Gc.test(e)?Gc.parse(e):R0.parse(e),transform:e=>xp(e)?e:e.hasOwnProperty("red")?gu.transform(e):Gc.transform(e)};function iF(e){var t,n;return isNaN(e)&&xp(e)&&(((t=e.match(Qv))===null||t===void 0?void 0:t.length)||0)+(((n=e.match(G3))===null||n===void 0?void 0:n.length)||0)>0}const NS="number",jS="color",sF="var",oF="var(",A2="${}",aF=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function fp(e){const t=e.toString(),n=[],i={color:[],number:[],var:[]},o=[];let a=0;const d=t.replace(aF,c=>(os.test(c)?(i.color.push(a),o.push(jS),n.push(os.parse(c))):c.startsWith(oF)?(i.var.push(a),o.push(sF),n.push(c)):(i.number.push(a),o.push(NS),n.push(parseFloat(c))),++a,A2)).split(A2);return{values:n,split:d,indexes:i,types:o}}function VS(e){return fp(e).values}function US(e){const{split:t,types:n}=fp(e),i=t.length;return o=>{let a="";for(let l=0;ltypeof e=="number"?0:e;function uF(e){const t=VS(e);return US(e)(t.map(lF))}const Fl={test:iF,parse:VS,createTransformer:US,getAnimatableNone:uF},cF=new Set(["brightness","contrast","saturate","opacity"]);function dF(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[i]=n.match(Qv)||[];if(!i)return e;const o=n.replace(i,"");let a=cF.has(t)?1:0;return i!==n&&(a*=100),t+"("+a+o+")"}const fF=/\b([a-z-]*)\(.*?\)/gu,L0={...Fl,getAnimatableNone:e=>{const t=e.match(fF);return t?t.map(dF).join(" "):e}},$2={...gd,transform:Math.round},Jv={borderWidth:jn,borderTopWidth:jn,borderRightWidth:jn,borderBottomWidth:jn,borderLeftWidth:jn,borderRadius:jn,radius:jn,borderTopLeftRadius:jn,borderTopRightRadius:jn,borderBottomRightRadius:jn,borderBottomLeftRadius:jn,width:jn,maxWidth:jn,height:jn,maxHeight:jn,size:jn,top:jn,right:jn,bottom:jn,left:jn,padding:jn,paddingTop:jn,paddingRight:jn,paddingBottom:jn,paddingLeft:jn,margin:jn,marginTop:jn,marginRight:jn,marginBottom:jn,marginLeft:jn,rotate:ml,rotateX:ml,rotateY:ml,rotateZ:ml,scale:Om,scaleX:Om,scaleY:Om,scaleZ:Om,skew:ml,skewX:ml,skewY:ml,distance:jn,translateX:jn,translateY:jn,translateZ:jn,x:jn,y:jn,z:jn,perspective:jn,transformPerspective:jn,opacity:Vh,originX:k2,originY:k2,originZ:jn,zIndex:$2,backgroundPositionX:jn,backgroundPositionY:jn,fillOpacity:Vh,strokeOpacity:Vh,numOctaves:$2},hF={...Jv,color:os,backgroundColor:os,outlineColor:os,fill:os,stroke:os,borderColor:os,borderTopColor:os,borderRightColor:os,borderBottomColor:os,borderLeftColor:os,filter:L0,WebkitFilter:L0},ew=e=>hF[e];function WS(e,t){let n=ew(e);return n!==L0&&(n=Fl),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const pF=new Set(["auto","none","0"]);function mF(e,t,n){let i=0,o;for(;i{n.getValue(c).set(p)}),this.resolveNoneKeyframes()}}function qS(e){let t;return()=>(t===void 0&&(t=e()),t)}let Xm;function gF(){Xm=void 0}const Ra={now:()=>(Xm===void 0&&Ra.set(Qi.isProcessing||z3.useManualTiming?Qi.timestamp:performance.now()),Xm),set:e=>{Xm=e,queueMicrotask(gF)}},I2=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(Fl.test(e)||e==="0")&&!e.startsWith("url("));function _F(e){const t=e[0];if(e.length===1)return!0;for(let n=0;nvF?this.resolvedAt:this.createdAt:this.createdAt}get resolved(){return!this._resolved&&!this.hasAttemptedResolve&&tF(),this._resolved}onKeyframesResolved(t,n){this.resolvedAt=Ra.now(),this.hasAttemptedResolve=!0;const{name:i,type:o,velocity:a,delay:l,onComplete:d,onUpdate:c,isGenerator:p}=this.options;if(!p&&!yF(t,i,o,a))if(l)this.options.duration=0;else{c==null||c(Zg(t,this.options,n)),d==null||d(),this.resolveFinishedPromise();return}const v=this.initPlayback(t,n);v!==!1&&(this._resolved={keyframes:t,finalKeyframe:n,...v},this.onPostResolved())}onPostResolved(){}then(t,n){return this.currentFinishedPromise.then(t,n)}updateFinishedPromise(){this.currentFinishedPromise=new Promise(t=>{this.resolveFinishedPromise=t})}}function KS(e,t){return t?e*(1e3/t):0}const wF=5;function XS(e,t,n){const i=Math.max(t-wF,0);return KS(n-e(i),t-i)}const xy=.001,bF=.01,xF=10,TF=.05,MF=1;function kF({duration:e=800,bounce:t=.25,velocity:n=0,mass:i=1}){let o,a,l=1-t;l=Il(TF,MF,l),e=Il(bF,xF,za(e)),l<1?(o=p=>{const v=p*l,_=v*e,T=v-n,M=B0(p,l),I=Math.exp(-_);return xy-T/M*I},a=p=>{const _=p*l*e,T=_*n+n,M=Math.pow(l,2)*Math.pow(p,2)*e,I=Math.exp(-_),C=B0(Math.pow(p,2),l);return(-o(p)+xy>0?-1:1)*((T-M)*I)/C}):(o=p=>{const v=Math.exp(-p*e),_=(p-n)*e+1;return-xy+v*_},a=p=>{const v=Math.exp(-p*e),_=(n-p)*(e*e);return v*_});const d=5/e,c=EF(o,a,d);if(e=Da(e),isNaN(c))return{stiffness:100,damping:10,duration:e};{const p=Math.pow(c,2)*i;return{stiffness:p,damping:l*2*Math.sqrt(i*p),duration:e}}}const SF=12;function EF(e,t,n){let i=n;for(let o=1;oe[n]!==void 0)}function AF(e){let t={velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1,...e};if(!F2(e,PF)&&F2(e,CF)){const n=kF(e);t={...t,...n,mass:1},t.isResolvedFromDuration=!0}return t}function QS({keyframes:e,restDelta:t,restSpeed:n,...i}){const o=e[0],a=e[e.length-1],l={done:!1,value:o},{stiffness:d,damping:c,mass:p,duration:v,velocity:_,isResolvedFromDuration:T}=AF({...i,velocity:-za(i.velocity||0)}),M=_||0,I=c/(2*Math.sqrt(d*p)),C=a-o,E=za(Math.sqrt(d/p)),x=Math.abs(C)<5;n||(n=x?.01:2),t||(t=x?.005:.5);let k;if(I<1){const A=B0(E,I);k=N=>{const R=Math.exp(-I*E*N);return a-R*((M+I*E*C)/A*Math.sin(A*N)+C*Math.cos(A*N))}}else if(I===1)k=A=>a-Math.exp(-E*A)*(C+(M+E*C)*A);else{const A=E*Math.sqrt(I*I-1);k=N=>{const R=Math.exp(-I*E*N),B=Math.min(A*N,300);return a-R*((M+I*E*C)*Math.sinh(B)+A*C*Math.cosh(B))/A}}return{calculatedDuration:T&&v||null,next:A=>{const N=k(A);if(T)l.done=A>=v;else{let R=0;I<1&&(R=A===0?Da(M):XS(k,A,N));const B=Math.abs(R)<=n,W=Math.abs(a-N)<=t;l.done=B&&W}return l.value=l.done?a:N,l}}}function O2({keyframes:e,velocity:t=0,power:n=.8,timeConstant:i=325,bounceDamping:o=10,bounceStiffness:a=500,modifyTarget:l,min:d,max:c,restDelta:p=.5,restSpeed:v}){const _=e[0],T={done:!1,value:_},M=j=>d!==void 0&&jc,I=j=>d===void 0?c:c===void 0||Math.abs(d-j)-C*Math.exp(-j/i),A=j=>x+k(j),N=j=>{const ae=k(j),ve=A(j);T.done=Math.abs(ae)<=p,T.value=T.done?x:ve};let R,B;const W=j=>{M(T.value)&&(R=j,B=QS({keyframes:[T.value,I(T.value)],velocity:XS(A,j,T.value),damping:o,stiffness:a,restDelta:p,restSpeed:v}))};return W(0),{calculatedDuration:null,next:j=>{let ae=!1;return!B&&R===void 0&&(ae=!0,N(j),W(j)),R!==void 0&&j>=R?B.next(j-R):(!ae&&N(j),T)}}}const YS=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,$F=1e-7,IF=12;function FF(e,t,n,i,o){let a,l,d=0;do l=t+(n-t)/2,a=YS(l,i,o)-e,a>0?n=l:t=l;while(Math.abs(a)>$F&&++dFF(a,0,1,e,n);return a=>a===0||a===1?a:YS(o(a),t,i)}const OF=Mp(.42,0,1,1),DF=Mp(0,0,.58,1),ZS=Mp(.42,0,.58,1),zF=e=>Array.isArray(e)&&typeof e[0]!="number",JS=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,eE=e=>t=>1-e(1-t),tw=e=>1-Math.sin(Math.acos(e)),tE=eE(tw),RF=JS(tw),nE=Mp(.33,1.53,.69,.99),nw=eE(nE),LF=JS(nw),BF=e=>(e*=2)<1?.5*nw(e):.5*(2-Math.pow(2,-10*(e-1))),D2={linear:us,easeIn:OF,easeInOut:ZS,easeOut:DF,circIn:tw,circInOut:RF,circOut:tE,backIn:nw,backInOut:LF,backOut:nE,anticipate:BF},z2=e=>{if(Array.isArray(e)){O0(e.length===4);const[t,n,i,o]=e;return Mp(t,n,i,o)}else if(typeof e=="string")return O0(D2[e]!==void 0),D2[e];return e},NF=(e,t)=>n=>t(e(n)),La=(...e)=>e.reduce(NF),hp=(e,t,n)=>{const i=t-e;return i===0?1:(n-e)/i},ei=(e,t,n)=>e+(t-e)*n;function Ty(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function jF({hue:e,saturation:t,lightness:n,alpha:i}){e/=360,t/=100,n/=100;let o=0,a=0,l=0;if(!t)o=a=l=n;else{const d=n<.5?n*(1+t):n+t-n*t,c=2*n-d;o=Ty(c,d,e+1/3),a=Ty(c,d,e),l=Ty(c,d,e-1/3)}return{red:Math.round(o*255),green:Math.round(a*255),blue:Math.round(l*255),alpha:i}}function Cg(e,t){return n=>n>0?t:e}const My=(e,t,n)=>{const i=e*e,o=n*(t*t-i)+i;return o<0?0:Math.sqrt(o)},VF=[R0,gu,Gc],UF=e=>VF.find(t=>t.test(e));function R2(e){const t=UF(e);if(!t)return!1;let n=t.parse(e);return t===Gc&&(n=jF(n)),n}const L2=(e,t)=>{const n=R2(e),i=R2(t);if(!n||!i)return Cg(e,t);const o={...n};return a=>(o.red=My(n.red,i.red,a),o.green=My(n.green,i.green,a),o.blue=My(n.blue,i.blue,a),o.alpha=ei(n.alpha,i.alpha,a),gu.transform(o))},N0=new Set(["none","hidden"]);function WF(e,t){return N0.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function GF(e,t){return n=>ei(e,t,n)}function rw(e){return typeof e=="number"?GF:typeof e=="string"?Xv(e)?Cg:os.test(e)?L2:KF:Array.isArray(e)?rE:typeof e=="object"?os.test(e)?L2:qF:Cg}function rE(e,t){const n=[...e],i=n.length,o=e.map((a,l)=>rw(a)(a,t[l]));return a=>{for(let l=0;l{for(const a in i)n[a]=i[a](o);return n}}function HF(e,t){var n;const i=[],o={color:0,var:0,number:0};for(let a=0;a{const n=Fl.createTransformer(t),i=fp(e),o=fp(t);return i.indexes.var.length===o.indexes.var.length&&i.indexes.color.length===o.indexes.color.length&&i.indexes.number.length>=o.indexes.number.length?N0.has(e)&&!o.values.length||N0.has(t)&&!i.values.length?WF(e,t):La(rE(HF(i,o),o.values),n):Cg(e,t)};function iE(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?ei(e,t,n):rw(e)(e,t)}function XF(e,t,n){const i=[],o=n||iE,a=e.length-1;for(let l=0;lt[0];if(a===2&&e[0]===e[1])return()=>t[1];e[0]>e[a-1]&&(e=[...e].reverse(),t=[...t].reverse());const l=XF(t,i,o),d=l.length,c=p=>{let v=0;if(d>1)for(;vc(Il(e[0],e[a-1],p)):c}function YF(e,t){const n=e[e.length-1];for(let i=1;i<=t;i++){const o=hp(0,t,i);e.push(ei(n,1,o))}}function ZF(e){const t=[0];return YF(t,e.length-1),t}function JF(e,t){return e.map(n=>n*t)}function eO(e,t){return e.map(()=>t||ZS).splice(0,e.length-1)}function Pg({duration:e=300,keyframes:t,times:n,ease:i="easeInOut"}){const o=zF(i)?i.map(z2):z2(i),a={done:!1,value:t[0]},l=JF(n&&n.length===t.length?n:ZF(t),e),d=QF(l,t,{ease:Array.isArray(o)?o:eO(t,o)});return{calculatedDuration:e,next:c=>(a.value=d(c),a.done=c>=e,a)}}const B2=2e4;function tO(e){let t=0;const n=50;let i=e.next(t);for(;!i.done&&t=B2?1/0:t}const nO=e=>{const t=({timestamp:n})=>e(n);return{start:()=>Dr.update(t,!0),stop:()=>Wa(t),now:()=>Qi.isProcessing?Qi.timestamp:Ra.now()}},rO={decay:O2,inertia:O2,tween:Pg,keyframes:Pg,spring:QS},iO=e=>e/100;class iw extends HS{constructor(t){super(t),this.holdTime=null,this.cancelTime=null,this.currentTime=0,this.playbackSpeed=1,this.pendingPlayState="running",this.startTime=null,this.state="idle",this.stop=()=>{if(this.resolver.cancel(),this.isStopped=!0,this.state==="idle")return;this.teardown();const{onStop:c}=this.options;c&&c()};const{name:n,motionValue:i,element:o,keyframes:a}=this.options,l=(o==null?void 0:o.KeyframeResolver)||Yv,d=(c,p)=>this.onKeyframesResolved(c,p);this.resolver=new l(a,d,n,i,o),this.resolver.scheduleResolve()}initPlayback(t){const{type:n="keyframes",repeat:i=0,repeatDelay:o=0,repeatType:a,velocity:l=0}=this.options,d=rO[n]||Pg;let c,p;d!==Pg&&typeof t[0]!="number"&&(c=La(iO,iE(t[0],t[1])),t=[0,100]);const v=d({...this.options,keyframes:t});a==="mirror"&&(p=d({...this.options,keyframes:[...t].reverse(),velocity:-l})),v.calculatedDuration===null&&(v.calculatedDuration=tO(v));const{calculatedDuration:_}=v,T=_+o,M=T*(i+1)-o;return{generator:v,mirroredGenerator:p,mapPercentToKeyframes:c,calculatedDuration:_,resolvedDuration:T,totalDuration:M}}onPostResolved(){const{autoplay:t=!0}=this.options;this.play(),this.pendingPlayState==="paused"||!t?this.pause():this.state=this.pendingPlayState}tick(t,n=!1){const{resolved:i}=this;if(!i){const{keyframes:j}=this.options;return{done:!0,value:j[j.length-1]}}const{finalKeyframe:o,generator:a,mirroredGenerator:l,mapPercentToKeyframes:d,keyframes:c,calculatedDuration:p,totalDuration:v,resolvedDuration:_}=i;if(this.startTime===null)return a.next(0);const{delay:T,repeat:M,repeatType:I,repeatDelay:C,onUpdate:E}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-v/this.speed,this.startTime)),n?this.currentTime=t:this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=Math.round(t-this.startTime)*this.speed;const x=this.currentTime-T*(this.speed>=0?1:-1),k=this.speed>=0?x<0:x>v;this.currentTime=Math.max(x,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=v);let A=this.currentTime,N=a;if(M){const j=Math.min(this.currentTime,v)/_;let ae=Math.floor(j),ve=j%1;!ve&&j>=1&&(ve=1),ve===1&&ae--,ae=Math.min(ae,M+1),!!(ae%2)&&(I==="reverse"?(ve=1-ve,C&&(ve-=C/_)):I==="mirror"&&(N=l)),A=Il(0,1,ve)*_}const R=k?{done:!1,value:c[0]}:N.next(A);d&&(R.value=d(R.value));let{done:B}=R;!k&&p!==null&&(B=this.speed>=0?this.currentTime>=v:this.currentTime<=0);const W=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&B);return W&&o!==void 0&&(R.value=Zg(c,this.options,o)),E&&E(R.value),W&&this.finish(),R}get duration(){const{resolved:t}=this;return t?za(t.calculatedDuration):0}get time(){return za(this.currentTime)}set time(t){t=Da(t),this.currentTime=t,this.holdTime!==null||this.speed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.speed)}get speed(){return this.playbackSpeed}set speed(t){const n=this.playbackSpeed!==t;this.playbackSpeed=t,n&&(this.time=za(this.currentTime))}play(){if(this.resolver.isScheduled||this.resolver.resume(),!this._resolved){this.pendingPlayState="running";return}if(this.isStopped)return;const{driver:t=nO,onPlay:n,startTime:i}=this.options;this.driver||(this.driver=t(a=>this.tick(a))),n&&n();const o=this.driver.now();this.holdTime!==null?this.startTime=o-this.holdTime:this.startTime?this.state==="finished"&&(this.startTime=o):this.startTime=i??this.calcStartTime(),this.state==="finished"&&this.updateFinishedPromise(),this.cancelTime=this.startTime,this.holdTime=null,this.state="running",this.driver.start()}pause(){var t;if(!this._resolved){this.pendingPlayState="paused";return}this.state="paused",this.holdTime=(t=this.currentTime)!==null&&t!==void 0?t:0}complete(){this.state!=="running"&&this.play(),this.pendingPlayState=this.state="finished",this.holdTime=null}finish(){this.teardown(),this.state="finished";const{onComplete:t}=this.options;t&&t()}cancel(){this.cancelTime!==null&&this.tick(this.cancelTime),this.teardown(),this.updateFinishedPromise()}teardown(){this.state="idle",this.stopDriver(),this.resolveFinishedPromise(),this.updateFinishedPromise(),this.startTime=this.cancelTime=null,this.resolver.cancel()}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}}const sE=new Set(["opacity","clipPath","filter","transform"]),oE=e=>Array.isArray(e)&&typeof e[0]=="number";function aE(e){return!!(!e||typeof e=="string"&&e in sw||oE(e)||Array.isArray(e)&&e.every(aE))}const $h=([e,t,n,i])=>`cubic-bezier(${e}, ${t}, ${n}, ${i})`,sw={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:$h([0,.65,.55,1]),circOut:$h([.55,0,1,.45]),backIn:$h([.31,.01,.66,-.59]),backOut:$h([.33,1.53,.69,.99])};function sO(e){return lE(e)||sw.easeOut}function lE(e){if(e)return oE(e)?$h(e):Array.isArray(e)?e.map(sO):sw[e]}function oO(e,t,n,{delay:i=0,duration:o=300,repeat:a=0,repeatType:l="loop",ease:d,times:c}={}){const p={[t]:n};c&&(p.offset=c);const v=lE(d);return Array.isArray(v)&&(p.easing=v),e.animate(p,{delay:i,duration:o,easing:Array.isArray(v)?"linear":v,fill:"both",iterations:a+1,direction:l==="reverse"?"alternate":"normal"})}const aO=qS(()=>Object.hasOwnProperty.call(Element.prototype,"animate")),Ag=10,lO=2e4;function uO(e){return e.type==="spring"||!aE(e.ease)}function cO(e,t){const n=new iw({...t,keyframes:e,repeat:0,delay:0,isGenerator:!0});let i={done:!1,value:e[0]};const o=[];let a=0;for(;!i.done&&athis.onKeyframesResolved(l,d),n,i,o),this.resolver.scheduleResolve()}initPlayback(t,n){var i;let{duration:o=300,times:a,ease:l,type:d,motionValue:c,name:p,startTime:v}=this.options;if(!(!((i=c.owner)===null||i===void 0)&&i.current))return!1;if(uO(this.options)){const{onComplete:T,onUpdate:M,motionValue:I,element:C,...E}=this.options,x=cO(t,E);t=x.keyframes,t.length===1&&(t[1]=t[0]),o=x.duration,a=x.times,l=x.ease,d="keyframes"}const _=oO(c.owner.current,p,t,{...this.options,duration:o,times:a,ease:l});return _.startTime=v??this.calcStartTime(),this.pendingTimeline?(_.timeline=this.pendingTimeline,this.pendingTimeline=void 0):_.onfinish=()=>{const{onComplete:T}=this.options;c.set(Zg(t,this.options,n)),T&&T(),this.cancel(),this.resolveFinishedPromise()},{animation:_,duration:o,times:a,type:d,ease:l,keyframes:t}}get duration(){const{resolved:t}=this;if(!t)return 0;const{duration:n}=t;return za(n)}get time(){const{resolved:t}=this;if(!t)return 0;const{animation:n}=t;return za(n.currentTime||0)}set time(t){const{resolved:n}=this;if(!n)return;const{animation:i}=n;i.currentTime=Da(t)}get speed(){const{resolved:t}=this;if(!t)return 1;const{animation:n}=t;return n.playbackRate}set speed(t){const{resolved:n}=this;if(!n)return;const{animation:i}=n;i.playbackRate=t}get state(){const{resolved:t}=this;if(!t)return"idle";const{animation:n}=t;return n.playState}get startTime(){const{resolved:t}=this;if(!t)return null;const{animation:n}=t;return n.startTime}attachTimeline(t){if(!this._resolved)this.pendingTimeline=t;else{const{resolved:n}=this;if(!n)return us;const{animation:i}=n;i.timeline=t,i.onfinish=null}return us}play(){if(this.isStopped)return;const{resolved:t}=this;if(!t)return;const{animation:n}=t;n.playState==="finished"&&this.updateFinishedPromise(),n.play()}pause(){const{resolved:t}=this;if(!t)return;const{animation:n}=t;n.pause()}stop(){if(this.resolver.cancel(),this.isStopped=!0,this.state==="idle")return;this.resolveFinishedPromise(),this.updateFinishedPromise();const{resolved:t}=this;if(!t)return;const{animation:n,keyframes:i,duration:o,type:a,ease:l,times:d}=t;if(n.playState==="idle"||n.playState==="finished")return;if(this.time){const{motionValue:p,onUpdate:v,onComplete:_,element:T,...M}=this.options,I=new iw({...M,keyframes:i,duration:o,type:a,ease:l,times:d,isGenerator:!0}),C=Da(this.time);p.setWithVelocity(I.sample(C-Ag).value,I.sample(C).value,Ag)}const{onStop:c}=this.options;c&&c(),this.cancel()}complete(){const{resolved:t}=this;t&&t.animation.finish()}cancel(){const{resolved:t}=this;t&&t.animation.cancel()}static supports(t){const{motionValue:n,name:i,repeatDelay:o,repeatType:a,damping:l,type:d}=t;return aO()&&i&&sE.has(i)&&n&&n.owner&&n.owner.current instanceof HTMLElement&&!n.owner.getProps().onUpdate&&!o&&a!=="mirror"&&l!==0&&d!=="inertia"}}function dO(e,t){let n;const i=()=>{const{currentTime:o}=t,l=(o===null?0:o.value)/100;n!==l&&e(l),n=l};return Dr.update(i,!0),()=>Wa(i)}const fO=qS(()=>window.ScrollTimeline!==void 0);class hO{constructor(t){this.stop=()=>this.runAll("stop"),this.animations=t.filter(Boolean)}then(t,n){return Promise.all(this.animations).then(t).catch(n)}getAll(t){return this.animations[0][t]}setAll(t,n){for(let i=0;i{if(fO()&&i.attachTimeline)i.attachTimeline(t);else return i.pause(),dO(o=>{i.time=i.duration*o},t)});return()=>{n.forEach((i,o)=>{i&&i(),this.animations[o].stop()})}}get time(){return this.getAll("time")}set time(t){this.setAll("time",t)}get speed(){return this.getAll("speed")}set speed(t){this.setAll("speed",t)}get startTime(){return this.getAll("startTime")}get duration(){let t=0;for(let n=0;nn[t]())}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}const ow=(e,t,n,i={},o,a,l)=>d=>{const c=Kv(i,e)||{},p=c.delay||i.delay||0;let{elapsed:v=0}=i;v=v-Da(p);let _={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...c,delay:-v,onUpdate:M=>{t.set(M),c.onUpdate&&c.onUpdate(M)},onComplete:()=>{d(),c.onComplete&&c.onComplete(),l&&l()},onStop:l,name:e,motionValue:t,element:a?void 0:o};D3(c)||(_={..._,...O3(e,_)}),_.duration&&(_.duration=Da(_.duration)),_.repeatDelay&&(_.repeatDelay=Da(_.repeatDelay)),_.from!==void 0&&(_.keyframes[0]=_.from);let T=!1;if((_.type===!1||_.duration===0&&!_.repeatDelay)&&(_.duration=0,_.delay===0&&(T=!0)),T&&!a&&t.get()!==void 0){const M=Zg(_.keyframes,c);if(M!==void 0)return Dr.update(()=>{_.onUpdate(M),_.onComplete()}),new hO([])}return!a&&N2.supports(_)?new N2(_):new iw(_)},pO=e=>!!(e&&typeof e=="object"&&e.mix&&e.toValue),mO=e=>F0(e)?e[e.length-1]||0:e;function Jg(e,t){e.indexOf(t)===-1&&e.push(t)}function e_(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}class aw{constructor(){this.subscriptions=[]}add(t){return Jg(this.subscriptions,t),()=>e_(this.subscriptions,t)}notify(t,n,i){const o=this.subscriptions.length;if(o)if(o===1)this.subscriptions[0](t,n,i);else for(let a=0;a!isNaN(parseFloat(e));class uE{constructor(t,n={}){this.version="11.5.4",this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,o=!0)=>{const a=Ra.now();this.updatedAt!==a&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&this.events.change&&this.events.change.notify(this.current),o&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Ra.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=gO(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new aw);const i=this.events[t].add(n);return t==="change"?()=>{i(),Dr.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t,n=!0){!n||!this.passiveEffect?this.updateAndNotify(t,n):this.passiveEffect(t,this.updateAndNotify)}setWithVelocity(t,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-i}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=Ra.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>j2)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,j2);return KS(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function pp(e,t){return new uE(e,t)}function _O(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,pp(n))}function yO(e,t){const n=Yg(e,t);let{transitionEnd:i={},transition:o={},...a}=n||{};a={...a,...i};for(const l in a){const d=mO(a[l]);_O(e,l,d)}}const t_=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),vO="framerAppearId",cE="data-"+t_(vO);function dE(e){return e.props[cE]}function fE(e){if(Rl.has(e))return"transform";if(sE.has(e))return t_(e)}class wO extends uE{constructor(){super(...arguments),this.output=[],this.counts=new Map}add(t){const n=fE(t);if(!n)return;const i=this.counts.get(n)||0;this.counts.set(n,i+1),i===0&&(this.output.push(n),this.update());let o=!1;return()=>{if(o)return;o=!0;const a=this.counts.get(n)-1;this.counts.set(n,a),a===0&&(e_(this.output,n),this.update())}}update(){this.set(this.output.length?this.output.join(", "):"auto")}}const ls=e=>!!(e&&e.getVelocity);function bO(e){return!!(ls(e)&&e.add)}function j0(e,t){var n;if(!e.applyWillChange)return;let i=e.getValue("willChange");if(!i&&!(!((n=e.props.style)===null||n===void 0)&&n.willChange)&&(i=new wO("auto"),e.addValue("willChange",i)),bO(i))return i.add(t)}function xO({protectedKeys:e,needsAnimating:t},n){const i=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,i}function hE(e,t,{delay:n=0,transitionOverride:i,type:o}={}){var a;let{transition:l=e.getDefaultTransition(),transitionEnd:d,...c}=t;i&&(l=i);const p=[],v=o&&e.animationState&&e.animationState.getState()[o];for(const _ in c){const T=e.getValue(_,(a=e.latestValues[_])!==null&&a!==void 0?a:null),M=c[_];if(M===void 0||v&&xO(v,_))continue;const I={delay:n,...Kv(l||{},_)};let C=!1;if(window.MotionHandoffAnimation){const x=dE(e);if(x){const k=window.MotionHandoffAnimation(x,_,Dr);k!==null&&(I.startTime=k,C=!0)}}T.start(ow(_,T,M,e.shouldReduceMotion&&Rl.has(_)?{type:!1}:I,e,C,j0(e,_)));const E=T.animation;E&&p.push(E)}return d&&Promise.all(p).then(()=>{Dr.update(()=>{d&&yO(e,d)})}),p}function V0(e,t,n={}){var i;const o=Yg(e,t,n.type==="exit"?(i=e.presenceContext)===null||i===void 0?void 0:i.custom:void 0);let{transition:a=e.getDefaultTransition()||{}}=o||{};n.transitionOverride&&(a=n.transitionOverride);const l=o?()=>Promise.all(hE(e,o,n)):()=>Promise.resolve(),d=e.variantChildren&&e.variantChildren.size?(p=0)=>{const{delayChildren:v=0,staggerChildren:_,staggerDirection:T}=a;return TO(e,t,v+p,_,T,n)}:()=>Promise.resolve(),{when:c}=a;if(c){const[p,v]=c==="beforeChildren"?[l,d]:[d,l];return p().then(()=>v())}else return Promise.all([l(),d(n.delay)])}function TO(e,t,n=0,i=0,o=1,a){const l=[],d=(e.variantChildren.size-1)*i,c=o===1?(p=0)=>p*i:(p=0)=>d-p*i;return Array.from(e.variantChildren).sort(MO).forEach((p,v)=>{p.notify("AnimationStart",t),l.push(V0(p,t,{...a,delay:n+c(v)}).then(()=>p.notify("AnimationComplete",t)))}),Promise.all(l)}function MO(e,t){return e.sortNodePosition(t)}function kO(e,t,n={}){e.notify("AnimationStart",t);let i;if(Array.isArray(t)){const o=t.map(a=>V0(e,a,n));i=Promise.all(o)}else if(typeof t=="string")i=V0(e,t,n);else{const o=typeof t=="function"?Yg(e,t,n.custom):t;i=Promise.all(hE(e,o,n))}return i.then(()=>{e.notify("AnimationComplete",t)})}const SO=[...qv].reverse(),EO=qv.length;function CO(e){return t=>Promise.all(t.map(({animation:n,options:i})=>kO(e,n,i)))}function PO(e){let t=CO(e),n=V2(),i=!0;const o=c=>(p,v)=>{var _;const T=Yg(e,v,c==="exit"?(_=e.presenceContext)===null||_===void 0?void 0:_.custom:void 0);if(T){const{transition:M,transitionEnd:I,...C}=T;p={...p,...C,...I}}return p};function a(c){t=c(e)}function l(c){const p=e.getProps(),v=e.getVariantContext(!0)||{},_=[],T=new Set;let M={},I=1/0;for(let E=0;EI&&N,ae=!1;const ve=Array.isArray(A)?A:[A];let Ne=ve.reduce(o(x),{});R===!1&&(Ne={});const{prevResolvedValues:oe={}}=k,Se={...oe,...Ne},G=Ce=>{j=!0,T.has(Ce)&&(ae=!0,T.delete(Ce)),k.needsAnimating[Ce]=!0;const gt=e.getValue(Ce);gt&&(gt.liveStyle=!1)};for(const Ce in Se){const gt=Ne[Ce],Me=oe[Ce];if(M.hasOwnProperty(Ce))continue;let te=!1;F0(gt)&&F0(Me)?te=!CS(gt,Me):te=gt!==Me,te?gt!=null?G(Ce):T.add(Ce):gt!==void 0&&T.has(Ce)?G(Ce):k.protectedKeys[Ce]=!0}k.prevProp=A,k.prevResolvedValues=Ne,k.isActive&&(M={...M,...Ne}),i&&e.blockInitialAnimation&&(j=!1),j&&(!B||ae)&&_.push(...ve.map(Ce=>({animation:Ce,options:{type:x}})))}if(T.size){const E={};T.forEach(x=>{const k=e.getBaseTarget(x),A=e.getValue(x);A&&(A.liveStyle=!0),E[x]=k??null}),_.push({animation:E})}let C=!!_.length;return i&&(p.initial===!1||p.initial===p.animate)&&!e.manuallyAnimateOnMount&&(C=!1),i=!1,C?t(_):Promise.resolve()}function d(c,p){var v;if(n[c].isActive===p)return Promise.resolve();(v=e.variantChildren)===null||v===void 0||v.forEach(T=>{var M;return(M=T.animationState)===null||M===void 0?void 0:M.setActive(c,p)}),n[c].isActive=p;const _=l(c);for(const T in n)n[T].protectedKeys={};return _}return{animateChanges:l,setActive:d,setAnimateFunction:a,getState:()=>n,reset:()=>{n=V2(),i=!0}}}function AO(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!CS(t,e):!1}function au(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function V2(){return{animate:au(!0),whileInView:au(),whileHover:au(),whileTap:au(),whileDrag:au(),whileFocus:au(),exit:au()}}class Ll{constructor(t){this.isMounted=!1,this.node=t}update(){}}class $O extends Ll{constructor(t){super(t),t.animationState||(t.animationState=PO(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();cp(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)===null||t===void 0||t.call(this)}}let IO=0;class FO extends Ll{constructor(){super(...arguments),this.id=IO++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===i)return;const o=this.node.animationState.setActive("exit",!t);n&&!t&&o.then(()=>n(this.id))}mount(){const{register:t}=this.node.presenceContext||{};t&&(this.unmount=t(this.id))}unmount(){}}const OO={animation:{Feature:$O},exit:{Feature:FO}},pE=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1;function n_(e,t="page"){return{point:{x:e[`${t}X`],y:e[`${t}Y`]}}}const DO=e=>t=>pE(t)&&e(t,n_(t));function Ia(e,t,n,i={passive:!0}){return e.addEventListener(t,n,i),()=>e.removeEventListener(t,n)}function Ba(e,t,n,i){return Ia(e,t,DO(n),i)}const U2=(e,t)=>Math.abs(e-t);function zO(e,t){const n=U2(e.x,t.x),i=U2(e.y,t.y);return Math.sqrt(n**2+i**2)}class mE{constructor(t,n,{transformPagePoint:i,contextWindow:o,dragSnapToOrigin:a=!1}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const _=Sy(this.lastMoveEventInfo,this.history),T=this.startEvent!==null,M=zO(_.offset,{x:0,y:0})>=3;if(!T&&!M)return;const{point:I}=_,{timestamp:C}=Qi;this.history.push({...I,timestamp:C});const{onStart:E,onMove:x}=this.handlers;T||(E&&E(this.lastMoveEvent,_),this.startEvent=this.lastMoveEvent),x&&x(this.lastMoveEvent,_)},this.handlePointerMove=(_,T)=>{this.lastMoveEvent=_,this.lastMoveEventInfo=ky(T,this.transformPagePoint),Dr.update(this.updatePoint,!0)},this.handlePointerUp=(_,T)=>{this.end();const{onEnd:M,onSessionEnd:I,resumeAnimation:C}=this.handlers;if(this.dragSnapToOrigin&&C&&C(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const E=Sy(_.type==="pointercancel"?this.lastMoveEventInfo:ky(T,this.transformPagePoint),this.history);this.startEvent&&M&&M(_,E),I&&I(_,E)},!pE(t))return;this.dragSnapToOrigin=a,this.handlers=n,this.transformPagePoint=i,this.contextWindow=o||window;const l=n_(t),d=ky(l,this.transformPagePoint),{point:c}=d,{timestamp:p}=Qi;this.history=[{...c,timestamp:p}];const{onSessionStart:v}=n;v&&v(t,Sy(d,this.history)),this.removeListeners=La(Ba(this.contextWindow,"pointermove",this.handlePointerMove),Ba(this.contextWindow,"pointerup",this.handlePointerUp),Ba(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),Wa(this.updatePoint)}}function ky(e,t){return t?{point:t(e.point)}:e}function W2(e,t){return{x:e.x-t.x,y:e.y-t.y}}function Sy({point:e},t){return{point:e,delta:W2(e,gE(t)),offset:W2(e,RO(t)),velocity:LO(t,.1)}}function RO(e){return e[0]}function gE(e){return e[e.length-1]}function LO(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,i=null;const o=gE(e);for(;n>=0&&(i=e[n],!(o.timestamp-i.timestamp>Da(t)));)n--;if(!i)return{x:0,y:0};const a=za(o.timestamp-i.timestamp);if(a===0)return{x:0,y:0};const l={x:(o.x-i.x)/a,y:(o.y-i.y)/a};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function _E(e){let t=null;return()=>{const n=()=>{t=null};return t===null?(t=e,n):!1}}const G2=_E("dragHorizontal"),q2=_E("dragVertical");function yE(e){let t=!1;if(e==="y")t=q2();else if(e==="x")t=G2();else{const n=G2(),i=q2();n&&i?t=()=>{n(),i()}:(n&&n(),i&&i())}return t}function vE(){const e=yE(!0);return e?(e(),!1):!0}function qc(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}const wE=1e-4,BO=1-wE,NO=1+wE,bE=.01,jO=0-bE,VO=0+bE;function qs(e){return e.max-e.min}function UO(e,t,n){return Math.abs(e-t)<=n}function H2(e,t,n,i=.5){e.origin=i,e.originPoint=ei(t.min,t.max,e.origin),e.scale=qs(n)/qs(t),e.translate=ei(n.min,n.max,e.origin)-e.originPoint,(e.scale>=BO&&e.scale<=NO||isNaN(e.scale))&&(e.scale=1),(e.translate>=jO&&e.translate<=VO||isNaN(e.translate))&&(e.translate=0)}function Wh(e,t,n,i){H2(e.x,t.x,n.x,i?i.originX:void 0),H2(e.y,t.y,n.y,i?i.originY:void 0)}function K2(e,t,n){e.min=n.min+t.min,e.max=e.min+qs(t)}function WO(e,t,n){K2(e.x,t.x,n.x),K2(e.y,t.y,n.y)}function X2(e,t,n){e.min=t.min-n.min,e.max=e.min+qs(t)}function Gh(e,t,n){X2(e.x,t.x,n.x),X2(e.y,t.y,n.y)}function GO(e,{min:t,max:n},i){return t!==void 0&&en&&(e=i?ei(n,e,i.max):Math.min(e,n)),e}function Q2(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function qO(e,{top:t,left:n,bottom:i,right:o}){return{x:Q2(e.x,n,o),y:Q2(e.y,t,i)}}function Y2(e,t){let n=t.min-e.min,i=t.max-e.max;return t.max-t.mini?n=hp(t.min,t.max-i,e.min):i>o&&(n=hp(e.min,e.max-o,t.min)),Il(0,1,n)}function XO(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const U0=.35;function QO(e=U0){return e===!1?e=0:e===!0&&(e=U0),{x:Z2(e,"left","right"),y:Z2(e,"top","bottom")}}function Z2(e,t,n){return{min:J2(e,t),max:J2(e,n)}}function J2(e,t){return typeof e=="number"?e:e[t]||0}const eT=()=>({translate:0,scale:1,origin:0,originPoint:0}),Hc=()=>({x:eT(),y:eT()}),tT=()=>({min:0,max:0}),pi=()=>({x:tT(),y:tT()});function io(e){return[e("x"),e("y")]}function xE({top:e,left:t,right:n,bottom:i}){return{x:{min:t,max:n},y:{min:e,max:i}}}function YO({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function ZO(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),i=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}function Ey(e){return e===void 0||e===1}function W0({scale:e,scaleX:t,scaleY:n}){return!Ey(e)||!Ey(t)||!Ey(n)}function cu(e){return W0(e)||TE(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function TE(e){return nT(e.x)||nT(e.y)}function nT(e){return e&&e!=="0%"}function $g(e,t,n){const i=e-n,o=t*i;return n+o}function rT(e,t,n,i,o){return o!==void 0&&(e=$g(e,o,i)),$g(e,n,i)+t}function G0(e,t=0,n=1,i,o){e.min=rT(e.min,t,n,i,o),e.max=rT(e.max,t,n,i,o)}function ME(e,{x:t,y:n}){G0(e.x,t.translate,t.scale,t.originPoint),G0(e.y,n.translate,n.scale,n.originPoint)}const iT=.999999999999,sT=1.0000000000001;function JO(e,t,n,i=!1){const o=n.length;if(!o)return;t.x=t.y=1;let a,l;for(let d=0;diT&&(t.x=1),t.yiT&&(t.y=1)}function Kc(e,t){e.min=e.min+t,e.max=e.max+t}function oT(e,t,n,i,o=.5){const a=ei(e.min,e.max,o);G0(e,t,n,a,i)}function Xc(e,t){oT(e.x,t.x,t.scaleX,t.scale,t.originX),oT(e.y,t.y,t.scaleY,t.scale,t.originY)}function kE(e,t){return xE(ZO(e.getBoundingClientRect(),t))}function eD(e,t,n){const i=kE(e,n),{scroll:o}=t;return o&&(Kc(i.x,o.offset.x),Kc(i.y,o.offset.y)),i}const SE=({current:e})=>e?e.ownerDocument.defaultView:null,tD=new WeakMap;class nD{constructor(t){this.openGlobalLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=pi(),this.visualElement=t}start(t,{snapToCursor:n=!1}={}){const{presenceContext:i}=this.visualElement;if(i&&i.isPresent===!1)return;const o=v=>{const{dragSnapToOrigin:_}=this.getProps();_?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(n_(v,"page").point)},a=(v,_)=>{var T;const{drag:M,dragPropagation:I,onDragStart:C}=this.getProps();if(M&&!I&&(this.openGlobalLock&&this.openGlobalLock(),this.openGlobalLock=yE(M),!this.openGlobalLock))return;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),io(x=>{let k=this.getAxisMotionValue(x).get()||0;if(aa.test(k)){const{projection:A}=this.visualElement;if(A&&A.layout){const N=A.layout.layoutBox[x];N&&(k=qs(N)*(parseFloat(k)/100))}}this.originPoint[x]=k}),C&&Dr.postRender(()=>C(v,_)),(T=this.removeWillChange)===null||T===void 0||T.call(this),this.removeWillChange=j0(this.visualElement,"transform");const{animationState:E}=this.visualElement;E&&E.setActive("whileDrag",!0)},l=(v,_)=>{const{dragPropagation:T,dragDirectionLock:M,onDirectionLock:I,onDrag:C}=this.getProps();if(!T&&!this.openGlobalLock)return;const{offset:E}=_;if(M&&this.currentDirection===null){this.currentDirection=rD(E),this.currentDirection!==null&&I&&I(this.currentDirection);return}this.updateAxis("x",_.point,E),this.updateAxis("y",_.point,E),this.visualElement.render(),C&&C(v,_)},d=(v,_)=>this.stop(v,_),c=()=>io(v=>{var _;return this.getAnimationState(v)==="paused"&&((_=this.getAxisMotionValue(v).animation)===null||_===void 0?void 0:_.play())}),{dragSnapToOrigin:p}=this.getProps();this.panSession=new mE(t,{onSessionStart:o,onStart:a,onMove:l,onSessionEnd:d,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:p,contextWindow:SE(this.visualElement)})}stop(t,n){var i;(i=this.removeWillChange)===null||i===void 0||i.call(this);const o=this.isDragging;if(this.cancel(),!o)return;const{velocity:a}=n;this.startAnimation(a);const{onDragEnd:l}=this.getProps();l&&Dr.postRender(()=>l(t,n))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openGlobalLock&&(this.openGlobalLock(),this.openGlobalLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,i){const{drag:o}=this.getProps();if(!i||!Dm(t,o,this.currentDirection))return;const a=this.getAxisMotionValue(t);let l=this.originPoint[t]+i[t];this.constraints&&this.constraints[t]&&(l=GO(l,this.constraints[t],this.elastic[t])),a.set(l)}resolveConstraints(){var t;const{dragConstraints:n,dragElastic:i}=this.getProps(),o=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(t=this.visualElement.projection)===null||t===void 0?void 0:t.layout,a=this.constraints;n&&qc(n)?this.constraints||(this.constraints=this.resolveRefConstraints()):n&&o?this.constraints=qO(o.layoutBox,n):this.constraints=!1,this.elastic=QO(i),a!==this.constraints&&o&&this.constraints&&!this.hasMutatedConstraints&&io(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=XO(o.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!qc(t))return!1;const i=t.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const a=eD(i,o.root,this.visualElement.getTransformPagePoint());let l=HO(o.layout.layoutBox,a);if(n){const d=n(YO(l));this.hasMutatedConstraints=!!d,d&&(l=xE(d))}return l}startAnimation(t){const{drag:n,dragMomentum:i,dragElastic:o,dragTransition:a,dragSnapToOrigin:l,onDragTransitionEnd:d}=this.getProps(),c=this.constraints||{},p=io(v=>{if(!Dm(v,n,this.currentDirection))return;let _=c&&c[v]||{};l&&(_={min:0,max:0});const T=o?200:1e6,M=o?40:1e7,I={type:"inertia",velocity:i?t[v]:0,bounceStiffness:T,bounceDamping:M,timeConstant:750,restDelta:1,restSpeed:10,...a,..._};return this.startAxisValueAnimation(v,I)});return Promise.all(p).then(d)}startAxisValueAnimation(t,n){const i=this.getAxisMotionValue(t);return i.start(ow(t,i,0,n,this.visualElement,!1,j0(this.visualElement,t)))}stopAnimation(){io(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){io(t=>{var n;return(n=this.getAxisMotionValue(t).animation)===null||n===void 0?void 0:n.pause()})}getAnimationState(t){var n;return(n=this.getAxisMotionValue(t).animation)===null||n===void 0?void 0:n.state}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,i=this.visualElement.getProps(),o=i[n];return o||this.visualElement.getValue(t,(i.initial?i.initial[t]:void 0)||0)}snapToCursor(t){io(n=>{const{drag:i}=this.getProps();if(!Dm(n,i,this.currentDirection))return;const{projection:o}=this.visualElement,a=this.getAxisMotionValue(n);if(o&&o.layout){const{min:l,max:d}=o.layout.layoutBox[n];a.set(t[n]-ei(l,d,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!qc(n)||!i||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};io(l=>{const d=this.getAxisMotionValue(l);if(d&&this.constraints!==!1){const c=d.get();o[l]=KO({min:c,max:c},this.constraints[l])}});const{transformTemplate:a}=this.visualElement.getProps();this.visualElement.current.style.transform=a?a({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),io(l=>{if(!Dm(l,t,null))return;const d=this.getAxisMotionValue(l),{min:c,max:p}=this.constraints[l];d.set(ei(c,p,o[l]))})}addListeners(){if(!this.visualElement.current)return;tD.set(this.visualElement,this);const t=this.visualElement.current,n=Ba(t,"pointerdown",c=>{const{drag:p,dragListener:v=!0}=this.getProps();p&&v&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();qc(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:o}=this.visualElement,a=o.addEventListener("measure",i);o&&!o.layout&&(o.root&&o.root.updateScroll(),o.updateLayout()),Dr.read(i);const l=Ia(window,"resize",()=>this.scalePositionWithinConstraints()),d=o.addEventListener("didUpdate",({delta:c,hasLayoutChanged:p})=>{this.isDragging&&p&&(io(v=>{const _=this.getAxisMotionValue(v);_&&(this.originPoint[v]+=c[v].translate,_.set(_.get()+c[v].translate))}),this.visualElement.render())});return()=>{l(),n(),a(),d&&d()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:o=!1,dragConstraints:a=!1,dragElastic:l=U0,dragMomentum:d=!0}=t;return{...t,drag:n,dragDirectionLock:i,dragPropagation:o,dragConstraints:a,dragElastic:l,dragMomentum:d}}}function Dm(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function rD(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class iD extends Ll{constructor(t){super(t),this.removeGroupControls=us,this.removeListeners=us,this.controls=new nD(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||us}unmount(){this.removeGroupControls(),this.removeListeners()}}const aT=e=>(t,n)=>{e&&Dr.postRender(()=>e(t,n))};class sD extends Ll{constructor(){super(...arguments),this.removePointerDownListener=us}onPointerDown(t){this.session=new mE(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:SE(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:i,onPanEnd:o}=this.node.getProps();return{onSessionStart:aT(t),onStart:aT(n),onMove:i,onEnd:(a,l)=>{delete this.session,o&&Dr.postRender(()=>o(a,l))}}}mount(){this.removePointerDownListener=Ba(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const lw=en.createContext(null);function oD(){const e=en.useContext(lw);if(e===null)return[!0,null];const{isPresent:t,onExitComplete:n,register:i}=e,o=en.useId();en.useEffect(()=>i(o),[]);const a=en.useCallback(()=>n&&n(o),[o,n]);return!t&&n?[!1,a]:[!0]}const EE=en.createContext({}),CE=en.createContext({}),Qm={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function lT(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const kh={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(jn.test(e))e=parseFloat(e);else return e;const n=lT(e,t.target.x),i=lT(e,t.target.y);return`${n}% ${i}%`}},aD={correct:(e,{treeScale:t,projectionDelta:n})=>{const i=e,o=Fl.parse(e);if(o.length>5)return i;const a=Fl.createTransformer(e),l=typeof o[0]!="number"?1:0,d=n.x.scale*t.x,c=n.y.scale*t.y;o[0+l]/=d,o[1+l]/=c;const p=ei(d,c,.5);return typeof o[2+l]=="number"&&(o[2+l]/=p),typeof o[3+l]=="number"&&(o[3+l]/=p),a(o)}},Ig={};function lD(e){Object.assign(Ig,e)}const{schedule:uw,cancel:gR}=PS(queueMicrotask,!1);class uD extends en.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i,layoutId:o}=this.props,{projection:a}=t;lD(cD),a&&(n.group&&n.group.add(a),i&&i.register&&o&&i.register(a),a.root.didUpdate(),a.addEventListener("animationComplete",()=>{this.safeToRemove()}),a.setOptions({...a.options,onExitComplete:()=>this.safeToRemove()})),Qm.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:i,drag:o,isPresent:a}=this.props,l=i.projection;return l&&(l.isPresent=a,o||t.layoutDependency!==n||n===void 0?l.willUpdate():this.safeToRemove(),t.isPresent!==a&&(a?l.promote():l.relegate()||Dr.postRender(()=>{const d=l.getStack();(!d||!d.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),uw.postRender(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:o}=t;o&&(o.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(o),i&&i.deregister&&i.deregister(o))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function PE(e){const[t,n]=oD(),i=en.useContext(EE);return Yt.jsx(uD,{...e,layoutGroup:i,switchLayoutGroup:en.useContext(CE),isPresent:t,safeToRemove:n})}const cD={borderRadius:{...kh,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:kh,borderTopRightRadius:kh,borderBottomLeftRadius:kh,borderBottomRightRadius:kh,boxShadow:aD},AE=["TopLeft","TopRight","BottomLeft","BottomRight"],dD=AE.length,uT=e=>typeof e=="string"?parseFloat(e):e,cT=e=>typeof e=="number"||jn.test(e);function fD(e,t,n,i,o,a){o?(e.opacity=ei(0,n.opacity!==void 0?n.opacity:1,hD(i)),e.opacityExit=ei(t.opacity!==void 0?t.opacity:1,0,pD(i))):a&&(e.opacity=ei(t.opacity!==void 0?t.opacity:1,n.opacity!==void 0?n.opacity:1,i));for(let l=0;lit?1:n(hp(e,t,i))}function fT(e,t){e.min=t.min,e.max=t.max}function ro(e,t){fT(e.x,t.x),fT(e.y,t.y)}function hT(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function pT(e,t,n,i,o){return e-=t,e=$g(e,1/n,i),o!==void 0&&(e=$g(e,1/o,i)),e}function mD(e,t=0,n=1,i=.5,o,a=e,l=e){if(aa.test(t)&&(t=parseFloat(t),t=ei(l.min,l.max,t/100)-l.min),typeof t!="number")return;let d=ei(a.min,a.max,i);e===a&&(d-=t),e.min=pT(e.min,t,n,d,o),e.max=pT(e.max,t,n,d,o)}function mT(e,t,[n,i,o],a,l){mD(e,t[n],t[i],t[o],t.scale,a,l)}const gD=["x","scaleX","originX"],_D=["y","scaleY","originY"];function gT(e,t,n,i){mT(e.x,t,gD,n?n.x:void 0,i?i.x:void 0),mT(e.y,t,_D,n?n.y:void 0,i?i.y:void 0)}function _T(e){return e.translate===0&&e.scale===1}function IE(e){return _T(e.x)&&_T(e.y)}function yT(e,t){return e.min===t.min&&e.max===t.max}function yD(e,t){return yT(e.x,t.x)&&yT(e.y,t.y)}function vT(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function FE(e,t){return vT(e.x,t.x)&&vT(e.y,t.y)}function wT(e){return qs(e.x)/qs(e.y)}function bT(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class vD{constructor(){this.members=[]}add(t){Jg(this.members,t),t.scheduleRender()}remove(t){if(e_(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(o=>t===o);if(n===0)return!1;let i;for(let o=n;o>=0;o--){const a=this.members[o];if(a.isPresent!==!1){i=a;break}}return i?(this.promote(i),!0):!1}promote(t,n){const i=this.lead;if(t!==i&&(this.prevLead=i,this.lead=t,t.show(),i)){i.instance&&i.scheduleRender(),t.scheduleRender(),t.resumeFrom=i,n&&(t.resumeFrom.preserveOpacity=!0),i.snapshot&&(t.snapshot=i.snapshot,t.snapshot.latestValues=i.animationValues||i.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:o}=t.options;o===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:i}=t;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function wD(e,t,n){let i="";const o=e.x.translate/t.x,a=e.y.translate/t.y,l=(n==null?void 0:n.z)||0;if((o||a||l)&&(i=`translate3d(${o}px, ${a}px, ${l}px) `),(t.x!==1||t.y!==1)&&(i+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:p,rotate:v,rotateX:_,rotateY:T,skewX:M,skewY:I}=n;p&&(i=`perspective(${p}px) ${i}`),v&&(i+=`rotate(${v}deg) `),_&&(i+=`rotateX(${_}deg) `),T&&(i+=`rotateY(${T}deg) `),M&&(i+=`skewX(${M}deg) `),I&&(i+=`skewY(${I}deg) `)}const d=e.x.scale*t.x,c=e.y.scale*t.y;return(d!==1||c!==1)&&(i+=`scale(${d}, ${c})`),i||"none"}const bD=(e,t)=>e.depth-t.depth;class xD{constructor(){this.children=[],this.isDirty=!1}add(t){Jg(this.children,t),this.isDirty=!0}remove(t){e_(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(bD),this.isDirty=!1,this.children.forEach(t)}}function Ym(e){const t=ls(e)?e.get():e;return pO(t)?t.toValue():t}function TD(e,t){const n=Ra.now(),i=({timestamp:o})=>{const a=o-n;a>=t&&(Wa(i),e(a-t))};return Dr.read(i,!0),()=>Wa(i)}function MD(e){return e instanceof SVGElement&&e.tagName!=="svg"}function kD(e,t,n){const i=ls(e)?e:pp(e);return i.start(ow("",i,t,n)),i.animation}const du={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0},Ih=typeof window<"u"&&window.MotionDebug!==void 0,Cy=["","X","Y","Z"],SD={visibility:"hidden"},xT=1e3;let ED=0;function Py(e,t,n,i){const{latestValues:o}=t;o[e]&&(n[e]=o[e],t.setStaticValue(e,0),i&&(i[e]=0))}function OE(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=dE(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:o,layoutId:a}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",Dr,!(o||a))}const{parent:i}=e;i&&!i.hasCheckedOptimisedAppear&&OE(i)}function DE({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:i,resetTransform:o}){return class{constructor(l={},d=t==null?void 0:t()){this.id=ED++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,Ih&&(du.totalNodes=du.resolvedTargetDeltas=du.recalculatedProjection=0),this.nodes.forEach(AD),this.nodes.forEach(DD),this.nodes.forEach(zD),this.nodes.forEach($D),Ih&&window.MotionDebug.record(du)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=l,this.root=d?d.root||d:this,this.path=d?[...d.path,d]:[],this.parent=d,this.depth=d?d.depth+1:0;for(let c=0;cthis.root.updateBlockedByResize=!1;e(l,()=>{this.root.updateBlockedByResize=!0,_&&_(),_=TD(T,250),Qm.hasAnimatedSinceResize&&(Qm.hasAnimatedSinceResize=!1,this.nodes.forEach(MT))})}c&&this.root.registerSharedNode(c,this),this.options.animate!==!1&&v&&(c||p)&&this.addEventListener("didUpdate",({delta:_,hasLayoutChanged:T,hasRelativeTargetChanged:M,layout:I})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const C=this.options.transition||v.getDefaultTransition()||jD,{onLayoutAnimationStart:E,onLayoutAnimationComplete:x}=v.getProps(),k=!this.targetLayout||!FE(this.targetLayout,I)||M,A=!T&&M;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||A||T&&(k||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(_,A);const N={...Kv(C,"layout"),onPlay:E,onComplete:x};(v.shouldReduceMotion||this.options.layoutRoot)&&(N.delay=0,N.type=!1),this.startAnimation(N)}else T||MT(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=I})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,Wa(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(RD),this.animationId++)}getTransformTemplate(){const{visualElement:l}=this.options;return l&&l.getProps().transformTemplate}willUpdate(l=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&OE(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let v=0;v{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure())}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const R=N/1e3;kT(_.x,l.x,R),kT(_.y,l.y,R),this.setTargetDelta(_),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Gh(T,this.layout.layoutBox,this.relativeParent.layout.layoutBox),BD(this.relativeTarget,this.relativeTargetOrigin,T,R),A&&yD(this.relativeTarget,A)&&(this.isProjectionDirty=!1),A||(A=pi()),ro(A,this.relativeTarget)),C&&(this.animationValues=v,fD(v,p,this.latestValues,R,k,x)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){this.notifyListeners("animationStart"),this.currentAnimation&&this.currentAnimation.stop(),this.resumingFrom&&this.resumingFrom.currentAnimation&&this.resumingFrom.currentAnimation.stop(),this.pendingAnimation&&(Wa(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Dr.update(()=>{Qm.hasAnimatedSinceResize=!0,this.currentAnimation=kD(0,xT,{...l,onUpdate:d=>{this.mixTargetDelta(d),l.onUpdate&&l.onUpdate(d)},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(xT),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:d,target:c,layout:p,latestValues:v}=l;if(!(!d||!c||!p)){if(this!==l&&this.layout&&p&&zE(this.options.animationType,this.layout.layoutBox,p.layoutBox)){c=this.target||pi();const _=qs(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+_;const T=qs(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+T}ro(d,c),Xc(d,v),Wh(this.projectionDeltaWithTransform,this.layoutCorrected,d,v)}}registerSharedNode(l,d){this.sharedNodes.has(l)||this.sharedNodes.set(l,new vD),this.sharedNodes.get(l).add(d);const p=d.options.initialPromotionConfig;d.promote({transition:p?p.transition:void 0,preserveFollowOpacity:p&&p.shouldPreserveFollowOpacity?p.shouldPreserveFollowOpacity(d):void 0})}isLead(){const l=this.getStack();return l?l.lead===this:!0}getLead(){var l;const{layoutId:d}=this.options;return d?((l=this.getStack())===null||l===void 0?void 0:l.lead)||this:this}getPrevLead(){var l;const{layoutId:d}=this.options;return d?(l=this.getStack())===null||l===void 0?void 0:l.prevLead:void 0}getStack(){const{layoutId:l}=this.options;if(l)return this.root.sharedNodes.get(l)}promote({needsReset:l,transition:d,preserveFollowOpacity:c}={}){const p=this.getStack();p&&p.promote(this,c),l&&(this.projectionDelta=void 0,this.needsReset=!0),d&&this.setOptions({transition:d})}relegate(){const l=this.getStack();return l?l.relegate(this):!1}resetSkewAndRotation(){const{visualElement:l}=this.options;if(!l)return;let d=!1;const{latestValues:c}=l;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(d=!0),!d)return;const p={};c.z&&Py("z",l,p,this.animationValues);for(let v=0;v{var d;return(d=l.currentAnimation)===null||d===void 0?void 0:d.stop()}),this.root.nodes.forEach(TT),this.root.sharedNodes.clear()}}}function CD(e){e.updateLayout()}function PD(e){var t;const n=((t=e.resumeFrom)===null||t===void 0?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&n&&e.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:o}=e.layout,{animationType:a}=e.options,l=n.source!==e.layout.source;a==="size"?io(_=>{const T=l?n.measuredBox[_]:n.layoutBox[_],M=qs(T);T.min=i[_].min,T.max=T.min+M}):zE(a,n.layoutBox,i)&&io(_=>{const T=l?n.measuredBox[_]:n.layoutBox[_],M=qs(i[_]);T.max=T.min+M,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[_].max=e.relativeTarget[_].min+M)});const d=Hc();Wh(d,i,n.layoutBox);const c=Hc();l?Wh(c,e.applyTransform(o,!0),n.measuredBox):Wh(c,i,n.layoutBox);const p=!IE(d);let v=!1;if(!e.resumeFrom){const _=e.getClosestProjectingParent();if(_&&!_.resumeFrom){const{snapshot:T,layout:M}=_;if(T&&M){const I=pi();Gh(I,n.layoutBox,T.layoutBox);const C=pi();Gh(C,i,M.layoutBox),FE(I,C)||(v=!0),_.options.layoutRoot&&(e.relativeTarget=C,e.relativeTargetOrigin=I,e.relativeParent=_)}}}e.notifyListeners("didUpdate",{layout:i,snapshot:n,delta:c,layoutDelta:d,hasLayoutChanged:p,hasRelativeTargetChanged:v})}else if(e.isLead()){const{onExitComplete:i}=e.options;i&&i()}e.options.transition=void 0}function AD(e){Ih&&du.totalNodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function $D(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function ID(e){e.clearSnapshot()}function TT(e){e.clearMeasurements()}function FD(e){e.isLayoutDirty=!1}function OD(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function MT(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function DD(e){e.resolveTargetDelta()}function zD(e){e.calcProjection()}function RD(e){e.resetSkewAndRotation()}function LD(e){e.removeLeadSnapshot()}function kT(e,t,n){e.translate=ei(t.translate,0,n),e.scale=ei(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function ST(e,t,n,i){e.min=ei(t.min,n.min,i),e.max=ei(t.max,n.max,i)}function BD(e,t,n,i){ST(e.x,t.x,n.x,i),ST(e.y,t.y,n.y,i)}function ND(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const jD={duration:.45,ease:[.4,0,.1,1]},ET=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),CT=ET("applewebkit/")&&!ET("chrome/")?Math.round:us;function PT(e){e.min=CT(e.min),e.max=CT(e.max)}function VD(e){PT(e.x),PT(e.y)}function zE(e,t,n){return e==="position"||e==="preserve-aspect"&&!UO(wT(t),wT(n),.2)}function UD(e){var t;return e!==e.root&&((t=e.scroll)===null||t===void 0?void 0:t.wasRoot)}const WD=DE({attachResizeListener:(e,t)=>Ia(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Ay={current:void 0},RE=DE({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Ay.current){const e=new WD({});e.mount(window),e.setOptions({layoutScroll:!0}),Ay.current=e}return Ay.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),GD={pan:{Feature:sD},drag:{Feature:iD,ProjectionNode:RE,MeasureLayout:PE}};function AT(e,t){const n=t?"pointerenter":"pointerleave",i=t?"onHoverStart":"onHoverEnd",o=(a,l)=>{if(a.pointerType==="touch"||vE())return;const d=e.getProps();e.animationState&&d.whileHover&&e.animationState.setActive("whileHover",t);const c=d[i];c&&Dr.postRender(()=>c(a,l))};return Ba(e.current,n,o,{passive:!e.getProps()[i]})}class qD extends Ll{mount(){this.unmount=La(AT(this.node,!0),AT(this.node,!1))}unmount(){}}class HD extends Ll{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=La(Ia(this.node.current,"focus",()=>this.onFocus()),Ia(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}const LE=(e,t)=>t?e===t?!0:LE(e,t.parentElement):!1;function $y(e,t){if(!t)return;const n=new PointerEvent("pointer"+e);t(n,n_(n))}class KD extends Ll{constructor(){super(...arguments),this.removeStartListeners=us,this.removeEndListeners=us,this.removeAccessibleListeners=us,this.startPointerPress=(t,n)=>{if(this.isPressing)return;this.removeEndListeners();const i=this.node.getProps(),a=Ba(window,"pointerup",(d,c)=>{if(!this.checkPressEnd())return;const{onTap:p,onTapCancel:v,globalTapTarget:_}=this.node.getProps(),T=!_&&!LE(this.node.current,d.target)?v:p;T&&Dr.update(()=>T(d,c))},{passive:!(i.onTap||i.onPointerUp)}),l=Ba(window,"pointercancel",(d,c)=>this.cancelPress(d,c),{passive:!(i.onTapCancel||i.onPointerCancel)});this.removeEndListeners=La(a,l),this.startPress(t,n)},this.startAccessiblePress=()=>{const t=a=>{if(a.key!=="Enter"||this.isPressing)return;const l=d=>{d.key!=="Enter"||!this.checkPressEnd()||$y("up",(c,p)=>{const{onTap:v}=this.node.getProps();v&&Dr.postRender(()=>v(c,p))})};this.removeEndListeners(),this.removeEndListeners=Ia(this.node.current,"keyup",l),$y("down",(d,c)=>{this.startPress(d,c)})},n=Ia(this.node.current,"keydown",t),i=()=>{this.isPressing&&$y("cancel",(a,l)=>this.cancelPress(a,l))},o=Ia(this.node.current,"blur",i);this.removeAccessibleListeners=La(n,o)}}startPress(t,n){this.isPressing=!0;const{onTapStart:i,whileTap:o}=this.node.getProps();o&&this.node.animationState&&this.node.animationState.setActive("whileTap",!0),i&&Dr.postRender(()=>i(t,n))}checkPressEnd(){return this.removeEndListeners(),this.isPressing=!1,this.node.getProps().whileTap&&this.node.animationState&&this.node.animationState.setActive("whileTap",!1),!vE()}cancelPress(t,n){if(!this.checkPressEnd())return;const{onTapCancel:i}=this.node.getProps();i&&Dr.postRender(()=>i(t,n))}mount(){const t=this.node.getProps(),n=Ba(t.globalTapTarget?window:this.node.current,"pointerdown",this.startPointerPress,{passive:!(t.onTapStart||t.onPointerStart)}),i=Ia(this.node.current,"focus",this.startAccessiblePress);this.removeStartListeners=La(n,i)}unmount(){this.removeStartListeners(),this.removeEndListeners(),this.removeAccessibleListeners()}}const q0=new WeakMap,Iy=new WeakMap,XD=e=>{const t=q0.get(e.target);t&&t(e)},QD=e=>{e.forEach(XD)};function YD({root:e,...t}){const n=e||document;Iy.has(n)||Iy.set(n,{});const i=Iy.get(n),o=JSON.stringify(t);return i[o]||(i[o]=new IntersectionObserver(QD,{root:e,...t})),i[o]}function ZD(e,t,n){const i=YD(t);return q0.set(e,n),i.observe(e),()=>{q0.delete(e),i.unobserve(e)}}const JD={some:0,all:1};class ez extends Ll{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:i,amount:o="some",once:a}=t,l={root:n?n.current:void 0,rootMargin:i,threshold:typeof o=="number"?o:JD[o]},d=c=>{const{isIntersecting:p}=c;if(this.isInView===p||(this.isInView=p,a&&!p&&this.hasEnteredView))return;p&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",p);const{onViewportEnter:v,onViewportLeave:_}=this.node.getProps(),T=p?v:_;T&&T(c)};return ZD(this.node.current,l,d)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(tz(t,n))&&this.startObserver()}unmount(){}}function tz({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const nz={inView:{Feature:ez},tap:{Feature:KD},focus:{Feature:HD},hover:{Feature:qD}},rz={layout:{ProjectionNode:RE,MeasureLayout:PE}},BE=en.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"}),r_=en.createContext({}),cw=typeof window<"u",iz=cw?en.useLayoutEffect:en.useEffect,NE=en.createContext({strict:!1});let $T=!1;function sz(e,t,n,i,o){var a;const{visualElement:l}=en.useContext(r_),d=en.useContext(NE),c=en.useContext(lw),p=en.useContext(BE).reducedMotion,v=en.useRef();i=i||d.renderer,!v.current&&i&&(v.current=i(e,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:p}));const _=v.current,T=en.useContext(CE);_&&!_.projection&&o&&(_.type==="html"||_.type==="svg")&&az(v.current,n,o,T),en.useInsertionEffect(()=>{_&&_.update(n,c)});const M=n[cE],I=en.useRef(!!M&&!window.MotionHandoffIsComplete&&((a=window.MotionHasOptimisedAnimation)===null||a===void 0?void 0:a.call(window,M)));return iz(()=>{_&&(_.updateFeatures(),uw.render(_.render),I.current&&_.animationState&&_.animationState.animateChanges())}),en.useEffect(()=>{_&&(!I.current&&_.animationState&&_.animationState.animateChanges(),I.current=!1,$T||($T=!0,queueMicrotask(oz)))}),_}function oz(){window.MotionHandoffIsComplete=!0}function az(e,t,n,i){const{layoutId:o,layout:a,drag:l,dragConstraints:d,layoutScroll:c,layoutRoot:p}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:jE(e.parent)),e.projection.setOptions({layoutId:o,layout:a,alwaysMeasureLayout:!!l||d&&qc(d),visualElement:e,animationType:typeof a=="string"?a:"both",initialPromotionConfig:i,layoutScroll:c,layoutRoot:p})}function jE(e){if(e)return e.options.allowProjection!==!1?e.projection:jE(e.parent)}function lz(e,t,n){return en.useCallback(i=>{i&&e.mount&&e.mount(i),t&&(i?t.mount(i):t.unmount()),n&&(typeof n=="function"?n(i):qc(n)&&(n.current=i))},[t])}function i_(e){return cp(e.animate)||Hv.some(t=>dp(e[t]))}function VE(e){return!!(i_(e)||e.variants)}function uz(e,t){if(i_(e)){const{initial:n,animate:i}=e;return{initial:n===!1||dp(n)?n:void 0,animate:dp(i)?i:void 0}}return e.inherit!==!1?t:{}}function cz(e){const{initial:t,animate:n}=uz(e,en.useContext(r_));return en.useMemo(()=>({initial:t,animate:n}),[IT(t),IT(n)])}function IT(e){return Array.isArray(e)?e.join(" "):e}const FT={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},cd={};for(const e in FT)cd[e]={isEnabled:t=>FT[e].some(n=>!!t[n])};function dz(e){for(const t in e)cd[t]={...cd[t],...e[t]}}const fz=Symbol.for("motionComponentSymbol");function hz({preloadedFeatures:e,createVisualElement:t,useRender:n,useVisualState:i,Component:o}){e&&dz(e);function a(d,c){let p;const v={...en.useContext(BE),...d,layoutId:pz(d)},{isStatic:_}=v,T=cz(d),M=i(d,_);if(!_&&cw){mz();const I=gz(v);p=I.MeasureLayout,T.visualElement=sz(o,M,v,t,I.ProjectionNode)}return Yt.jsxs(r_.Provider,{value:T,children:[p&&T.visualElement?Yt.jsx(p,{visualElement:T.visualElement,...v}):null,n(o,d,lz(M,T.visualElement,c),M,_,T.visualElement)]})}const l=en.forwardRef(a);return l[fz]=o,l}function pz({layoutId:e}){const t=en.useContext(EE).id;return t&&e!==void 0?t+"-"+e:e}function mz(e,t){en.useContext(NE).strict}function gz(e){const{drag:t,layout:n}=cd;if(!t&&!n)return{};const i={...t,...n};return{MeasureLayout:t!=null&&t.isEnabled(e)||n!=null&&n.isEnabled(e)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}const _z=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function dw(e){return typeof e!="string"||e.includes("-")?!1:!!(_z.indexOf(e)>-1||/[A-Z]/u.test(e))}function UE(e,{style:t,vars:n},i,o){Object.assign(e.style,t,o&&o.getProjectionStyles(i));for(const a in n)e.style.setProperty(a,n[a])}const WE=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function GE(e,t,n,i){UE(e,t,void 0,i);for(const o in t.attrs)e.setAttribute(WE.has(o)?o:t_(o),t.attrs[o])}function qE(e,{layout:t,layoutId:n}){return Rl.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Ig[e]||e==="opacity")}function fw(e,t,n){var i;const{style:o}=e,a={};for(const l in o)(ls(o[l])||t.style&&ls(t.style[l])||qE(l,e)||((i=n==null?void 0:n.getValue(l))===null||i===void 0?void 0:i.liveStyle)!==void 0)&&(a[l]=o[l]);return n&&o&&typeof o.willChange=="string"&&(n.applyWillChange=!1),a}function HE(e,t,n){const i=fw(e,t,n);for(const o in e)if(ls(e[o])||ls(t[o])){const a=bp.indexOf(o)!==-1?"attr"+o.charAt(0).toUpperCase()+o.substring(1):o;i[a]=e[o]}return i}function yz(e){const t=en.useRef(null);return t.current===null&&(t.current=e()),t.current}function vz({applyWillChange:e=!1,scrapeMotionValuesFromProps:t,createRenderState:n,onMount:i},o,a,l,d){const c={latestValues:bz(o,a,l,d?!1:e,t),renderState:n()};return i&&(c.mount=p=>i(o,p,c)),c}const KE=e=>(t,n)=>{const i=en.useContext(r_),o=en.useContext(lw),a=()=>vz(e,t,i,o,n);return n?a():yz(a)};function wz(e,t){const n=fE(t);n&&Jg(e,n)}function OT(e,t,n){const i=Array.isArray(t)?t:[t];for(let o=0;o{for(const k in E){let A=E[k];if(Array.isArray(A)){const N=I?A.length-1:0;A=A[N]}A!==null&&(l[k]=A)}for(const k in x)l[k]=x[k]}),c&&(_&&v!==!1&&!cp(_)&&OT(e,_,E=>{for(const x in E)wz(d,x)}),d.length&&(l.willChange=d.join(","))),l}const hw=()=>({style:{},transform:{},transformOrigin:{},vars:{}}),XE=()=>({...hw(),attrs:{}}),QE=(e,t)=>t&&typeof e=="number"?t.transform(e):e,xz={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Tz=bp.length;function Mz(e,t,n){let i="",o=!0;for(let a=0;atypeof e=="string"&&e.toLowerCase()==="svg",Pz={useVisualState:KE({scrapeMotionValuesFromProps:HE,createRenderState:XE,onMount:(e,t,{renderState:n,latestValues:i})=>{Dr.read(()=>{try{n.dimensions=typeof t.getBBox=="function"?t.getBBox():t.getBoundingClientRect()}catch{n.dimensions={x:0,y:0,width:0,height:0}}}),Dr.render(()=>{mw(n,i,gw(t.tagName),e.transformTemplate),GE(t,n)})}})},Az={useVisualState:KE({applyWillChange:!0,scrapeMotionValuesFromProps:fw,createRenderState:hw})};function YE(e,t,n){for(const i in t)!ls(t[i])&&!qE(i,n)&&(e[i]=t[i])}function $z({transformTemplate:e},t){return en.useMemo(()=>{const n=hw();return pw(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Iz(e,t){const n=e.style||{},i={};return YE(i,n,e),Object.assign(i,$z(e,t)),i}function Fz(e,t){const n={},i=Iz(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=i,n}const Oz=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function Fg(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||Oz.has(e)}let ZE=e=>!Fg(e);function Dz(e){e&&(ZE=t=>t.startsWith("on")?!Fg(t):e(t))}try{Dz(require("@emotion/is-prop-valid").default)}catch{}function zz(e,t,n){const i={};for(const o in e)o==="values"&&typeof e.values=="object"||(ZE(o)||n===!0&&Fg(o)||!t&&!Fg(o)||e.draggable&&o.startsWith("onDrag"))&&(i[o]=e[o]);return i}function Rz(e,t,n,i){const o=en.useMemo(()=>{const a=XE();return mw(a,t,gw(i),e.transformTemplate),{...a.attrs,style:{...a.style}}},[t]);if(e.style){const a={};YE(a,e.style,e),o.style={...a,...o.style}}return o}function Lz(e=!1){return(n,i,o,{latestValues:a},l)=>{const c=(dw(n)?Rz:Fz)(i,a,l,n),p=zz(i,typeof n=="string",e),v=n!==en.Fragment?{...p,...c,ref:o}:{},{children:_}=i,T=en.useMemo(()=>ls(_)?_.get():_,[_]);return en.createElement(n,{...v,children:T})}}function Bz(e,t){return function(i,{forwardMotionProps:o}={forwardMotionProps:!1}){const l={...dw(i)?Pz:Az,preloadedFeatures:e,useRender:Lz(o),createVisualElement:t,Component:i};return hz(l)}}const H0={current:null},JE={current:!1};function Nz(){if(JE.current=!0,!!cw)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>H0.current=e.matches;e.addListener(t),t()}else H0.current=!1}function jz(e,t,n){for(const i in t){const o=t[i],a=n[i];if(ls(o))e.addValue(i,o);else if(ls(a))e.addValue(i,pp(o,{owner:e}));else if(a!==o)if(e.hasValue(i)){const l=e.getValue(i);l.liveStyle===!0?l.jump(o):l.hasAnimated||l.set(o)}else{const l=e.getStaticValue(i);e.addValue(i,pp(l!==void 0?l:o,{owner:e}))}}for(const i in n)t[i]===void 0&&e.removeValue(i);return t}const zT=new WeakMap,Vz=[...zS,os,Fl],Uz=e=>Vz.find(DS(e)),RT=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"],Wz=Hv.length;class Gz{scrapeMotionValuesFromProps(t,n,i){return{}}constructor({parent:t,props:n,presenceContext:i,reducedMotionConfig:o,blockInitialAnimation:a,visualState:l},d={}){this.applyWillChange=!1,this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Yv,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.isRenderScheduled=!1,this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.isRenderScheduled=!1,this.scheduleRender=()=>{this.isRenderScheduled||(this.isRenderScheduled=!0,Dr.render(this.render,!1,!0))};const{latestValues:c,renderState:p}=l;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=p,this.parent=t,this.props=n,this.presenceContext=i,this.depth=t?t.depth+1:0,this.reducedMotionConfig=o,this.options=d,this.blockInitialAnimation=!!a,this.isControllingVariants=i_(n),this.isVariantNode=VE(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:v,..._}=this.scrapeMotionValuesFromProps(n,{},this);for(const T in _){const M=_[T];c[T]!==void 0&&ls(M)&&M.set(c[T],!1)}}mount(t){this.current=t,zT.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),JE.current||Nz(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:H0.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){zT.delete(this.current),this.projection&&this.projection.unmount(),Wa(this.notifyUpdate),Wa(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}bindToMotionValue(t,n){this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)();const i=Rl.has(t),o=n.on("change",d=>{this.latestValues[t]=d,this.props.onUpdate&&Dr.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),a=n.on("renderRequest",this.scheduleRender);let l;window.MotionCheckAppearSync&&(l=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{o(),a(),l&&l(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in cd){const n=cd[t];if(!n)continue;const{isEnabled:i,Feature:o}=n;if(!this.features[t]&&o&&i(this.props)&&(this.features[t]=new o(this)),this.features[t]){const a=this.features[t];a.isMounted?a.update():(a.mount(),a.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):pi()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;in.variantChildren.delete(t)}addValue(t,n){const i=this.values.get(t);n!==i&&(i&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let i=this.values.get(t);return i===void 0&&n!==void 0&&(i=pp(n===null?void 0:n,{owner:this}),this.addValue(t,i)),i}readValue(t,n){var i;let o=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:(i=this.getBaseTargetFromProps(this.props,t))!==null&&i!==void 0?i:this.readValueFromInstance(this.current,t,this.options);return o!=null&&(typeof o=="string"&&($S(o)||AS(o))?o=parseFloat(o):!Uz(o)&&Fl.test(n)&&(o=WS(t,n)),this.setBaseTarget(t,ls(o)?o.get():o)),ls(o)?o.get():o}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var n;const{initial:i}=this.props;let o;if(typeof i=="string"||typeof i=="object"){const l=Gv(this.props,i,(n=this.presenceContext)===null||n===void 0?void 0:n.custom);l&&(o=l[t])}if(i&&o!==void 0)return o;const a=this.getBaseTargetFromProps(this.props,t);return a!==void 0&&!ls(a)?a:this.initialValues[t]!==void 0&&o===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new aw),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}}class eC extends Gz{constructor(){super(...arguments),this.KeyframeResolver=GS}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:i}){delete n[t],delete i[t]}}function qz(e){return window.getComputedStyle(e)}class Hz extends eC{constructor(){super(...arguments),this.type="html",this.applyWillChange=!0,this.renderInstance=UE}readValueFromInstance(t,n){if(Rl.has(n)){const i=ew(n);return i&&i.default||0}else{const i=qz(t),o=(FS(n)?i.getPropertyValue(n):i[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return kE(t,n)}build(t,n,i){pw(t,n,i.transformTemplate)}scrapeMotionValuesFromProps(t,n,i){return fw(t,n,i)}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;ls(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Kz extends eC{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=pi}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Rl.has(n)){const i=ew(n);return i&&i.default||0}return n=WE.has(n)?n:t_(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,i){return HE(t,n,i)}build(t,n,i){mw(t,n,this.isSVGTag,i.transformTemplate)}renderInstance(t,n,i,o){GE(t,n,i,o)}mount(t){this.isSVGTag=gw(t.tagName),super.mount(t)}}const Xz=(e,t)=>dw(e)?new Kz(t):new Hz(t,{allowProjection:e!==en.Fragment}),Qz=Bz({...OO,...nz,...GD,...rz},Xz),na=P3(Qz);function Yz(){const e=h3(()=>Oa.images.reverse().toArray()),[t,n]=en.useState(null),[i,o]=en.useState([]),[a,l]=en.useState(!1),[d,c]=en.useState(null),[p,v]=en.useState(!1),_=en.useMemo(()=>(e==null?void 0:e.filter(A=>A.processedFile instanceof File).length)||0,[e]),T=()=>{i.length===(e==null?void 0:e.length)?o([]):o((e==null?void 0:e.map(A=>A.id).filter(A=>A!==void 0))||[])},M=async()=>{await Oa.images.bulkDelete(i),o([])},I=async()=>{const A=await Oa.images.where("id").anyOf(i).toArray(),N=new wS;for(const B of A)B.processedFile instanceof File&&N.file(B.processedFile.name,B.processedFile);const R=await N.generateAsync({type:"blob"});xS.saveAs(R,"selected_processed_images.zip")},C=()=>{v(!p),p||o([])},E=A=>{if(!p)return;l(!0),c(A);const N=e==null?void 0:e[A].id;N!==void 0&&o(R=>R.includes(N)?R.filter(B=>B!==N):[...R,N])},x=()=>{l(!1),c(null)},k=A=>{if(p&&a&&d!==null&&e){const N=e[A].id;N!==void 0&&o(R=>R.includes(e[d].id??-1)?Array.from(new Set([...R,N])):R.filter(W=>W!==N))}};return en.useEffect(()=>{const A=()=>{l(!1),c(null)};return window.addEventListener("mouseup",A),()=>{window.removeEventListener("mouseup",A)}},[]),Yt.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 sm:p-6 rounded-lg shadow-lg",children:[Yt.jsxs("div",{className:"flex justify-between items-center mb-4",children:[Yt.jsxs("h2",{className:"text-xl sm:text-2xl font-bold text-gray-800 dark:text-white",children:["Images: ",e==null?void 0:e.length," (Processed: ",_,", Selected: ",i.length,")"]}),Yt.jsxs("div",{className:"flex gap-2 items-center",children:[Yt.jsxs("button",{onClick:C,className:`text-white px-3 py-1 rounded-full text-sm transition-colors ${p?"bg-blue-500 hover:bg-blue-600":"bg-gray-500 hover:bg-gray-600"}`,children:[p?Yt.jsx(E3,{className:"inline mr-2"}):Yt.jsx(S3,{className:"inline mr-2"}),p?"Disable Selection":"Enable Selection"]}),p&&Yt.jsxs(Yt.Fragment,{children:[Yt.jsx("button",{onClick:T,className:"bg-blue-500 text-white px-3 py-1 rounded-full text-sm hover:bg-blue-600 transition-colors",children:i.length===(e==null?void 0:e.length)?"Deselect All":"Select All"}),Yt.jsxs("button",{onClick:M,disabled:i.length===0,className:"bg-red-500 text-white px-3 py-1 rounded-full text-sm hover:bg-red-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:["Delete Selected (",i.length,")"]}),Yt.jsxs("button",{onClick:I,disabled:i.length===0,className:"bg-green-500 text-white px-3 py-1 rounded-full text-sm hover:bg-green-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:["Download Selected (",i.length,")"]})]})]})]}),Yt.jsx(na.div,{className:"gap-2 sm:gap-4 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5",layout:!0,children:e==null?void 0:e.map((A,N)=>A.file.type.includes("video")?Yt.jsx(Zz,{video:A},A.id):Yt.jsx(Jz,{image:A,onPreview:()=>n(A),isSelected:i.includes(A.id??-1),onToggleSelect:()=>{p&&o(R=>R.includes(A.id??-1)?R.filter(B=>B!==A.id):[...R,A.id??-1])},onMouseDown:()=>E(N),onMouseEnter:()=>k(N),onMouseUp:x,selectionEnabled:p},A.id))}),t&&Yt.jsx(eR,{image:t,onClose:()=>n(null)})]})}function Zz({video:e}){const t=URL.createObjectURL(e.file);return Yt.jsx("div",{className:"aspect-square rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow duration-300",children:Yt.jsx("video",{className:"w-full h-full object-cover",loop:!0,muted:!0,autoPlay:!0,playsInline:!0,src:t})})}function Jz({image:e,onPreview:t,isSelected:n,onToggleSelect:i,onMouseDown:o,onMouseEnter:a,onMouseUp:l,selectionEnabled:d}){const[c,p]=en.useState(!1),v=en.useRef(null),_=e.processedFile instanceof File,T=URL.createObjectURL(e.file),M=_?URL.createObjectURL(e.processedFile):"",I=async C=>{if(C.stopPropagation(),_)try{const E=await fetch(M).then(x=>x.blob());await navigator.clipboard.write([new ClipboardItem({[E.type]:E})]),alert("Image copied to clipboard!")}catch(E){console.error("Failed to copy image: ",E),alert("Failed to copy image. See console for details.")}};return Yt.jsxs(na.div,{ref:v,className:`aspect-square relative group rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-all duration-300 cursor-pointer image-hover ${n&&d?"selected-image":""}`,onClick:C=>{C.stopPropagation(),d?i():t()},onMouseDown:C=>{C.preventDefault(),d&&o()},onMouseEnter:()=>{p(!0),a()},onMouseLeave:()=>p(!1),onMouseUp:l,whileHover:{scale:1.05},transition:{type:"spring",stiffness:300,damping:10},children:[Yt.jsx(na.img,{className:"w-full h-full object-cover",src:T,alt:e.file.name,initial:{opacity:0},animate:{opacity:1},transition:{duration:.3}}),!_&&Yt.jsxs(na.div,{className:"absolute inset-0 overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.5},children:[Yt.jsx("div",{className:"absolute inset-0 bg-black bg-opacity-50 dark:bg-opacity-70"}),Yt.jsx(na.div,{className:"absolute inset-0 matrix-scan",initial:{y:"-100%"},animate:{y:"100%"},transition:{repeat:1/0,duration:2,ease:"linear"}}),Yt.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:Yt.jsx("div",{className:"text-green-400 dark:text-green-300 font-mono text-lg",children:"Processing..."})})]}),_&&Yt.jsx(na.img,{className:"absolute inset-0 w-full h-full object-cover bg-checkered",src:M,alt:"Processed",initial:{opacity:0},animate:{opacity:c?0:1},transition:{duration:.3}}),c&&_&&Yt.jsx(na.div,{className:"absolute inset-x-0 bottom-4 flex justify-center items-center",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.3},children:Yt.jsx("div",{className:"bg-black bg-opacity-50 text-white px-2 py-1 rounded-full text-sm",children:"Hover to see original"})}),Yt.jsxs(na.div,{className:"controls absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-all duration-300 flex justify-end gap-2",initial:{opacity:0,y:-10},animate:{opacity:c?1:0,y:c?0:-10},transition:{duration:.3},children:[Yt.jsx("button",{onClick:C=>{C.stopPropagation(),Oa.images.delete(e.id)},className:"bg-red-500 text-white p-2 rounded-full text-xs sm:text-sm hover:bg-red-600 transition-colors button-hover",children:Yt.jsx(C3,{})}),_&&Yt.jsxs(Yt.Fragment,{children:[Yt.jsx("button",{onClick:I,className:"bg-blue-500 text-white p-2 rounded-full text-xs sm:text-sm hover:bg-blue-600 transition-colors button-hover",children:Yt.jsx(SS,{})}),Yt.jsx("a",{href:M,download:e.processedFile instanceof File?e.processedFile.name:void 0,className:"bg-green-500 text-white p-2 rounded-full text-xs sm:text-sm hover:bg-green-600 transition-colors flex items-center justify-center button-hover",onClick:C=>C.stopPropagation(),children:Yt.jsx(ES,{})})]})]}),d&&Yt.jsx(na.div,{className:"absolute top-2 left-2 z-10",initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:300,damping:20},children:Yt.jsx(na.div,{className:`w-6 h-6 rounded-full border-2 ${n?"bg-blue-500 border-blue-500":"border-white"} flex items-center justify-center`,initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:300,damping:20},children:n&&Yt.jsx(b3,{className:"text-white"})})})]})}function eR({image:e,onClose:t}){const n=e.processedFile instanceof File,i=URL.createObjectURL(e.file),o=n?URL.createObjectURL(e.processedFile):"",a=async()=>{if(n)try{const l=await fetch(o).then(d=>d.blob());await navigator.clipboard.write([new ClipboardItem({[l.type]:l})]),alert("Image copied to clipboard!")}catch(l){console.error("Failed to copy image: ",l),alert("Failed to copy image. See console for details.")}};return Yt.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",onClick:t,children:Yt.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 sm:p-6 rounded-lg max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:l=>l.stopPropagation(),children:[Yt.jsxs("div",{className:"flex justify-between items-center mb-4",children:[Yt.jsx("h3",{className:"text-xl sm:text-2xl font-bold text-gray-800 dark:text-white",children:e.file.name}),Yt.jsx("button",{onClick:t,className:"text-2xl sm:text-3xl text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-white transition-colors",children:Yt.jsx(k3,{})})]}),Yt.jsxs("div",{className:"grid gap-4 sm:gap-6 grid-cols-1 sm:grid-cols-2",children:[Yt.jsxs("div",{children:[Yt.jsx("h4",{className:"text-base sm:text-lg font-semibold mb-2 text-gray-700 dark:text-gray-300",children:"Original"}),Yt.jsx("img",{src:i,alt:"Original",className:"w-full h-auto rounded-lg shadow-md"})]}),Yt.jsxs("div",{children:[Yt.jsx("h4",{className:"text-base sm:text-lg font-semibold mb-2 text-gray-700 dark:text-gray-300",children:"Processed"}),n?Yt.jsx("img",{src:o,alt:"Processed",className:"w-full h-auto bg-checkered rounded-lg shadow-md"}):Yt.jsx("div",{className:"w-full h-0 pb-[100%] bg-gray-200 animate-pulse rounded-lg"})]})]}),Yt.jsx("div",{className:"mt-4 sm:mt-6 flex flex-wrap justify-end gap-2 sm:gap-4",children:n&&Yt.jsxs(Yt.Fragment,{children:[Yt.jsxs("button",{onClick:a,className:"bg-blue-500 text-white px-4 py-2 rounded-full hover:bg-blue-600 transition-colors text-sm sm:text-base font-semibold flex items-center",children:[Yt.jsx(SS,{className:"mr-2"})," Copy to Clipboard"]}),Yt.jsxs("a",{href:o,download:e.processedFile instanceof File?e.processedFile.name:void 0,className:"bg-green-500 text-white px-4 py-2 rounded-full hover:bg-green-600 transition-colors text-sm sm:text-base font-semibold flex items-center",children:[Yt.jsx(ES,{className:"mr-2"})," Download Processed Image"]})]})})]})})}const LT="Xenova/modnet";var BT;(BT=$0.backends.onnx)!=null&&BT.wasm&&($0.backends.onnx.wasm.proxy=!1);let K0=null,X0=null,Fy=null;function tR(){return Fy||(Fy=(async()=>{K0=await _S.from_pretrained(LT,{device:"webgpu"}),X0=await yS.from_pretrained(LT)})()),Fy}async function nR(e){(!K0||!X0)&&await tR();const t=await w2.fromURL(URL.createObjectURL(e)),{pixel_values:n}=await X0(t),{output:i}=await K0({input:n}),o=(await w2.fromTensor(i[0].mul(255).to("uint8")).resize(t.width,t.height)).data,a=document.createElement("canvas");a.width=t.width,a.height=t.height;const l=a.getContext("2d");if(!l)throw new Error("Could not get 2d context");l.drawImage(t.toCanvas(),0,0);const d=l.getImageData(0,0,t.width,t.height);for(let T=0;Ta.toBlob(I=>I?T(I):M(),"image/png")),[p,v]=e.name.split(".");return new File([c],`${p}-bg-blasted.png`,{type:"image/png"})}async function rR(){console.log("Processing images...");const e=Oa.images.where("processedFile").equals("null").reverse();console.log("imagesToProcess",await e.toArray());for(const t of await e.toArray()){console.log("Processing image",t.id);const n=await nR(t.file);await Oa.images.update(t.id,{processedFile:n})}console.log("Processing images done")}function iR(){en.useState([]),en.useState([]),en.useState(!1),en.useState(!1);const[e,t]=en.useState(!0),[n,i]=en.useState(null),o=en.useRef(null),a=en.useRef(null),[l,d]=en.useState(!1);en.useEffect(()=>{(async()=>{try{if(!("gpu"in navigator))throw new Error("WebGPU is not supported in this browser.");const E="Xenova/modnet";$0.backends.onnx.wasm.proxy=!1,o.current??(o.current=await _S.from_pretrained(E,{device:"webgpu"})),a.current??(a.current=await yS.from_pretrained(E))}catch(E){i(E)}t(!1)})()},[]);const c=en.useCallback(async E=>{for(const x of E){const k=await Oa.images.add({file:x,processedFile:"null"});console.log(`Added image with id ${k}`)}await rR()},[]),{getRootProps:p,getInputProps:v,isDragActive:_,isDragAccept:T,isDragReject:M}=fS({onDrop:c,accept:{"image/*":[".jpeg",".jpg",".png",".mp4"]}}),I=async()=>{const E=await Oa.images.toArray(),x=new wS;for(const A of E)A.processedFile instanceof File&&x.file(A.processedFile.name,A.processedFile);const k=await x.generateAsync({type:"blob"});xS.saveAs(k,"processed_images.zip")},C=()=>{d(!l),document.documentElement.classList.toggle("dark"),localStorage.setItem("darkMode",(!l).toString())};return n?Yt.jsx("div",{className:"min-h-screen bg-gradient-to-br from-red-100 to-red-200 text-red-800 flex items-center justify-center",children:Yt.jsxs("div",{className:"text-center bg-white p-8 rounded-lg shadow-2xl",children:[Yt.jsx("h2",{className:"text-4xl font-bold mb-4",children:"ERROR"}),Yt.jsx("p",{className:"text-xl max-w-[500px]",children:n.message})]})}):e?Yt.jsx("div",{className:"min-h-screen bg-gradient-to-br from-blue-100 to-purple-100 text-blue-800 flex items-center justify-center",children:Yt.jsxs("div",{className:"text-center",children:[Yt.jsx("div",{className:"inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-800 mb-4"}),Yt.jsx("p",{className:"text-xl",children:"Loading background removal model..."})]})}):Yt.jsx("div",{className:`min-h-screen bg-gradient-to-br ${l?"from-gray-800 to-gray-900 text-white":"from-blue-100 to-purple-100 text-gray-800"} p-4 sm:p-8 transition-colors duration-300`,children:Yt.jsxs("div",{className:"max-w-6xl mx-auto",children:[Yt.jsx("div",{className:"flex justify-end mb-4",children:Yt.jsx("button",{onClick:C,className:"p-2 rounded-full bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white",children:l?Yt.jsx(M3,{}):Yt.jsx(T3,{})})}),Yt.jsx("h1",{className:"text-3xl sm:text-5xl font-bold mb-2 sm:mb-4 text-center text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-purple-600 dark:from-blue-400 dark:to-purple-400",children:"Remove Background WebGPU"}),Yt.jsxs("h2",{className:"text-lg sm:text-xl font-semibold mb-4 sm:mb-6 text-center text-gray-600",children:["In-browser background removal, powered by"," ",Yt.jsx("a",{className:"underline hover:text-blue-600 transition-colors",target:"_blank",href:"https://github.com/xenova/transformers.js",children:"🤗 Transformers.js"})]}),Yt.jsxs("div",{className:"flex flex-wrap justify-center mb-4 sm:mb-8 gap-4 sm:gap-8",children:[Yt.jsx("a",{className:"underline hover:text-blue-600 transition-colors",target:"_blank",href:"https://github.com/huggingface/transformers.js-examples/blob/main/LICENSE",children:"License (Apache 2.0)"}),Yt.jsx("a",{className:"underline hover:text-blue-600 transition-colors",target:"_blank",href:"https://huggingface.co./Xenova/modnet",children:"Model (MODNet)"}),Yt.jsx("a",{className:"underline hover:text-blue-600 transition-colors",target:"_blank",href:"https://github.com/huggingface/transformers.js-examples/tree/main/remove-background-webgpu/",children:"Code (GitHub)"})]}),Yt.jsx("div",{className:"flex justify-center mb-4 sm:mb-8",children:Yt.jsxs("button",{onClick:I,className:"bg-green-500 text-white px-4 sm:px-6 py-2 rounded-full hover:bg-green-600 transition-colors text-sm sm:text-lg font-semibold flex items-center",children:[Yt.jsx(x3,{className:"mr-2"}),"Download All Processed Images"]})}),Yt.jsxs("div",{...p(),className:`p-4 sm:p-8 mb-4 sm:mb-8 border-2 border-dashed rounded-lg text-center cursor-pointer transition-all duration-300 ease-in-out hover:shadow-xl bg-white ${T?"border-green-500 bg-green-100":""} ${M?"border-red-500 bg-red-100":""} ${_?"border-blue-500 bg-blue-100":"border-gray-300 hover:border-blue-400 hover:bg-blue-50"} `,children:[Yt.jsx("input",{...v(),className:"hidden"}),Yt.jsx("p",{className:"text-lg sm:text-xl mb-2",children:_?"Drop the images here...":"Drag and drop some images here"}),Yt.jsx("p",{className:"text-xs sm:text-sm text-gray-500",children:"or click to select files"})]}),Yt.jsx(Yz,{})]})})}Zk(document.getElementById("root")).render(Yt.jsx(en.StrictMode,{children:Yt.jsx(iR,{})}));