(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 Eo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Eg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var FM={exports:{}},Cg={},OM={exports:{}},hr={};/** * @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 Hh=Symbol.for("react.element"),PP=Symbol.for("react.portal"),AP=Symbol.for("react.fragment"),$P=Symbol.for("react.strict_mode"),IP=Symbol.for("react.profiler"),FP=Symbol.for("react.provider"),OP=Symbol.for("react.context"),DP=Symbol.for("react.forward_ref"),zP=Symbol.for("react.suspense"),RP=Symbol.for("react.memo"),LP=Symbol.for("react.lazy"),Hb=Symbol.iterator;function BP(e){return e===null||typeof e!="object"?null:(e=Hb&&e[Hb]||e["@@iterator"],typeof e=="function"?e:null)}var DM={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},zM=Object.assign,RM={};function rd(e,t,n){this.props=e,this.context=t,this.refs=RM,this.updater=n||DM}rd.prototype.isReactComponent={};rd.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")};rd.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function LM(){}LM.prototype=rd.prototype;function U0(e,t,n){this.props=e,this.context=t,this.refs=RM,this.updater=n||DM}var W0=U0.prototype=new LM;W0.constructor=U0;zM(W0,rd.prototype);W0.isPureReactComponent=!0;var Kb=Array.isArray,BM=Object.prototype.hasOwnProperty,G0={current:null},NM={key:!0,ref:!0,__self:!0,__source:!0};function jM(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)BM.call(t,i)&&!NM.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(Ze,Pe))uto(Mt,Ze)?(te[ne]=Mt,te[ut]=Pe,ne=ut):(te[ne]=Ze,te[Qe]=Pe,ne=Qe);else if(uto(Mt,Pe))te[ne]=Mt,te[ut]=Pe,ne=ut;else break e}}return fe}function o(te,fe){var Pe=te.sortIndex-fe.sortIndex;return Pe!==0?Pe: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=[],h=[],w=1,_=null,M=3,T=!1,F=!1,C=!1,E=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,S=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function P(te){for(var fe=n(h);fe!==null;){if(fe.callback===null)i(h);else if(fe.startTime<=te)i(h),fe.sortIndex=fe.expirationTime,t(c,fe);else break;fe=n(h)}}function j(te){if(C=!1,P(te),!F)if(n(c)!==null)F=!0,pt(L);else{var fe=n(h);fe!==null&&Te(j,fe.startTime-te)}}function L(te,fe){F=!1,C&&(C=!1,x(V),V=-1),T=!0;var Pe=M;try{for(P(fe),_=n(c);_!==null&&(!(_.expirationTime>fe)||te&&!Re());){var ne=_.callback;if(typeof ne=="function"){_.callback=null,M=_.priorityLevel;var xe=ne(_.expirationTime<=fe);fe=e.unstable_now(),typeof xe=="function"?_.callback=xe:_===n(c)&&i(c),P(fe)}else i(c);_=n(c)}if(_!==null)var ht=!0;else{var Qe=n(h);Qe!==null&&Te(j,Qe.startTime-fe),ht=!1}return ht}finally{_=null,M=Pe,T=!1}}var N=!1,W=null,V=-1,ce=5,ge=-1;function Re(){return!(e.unstable_now()-gete||125ne?(te.sortIndex=Pe,t(h,te),n(c)===null&&te===n(h)&&(C?(x(V),V=-1):C=!0,Te(j,Pe-ne))):(te.sortIndex=xe,t(c,te),F||T||(F=!0,pt(L))),te},e.unstable_shouldYield=Re,e.unstable_wrapCallback=function(te){var fe=M;return function(){var Pe=M;M=fe;try{return te.apply(this,arguments)}finally{M=Pe}}}})(qM);GM.exports=qM;var QP=GM.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 YP=Yt,Ns=QP;function Zt(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"),Py=Object.prototype.hasOwnProperty,ZP=/^[: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]*$/,Qb={},Yb={};function JP(e){return Py.call(Yb,e)?!0:Py.call(Qb,e)?!1:ZP.test(e)?Yb[e]=!0:(Qb[e]=!0,!1)}function eA(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 tA(e,t,n,i){if(t===null||typeof t>"u"||eA(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 ys(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 Wi={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Wi[e]=new ys(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Wi[t]=new ys(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Wi[e]=new ys(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Wi[e]=new ys(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){Wi[e]=new ys(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Wi[e]=new ys(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Wi[e]=new ys(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Wi[e]=new ys(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Wi[e]=new ys(e,5,!1,e.toLowerCase(),null,!1,!1)});var H0=/[\-:]([a-z])/g;function K0(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(H0,K0);Wi[t]=new ys(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(H0,K0);Wi[t]=new ys(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(H0,K0);Wi[t]=new ys(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Wi[e]=new ys(e,1,!1,e.toLowerCase(),null,!1,!1)});Wi.xlinkHref=new ys("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Wi[e]=new ys(e,1,!1,e.toLowerCase(),null,!0,!0)});function X0(e,t,n,i){var o=Wi.hasOwnProperty(t)?Wi[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{V_=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ih(e):""}function nA(e){switch(e.tag){case 5:return ih(e.type);case 16:return ih("Lazy");case 13:return ih("Suspense");case 19:return ih("SuspenseList");case 0:case 2:case 15:return e=U_(e.type,!1),e;case 11:return e=U_(e.type.render,!1),e;case 1:return e=U_(e.type,!0),e;default:return""}}function Fy(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 kc:return"Fragment";case Sc:return"Portal";case Ay:return"Profiler";case Q0:return"StrictMode";case $y:return"Suspense";case Iy:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case XM:return(e.displayName||"Context")+".Consumer";case KM:return(e._context.displayName||"Context")+".Provider";case Y0:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Z0:return t=e.displayName||null,t!==null?t:Fy(e.type)||"Memo";case hl:t=e._payload,e=e._init;try{return Fy(e(t))}catch{}}return null}function rA(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 Fy(t);case 8:return t===Q0?"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 El(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function YM(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function iA(e){var t=YM(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 um(e){e._valueTracker||(e._valueTracker=iA(e))}function ZM(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),i="";return e&&(i=YM(e)?e.checked?"true":"false":e.value),e=i,e!==n?(t.setValue(e),!0):!1}function Gm(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 Oy(e,t){var n=t.checked;return ri({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Jb(e,t){var n=t.defaultValue==null?"":t.defaultValue,i=t.checked!=null?t.checked:t.defaultChecked;n=El(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 JM(e,t){t=t.checked,t!=null&&X0(e,"checked",t,!1)}function Dy(e,t){JM(e,t);var n=El(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")?zy(e,t.type,n):t.hasOwnProperty("defaultValue")&&zy(e,t.type,El(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ex(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 zy(e,t,n){(t!=="number"||Gm(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var sh=Array.isArray;function Vc(e,t,n,i){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=cm.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Sh(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var dh={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},sA=["Webkit","ms","Moz","O"];Object.keys(dh).forEach(function(e){sA.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),dh[t]=dh[e]})});function rT(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||dh.hasOwnProperty(e)&&dh[e]?(""+t).trim():t+"px"}function iT(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var i=n.indexOf("--")===0,o=rT(n,t[n],i);n==="float"&&(n="cssFloat"),i?e.setProperty(n,o):e[n]=o}}var oA=ri({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 By(e,t){if(t){if(oA[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Zt(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Zt(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Zt(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Zt(62))}}function Ny(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 jy=null;function J0(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Vy=null,Uc=null,Wc=null;function rx(e){if(e=Qh(e)){if(typeof Vy!="function")throw Error(Zt(280));var t=e.stateNode;t&&(t=Fg(t),Vy(e.stateNode,e.type,t))}}function sT(e){Uc?Wc?Wc.push(e):Wc=[e]:Uc=e}function oT(){if(Uc){var e=Uc,t=Wc;if(Wc=Uc=null,rx(e),t)for(e=0;e>>=0,e===0?32:31-(_A(e)/yA|0)|0}var dm=64,fm=4194304;function oh(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 Xm(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=oh(d):(a&=l,a!==0&&(i=oh(a)))}else l=n&~o,l!==0?i=oh(l):a!==0&&(i=oh(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 Kh(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Co(t),e[t]=n}function xA(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=hh),fx=" ",hx=!1;function kT(e,t){switch(e){case"keyup":return QA.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ET(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ec=!1;function ZA(e,t){switch(e){case"compositionend":return ET(t);case"keypress":return t.which!==32?null:(hx=!0,fx);case"textInput":return e=t.data,e===fx&&hx?null:e;default:return null}}function JA(e,t){if(Ec)return e==="compositionend"||!av&&kT(e,t)?(e=TT(),Im=iv=_l=null,Ec=!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=_x(n)}}function $T(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?$T(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function IT(){for(var e=window,t=Gm();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Gm(e.document)}return t}function lv(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 l$(e){var t=IT(),n=e.focusedElem,i=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&$T(n.ownerDocument.documentElement,n)){if(i!==null&&lv(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=yx(n,a);var l=yx(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,Cc=null,Ky=null,mh=null,Xy=!1;function vx(e,t,n){var i=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Xy||Cc==null||Cc!==Gm(i)||(i=Cc,"selectionStart"in i&&lv(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}),mh&&$h(mh,i)||(mh=i,i=Zm(Ky,"onSelect"),0$c||(e.current=t0[$c],t0[$c]=null,$c--)}function Vr(e,t){$c++,t0[$c]=e.current,e.current=t}var Cl={},ss=Il(Cl),Cs=Il(!1),bu=Cl;function Xc(e,t){var n=e.type.contextTypes;if(!n)return Cl;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 Ps(e){return e=e.childContextTypes,e!=null}function eg(){qr(Cs),qr(ss)}function kx(e,t,n){if(ss.current!==Cl)throw Error(Zt(168));Vr(ss,t),Vr(Cs,n)}function jT(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(Zt(108,rA(e)||"Unknown",o));return ri({},n,i)}function tg(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cl,bu=ss.current,Vr(ss,e),Vr(Cs,Cs.current),!0}function Ex(e,t,n){var i=e.stateNode;if(!i)throw Error(Zt(169));n?(e=jT(e,t,bu),i.__reactInternalMemoizedMergedChildContext=e,qr(Cs),qr(ss),Vr(ss,e)):qr(Cs),Vr(Cs,n)}var Ea=null,Og=!1,ry=!1;function VT(e){Ea===null?Ea=[e]:Ea.push(e)}function w$(e){Og=!0,VT(e)}function Fl(){if(!ry&&Ea!==null){ry=!0;var e=0,t=Or;try{var n=Ea;for(Or=1;e>=l,o-=l,Ca=1<<32-Co(t)+o|n<V?(ce=W,W=null):ce=W.sibling;var ge=M(x,W,P[V],j);if(ge===null){W===null&&(W=ce);break}e&&W&&ge.alternate===null&&t(x,W),S=a(ge,S,V),N===null?L=ge:N.sibling=ge,N=ge,W=ce}if(V===P.length)return n(x,W),Xr&&uu(x,V),L;if(W===null){for(;VV?(ce=W,W=null):ce=W.sibling;var Re=M(x,W,ge.value,j);if(Re===null){W===null&&(W=ce);break}e&&W&&Re.alternate===null&&t(x,W),S=a(Re,S,V),N===null?L=Re:N.sibling=Re,N=Re,W=ce}if(ge.done)return n(x,W),Xr&&uu(x,V),L;if(W===null){for(;!ge.done;V++,ge=P.next())ge=_(x,ge.value,j),ge!==null&&(S=a(ge,S,V),N===null?L=ge:N.sibling=ge,N=ge);return Xr&&uu(x,V),L}for(W=i(x,W);!ge.done;V++,ge=P.next())ge=T(W,x,V,ge.value,j),ge!==null&&(e&&ge.alternate!==null&&W.delete(ge.key===null?V:ge.key),S=a(ge,S,V),N===null?L=ge:N.sibling=ge,N=ge);return e&&W.forEach(function(oe){return t(x,oe)}),Xr&&uu(x,V),L}function E(x,S,P,j){if(typeof P=="object"&&P!==null&&P.type===kc&&P.key===null&&(P=P.props.children),typeof P=="object"&&P!==null){switch(P.$$typeof){case lm:e:{for(var L=P.key,N=S;N!==null;){if(N.key===L){if(L=P.type,L===kc){if(N.tag===7){n(x,N.sibling),S=o(N,P.props.children),S.return=x,x=S;break e}}else if(N.elementType===L||typeof L=="object"&&L!==null&&L.$$typeof===hl&&Ax(L)===N.type){n(x,N.sibling),S=o(N,P.props),S.ref=Jf(x,N,P),S.return=x,x=S;break e}n(x,N);break}else t(x,N);N=N.sibling}P.type===kc?(S=vu(P.props.children,x.mode,j,P.key),S.return=x,x=S):(j=Nm(P.type,P.key,P.props,null,x.mode,j),j.ref=Jf(x,S,P),j.return=x,x=j)}return l(x);case Sc:e:{for(N=P.key;S!==null;){if(S.key===N)if(S.tag===4&&S.stateNode.containerInfo===P.containerInfo&&S.stateNode.implementation===P.implementation){n(x,S.sibling),S=o(S,P.children||[]),S.return=x,x=S;break e}else{n(x,S);break}else t(x,S);S=S.sibling}S=dy(P,x.mode,j),S.return=x,x=S}return l(x);case hl:return N=P._init,E(x,S,N(P._payload),j)}if(sh(P))return F(x,S,P,j);if(Kf(P))return C(x,S,P,j);vm(x,P)}return typeof P=="string"&&P!==""||typeof P=="number"?(P=""+P,S!==null&&S.tag===6?(n(x,S.sibling),S=o(S,P),S.return=x,x=S):(n(x,S),S=cy(P,x.mode,j),S.return=x,x=S),l(x)):n(x,S)}return E}var Yc=qT(!0),HT=qT(!1),ig=Il(null),sg=null,Oc=null,fv=null;function hv(){fv=Oc=sg=null}function pv(e){var t=ig.current;qr(ig),e._currentValue=t}function i0(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 qc(e,t){sg=e,fv=Oc=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Es=!0),e.firstContext=null)}function so(e){var t=e._currentValue;if(fv!==e)if(e={context:e,memoizedValue:t,next:null},Oc===null){if(sg===null)throw Error(Zt(308));Oc=e,sg.dependencies={lanes:0,firstContext:e}}else Oc=Oc.next=e;return t}var mu=null;function mv(e){mu===null?mu=[e]:mu.push(e)}function KT(e,t,n,i){var o=t.interleaved;return o===null?(n.next=n,mv(t)):(n.next=o.next,o.next=n),t.interleaved=n,Na(e,i)}function Na(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 pl=!1;function gv(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function XT(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 $a(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ml(e,t,n){var i=e.updateQueue;if(i===null)return null;if(i=i.shared,wr&2){var o=i.pending;return o===null?t.next=t:(t.next=o.next,o.next=t),i.pending=t,Na(e,n)}return o=i.interleaved,o===null?(t.next=t,mv(i)):(t.next=o.next,o.next=t),i.interleaved=t,Na(e,n)}function Om(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,tv(e,n)}}function $x(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 og(e,t,n,i){var o=e.updateQueue;pl=!1;var a=o.firstBaseUpdate,l=o.lastBaseUpdate,d=o.shared.pending;if(d!==null){o.shared.pending=null;var c=d,h=c.next;c.next=null,l===null?a=h:l.next=h,l=c;var w=e.alternate;w!==null&&(w=w.updateQueue,d=w.lastBaseUpdate,d!==l&&(d===null?w.firstBaseUpdate=h:d.next=h,w.lastBaseUpdate=c))}if(a!==null){var _=o.baseState;l=0,w=h=c=null,d=a;do{var M=d.lane,T=d.eventTime;if((i&M)===M){w!==null&&(w=w.next={eventTime:T,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var F=e,C=d;switch(M=t,T=n,C.tag){case 1:if(F=C.payload,typeof F=="function"){_=F.call(T,_,M);break e}_=F;break e;case 3:F.flags=F.flags&-65537|128;case 0:if(F=C.payload,M=typeof F=="function"?F.call(T,_,M):F,M==null)break e;_=ri({},_,M);break e;case 2:pl=!0}}d.callback!==null&&d.lane!==0&&(e.flags|=64,M=o.effects,M===null?o.effects=[d]:M.push(d))}else T={eventTime:T,lane:M,tag:d.tag,payload:d.payload,callback:d.callback,next:null},w===null?(h=w=T,c=_):w=w.next=T,l|=M;if(d=d.next,d===null){if(d=o.shared.pending,d===null)break;M=d,d=M.next,M.next=null,o.lastBaseUpdate=M,o.shared.pending=null}}while(!0);if(w===null&&(c=_),o.baseState=c,o.firstBaseUpdate=h,o.lastBaseUpdate=w,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 Ix(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var i=sy.transition;sy.transition={};try{e(!1),t()}finally{Or=n,sy.transition=i}}function fS(){return oo().memoizedState}function T$(e,t,n){var i=Sl(e);if(n={lane:i,action:n,hasEagerState:!1,eagerState:null,next:null},hS(e))pS(t,n);else if(n=KT(e,t,n,i),n!==null){var o=gs();Po(n,e,i,o),mS(n,t,i)}}function S$(e,t,n){var i=Sl(e),o={lane:i,action:n,hasEagerState:!1,eagerState:null,next:null};if(hS(e))pS(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,Ao(d,l)){var c=t.interleaved;c===null?(o.next=o,mv(t)):(o.next=c.next,c.next=o),t.interleaved=o;return}}catch{}finally{}n=KT(e,t,o,i),n!==null&&(o=gs(),Po(n,e,i,o),mS(n,t,i))}}function hS(e){var t=e.alternate;return e===ni||t!==null&&t===ni}function pS(e,t){gh=lg=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function mS(e,t,n){if(n&4194240){var i=t.lanes;i&=e.pendingLanes,n|=i,t.lanes=n,tv(e,n)}}var ug={readContext:so,useCallback:Ji,useContext:Ji,useEffect:Ji,useImperativeHandle:Ji,useInsertionEffect:Ji,useLayoutEffect:Ji,useMemo:Ji,useReducer:Ji,useRef:Ji,useState:Ji,useDebugValue:Ji,useDeferredValue:Ji,useTransition:Ji,useMutableSource:Ji,useSyncExternalStore:Ji,useId:Ji,unstable_isNewReconciler:!1},k$={readContext:so,useCallback:function(e,t){return na().memoizedState=[e,t===void 0?null:t],e},useContext:so,useEffect:Ox,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,zm(4194308,4,aS.bind(null,t,e),n)},useLayoutEffect:function(e,t){return zm(4194308,4,e,t)},useInsertionEffect:function(e,t){return zm(4,2,e,t)},useMemo:function(e,t){var n=na();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var i=na();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=T$.bind(null,ni,e),[i.memoizedState,e]},useRef:function(e){var t=na();return e={current:e},t.memoizedState=e},useState:Fx,useDebugValue:Tv,useDeferredValue:function(e){return na().memoizedState=e},useTransition:function(){var e=Fx(!1),t=e[0];return e=M$.bind(null,e[1]),na().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var i=ni,o=na();if(Xr){if(n===void 0)throw Error(Zt(407));n=n()}else{if(n=t(),zi===null)throw Error(Zt(349));Mu&30||JT(i,t,n)}o.memoizedState=n;var a={value:n,getSnapshot:t};return o.queue=a,Ox(tS.bind(null,i,a,e),[e]),i.flags|=2048,Bh(9,eS.bind(null,i,a,n,t),void 0,null),n},useId:function(){var e=na(),t=zi.identifierPrefix;if(Xr){var n=Pa,i=Ca;n=(i&~(1<<32-Co(i)-1)).toString(32)+n,t=":"+t+"R"+n,n=Rh++,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[ra]=t,e[Oh]=i,SS(e,t,!1,!1),t.stateNode=e;e:{switch(l=Ny(n,i),n){case"dialog":Gr("cancel",e),Gr("close",e),o=i;break;case"iframe":case"object":case"embed":Gr("load",e),o=i;break;case"video":case"audio":for(o=0;oed&&(t.flags|=128,i=!0,eh(a,!1),t.lanes=4194304)}else{if(!i)if(e=ag(l),e!==null){if(t.flags|=128,i=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eh(a,!0),a.tail===null&&a.tailMode==="hidden"&&!l.alternate&&!Xr)return es(t),null}else 2*pi()-a.renderingStartTime>ed&&n!==1073741824&&(t.flags|=128,i=!0,eh(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=pi(),t.sibling=null,n=ei.current,Vr(ei,i?n&1|2:n&1),t):(es(t),null);case 22:case 23:return Av(),i=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==i&&(t.flags|=8192),i&&t.mode&1?zs&1073741824&&(es(t),t.subtreeFlags&6&&(t.flags|=8192)):es(t),null;case 24:return null;case 25:return null}throw Error(Zt(156,t.tag))}function O$(e,t){switch(cv(t),t.tag){case 1:return Ps(t.type)&&eg(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Zc(),qr(Cs),qr(ss),vv(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return yv(t),null;case 13:if(qr(ei),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Zt(340));Qc()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return qr(ei),null;case 4:return Zc(),null;case 10:return pv(t.type._context),null;case 22:case 23:return Av(),null;case 24:return null;default:return null}}var bm=!1,ns=!1,D$=typeof WeakSet=="function"?WeakSet:Set,wn=null;function Dc(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(i){ai(e,t,i)}else n.current=null}function h0(e,t,n){try{n()}catch(i){ai(e,t,i)}}var Gx=!1;function z$(e,t){if(Qy=Qm,e=IT(),lv(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,h=0,w=0,_=e,M=null;t:for(;;){for(var T;_!==n||o!==0&&_.nodeType!==3||(d=l+o),_!==a||i!==0&&_.nodeType!==3||(c=l+i),_.nodeType===3&&(l+=_.nodeValue.length),(T=_.firstChild)!==null;)M=_,_=T;for(;;){if(_===e)break t;if(M===n&&++h===o&&(d=l),M===a&&++w===i&&(c=l),(T=_.nextSibling)!==null)break;_=M,M=_.parentNode}_=T}n=d===-1||c===-1?null:{start:d,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Yy={focusedElem:e,selectionRange:n},Qm=!1,wn=t;wn!==null;)if(t=wn,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,wn=e;else for(;wn!==null;){t=wn;try{var F=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(F!==null){var C=F.memoizedProps,E=F.memoizedState,x=t.stateNode,S=x.getSnapshotBeforeUpdate(t.elementType===t.type?C:To(t.type,C),E);x.__reactInternalSnapshotBeforeUpdate=S}break;case 3:var P=t.stateNode.containerInfo;P.nodeType===1?P.textContent="":P.nodeType===9&&P.documentElement&&P.removeChild(P.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Zt(163))}}catch(j){ai(t,t.return,j)}if(e=t.sibling,e!==null){e.return=t.return,wn=e;break}wn=t.return}return F=Gx,Gx=!1,F}function _h(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&&h0(t,n,a)}o=o.next}while(o!==i)}}function Rg(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 p0(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 CS(e){var t=e.alternate;t!==null&&(e.alternate=null,CS(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[ra],delete t[Oh],delete t[e0],delete t[y$],delete t[v$])),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 PS(e){return e.tag===5||e.tag===3||e.tag===4}function qx(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||PS(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 m0(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=Jm));else if(i!==4&&(e=e.child,e!==null))for(m0(e,t,n),e=e.sibling;e!==null;)m0(e,t,n),e=e.sibling}function g0(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(g0(e,t,n),e=e.sibling;e!==null;)g0(e,t,n),e=e.sibling}var ji=null,So=!1;function dl(e,t,n){for(n=n.child;n!==null;)AS(e,t,n),n=n.sibling}function AS(e,t,n){if(ia&&typeof ia.onCommitFiberUnmount=="function")try{ia.onCommitFiberUnmount(Pg,n)}catch{}switch(n.tag){case 5:ns||Dc(n,t);case 6:var i=ji,o=So;ji=null,dl(e,t,n),ji=i,So=o,ji!==null&&(So?(e=ji,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ji.removeChild(n.stateNode));break;case 18:ji!==null&&(So?(e=ji,n=n.stateNode,e.nodeType===8?ny(e.parentNode,n):e.nodeType===1&&ny(e,n),Ph(e)):ny(ji,n.stateNode));break;case 4:i=ji,o=So,ji=n.stateNode.containerInfo,So=!0,dl(e,t,n),ji=i,So=o;break;case 0:case 11:case 14:case 15:if(!ns&&(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)&&h0(n,t,l),o=o.next}while(o!==i)}dl(e,t,n);break;case 1:if(!ns&&(Dc(n,t),i=n.stateNode,typeof i.componentWillUnmount=="function"))try{i.props=n.memoizedProps,i.state=n.memoizedState,i.componentWillUnmount()}catch(d){ai(n,t,d)}dl(e,t,n);break;case 21:dl(e,t,n);break;case 22:n.mode&1?(ns=(i=ns)||n.memoizedState!==null,dl(e,t,n),ns=i):dl(e,t,n);break;default:dl(e,t,n)}}function Hx(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new D$),t.forEach(function(i){var o=G$.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=pi()-i,i=(120>i?120:480>i?480:1080>i?1080:1920>i?1920:3e3>i?3e3:4320>i?4320:1960*L$(i/1960))-i,10e?16:e,yl===null)var i=!1;else{if(e=yl,yl=null,fg=0,wr&6)throw Error(Zt(331));var o=wr;for(wr|=4,wn=e.current;wn!==null;){var a=wn,l=a.child;if(wn.flags&16){var d=a.deletions;if(d!==null){for(var c=0;cpi()-Cv?yu(e,0):Ev|=n),As(e,t)}function LS(e,t){t===0&&(e.mode&1?(t=fm,fm<<=1,!(fm&130023424)&&(fm=4194304)):t=1);var n=gs();e=Na(e,t),e!==null&&(Kh(e,t,n),As(e,n))}function W$(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),LS(e,n)}function G$(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(Zt(314))}i!==null&&i.delete(t),LS(e,n)}var BS;BS=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Cs.current)Es=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Es=!1,I$(e,t,n);Es=!!(e.flags&131072)}else Es=!1,Xr&&t.flags&1048576&&UT(t,rg,t.index);switch(t.lanes=0,t.tag){case 2:var i=t.type;Rm(e,t),e=t.pendingProps;var o=Xc(t,ss.current);qc(t,n),o=bv(null,t,i,e,o,n);var a=xv();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,Ps(i)?(a=!0,tg(t)):a=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,gv(t),o.updater=zg,t.stateNode=o,o._reactInternals=t,o0(t,i,e,n),t=u0(null,t,i,!0,a,n)):(t.tag=0,Xr&&a&&uv(t),ms(null,t,o,n),t=t.child),t;case 16:i=t.elementType;e:{switch(Rm(e,t),e=t.pendingProps,o=i._init,i=o(i._payload),t.type=i,o=t.tag=H$(i),e=To(i,e),o){case 0:t=l0(null,t,i,e,n);break e;case 1:t=Vx(null,t,i,e,n);break e;case 11:t=Nx(null,t,i,e,n);break e;case 14:t=jx(null,t,i,To(i.type,e),n);break e}throw Error(Zt(306,i,""))}return t;case 0:return i=t.type,o=t.pendingProps,o=t.elementType===i?o:To(i,o),l0(e,t,i,o,n);case 1:return i=t.type,o=t.pendingProps,o=t.elementType===i?o:To(i,o),Vx(e,t,i,o,n);case 3:e:{if(xS(t),e===null)throw Error(Zt(387));i=t.pendingProps,a=t.memoizedState,o=a.element,XT(e,t),og(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=Jc(Error(Zt(423)),t),t=Ux(e,t,i,n,o);break e}else if(i!==o){o=Jc(Error(Zt(424)),t),t=Ux(e,t,i,n,o);break e}else for(Ls=xl(t.stateNode.containerInfo.firstChild),Bs=t,Xr=!0,ko=null,n=HT(t,null,i,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Qc(),i===o){t=ja(e,t,n);break e}ms(e,t,i,n)}t=t.child}return t;case 5:return QT(t),e===null&&r0(t),i=t.type,o=t.pendingProps,a=e!==null?e.memoizedProps:null,l=o.children,Zy(i,o)?l=null:a!==null&&Zy(i,a)&&(t.flags|=32),bS(e,t),ms(e,t,l,n),t.child;case 6:return e===null&&r0(t),null;case 13:return MS(e,t,n);case 4:return _v(t,t.stateNode.containerInfo),i=t.pendingProps,e===null?t.child=Yc(t,null,i,n):ms(e,t,i,n),t.child;case 11:return i=t.type,o=t.pendingProps,o=t.elementType===i?o:To(i,o),Nx(e,t,i,o,n);case 7:return ms(e,t,t.pendingProps,n),t.child;case 8:return ms(e,t,t.pendingProps.children,n),t.child;case 12:return ms(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,Vr(ig,i._currentValue),i._currentValue=l,a!==null)if(Ao(a.value,l)){if(a.children===o.children&&!Cs.current){t=ja(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=$a(-1,n&-n),c.tag=2;var h=a.updateQueue;if(h!==null){h=h.shared;var w=h.pending;w===null?c.next=c:(c.next=w.next,w.next=c),h.pending=c}}a.lanes|=n,c=a.alternate,c!==null&&(c.lanes|=n),i0(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(Zt(341));l.lanes|=n,d=l.alternate,d!==null&&(d.lanes|=n),i0(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}ms(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,i=t.pendingProps.children,qc(t,n),o=so(o),i=i(o),t.flags|=1,ms(e,t,i,n),t.child;case 14:return i=t.type,o=To(i,t.pendingProps),o=To(i.type,o),jx(e,t,i,o,n);case 15:return vS(e,t,t.type,t.pendingProps,n);case 17:return i=t.type,o=t.pendingProps,o=t.elementType===i?o:To(i,o),Rm(e,t),t.tag=1,Ps(i)?(e=!0,tg(t)):e=!1,qc(t,n),gS(t,i,o),o0(t,i,o,n),u0(null,t,i,!0,e,n);case 19:return TS(e,t,n);case 22:return wS(e,t,n)}throw Error(Zt(156,t.tag))};function NS(e,t){return hT(e,t)}function q$(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 ro(e,t,n,i){return new q$(e,t,n,i)}function Iv(e){return e=e.prototype,!(!e||!e.isReactComponent)}function H$(e){if(typeof e=="function")return Iv(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Y0)return 11;if(e===Z0)return 14}return 2}function kl(e,t){var n=e.alternate;return n===null?(n=ro(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 Nm(e,t,n,i,o,a){var l=2;if(i=e,typeof e=="function")Iv(e)&&(l=1);else if(typeof e=="string")l=5;else e:switch(e){case kc:return vu(n.children,o,a,t);case Q0:l=8,o|=8;break;case Ay:return e=ro(12,n,t,o|2),e.elementType=Ay,e.lanes=a,e;case $y:return e=ro(13,n,t,o),e.elementType=$y,e.lanes=a,e;case Iy:return e=ro(19,n,t,o),e.elementType=Iy,e.lanes=a,e;case QM:return Bg(n,o,a,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case KM:l=10;break e;case XM:l=9;break e;case Y0:l=11;break e;case Z0:l=14;break e;case hl:l=16,i=null;break e}throw Error(Zt(130,e==null?e:typeof e,""))}return t=ro(l,n,t,o),t.elementType=e,t.type=i,t.lanes=a,t}function vu(e,t,n,i){return e=ro(7,e,i,t),e.lanes=n,e}function Bg(e,t,n,i){return e=ro(22,e,i,t),e.elementType=QM,e.lanes=n,e.stateNode={isHidden:!1},e}function cy(e,t,n){return e=ro(6,e,null,t),e.lanes=n,e}function dy(e,t,n){return t=ro(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function K$(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=G_(0),this.expirationTimes=G_(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=G_(0),this.identifierPrefix=i,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Fv(e,t,n,i,o,a,l,d,c){return e=new K$(e,t,n,d,c),t===1?(t=1,a===!0&&(t|=8)):t=0,a=ro(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:i,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},gv(a),e}function X$(e,t,n){var i=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(WS)}catch(e){console.error(e)}}WS(),WM.exports=Vs;var eI=WM.exports,GS,t2=eI;GS=t2.createRoot,t2.hydrateRoot;var qS={exports:{}},tI="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",nI=tI,rI=nI;function HS(){}function KS(){}KS.resetWarningCache=HS;var iI=function(){function e(i,o,a,l,d,c){if(c!==rI){var h=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 h.name="Invariant Violation",h}}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:KS,resetWarningCache:HS};return n.PropTypes=n,n};qS.exports=iI();var sI=qS.exports;const Lr=Eg(sI);function od(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(w){try{h(i.next(w))}catch(_){l(_)}}function c(w){try{h(i.throw(w))}catch(_){l(_)}}function h(w){w.done?a(w.value):o(w.value).then(d,c)}h((i=i.apply(e,t||[])).next())})}function ad(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(h){return function(w){return c([h,w])}}function c(h){if(i)throw new TypeError("Generator is already executing.");for(;l&&(l=0,h[0]&&(n=0)),n;)try{if(i=1,o&&(a=h[0]&2?o.return:h[0]?o.throw||((a=o.return)&&a.call(o),0):o.next)&&!(a=a.call(o,h[1])).done)return a;switch(o=0,a&&(h=[h[0]&2,a.value]),h[0]){case 0:case 1:a=h;break;case 4:return n.label++,{value:h[1],done:!1};case 5:n.label++,o=h[1],h=[0];continue;case 7:h=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(h[0]===6||h[0]===2)){n=0;continue}if(h[0]===3&&(!a||h[1]>a[0]&&h[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 r2(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 aI(e){var t=e.name,n=t&&t.lastIndexOf(".")!==-1;if(n&&!e.type){var i=t.split(".").pop().toLowerCase(),o=oI.get(i);o&&Object.defineProperty(e,"type",{value:o,writable:!1,configurable:!1,enumerable:!0})}return e}var lI=[".DS_Store","Thumbs.db"];function uI(e){return od(this,void 0,void 0,function(){return ad(this,function(t){return mg(e)&&cI(e.dataTransfer)?[2,pI(e.dataTransfer,e.type)]:dI(e)?[2,fI(e)]:Array.isArray(e)&&e.every(function(n){return"getFile"in n&&typeof n.getFile=="function"})?[2,hI(e)]:[2,[]]})})}function cI(e){return mg(e)}function dI(e){return mg(e)&&mg(e.target)}function mg(e){return typeof e=="object"&&e!==null}function fI(e){return b0(e.target.files).map(function(t){return Zh(t)})}function hI(e){return od(this,void 0,void 0,function(){var t;return ad(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 Zh(i)})]}})})}function pI(e,t){return od(this,void 0,void 0,function(){var n,i;return ad(this,function(o){switch(o.label){case 0:return e.items?(n=b0(e.items).filter(function(a){return a.kind==="file"}),t!=="drop"?[2,n]:[4,Promise.all(n.map(mI))]):[3,2];case 1:return i=o.sent(),[2,i2(XS(i))];case 2:return[2,i2(b0(e.files).map(function(a){return Zh(a)}))]}})})}function i2(e){return e.filter(function(t){return lI.indexOf(t.name)===-1})}function b0(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,u2(n)];if(e.sizen)return[!1,u2(n)]}return[!0,null]}function hu(e){return e!=null}function $I(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 h=JS(c,n),w=jh(h,1),_=w[0],M=ek(c,i,o),T=jh(M,1),F=T[0],C=d?d(c):null;return _&&F&&!C})}function gg(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function Tm(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 d2(e){e.preventDefault()}function II(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function FI(e){return e.indexOf("Edge/")!==-1}function OI(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return II(e)||FI(e)}function ea(){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 YI(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 Rv=Yt.forwardRef(function(e,t){var n=e.children,i=_g(e,NI),o=sk(i),a=o.open,l=_g(o,jI);return Yt.useImperativeHandle(t,function(){return{open:a}},[a]),Rs.createElement(Yt.Fragment,null,n(Jr(Jr({},l),{},{open:a})))});Rv.displayName="Dropzone";var ik={disabled:!1,getFilesFromEvent:uI,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};Rv.defaultProps=ik;Rv.propTypes={children:Lr.func,accept:Lr.objectOf(Lr.arrayOf(Lr.string)),multiple:Lr.bool,preventDropOnDocument:Lr.bool,noClick:Lr.bool,noKeyboard:Lr.bool,noDrag:Lr.bool,noDragEventsBubbling:Lr.bool,minSize:Lr.number,maxSize:Lr.number,maxFiles:Lr.number,disabled:Lr.bool,getFilesFromEvent:Lr.func,onFileDialogCancel:Lr.func,onFileDialogOpen:Lr.func,useFsAccessApi:Lr.bool,autoFocus:Lr.bool,onDragEnter:Lr.func,onDragLeave:Lr.func,onDragOver:Lr.func,onDrop:Lr.func,onDropAccepted:Lr.func,onDropRejected:Lr.func,onError:Lr.func,validator:Lr.func};var S0={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function sk(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Jr(Jr({},ik),e),n=t.accept,i=t.disabled,o=t.getFilesFromEvent,a=t.maxSize,l=t.minSize,d=t.multiple,c=t.maxFiles,h=t.onDragEnter,w=t.onDragLeave,_=t.onDragOver,M=t.onDrop,T=t.onDropAccepted,F=t.onDropRejected,C=t.onFileDialogCancel,E=t.onFileDialogOpen,x=t.useFsAccessApi,S=t.autoFocus,P=t.preventDropOnDocument,j=t.noClick,L=t.noKeyboard,N=t.noDrag,W=t.noDragEventsBubbling,V=t.onError,ce=t.validator,ge=Yt.useMemo(function(){return RI(n)},[n]),Re=Yt.useMemo(function(){return zI(n)},[n]),oe=Yt.useMemo(function(){return typeof E=="function"?E:h2},[E]),Se=Yt.useMemo(function(){return typeof C=="function"?C:h2},[C]),G=Yt.useRef(null),Ce=Yt.useRef(null),pt=Yt.useReducer(ZI,S0),Te=fy(pt,2),te=Te[0],fe=Te[1],Pe=te.isFocused,ne=te.isFileDialogActive,xe=Yt.useRef(typeof window<"u"&&window.isSecureContext&&x&&DI()),ht=function(){!xe.current&&ne&&setTimeout(function(){if(Ce.current){var Ie=Ce.current.files;Ie.length||(fe({type:"closeDialog"}),Se())}},300)};Yt.useEffect(function(){return window.addEventListener("focus",ht,!1),function(){window.removeEventListener("focus",ht,!1)}},[Ce,ne,Se,xe]);var Qe=Yt.useRef([]),Ze=function(Ie){G.current&&G.current.contains(Ie.target)||(Ie.preventDefault(),Qe.current=[])};Yt.useEffect(function(){return P&&(document.addEventListener("dragover",d2,!1),document.addEventListener("drop",Ze,!1)),function(){P&&(document.removeEventListener("dragover",d2),document.removeEventListener("drop",Ze))}},[G,P]),Yt.useEffect(function(){return!i&&S&&G.current&&G.current.focus(),function(){}},[G,S,i]);var ut=Yt.useCallback(function(pe){V?V(pe):console.error(pe)},[V]),Mt=Yt.useCallback(function(pe){pe.preventDefault(),pe.persist(),H(pe),Qe.current=[].concat(WI(Qe.current),[pe.target]),Tm(pe)&&Promise.resolve(o(pe)).then(function(Ie){if(!(gg(pe)&&!W)){var Xe=Ie.length,St=Xe>0&&$I({files:Ie,accept:ge,minSize:l,maxSize:a,multiple:d,maxFiles:c,validator:ce}),ft=Xe>0&&!St;fe({isDragAccept:St,isDragReject:ft,isDragActive:!0,type:"setDraggedFiles"}),h&&h(pe)}}).catch(function(Ie){return ut(Ie)})},[o,h,ut,W,ge,l,a,d,c,ce]),Ft=Yt.useCallback(function(pe){pe.preventDefault(),pe.persist(),H(pe);var Ie=Tm(pe);if(Ie&&pe.dataTransfer)try{pe.dataTransfer.dropEffect="copy"}catch{}return Ie&&_&&_(pe),!1},[_,W]),Ve=Yt.useCallback(function(pe){pe.preventDefault(),pe.persist(),H(pe);var Ie=Qe.current.filter(function(St){return G.current&&G.current.contains(St)}),Xe=Ie.indexOf(pe.target);Xe!==-1&&Ie.splice(Xe,1),Qe.current=Ie,!(Ie.length>0)&&(fe({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),Tm(pe)&&w&&w(pe))},[G,w,W]),ke=Yt.useCallback(function(pe,Ie){var Xe=[],St=[];pe.forEach(function(ft){var Dt=JS(ft,ge),Jt=fy(Dt,2),kt=Jt[0],ve=Jt[1],Ne=ek(ft,l,a),rt=fy(Ne,2),Ye=rt[0],mt=rt[1],At=ce?ce(ft):null;if(kt&&Ye&&!At)Xe.push(ft);else{var jt=[ve,mt];At&&(jt=jt.concat(At)),St.push({file:ft,errors:jt.filter(function(it){return it})})}}),(!d&&Xe.length>1||d&&c>=1&&Xe.length>c)&&(Xe.forEach(function(ft){St.push({file:ft,errors:[AI]})}),Xe.splice(0)),fe({acceptedFiles:Xe,fileRejections:St,type:"setFiles"}),M&&M(Xe,St,Ie),St.length>0&&F&&F(St,Ie),Xe.length>0&&T&&T(Xe,Ie)},[fe,d,ge,l,a,c,M,T,F,ce]),lt=Yt.useCallback(function(pe){pe.preventDefault(),pe.persist(),H(pe),Qe.current=[],Tm(pe)&&Promise.resolve(o(pe)).then(function(Ie){gg(pe)&&!W||ke(Ie,pe)}).catch(function(Ie){return ut(Ie)}),fe({type:"reset"})},[o,ke,ut,W]),dt=Yt.useCallback(function(){if(xe.current){fe({type:"openDialog"}),oe();var pe={multiple:d,types:Re};window.showOpenFilePicker(pe).then(function(Ie){return o(Ie)}).then(function(Ie){ke(Ie,null),fe({type:"closeDialog"})}).catch(function(Ie){LI(Ie)?(Se(Ie),fe({type:"closeDialog"})):BI(Ie)?(xe.current=!1,Ce.current?(Ce.current.value=null,Ce.current.click()):ut(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."))):ut(Ie)});return}Ce.current&&(fe({type:"openDialog"}),oe(),Ce.current.value=null,Ce.current.click())},[fe,oe,Se,x,ke,ut,Re,d]),bt=Yt.useCallback(function(pe){!G.current||!G.current.isEqualNode(pe.target)||(pe.key===" "||pe.key==="Enter"||pe.keyCode===32||pe.keyCode===13)&&(pe.preventDefault(),dt())},[G,dt]),z=Yt.useCallback(function(){fe({type:"focus"})},[]),Fe=Yt.useCallback(function(){fe({type:"blur"})},[]),Oe=Yt.useCallback(function(){j||(OI()?setTimeout(dt,0):dt())},[j,dt]),he=function(Ie){return i?null:Ie},de=function(Ie){return L?null:he(Ie)},Ee=function(Ie){return N?null:he(Ie)},H=function(Ie){W&&Ie.stopPropagation()},se=Yt.useMemo(function(){return function(){var pe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Ie=pe.refKey,Xe=Ie===void 0?"ref":Ie,St=pe.role,ft=pe.onKeyDown,Dt=pe.onFocus,Jt=pe.onBlur,kt=pe.onClick,ve=pe.onDragEnter,Ne=pe.onDragOver,rt=pe.onDragLeave,Ye=pe.onDrop,mt=_g(pe,VI);return Jr(Jr(T0({onKeyDown:de(ea(ft,bt)),onFocus:de(ea(Dt,z)),onBlur:de(ea(Jt,Fe)),onClick:he(ea(kt,Oe)),onDragEnter:Ee(ea(ve,Mt)),onDragOver:Ee(ea(Ne,Ft)),onDragLeave:Ee(ea(rt,Ve)),onDrop:Ee(ea(Ye,lt)),role:typeof St=="string"&&St!==""?St:"presentation"},Xe,G),!i&&!L?{tabIndex:0}:{}),mt)}},[G,bt,z,Fe,Oe,Mt,Ft,Ve,lt,L,N,i]),K=Yt.useCallback(function(pe){pe.stopPropagation()},[]),_e=Yt.useMemo(function(){return function(){var pe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Ie=pe.refKey,Xe=Ie===void 0?"ref":Ie,St=pe.onChange,ft=pe.onClick,Dt=_g(pe,UI),Jt=T0({accept:ge,multiple:d,type:"file",style:{display:"none"},onChange:he(ea(St,lt)),onClick:he(ea(ft,K)),tabIndex:-1},Xe,Ce);return Jr(Jr({},Jt),Dt)}},[Ce,n,d,lt,i]);return Jr(Jr({},te),{},{isFocused:Pe&&!i,getRootProps:se,getInputProps:_e,rootRef:G,inputRef:Ce,open:he(dt)})}function ZI(e,t){switch(t.type){case"focus":return Jr(Jr({},e),{},{isFocused:!0});case"blur":return Jr(Jr({},e),{},{isFocused:!1});case"openDialog":return Jr(Jr({},S0),{},{isFileDialogActive:!0});case"closeDialog":return Jr(Jr({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return Jr(Jr({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return Jr(Jr({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return Jr({},S0);default:return e}}function h2(){}var hy={},ok={"./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:()=>Oe,Template:()=>Ee,parse:()=>Pe,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(H,se){this.value=H,this.type=se}};function l(H){return/\w/.test(H)}function d(H){return/[0-9]/.test(H)}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]],h=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function w(H,se={}){return H.endsWith(` `)&&(H=H.slice(0,-1)),H=H.replace(/{#.*?#}/gs,"{##}"),se.lstrip_blocks&&(H=H.replace(/^[ \t]*({[#%])/gm,"$1")),se.trim_blocks&&(H=H.replace(/([#%]})\n/g,"$1")),H.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function _(H,se={}){const K=[],_e=w(H,se);let pe=0;const Ie=Xe=>{let St="";for(;Xe(_e[pe]);){if(_e[pe]==="\\"){if(++pe,pe>=_e.length)throw new SyntaxError("Unexpected end of input");const ft=_e[pe++],Dt=h.get(ft);if(Dt===void 0)throw new SyntaxError(`Unexpected escaped character: ${ft}`);St+=Dt;continue}if(St+=_e[pe++],pe>=_e.length)throw new SyntaxError("Unexpected end of input")}return St};e:for(;pe<_e.length;){const Xe=K.at(-1)?.type;if(Xe===void 0||Xe===i.CloseStatement||Xe===i.CloseExpression){let ft="";for(;pe<_e.length&&!(_e[pe]==="{"&&(_e[pe+1]==="%"||_e[pe+1]==="{"));)ft+=_e[pe++];if(ft.length>0){K.push(new a(ft,i.Text));continue}}Ie(ft=>/\s/.test(ft));const St=_e[pe];if(St==="-"||St==="+"){const ft=K.at(-1)?.type;if(ft===i.Text||ft===void 0)throw new SyntaxError(`Unexpected character: ${St}`);switch(ft){case i.Identifier:case i.NumericLiteral:case i.BooleanLiteral:case i.StringLiteral:case i.CloseParen:case i.CloseSquareBracket:break;default:{++pe;const Dt=Ie(d);K.push(new a(`${St}${Dt}`,Dt.length>0?i.NumericLiteral:i.UnaryOperator));continue}}}for(const[ft,Dt]of c)if(_e.slice(pe,pe+ft.length)===ft){K.push(new a(ft,Dt)),pe+=ft.length;continue e}if(St==="'"||St==='"'){++pe;const ft=Ie(Dt=>Dt!==St);K.push(new a(ft,i.StringLiteral)),++pe;continue}if(d(St)){const ft=Ie(d);K.push(new a(ft,i.NumericLiteral));continue}if(l(St)){const ft=Ie(l),Dt=Object.hasOwn(o,ft)?o[ft]:i.Identifier;Dt===i.In&&K.at(-1)?.type===i.Not?(K.pop(),K.push(new a("not in",i.NotIn))):K.push(new a(ft,Dt));continue}throw new SyntaxError(`Unexpected character: ${St}`)}return K}var M=class{type="Statement"},T=class extends M{constructor(H){super(),this.body=H}type="Program"},F=class extends M{constructor(H,se,K){super(),this.test=H,this.body=se,this.alternate=K}type="If"},C=class extends M{constructor(H,se,K,_e){super(),this.loopvar=H,this.iterable=se,this.body=K,this.defaultBlock=_e}type="For"},E=class extends M{constructor(H,se){super(),this.assignee=H,this.value=se}type="Set"},x=class extends M{constructor(H,se,K){super(),this.name=H,this.args=se,this.body=K}type="Macro"},S=class extends M{type="Expression"},P=class extends S{constructor(H,se,K){super(),this.object=H,this.property=se,this.computed=K}type="MemberExpression"},j=class extends S{constructor(H,se){super(),this.callee=H,this.args=se}type="CallExpression"},L=class extends S{constructor(H){super(),this.value=H}type="Identifier"},N=class extends S{constructor(H){super(),this.value=H}type="Literal"},W=class extends N{type="NumericLiteral"},V=class extends N{type="StringLiteral"},ce=class extends N{type="BooleanLiteral"},ge=class extends N{type="ArrayLiteral"},Re=class extends N{type="TupleLiteral"},oe=class extends N{type="ObjectLiteral"},Se=class extends S{constructor(H,se,K){super(),this.operator=H,this.left=se,this.right=K}type="BinaryExpression"},G=class extends S{constructor(H,se){super(),this.operand=H,this.filter=se}type="FilterExpression"},Ce=class extends S{constructor(H,se){super(),this.iterable=H,this.test=se}type="SelectExpression"},pt=class extends S{constructor(H,se,K){super(),this.operand=H,this.negate=se,this.test=K}type="TestExpression"},Te=class extends S{constructor(H,se){super(),this.operator=H,this.argument=se}type="UnaryExpression"},te=class extends S{constructor(H=void 0,se=void 0,K=void 0){super(),this.start=H,this.stop=se,this.step=K}type="SliceExpression"},fe=class extends S{constructor(H,se){super(),this.key=H,this.value=se}type="KeywordArgumentExpression"};function Pe(H){const se=new T([]);let K=0;function _e(Et,Ht){const un=H[K++];if(!un||un.type!==Et)throw new Error(`Parser Error: ${Ht}. ${un.type} !== ${Et}.`);return un}function pe(){switch(H[K].type){case i.Text:return St();case i.OpenStatement:return ft();case i.OpenExpression:return Dt();default:throw new SyntaxError(`Unexpected token type: ${H[K].type}`)}}function Ie(...Et){return K+Et.length<=H.length&&Et.some((Ht,un)=>Ht!==H[K+un].type)}function Xe(...Et){return K+Et.length<=H.length&&Et.every((Ht,un)=>Ht===H[K+un].type)}function St(){return new V(_e(i.Text,"Expected text token").value)}function ft(){_e(i.OpenStatement,"Expected opening statement token");let Et;switch(H[K].type){case i.Set:++K,Et=Jt(),_e(i.CloseStatement,"Expected closing statement token");break;case i.If:++K,Et=kt(),_e(i.OpenStatement,"Expected {% token"),_e(i.EndIf,"Expected endif token"),_e(i.CloseStatement,"Expected %} token");break;case i.Macro:++K,Et=ve(),_e(i.OpenStatement,"Expected {% token"),_e(i.EndMacro,"Expected endmacro token"),_e(i.CloseStatement,"Expected %} token");break;case i.For:++K,Et=rt(),_e(i.OpenStatement,"Expected {% token"),_e(i.EndFor,"Expected endfor token"),_e(i.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${H[K].type}`)}return Et}function Dt(){_e(i.OpenExpression,"Expected opening expression token");const Et=Ye();return _e(i.CloseExpression,"Expected closing expression token"),Et}function Jt(){const Et=Ye();if(Xe(i.Equals)){++K;const Ht=Jt();return new E(Et,Ht)}return Et}function kt(){const Et=Ye();_e(i.CloseStatement,"Expected closing statement token");const Ht=[],un=[];for(;!(H[K]?.type===i.OpenStatement&&(H[K+1]?.type===i.ElseIf||H[K+1]?.type===i.Else||H[K+1]?.type===i.EndIf));)Ht.push(pe());if(H[K]?.type===i.OpenStatement&&H[K+1]?.type!==i.EndIf)if(++K,Xe(i.ElseIf))_e(i.ElseIf,"Expected elseif token"),un.push(kt());else for(_e(i.Else,"Expected else token"),_e(i.CloseStatement,"Expected closing statement token");!(H[K]?.type===i.OpenStatement&&H[K+1]?.type===i.EndIf);)un.push(pe());return new F(Et,Ht,un)}function ve(){const Et=Mn();if(Et.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Ht=fn();_e(i.CloseStatement,"Expected closing statement token");const un=[];for(;Ie(i.OpenStatement,i.EndMacro);)un.push(pe());return new x(Et,Ht,un)}function Ne(Et=!1){const Ht=Et?Mn:Ye,un=[Ht()],zr=Xe(i.Comma);for(;zr&&(++K,un.push(Ht()),!!Xe(i.Comma)););return zr?new Re(un):un[0]}function rt(){const Et=Ne(!0);if(!(Et instanceof L||Et instanceof Re))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Et.type} instead`);_e(i.In,"Expected `in` keyword following loop variable");const Ht=Ye();_e(i.CloseStatement,"Expected closing statement token");const un=[];for(;Ie(i.OpenStatement,i.EndFor)&&Ie(i.OpenStatement,i.Else);)un.push(pe());const zr=[];if(Xe(i.OpenStatement,i.Else))for(++K,++K,_e(i.CloseStatement,"Expected closing statement token");Ie(i.OpenStatement,i.EndFor);)zr.push(pe());return new C(Et,Ht,un,zr)}function Ye(){return mt()}function mt(){const Et=At();if(Xe(i.If)){++K;const Ht=At();if(Xe(i.Else)){++K;const un=At();return new F(Ht,[Et],[un])}else return new Ce(Et,Ht)}return Et}function At(){let Et=jt();for(;Xe(i.Or);){const Ht=H[K];++K;const un=jt();Et=new Se(Ht,Et,un)}return Et}function jt(){let Et=it();for(;Xe(i.And);){const Ht=H[K];++K;const un=it();Et=new Se(Ht,Et,un)}return Et}function it(){let Et;for(;Xe(i.Not);){const Ht=H[K];++K;const un=it();Et=new Te(Ht,un)}return Et??en()}function en(){let Et=Vt();for(;Xe(i.ComparisonBinaryOperator)||Xe(i.In)||Xe(i.NotIn);){const Ht=H[K];++K;const un=Vt();Et=new Se(Ht,Et,un)}return Et}function Vt(){let Et=Sn();for(;Xe(i.AdditiveBinaryOperator);){const Ht=H[K];++K;const un=Sn();Et=new Se(Ht,Et,un)}return Et}function xt(){const Et=mn();return Xe(i.OpenParen)?hn(Et):Et}function hn(Et){let Ht=new j(Et,fn());return Xe(i.OpenParen)&&(Ht=hn(Ht)),Ht}function fn(){_e(i.OpenParen,"Expected opening parenthesis for arguments list");const Et=Tn();return _e(i.CloseParen,"Expected closing parenthesis for arguments list"),Et}function Tn(){const Et=[];for(;!Xe(i.CloseParen);){let Ht=Ye();if(Xe(i.Equals)){if(++K,!(Ht instanceof L))throw new SyntaxError("Expected identifier for keyword argument");const un=Ye();Ht=new fe(Ht,un)}Et.push(Ht),Xe(i.Comma)&&++K}return Et}function bn(){const Et=[];let Ht=!1;for(;!Xe(i.CloseSquareBracket);)Xe(i.Colon)?(Et.push(void 0),++K,Ht=!0):(Et.push(Ye()),Xe(i.Colon)&&(++K,Ht=!0));if(Et.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Ht){if(Et.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new te(...Et)}return Et[0]}function mn(){let Et=Mn();for(;Xe(i.Dot)||Xe(i.OpenSquareBracket);){const Ht=H[K];++K;let un;const zr=Ht.type!==i.Dot;if(zr)un=bn(),_e(i.CloseSquareBracket,"Expected closing square bracket");else if(un=Mn(),un.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Et=new P(Et,un,zr)}return Et}function Sn(){let Et=An();for(;Xe(i.MultiplicativeBinaryOperator);){const Ht=H[K];++K;const un=An();Et=new Se(Ht,Et,un)}return Et}function An(){let Et=In();for(;Xe(i.Is);){++K;const Ht=Xe(i.Not);Ht&&++K;let un=Mn();if(un instanceof ce&&(un=new L(un.value.toString())),!(un instanceof L))throw new SyntaxError("Expected identifier for the test");Et=new pt(Et,Ht,un)}return Et}function In(){let Et=xt();for(;Xe(i.Pipe);){++K;let Ht=Mn();if(!(Ht instanceof L))throw new SyntaxError("Expected identifier for the filter");Xe(i.OpenParen)&&(Ht=hn(Ht)),Et=new G(Et,Ht)}return Et}function Mn(){const Et=H[K];switch(Et.type){case i.NumericLiteral:return++K,new W(Number(Et.value));case i.StringLiteral:return++K,new V(Et.value);case i.BooleanLiteral:return++K,new ce(Et.value.toLowerCase()==="true");case i.Identifier:return++K,new L(Et.value);case i.OpenParen:{++K;const Ht=Ne();if(H[K].type!==i.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${H[K].type} instead`);return++K,Ht}case i.OpenSquareBracket:{++K;const Ht=[];for(;!Xe(i.CloseSquareBracket);)Ht.push(Ye()),Xe(i.Comma)&&++K;return++K,new ge(Ht)}case i.OpenCurlyBracket:{++K;const Ht=new Map;for(;!Xe(i.CloseCurlyBracket);){const un=Ye();_e(i.Colon,"Expected colon between key and value in object literal");const zr=Ye();Ht.set(un,zr),Xe(i.Comma)&&++K}return++K,new oe(Ht)}default:throw new SyntaxError(`Unexpected token: ${Et.type}`)}}for(;K=0?(se=(se??=0)<0?Math.max(H.length+se,0):Math.min(se,H.length),K=(K??=H.length)<0?Math.max(H.length+K,0):Math.min(K,H.length)):(se=(se??=H.length-1)<0?Math.max(H.length+se,-1):Math.min(se,H.length-1),K=(K??=-1)<-1?Math.max(H.length+K,-1):Math.min(K,H.length-1));const Ie=[];for(let Xe=se;pe*Xese.toUpperCase())}var Qe=class{type="RuntimeValue";value;builtins=new Map;constructor(H=void 0){this.value=H}__bool__(){return new Mt(!!this.value)}},Ze=class extends Qe{type="NumericValue"},ut=class extends Qe{type="StringValue";builtins=new Map([["upper",new dt(()=>new ut(this.value.toUpperCase()))],["lower",new dt(()=>new ut(this.value.toLowerCase()))],["strip",new dt(()=>new ut(this.value.trim()))],["title",new dt(()=>new ut(ht(this.value)))],["length",new Ze(this.value.length)]])},Mt=class extends Qe{type="BooleanValue"},Ft=class extends Qe{type="ObjectValue";__bool__(){return new Mt(this.value.size>0)}builtins=new Map([["get",new dt(([H,se])=>{if(!(H instanceof ut))throw new Error(`Object key must be a string: got ${H.type}`);return this.value.get(H.value)??se??new bt})],["items",new dt(()=>new ke(Array.from(this.value.entries()).map(([H,se])=>new ke([new ut(H),se]))))]])},Ve=class extends Ft{type="KeywordArgumentsValue"},ke=class extends Qe{type="ArrayValue";builtins=new Map([["length",new Ze(this.value.length)]]);__bool__(){return new Mt(this.value.length>0)}},lt=class extends ke{type="TupleValue"},dt=class extends Qe{type="FunctionValue"},bt=class extends Qe{type="NullValue"},z=class extends Qe{type="UndefinedValue"},Fe=class{constructor(H){this.parent=H}variables=new Map([["namespace",new dt(H=>{if(H.length===0)return new Ft(new Map);if(H.length!==1||!(H[0]instanceof Ft))throw new Error("`namespace` expects either zero arguments or a single object argument");return H[0]})]]);tests=new Map([["boolean",H=>H.type==="BooleanValue"],["callable",H=>H instanceof dt],["odd",H=>{if(H.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${H.type}`);return H.value%2!==0}],["even",H=>{if(H.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${H.type}`);return H.value%2===0}],["false",H=>H.type==="BooleanValue"&&!H.value],["true",H=>H.type==="BooleanValue"&&H.value],["string",H=>H.type==="StringValue"],["number",H=>H.type==="NumericValue"],["integer",H=>H.type==="NumericValue"&&Number.isInteger(H.value)],["iterable",H=>H instanceof ke||H instanceof ut],["lower",H=>{const se=H.value;return H.type==="StringValue"&&se===se.toLowerCase()}],["upper",H=>{const se=H.value;return H.type==="StringValue"&&se===se.toUpperCase()}],["none",H=>H.type==="NullValue"],["defined",H=>H.type!=="UndefinedValue"],["undefined",H=>H.type==="UndefinedValue"],["equalto",(H,se)=>H.value===se.value],["eq",(H,se)=>H.value===se.value]]);set(H,se){return this.declareVariable(H,he(se))}declareVariable(H,se){if(this.variables.has(H))throw new SyntaxError(`Variable already declared: ${H}`);return this.variables.set(H,se),se}setVariable(H,se){return this.variables.set(H,se),se}resolve(H){if(this.variables.has(H))return this;if(this.parent)return this.parent.resolve(H);throw new Error(`Unknown variable: ${H}`)}lookupVariable(H){try{return this.resolve(H).variables.get(H)??new z}catch{return new z}}},Oe=class{global;constructor(H){this.global=H??new Fe}run(H){return this.evaluate(H,this.global)}evaluateBinaryExpression(H,se){const K=this.evaluate(H.left,se);switch(H.operator.value){case"and":return K.__bool__().value?this.evaluate(H.right,se):K;case"or":return K.__bool__().value?K:this.evaluate(H.right,se)}const _e=this.evaluate(H.right,se);switch(H.operator.value){case"==":return new Mt(K.value==_e.value);case"!=":return new Mt(K.value!=_e.value)}if(K instanceof z||_e instanceof z)throw new Error("Cannot perform operation on undefined values");if(K instanceof bt||_e instanceof bt)throw new Error("Cannot perform operation on null values");if(K instanceof Ze&&_e instanceof Ze)switch(H.operator.value){case"+":return new Ze(K.value+_e.value);case"-":return new Ze(K.value-_e.value);case"*":return new Ze(K.value*_e.value);case"/":return new Ze(K.value/_e.value);case"%":return new Ze(K.value%_e.value);case"<":return new Mt(K.value<_e.value);case">":return new Mt(K.value>_e.value);case">=":return new Mt(K.value>=_e.value);case"<=":return new Mt(K.value<=_e.value)}else if(K instanceof ke&&_e instanceof ke)switch(H.operator.value){case"+":return new ke(K.value.concat(_e.value))}else if(_e instanceof ke){const pe=_e.value.find(Ie=>Ie.value===K.value)!==void 0;switch(H.operator.value){case"in":return new Mt(pe);case"not in":return new Mt(!pe)}}if(K instanceof ut||_e instanceof ut)switch(H.operator.value){case"+":return new ut(K.value.toString()+_e.value.toString())}if(K instanceof ut&&_e instanceof ut)switch(H.operator.value){case"in":return new Mt(_e.value.includes(K.value));case"not in":return new Mt(!_e.value.includes(K.value))}if(K instanceof ut&&_e instanceof Ft)switch(H.operator.value){case"in":return new Mt(_e.value.has(K.value));case"not in":return new Mt(!_e.value.has(K.value))}throw new SyntaxError(`Unknown operator "${H.operator.value}" between ${K.type} and ${_e.type}`)}evaluateArguments(H,se){const K=[],_e=new Map;for(const pe of H)if(pe.type==="KeywordArgumentExpression"){const Ie=pe;_e.set(Ie.key.value,this.evaluate(Ie.value,se))}else{if(_e.size>0)throw new Error("Positional arguments must come before keyword arguments");K.push(this.evaluate(pe,se))}return[K,_e]}evaluateFilterExpression(H,se){const K=this.evaluate(H.operand,se);if(H.filter.type==="Identifier"){const _e=H.filter;if(_e.value==="tojson")return new ut(de(K));if(K instanceof ke)switch(_e.value){case"list":return K;case"first":return K.value[0];case"last":return K.value[K.value.length-1];case"length":return new Ze(K.value.length);case"reverse":return new ke(K.value.reverse());case"sort":return new ke(K.value.sort((pe,Ie)=>{if(pe.type!==Ie.type)throw new Error(`Cannot compare different types: ${pe.type} and ${Ie.type}`);switch(pe.type){case"NumericValue":return pe.value-Ie.value;case"StringValue":return pe.value.localeCompare(Ie.value);default:throw new Error(`Cannot compare type: ${pe.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${_e.value}`)}else if(K instanceof ut)switch(_e.value){case"length":return new Ze(K.value.length);case"upper":return new ut(K.value.toUpperCase());case"lower":return new ut(K.value.toLowerCase());case"title":return new ut(ht(K.value));case"capitalize":return new ut(K.value.charAt(0).toUpperCase()+K.value.slice(1));case"trim":return new ut(K.value.trim());case"indent":return new ut(K.value.split(` `).map((pe,Ie)=>Ie===0||pe.length===0?pe:" "+pe).join(` `));case"string":return K;default:throw new Error(`Unknown StringValue filter: ${_e.value}`)}else if(K instanceof Ze)switch(_e.value){case"abs":return new Ze(Math.abs(K.value));default:throw new Error(`Unknown NumericValue filter: ${_e.value}`)}else if(K instanceof Ft)switch(_e.value){case"items":return new ke(Array.from(K.value.entries()).map(([pe,Ie])=>new ke([new ut(pe),Ie])));case"length":return new Ze(K.value.size);default:throw new Error(`Unknown ObjectValue filter: ${_e.value}`)}throw new Error(`Cannot apply filter "${_e.value}" to type: ${K.type}`)}else if(H.filter.type==="CallExpression"){const _e=H.filter;if(_e.callee.type!=="Identifier")throw new Error(`Unknown filter: ${_e.callee.type}`);const pe=_e.callee.value;if(pe==="tojson"){const[,Ie]=this.evaluateArguments(_e.args,se),Xe=Ie.get("indent")??new bt;if(!(Xe instanceof Ze||Xe instanceof bt))throw new Error("If set, indent must be a number");return new ut(de(K,Xe.value))}if(K instanceof ke){switch(pe){case"selectattr":{if(K.value.some(Jt=>!(Jt instanceof Ft)))throw new Error("`selectattr` can only be applied to array of objects");if(_e.args.some(Jt=>Jt.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Ie,Xe,St]=_e.args.map(Jt=>this.evaluate(Jt,se));let ft;if(Xe){const Jt=se.tests.get(Xe.value);if(!Jt)throw new Error(`Unknown test: ${Xe.value}`);ft=Jt}else ft=(...Jt)=>Jt[0].__bool__().value;const Dt=K.value.filter(Jt=>{const kt=Jt.value.get(Ie.value);return kt?ft(kt,St):!1});return new ke(Dt)}case"map":{const[,Ie]=this.evaluateArguments(_e.args,se);if(Ie.has("attribute")){const Xe=Ie.get("attribute");if(!(Xe instanceof ut))throw new Error("attribute must be a string");const St=Ie.get("default"),ft=K.value.map(Dt=>{if(!(Dt instanceof Ft))throw new Error("items in map must be an object");return Dt.value.get(Xe.value)??St??new z});return new ke(ft)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${pe}`)}else if(K instanceof ut){switch(pe){case"indent":{const[Ie,Xe]=this.evaluateArguments(_e.args,se),St=Ie.at(0)??Xe.get("width")??new Ze(4);if(!(St instanceof Ze))throw new Error("width must be a number");const ft=Ie.at(1)??Xe.get("first")??new Mt(!1),Dt=Ie.at(2)??Xe.get("blank")??new Mt(!1),Jt=K.value.split(` `),kt=" ".repeat(St.value),ve=Jt.map((Ne,rt)=>!ft.value&&rt===0||!Dt.value&&Ne.length===0?Ne:kt+Ne);return new ut(ve.join(` `))}}throw new Error(`Unknown StringValue filter: ${pe}`)}else throw new Error(`Cannot apply filter "${pe}" to type: ${K.type}`)}throw new Error(`Unknown filter: ${H.filter.type}`)}evaluateTestExpression(H,se){const K=this.evaluate(H.operand,se),_e=se.tests.get(H.test.value);if(!_e)throw new Error(`Unknown test: ${H.test.value}`);const pe=_e(K);return new Mt(H.negate?!pe:pe)}evaluateUnaryExpression(H,se){const K=this.evaluate(H.argument,se);switch(H.operator.value){case"not":return new Mt(!K.value);default:throw new SyntaxError(`Unknown operator: ${H.operator.value}`)}}evalProgram(H,se){return this.evaluateBlock(H.body,se)}evaluateBlock(H,se){let K="";for(const _e of H){const pe=this.evaluate(_e,se);pe.type!=="NullValue"&&pe.type!=="UndefinedValue"&&(K+=pe.value)}return new ut(K)}evaluateIdentifier(H,se){return se.lookupVariable(H.value)}evaluateCallExpression(H,se){const[K,_e]=this.evaluateArguments(H.args,se);_e.size>0&&K.push(new Ve(_e));const pe=this.evaluate(H.callee,se);if(pe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${pe.type}`);return pe.value(K,se)}evaluateSliceExpression(H,se,K){if(!(H instanceof ke||H instanceof ut))throw new Error("Slice object must be an array or string");const _e=this.evaluate(se.start,K),pe=this.evaluate(se.stop,K),Ie=this.evaluate(se.step,K);if(!(_e instanceof Ze||_e instanceof z))throw new Error("Slice start must be numeric or undefined");if(!(pe instanceof Ze||pe instanceof z))throw new Error("Slice stop must be numeric or undefined");if(!(Ie instanceof Ze||Ie instanceof z))throw new Error("Slice step must be numeric or undefined");return H instanceof ke?new ke(xe(H.value,_e.value,pe.value,Ie.value)):new ut(xe(Array.from(H.value),_e.value,pe.value,Ie.value).join(""))}evaluateMemberExpression(H,se){const K=this.evaluate(H.object,se);let _e;if(H.computed){if(H.property.type==="SliceExpression")return this.evaluateSliceExpression(K,H.property,se);_e=this.evaluate(H.property,se)}else _e=new ut(H.property.value);let pe;if(K instanceof Ft){if(!(_e instanceof ut))throw new Error(`Cannot access property with non-string: got ${_e.type}`);pe=K.value.get(_e.value)??K.builtins.get(_e.value)}else if(K instanceof ke||K instanceof ut)if(_e instanceof Ze)pe=K.value.at(_e.value),K instanceof ut&&(pe=new ut(K.value.at(_e.value)));else if(_e instanceof ut)pe=K.builtins.get(_e.value);else throw new Error(`Cannot access property with non-string/non-number: got ${_e.type}`);else{if(!(_e instanceof ut))throw new Error(`Cannot access property with non-string: got ${_e.type}`);pe=K.builtins.get(_e.value)}return pe instanceof Qe?pe:new z}evaluateSet(H,se){const K=this.evaluate(H.value,se);if(H.assignee.type==="Identifier"){const _e=H.assignee.value;se.setVariable(_e,K)}else if(H.assignee.type==="MemberExpression"){const _e=H.assignee,pe=this.evaluate(_e.object,se);if(!(pe instanceof Ft))throw new Error("Cannot assign to member of non-object");if(_e.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");pe.value.set(_e.property.value,K)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(H.assignee)}`);return new bt}evaluateIf(H,se){const K=this.evaluate(H.test,se);return this.evaluateBlock(K.__bool__().value?H.body:H.alternate,se)}evaluateFor(H,se){const K=new Fe(se);let _e,pe;if(H.iterable.type==="SelectExpression"){const Dt=H.iterable;pe=this.evaluate(Dt.iterable,K),_e=Dt.test}else pe=this.evaluate(H.iterable,K);if(!(pe instanceof ke))throw new Error(`Expected iterable type in for loop: got ${pe.type}`);const Ie=[],Xe=[];for(let Dt=0;DtNe.setVariable(H.loopvar.value,kt);else if(H.loopvar.type==="TupleLiteral"){const Ne=H.loopvar;if(kt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${kt.type}`);const rt=kt;if(Ne.value.length!==rt.value.length)throw new Error(`Too ${Ne.value.length>rt.value.length?"few":"many"} items to unpack`);ve=Ye=>{for(let mt=0;mt0?Ie[Dt-1]:new z],["nextitem",Dt{const pe=new Fe(_e);K=K.slice();let Ie;K.at(-1)?.type==="KeywordArgumentsValue"&&(Ie=K.pop());for(let Xe=0;Xethis.evaluate(K,se)));case"TupleLiteral":return new lt(H.value.map(K=>this.evaluate(K,se)));case"ObjectLiteral":{const K=new Map;for(const[_e,pe]of H.value){const Ie=this.evaluate(_e,se);if(!(Ie instanceof ut))throw new Error(`Object keys must be strings: got ${Ie.type}`);K.set(Ie.value,this.evaluate(pe,se))}return new Ft(K)}case"Identifier":return this.evaluateIdentifier(H,se);case"CallExpression":return this.evaluateCallExpression(H,se);case"MemberExpression":return this.evaluateMemberExpression(H,se);case"UnaryExpression":return this.evaluateUnaryExpression(H,se);case"BinaryExpression":return this.evaluateBinaryExpression(H,se);case"FilterExpression":return this.evaluateFilterExpression(H,se);case"TestExpression":return this.evaluateTestExpression(H,se);default:throw new SyntaxError(`Unknown node type: ${H.type}`)}}};function he(H){switch(typeof H){case"number":return new Ze(H);case"string":return new ut(H);case"boolean":return new Mt(H);case"undefined":return new z;case"object":return H===null?new bt:Array.isArray(H)?new ke(H.map(he)):new Ft(new Map(Object.entries(H).map(([se,K])=>[se,he(K)])));case"function":return new dt((se,K)=>{const _e=H(...se.map(pe=>pe.value))??null;return he(_e)});default:throw new Error(`Cannot convert to runtime value: ${H}`)}}function de(H,se,K){const _e=K??0;switch(H.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(H.value);case"ArrayValue":case"ObjectValue":{const pe=se?" ".repeat(se):"",Ie=` `+pe.repeat(_e),Xe=Ie+pe;if(H.type==="ArrayValue"){const St=H.value.map(ft=>de(ft,se,_e+1));return se?`[${Xe}${St.join(`,${Xe}`)}${Ie}]`:`[${St.join(", ")}]`}else{const St=Array.from(H.value.entries()).map(([ft,Dt])=>{const Jt=`"${ft}": ${de(Dt,se,_e+1)}`;return se?`${Xe}${Jt}`:Jt});return se?`{${St.join(",")}${Ie}}`:`{${St.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${H.type}`)}}var Ee=class{parsed;constructor(H){const se=_(H,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Pe(se)}render(H){const se=new Fe;se.set("false",!1),se.set("true",!0),se.set("raise_exception",pe=>{throw new Error(pe)}),se.set("range",ne);for(const[pe,Ie]of Object.entries(H))se.set(pe,Ie);return new Oe(se).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,h,w)=>{if(h&&typeof h.init=="function"&&typeof h.createInferenceSessionHandler=="function"){const _=i.get(c);if(_===void 0)i.set(c,{backend:h,priority:w});else{if(_.priority>w)return;if(_.priority===w&&_.backend!==h)throw new Error(`cannot register backend "${c}" using priority ${w}`)}if(w>=0){const M=o.indexOf(c);M!==-1&&o.splice(M,1);for(let T=0;T{const h=i.get(c);if(!h)return"backend not found.";if(h.initialized)return h.backend;if(h.aborted)return h.error;{const w=!!h.initPromise;try{return w||(h.initPromise=h.backend.init(c)),await h.initPromise,h.initialized=!0,h.backend}catch(_){return w||(h.error=`${_}`,h.aborted=!0),h.error}finally{delete h.initPromise}}},d=async c=>{const h=c.executionProviders||[],w=h.map(E=>typeof E=="string"?E:E.name),_=w.length===0?o:w;let M;const T=[],F=new Set;for(const E of _){const x=await l(E);typeof x=="string"?T.push({name:E,err:x}):(M||(M=x),M===x&&F.add(E))}if(!M)throw new Error(`no available backend found. ERR: ${T.map(E=>`[${E.name}] ${E.err}`).join(", ")}`);for(const{name:E,err:x}of T)w.includes(E)&&console.warn(`removing requested execution provider "${E}" from session options because it is not available: ${x}`);const C=h.filter(E=>F.has(typeof E=="string"?E:E.name));return[M,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,h,w){(0,a.TRACE_FUNC_BEGIN)();const _={};let M={};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 T=!0;if(typeof h=="object"){if(h===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(h instanceof o.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(h)){if(h.length===0)throw new TypeError("'fetches' cannot be an empty array.");T=!1;for(const E of h){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 w=="object"&&w!==null)M=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else{let E=!1;const x=Object.getOwnPropertyNames(h);for(const S of this.outputNames)if(x.indexOf(S)!==-1){const P=h[S];(P===null||P instanceof o.Tensor)&&(E=!0,T=!1,_[S]=P)}if(E){if(typeof w=="object"&&w!==null)M=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else M=h}}else if(typeof h<"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(T)for(const E of this.outputNames)_[E]=null;const F=await this.handler.run(c,_,M),C={};for(const E in F)if(Object.hasOwnProperty.call(F,E)){const x=F[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,h,w,_){(0,a.TRACE_FUNC_BEGIN)();let M,T={};if(typeof c=="string"){if(M=c,typeof h=="object"&&h!==null)T=h;else if(typeof h<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof Uint8Array){if(M=c,typeof h=="object"&&h!==null)T=h;else if(typeof h<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&c instanceof SharedArrayBuffer){const x=c;let S=0,P=c.byteLength;if(typeof h=="object"&&h!==null)T=h;else if(typeof h=="number"){if(S=h,!Number.isSafeInteger(S))throw new RangeError("'byteOffset' must be an integer.");if(S<0||S>=x.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${x.byteLength}).`);if(P=c.byteLength-S,typeof w=="number"){if(P=w,!Number.isSafeInteger(P))throw new RangeError("'byteLength' must be an integer.");if(P<=0||S+P>x.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${x.byteLength-S}].`);if(typeof _=="object"&&_!==null)T=_;else if(typeof _<"u")throw new TypeError("'options' must be an object.")}else if(typeof w<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof h<"u")throw new TypeError("'options' must be an object.");M=new Uint8Array(x,S,P)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[F,C]=await(0,i.resolveBackendAndExecutionProviders)(T),E=await F.createInferenceSessionHandler(M,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 h,w;l?.tensorLayout!==void 0&&l.tensorLayout==="NHWC"?(h=a.dims[2],w=a.dims[3]):(h=a.dims[3],w=a.dims[2]);const _=l?.format!==void 0?l.format:"RGB",M=l?.norm;let T,F;M===void 0||M.mean===void 0?T=[255,255,255,255]:typeof M.mean=="number"?T=[M.mean,M.mean,M.mean,M.mean]:(T=[M.mean[0],M.mean[1],M.mean[2],0],M.mean[3]!==void 0&&(T[3]=M.mean[3])),M===void 0||M.bias===void 0?F=[0,0,0,0]:typeof M.bias=="number"?F=[M.bias,M.bias,M.bias,M.bias]:(F=[M.bias[0],M.bias[1],M.bias[2],0],M.bias[3]!==void 0&&(F[3]=M.bias[3]));const C=w*h;let E=0,x=C,S=C*2,P=-1;_==="RGBA"?(E=0,x=C,S=C*2,P=C*3):_==="RGB"?(E=0,x=C,S=C*2):_==="RBG"&&(E=0,S=C,x=C*2);for(let j=0;j{const d=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let c;if(d!=null){let h,w,_;l?.tensorLayout!==void 0&&l.tensorLayout==="NHWC"?(h=a.dims[2],w=a.dims[1],_=a.dims[3]):(h=a.dims[3],w=a.dims[2],_=a.dims[1]);const M=l!==void 0&&l.format!==void 0?l.format:"RGB",T=l?.norm;let F,C;T===void 0||T.mean===void 0?F=[255,255,255,255]:typeof T.mean=="number"?F=[T.mean,T.mean,T.mean,T.mean]:(F=[T.mean[0],T.mean[1],T.mean[2],255],T.mean[3]!==void 0&&(F[3]=T.mean[3])),T===void 0||T.bias===void 0?C=[0,0,0,0]:typeof T.bias=="number"?C=[T.bias,T.bias,T.bias,T.bias]:(C=[T.bias[0],T.bias[1],T.bias[2],0],T.bias[3]!==void 0&&(C[3]=T.bias[3]));const E=w*h;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 S=0,P=1,j=2,L=3,N=0,W=E,V=E*2,ce=-1;M==="RGBA"?(N=0,W=E,V=E*2,ce=E*3):M==="RGB"?(N=0,W=E,V=E*2):M==="RBG"&&(N=0,V=E,W=E*2),c=d.createImageData(h,w);for(let ge=0;ge{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=(h,w)=>{if(h===void 0)throw new Error("Image buffer must be defined");if(w.height===void 0||w.width===void 0)throw new Error("Image height and width must be defined");if(w.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:_,width:M}=w,T=w.norm??{mean:255,bias:0};let F,C;typeof T.mean=="number"?F=[T.mean,T.mean,T.mean,T.mean]:F=[T.mean[0],T.mean[1],T.mean[2],T.mean[3]??255],typeof T.bias=="number"?C=[T.bias,T.bias,T.bias,T.bias]:C=[T.bias[0],T.bias[1],T.bias[2],T.bias[3]??0];const E=w.format!==void 0?w.format:"RGBA",x=w.tensorFormat!==void 0&&w.tensorFormat!==void 0?w.tensorFormat:"RGB",S=_*M,P=x==="RGBA"?new Float32Array(S*4):new Float32Array(S*3);let j=4,L=0,N=1,W=2,V=3,ce=0,ge=S,Re=S*2,oe=-1;E==="RGB"&&(j=3,L=0,N=1,W=2,V=-1),x==="RGBA"?oe=S*3:x==="RBG"?(ce=0,Re=S,ge=S*2):x==="BGR"&&(Re=0,ge=S,ce=S*2);for(let G=0;G{const _=typeof HTMLImageElement<"u"&&h instanceof HTMLImageElement,M=typeof ImageData<"u"&&h instanceof ImageData,T=typeof ImageBitmap<"u"&&h instanceof ImageBitmap,F=typeof h=="string";let C,E=w??{};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")},S=P=>P instanceof HTMLCanvasElement||P instanceof OffscreenCanvas?P.getContext("2d"):null;if(_){const P=x();P.width=h.width,P.height=h.height;const j=S(P);if(j!=null){let L=h.height,N=h.width;if(w!==void 0&&w.resizedHeight!==void 0&&w.resizedWidth!==void 0&&(L=w.resizedHeight,N=w.resizedWidth),w!==void 0){if(E=w,w.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");E.tensorFormat="RGBA",E.height=L,E.width=N}else E.tensorFormat="RGBA",E.height=L,E.width=N;j.drawImage(h,0,0),C=j.getImageData(0,0,N,L).data}else throw new Error("Can not access image data")}else if(M){let P,j;if(w!==void 0&&w.resizedWidth!==void 0&&w.resizedHeight!==void 0?(P=w.resizedHeight,j=w.resizedWidth):(P=h.height,j=h.width),w!==void 0&&(E=w),E.format="RGBA",E.height=P,E.width=j,w!==void 0){const L=x();L.width=j,L.height=P;const N=S(L);if(N!=null)N.putImageData(h,0,0),C=N.getImageData(0,0,j,P).data;else throw new Error("Can not access image data")}else C=h.data}else if(T){if(w===void 0)throw new Error("Please provide image config with format for Imagebitmap");const P=x();P.width=h.width,P.height=h.height;const j=S(P);if(j!=null){const L=h.height,N=h.width;return j.drawImage(h,0,0,N,L),C=j.getImageData(0,0,N,L).data,E.height=L,E.width=N,o(C,E)}else throw new Error("Can not access image data")}else{if(F)return new Promise((P,j)=>{const L=x(),N=S(L);if(!h||!N)return j();const W=new Image;W.crossOrigin="Anonymous",W.src=h,W.onload=()=>{L.width=W.width,L.height=W.height,N.drawImage(W,0,0,L.width,L.height);const V=N.getImageData(0,0,L.width,L.height);E.height=L.height,E.width=L.width,P(o(V.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=(h,w)=>{const{width:_,height:M,download:T,dispose:F}=w,C=[1,M,_,4];return new i.Tensor({location:"texture",type:"float32",texture:h,dims:C,download:T,dispose:F})},d=(h,w)=>{const{dataType:_,dims:M,download:T,dispose:F}=w;return new i.Tensor({location:"gpu-buffer",type:_??"float32",gpuBuffer:h,dims:M,download:T,dispose:F})},c=(h,w,_)=>new i.Tensor({location:"cpu-pinned",type:h,data:w,dims:_??[w.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,h=typeof Float16Array<"u"&&Float16Array.from;d&&(i.set("int64",BigInt64Array),o.set(BigInt64Array,"int64")),c&&(i.set("uint64",BigUint64Array),o.set(BigUint64Array,"uint64")),h?(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(h,w,_){(0,a.checkTypedArray)();let M,T;if(typeof h=="object"&&"location"in h)switch(this.dataLocation=h.location,M=h.type,T=h.dims,h.location){case"cpu-pinned":{const C=a.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(M);if(!C)throw new TypeError(`unsupported type "${M}" to create tensor from pinned buffer`);if(!(h.data instanceof C))throw new TypeError(`buffer should be of type ${C.name}`);this.cpuData=h.data;break}case"texture":{if(M!=="float32")throw new TypeError(`unsupported type "${M}" to create tensor from texture`);this.gpuTextureData=h.texture,this.downloader=h.download,this.disposer=h.dispose;break}case"gpu-buffer":{if(M!=="float32"&&M!=="float16"&&M!=="int32"&&M!=="int64"&&M!=="uint32"&&M!=="uint8"&&M!=="bool")throw new TypeError(`unsupported type "${M}" to create tensor from gpu buffer`);this.gpuBufferData=h.gpuBuffer,this.downloader=h.download,this.disposer=h.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let C,E;if(typeof h=="string")if(M=h,E=_,h==="string"){if(!Array.isArray(w))throw new TypeError("A string tensor's data must be a string array.");C=w}else{const x=a.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(h);if(x===void 0)throw new TypeError(`Unsupported tensor type: ${h}.`);if(Array.isArray(w)){if(h==="float16"&&x===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");h==="uint64"||h==="int64"?C=x.from(w,BigInt):C=x.from(w)}else if(w instanceof x)C=w;else throw new TypeError(`A ${M} tensor's data must be type of ${x}`)}else if(E=w,Array.isArray(h)){if(h.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const x=typeof h[0];if(x==="string")M="string",C=h;else if(x==="boolean")M="bool",C=Uint8Array.from(h);else throw new TypeError(`Invalid element type of data array: ${x}.`)}else{const x=a.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(h.constructor);if(x===void 0)throw new TypeError(`Unsupported type for tensor data: ${h.constructor}.`);M=x,C=h}if(E===void 0)E=[C.length];else if(!Array.isArray(E))throw new TypeError("A tensor's dims must be a number array");T=E,this.cpuData=C,this.dataLocation="cpu"}const F=(0,l.calculateSize)(T);if(this.cpuData&&F!==this.cpuData.length)throw new Error(`Tensor's size(${F}) does not match data length(${this.cpuData.length}).`);this.type=M,this.dims=T,this.size=F}static async fromImage(h,w){return(0,o.tensorFromImage)(h,w)}static fromTexture(h,w){return(0,o.tensorFromTexture)(h,w)}static fromGpuBuffer(h,w){return(0,o.tensorFromGpuBuffer)(h,w)}static fromPinnedBuffer(h,w,_){return(0,o.tensorFromPinnedBuffer)(h,w,_)}toDataURL(h){return(0,i.tensorToDataURL)(this,h)}toImageData(h){return(0,i.tensorToImageData)(this,h)}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(h){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 w=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=w,h&&this.disposer&&(this.disposer(),this.disposer=void 0),w}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(h){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,l.tensorReshape)(this,h)}}},"./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,h)=>{(typeof i.env.trace>"u"?!i.env.wasm.trace:!i.env.trace)||console.timeStamp(`${c}::ORT::${h}`)},a=(c,h)=>{const w=new Error().stack?.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,h,w){this.handler=c,this.hasOptimizerModel=h,this.hasEvalModel=w}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,h){const w=c.evalModel||"",_=c.optimizerModel||"",M=h||{},[T,F]=await(0,i.resolveBackendAndExecutionProviders)(M);if(T.createTrainingSessionHandler){const C=await T.createTrainingSessionHandler(c.checkpointState,c.trainModel,w,_,F);return new l(C,!!c.optimizerModel,!!c.evalModel)}else throw new Error(a)}typeNarrowingForRunStep(c,h,w,_,M){const T={};let F={};if(typeof w!="object"||w===null||w instanceof o.Tensor||Array.isArray(w))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(h.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);T[E]=null}if(typeof M=="object"&&M!==null)F=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let E=!1;const x=Object.getOwnPropertyNames(_);for(const S of h)if(x.indexOf(S)!==-1){const P=_[S];(P===null||P instanceof o.Tensor)&&(E=!0,C=!1,T[S]=P)}if(E){if(typeof M=="object"&&M!==null)F=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else F=_}}else if(typeof _<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const E of c)if(typeof w[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(C)for(const E of h)T[E]=null;return[T,F]}convertHandlerReturnTypeToMapOfTensors(c){const h={};for(const w in c)if(Object.hasOwnProperty.call(c,w)){const _=c[w];_ instanceof o.Tensor?h[w]=_:h[w]=new o.Tensor(_.type,_.data,_.dims)}return h}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(c,h,w){const[_,M]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,c,h,w),T=await this.handler.runTrainStep(c,_,M);return this.convertHandlerReturnTypeToMapOfTensors(T)}async runOptimizerStep(c){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(c||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(c,h,w){if(this.hasEvalModel){const[_,M]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,c,h,w),T=await this.handler.runEvalStep(c,_,M);return this.convertHandlerReturnTypeToMapOfTensors(T)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(c=!0){return this.handler.getParametersSize(c)}async loadParametersBuffer(c,h=!0){const w=await this.getParametersSize(h);if(c.length!==4*w)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,h)}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:()=>de,TRACE:()=>lt,TRACE_FUNC_BEGIN:()=>bt,TRACE_FUNC_END:()=>z,Tensor:()=>Ve,TrainingSession:()=>St,default:()=>dC,env:()=>V,registerBackend:()=>F});/*! * 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),h=(r,s)=>{for(var u in s)i(r,u,{get:s[u],enumerable:!0})},w=(r,s,u,p)=>{if(s&&typeof s=="object"||typeof s=="function")for(let m of a(s))!l.call(r,m)&&m!==u&&i(r,m,{get:()=>s[m],enumerable:!(p=o(s,m))||p.enumerable});return r},_=r=>w(i({},"__esModule",{value:!0}),r),M,T,F,C,E,x=c(()=>{M=new Map,T=[],F=(r,s,u)=>{if(s&&typeof s.init=="function"&&typeof s.createInferenceSessionHandler=="function"){let p=M.get(r);if(p===void 0)M.set(r,{backend:s,priority:u});else{if(p.priority>u)return;if(p.priority===u&&p.backend!==s)throw new Error(`cannot register backend "${r}" using priority ${u}`)}if(u>=0){let m=T.indexOf(r);m!==-1&&T.splice(m,1);for(let g=0;g{let s=M.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(p){return u||(s.error=`${p}`,s.aborted=!0),s.error}finally{delete s.initPromise}}},E=async r=>{let s=r.executionProviders||[],u=s.map(I=>typeof I=="string"?I:I.name),p=u.length===0?T:u,m,g=[],y=new Set;for(let I of p){let O=await C(I);typeof O=="string"?g.push({name:I,err:O}):(m||(m=O),m===O&&y.add(I))}if(!m)throw new Error(`no available backend found. ERR: ${g.map(I=>`[${I.name}] ${I.err}`).join(", ")}`);for(let{name:I,err:O}of g)u.includes(I)&&console.warn(`removing requested execution provider "${I}" from session options because it is not available: ${O}`);let A=s.filter(I=>y.has(typeof I=="string"?I:I.name));return[m,new Proxy(r,{get:(I,O)=>O==="executionProviders"?A:Reflect.get(I,O)})]}}),S=c(()=>{x()}),P,j=c(()=>{P="1.20.0-dev.20240827-5d54dc1462"}),L,N,W=c(()=>{j(),L="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:P},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}`);L=r}},get logLevel(){return L}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),V,ce=c(()=>{W(),V=N}),ge,Re,oe=c(()=>{ge=(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 p=u.getContext("2d");if(p!=null){let m,g;s?.tensorLayout!==void 0&&s.tensorLayout==="NHWC"?(m=r.dims[2],g=r.dims[3]):(m=r.dims[3],g=r.dims[2]);let y=s?.format!==void 0?s.format:"RGB",A=s?.norm,I,O;A===void 0||A.mean===void 0?I=[255,255,255,255]:typeof A.mean=="number"?I=[A.mean,A.mean,A.mean,A.mean]:(I=[A.mean[0],A.mean[1],A.mean[2],0],A.mean[3]!==void 0&&(I[3]=A.mean[3])),A===void 0||A.bias===void 0?O=[0,0,0,0]:typeof A.bias=="number"?O=[A.bias,A.bias,A.bias,A.bias]:(O=[A.bias[0],A.bias[1],A.bias[2],0],A.bias[3]!==void 0&&(O[3]=A.bias[3]));let Q=g*m,k=0,J=Q,re=Q*2,ue=-1;y==="RGBA"?(k=0,J=Q,re=Q*2,ue=Q*3):y==="RGB"?(k=0,J=Q,re=Q*2):y==="RBG"&&(k=0,re=Q,J=Q*2);for(let ie=0;ie{let u=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),p;if(u!=null){let m,g,y;s?.tensorLayout!==void 0&&s.tensorLayout==="NHWC"?(m=r.dims[2],g=r.dims[1],y=r.dims[3]):(m=r.dims[3],g=r.dims[2],y=r.dims[1]);let A=s!==void 0&&s.format!==void 0?s.format:"RGB",I=s?.norm,O,Q;I===void 0||I.mean===void 0?O=[255,255,255,255]:typeof I.mean=="number"?O=[I.mean,I.mean,I.mean,I.mean]:(O=[I.mean[0],I.mean[1],I.mean[2],255],I.mean[3]!==void 0&&(O[3]=I.mean[3])),I===void 0||I.bias===void 0?Q=[0,0,0,0]:typeof I.bias=="number"?Q=[I.bias,I.bias,I.bias,I.bias]:(Q=[I.bias[0],I.bias[1],I.bias[2],0],I.bias[3]!==void 0&&(Q[3]=I.bias[3]));let k=g*m;if(s!==void 0&&(s.format!==void 0&&y===4&&s.format!=="RGBA"||y===3&&s.format!=="RGB"&&s.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let J=4,re=0,ue=1,ie=2,Ae=3,$e=0,me=k,Be=k*2,je=-1;A==="RGBA"?($e=0,me=k,Be=k*2,je=k*3):A==="RGB"?($e=0,me=k,Be=k*2):A==="RBG"&&($e=0,Be=k,me=k*2),p=u.createImageData(m,g);for(let et=0;et{Ft(),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:p}=s,m=s.norm??{mean:255,bias:0},g,y;typeof m.mean=="number"?g=[m.mean,m.mean,m.mean,m.mean]:g=[m.mean[0],m.mean[1],m.mean[2],m.mean[3]??255],typeof m.bias=="number"?y=[m.bias,m.bias,m.bias,m.bias]:y=[m.bias[0],m.bias[1],m.bias[2],m.bias[3]??0];let A=s.format!==void 0?s.format:"RGBA",I=s.tensorFormat!==void 0&&s.tensorFormat!==void 0?s.tensorFormat:"RGB",O=u*p,Q=I==="RGBA"?new Float32Array(O*4):new Float32Array(O*3),k=4,J=0,re=1,ue=2,ie=3,Ae=0,$e=O,me=O*2,Be=-1;A==="RGB"&&(k=3,J=0,re=1,ue=2,ie=-1),I==="RGBA"?Be=O*3:I==="RBG"?(Ae=0,me=O,$e=O*2):I==="BGR"&&(me=0,$e=O,Ae=O*2);for(let je=0;je{let u=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,p=typeof ImageData<"u"&&r instanceof ImageData,m=typeof ImageBitmap<"u"&&r instanceof ImageBitmap,g=typeof r=="string",y,A=s??{},I=()=>{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=Q=>Q instanceof HTMLCanvasElement||Q instanceof OffscreenCanvas?Q.getContext("2d"):null;if(u){let Q=I();Q.width=r.width,Q.height=r.height;let k=O(Q);if(k!=null){let J=r.height,re=r.width;if(s!==void 0&&s.resizedHeight!==void 0&&s.resizedWidth!==void 0&&(J=s.resizedHeight,re=s.resizedWidth),s!==void 0){if(A=s,s.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");A.tensorFormat="RGBA",A.height=J,A.width=re}else A.tensorFormat="RGBA",A.height=J,A.width=re;k.drawImage(r,0,0),y=k.getImageData(0,0,re,J).data}else throw new Error("Can not access image data")}else if(p){let Q,k;if(s!==void 0&&s.resizedWidth!==void 0&&s.resizedHeight!==void 0?(Q=s.resizedHeight,k=s.resizedWidth):(Q=r.height,k=r.width),s!==void 0&&(A=s),A.format="RGBA",A.height=Q,A.width=k,s!==void 0){let J=I();J.width=k,J.height=Q;let re=O(J);if(re!=null)re.putImageData(r,0,0),y=re.getImageData(0,0,k,Q).data;else throw new Error("Can not access image data")}else y=r.data}else if(m){if(s===void 0)throw new Error("Please provide image config with format for Imagebitmap");let Q=I();Q.width=r.width,Q.height=r.height;let k=O(Q);if(k!=null){let J=r.height,re=r.width;return k.drawImage(r,0,0,re,J),y=k.getImageData(0,0,re,J).data,A.height=J,A.width=re,Se(y,A)}else throw new Error("Can not access image data")}else{if(g)return new Promise((Q,k)=>{let J=I(),re=O(J);if(!r||!re)return k();let ue=new Image;ue.crossOrigin="Anonymous",ue.src=r,ue.onload=()=>{J.width=ue.width,J.height=ue.height,re.drawImage(ue,0,0,J.width,J.height);let ie=re.getImageData(0,0,J.width,J.height);A.height=J.height,A.width=J.width,Q(Se(ie.data,A))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(y!==void 0)return Se(y,A);throw new Error("Input data provided is not supported - aborted tensor creation")},Ce=(r,s)=>{let{width:u,height:p,download:m,dispose:g}=s,y=[1,p,u,4];return new Mt({location:"texture",type:"float32",texture:r,dims:y,download:m,dispose:g})},pt=(r,s)=>{let{dataType:u,dims:p,download:m,dispose:g}=s;return new Mt({location:"gpu-buffer",type:u??"float32",gpuBuffer:r,dims:p,download:m,dispose:g})},Te=(r,s,u)=>new Mt({location:"cpu-pinned",type:r,data:s,dims:u??[s.length]})}),fe,Pe,ne,xe,ht=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]]),Pe=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),Pe.set(BigInt64Array,"int64")),s&&(fe.set("uint64",BigUint64Array),Pe.set(BigUint64Array,"uint64")),u?(fe.set("float16",Float16Array),Pe.set(Float16Array,"float16")):fe.set("float16",Uint16Array)}}}),Qe,Ze,ut=c(()=>{Ft(),Qe=r=>{let s=1;for(let u=0;u{switch(r.location){case"cpu":return new Mt(r.type,r.data,s);case"cpu-pinned":return new Mt({location:"cpu-pinned",data:r.data,type:r.type,dims:s});case"texture":return new Mt({location:"texture",texture:r.texture,type:r.type,dims:s});case"gpu-buffer":return new Mt({location:"gpu-buffer",gpuBuffer:r.gpuBuffer,type:r.type,dims:s});default:throw new Error(`tensorReshape: tensor location ${r.location} is not supported`)}}}),Mt,Ft=c(()=>{oe(),te(),ht(),ut(),Mt=class{constructor(r,s,u){xe();let p,m;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,p=r.type,m=r.dims,r.location){case"cpu-pinned":{let y=fe.get(p);if(!y)throw new TypeError(`unsupported type "${p}" to create tensor from pinned buffer`);if(!(r.data instanceof y))throw new TypeError(`buffer should be of type ${y.name}`);this.cpuData=r.data;break}case"texture":{if(p!=="float32")throw new TypeError(`unsupported type "${p}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(p!=="float32"&&p!=="float16"&&p!=="int32"&&p!=="int64"&&p!=="uint32"&&p!=="uint8"&&p!=="bool"&&p!=="uint4"&&p!=="int4")throw new TypeError(`unsupported type "${p}" 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 y,A;if(typeof r=="string")if(p=r,A=u,r==="string"){if(!Array.isArray(s))throw new TypeError("A string tensor's data must be a string array.");y=s}else{let I=fe.get(r);if(I===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(s)){if(r==="float16"&&I===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${I.name} as data.`);r==="uint64"||r==="int64"?y=I.from(s,BigInt):y=I.from(s)}else if(s instanceof I)y=s;else throw new TypeError(`A ${p} tensor's data must be type of ${I}`)}else if(A=s,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let I=typeof r[0];if(I==="string")p="string",y=r;else if(I==="boolean")p="bool",y=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${I}.`)}else{let I=Pe.get(r.constructor);if(I===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);p=I,y=r}if(A===void 0)A=[y.length];else if(!Array.isArray(A))throw new TypeError("A tensor's dims must be a number array");m=A,this.cpuData=y,this.dataLocation="cpu"}let g=Qe(m);if(this.cpuData&&g!==this.cpuData.length&&!((p==="uint4"||p==="int4")&&Math.ceil(g/2)===this.cpuData.length))throw new Error(`Tensor's size(${g}) does not match data length(${this.cpuData.length}).`);this.type=p,this.dims=m,this.size=g}static async fromImage(r,s){return G(r,s)}static fromTexture(r,s){return Ce(r,s)}static fromGpuBuffer(r,s){return pt(r,s)}static fromPinnedBuffer(r,s,u){return Te(r,s,u)}toDataURL(r){return ge(this,r)}toImageData(r){return Re(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 Ze(this,r)}}}),Ve,ke=c(()=>{Ft(),Ve=Mt}),lt,dt,bt,z,Fe=c(()=>{W(),lt=(r,s)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${r}::ORT::${s}`)},dt=(r,s)=>{let u=new Error().stack?.split(/\r\n|\r|\n/g)||[],p=!1;for(let m=0;m{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||dt("BEGIN",r)},z=r=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||dt("END",r)}}),Oe,he=c(()=>{x(),ke(),Fe(),Oe=class ak{constructor(s){this.handler=s}async run(s,u,p){bt();let m={},g={};if(typeof s!="object"||s===null||s instanceof Ve||Array.isArray(s))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let y=!0;if(typeof u=="object"){if(u===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(u instanceof Ve)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.");y=!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}.`);m[O]=null}if(typeof p=="object"&&p!==null)g=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else{let O=!1,Q=Object.getOwnPropertyNames(u);for(let k of this.outputNames)if(Q.indexOf(k)!==-1){let J=u[k];(J===null||J instanceof Ve)&&(O=!0,y=!1,m[k]=J)}if(O){if(typeof p=="object"&&p!==null)g=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else g=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(y)for(let O of this.outputNames)m[O]=null;let A=await this.handler.run(s,m,g),I={};for(let O in A)if(Object.hasOwnProperty.call(A,O)){let Q=A[O];Q instanceof Ve?I[O]=Q:I[O]=new Ve(Q.type,Q.data,Q.dims)}return z(),I}async release(){return this.handler.dispose()}static async create(s,u,p,m){bt();let g,y={};if(typeof s=="string"){if(g=s,typeof u=="object"&&u!==null)y=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(s instanceof Uint8Array){if(g=s,typeof u=="object"&&u!==null)y=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 Q=s,k=0,J=s.byteLength;if(typeof u=="object"&&u!==null)y=u;else if(typeof u=="number"){if(k=u,!Number.isSafeInteger(k))throw new RangeError("'byteOffset' must be an integer.");if(k<0||k>=Q.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${Q.byteLength}).`);if(J=s.byteLength-k,typeof p=="number"){if(J=p,!Number.isSafeInteger(J))throw new RangeError("'byteLength' must be an integer.");if(J<=0||k+J>Q.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${Q.byteLength-k}].`);if(typeof m=="object"&&m!==null)y=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else if(typeof p<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof u<"u")throw new TypeError("'options' must be an object.");g=new Uint8Array(Q,k,J)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[A,I]=await E(y),O=await A.createInferenceSessionHandler(g,I);return z(),new ak(O)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),de,Ee=c(()=>{he(),de=Oe}),H=c(()=>{}),se=c(()=>{}),K=c(()=>{}),_e=c(()=>{}),pe,Ie,Xe=c(()=>{x(),ke(),pe="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Ie=class lk{constructor(s,u,p){this.handler=s,this.hasOptimizerModel=u,this.hasEvalModel=p}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 p=s.evalModel||"",m=s.optimizerModel||"",g=u||{},[y,A]=await E(g);if(y.createTrainingSessionHandler){let I=await y.createTrainingSessionHandler(s.checkpointState,s.trainModel,p,m,A);return new lk(I,!!s.optimizerModel,!!s.evalModel)}else throw new Error(pe)}typeNarrowingForRunStep(s,u,p,m,g){let y={},A={};if(typeof p!="object"||p===null||p instanceof Ve||Array.isArray(p))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let I=!0;if(typeof m=="object"){if(m===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(m instanceof Ve)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(m)){if(m.length===0)throw new TypeError("'fetches' cannot be an empty array.");I=!1;for(let O of m){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}.`);y[O]=null}if(typeof g=="object"&&g!==null)A=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else{let O=!1,Q=Object.getOwnPropertyNames(m);for(let k of u)if(Q.indexOf(k)!==-1){let J=m[k];(J===null||J instanceof Ve)&&(O=!0,I=!1,y[k]=J)}if(O){if(typeof g=="object"&&g!==null)A=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else A=m}}else if(typeof m<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let O of s)if(typeof p[O]>"u")throw new Error(`input '${O}' is missing in 'feeds'.`);if(I)for(let O of u)y[O]=null;return[y,A]}convertHandlerReturnTypeToMapOfTensors(s){let u={};for(let p in s)if(Object.hasOwnProperty.call(s,p)){let m=s[p];m instanceof Ve?u[p]=m:u[p]=new Ve(m.type,m.data,m.dims)}return u}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(s,u,p){let[m,g]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,s,u,p),y=await this.handler.runTrainStep(s,m,g);return this.convertHandlerReturnTypeToMapOfTensors(y)}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,p){if(this.hasEvalModel){let[m,g]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,s,u,p),y=await this.handler.runEvalStep(s,m,g);return this.convertHandlerReturnTypeToMapOfTensors(y)}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 p=await this.getParametersSize(u);if(s.length!==4*p)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()}}}),St,ft=c(()=>{Xe(),St=Ie}),Dt={};h(Dt,{InferenceSession:()=>de,TRACE:()=>lt,TRACE_FUNC_BEGIN:()=>bt,TRACE_FUNC_END:()=>z,Tensor:()=>Ve,TrainingSession:()=>St,env:()=>V,registerBackend:()=>F});var Jt=c(()=>{S(),ce(),Ee(),ke(),H(),se(),Fe(),K(),_e(),ft()}),kt=c(()=>{}),ve={};h(ve,{default:()=>Ye});var Ne,rt,Ye,mt=c(()=>{f1(),Qr(),In(),Ne="ort-wasm-proxy-worker",rt=globalThis.self?.name===Ne,rt&&(self.onmessage=r=>{let{type:s,in:u}=r.data;try{switch(s){case"init-wasm":ao(u.wasm).then(()=>{a_(u).then(()=>{postMessage({type:s})},p=>{postMessage({type:s,err:p})})},p=>{postMessage({type:s,err:p})});break;case"init-ep":{let{epName:p,env:m}=u;l_(m,p).then(()=>{postMessage({type:s})},g=>{postMessage({type:s,err:g})});break}case"copy-from":{let{buffer:p}=u,m=qp(p);postMessage({type:s,out:m});break}case"create":{let{model:p,options:m}=u;u_(p,m).then(g=>{postMessage({type:s,out:g})},g=>{postMessage({type:s,err:g})});break}case"release":c_(u),postMessage({type:s});break;case"run":{let{sessionId:p,inputIndices:m,inputs:g,outputIndices:y,options:A}=u;f_(p,m,g,y,new Array(y.length).fill(null),A).then(I=>{I.some(O=>O[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:I},p_([...g,...I]))},I=>{postMessage({type:s,err:I})});break}case"end-profiling":h_(u),postMessage({type:s});break;default:}}catch(p){postMessage({type:s,err:p})}}),Ye=rt?null:r=>new Worker(r??xt,{type:"module",name:Ne})}),At={};h(At,{default:()=>en});var jt,it,en,Vt=c(()=>{it=(jt=import.meta.url,async function(r={}){function s(){return ir.buffer!=Pr.buffer&&Ts(),Pr}function u(){return ir.buffer!=Pr.buffer&&Ts(),Nn}function p(){return ir.buffer!=Pr.buffer&&Ts(),ur}function m(){return ir.buffer!=Pr.buffer&&Ts(),Rt}function g(){return ir.buffer!=Pr.buffer&&Ts(),ln}function y(){return ir.buffer!=Pr.buffer&&Ts(),Jn}function A(){return ir.buffer!=Pr.buffer&&Ts(),Br}function I(){return ir.buffer!=Pr.buffer&&Ts(),xo}var O,Q,k=Object.assign({},r),J=new Promise((b,B)=>{O=b,Q=B}),re=typeof window=="object",ue=typeof importScripts=="function",ie=ue&&self.name=="em-pthread";k.mountExternalData=(b,B)=>{b.startsWith("./")&&(b=b.substring(2)),(k.Fb||(k.Fb=new Map)).set(b,B)},k.unmountExternalData=()=>{delete k.Fb};var Ae=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let $e=()=>{let b=(Z,ae,we)=>(...qe)=>{let $t=Yo,Nt=ae?.();qe=Z(...qe);let dn=ae?.();return Nt!==dn&&(Z=dn,we(Nt),ae=we=null),Yo!=$t?new Promise((gn,$n)=>{I_={resolve:gn,reject:$n}}):qe},B=Z=>async(...ae)=>{try{if(k.Eb)throw Error("Session already started");let we=k.Eb={bc:ae[0],errors:[]},qe=await Z(...ae);if(k.Eb!==we)throw Error("Session mismatch");k.Mb?.flush();let $t=we.errors;if(0<$t.length){let Nt=await Promise.all($t);if(Nt=Nt.filter(dn=>dn),0k._OrtCreateSession,Z=>k._OrtCreateSession=Z),k._OrtRun=B(b(k._OrtRun,()=>k._OrtRun,Z=>k._OrtRun=Z)),k._OrtRunWithBinding=B(b(k._OrtRunWithBinding,()=>k._OrtRunWithBinding,Z=>k._OrtRunWithBinding=Z)),k._OrtBindInput=b(k._OrtBindInput,()=>k._OrtBindInput,Z=>k._OrtBindInput=Z),$e=void 0};k.jsepInit=(b,B)=>{if($e?.(),b==="webgpu"){[k.Mb,k.Tb,k.Xb,k.Nb,k.Wb,k.jb,k.Yb,k.$b,k.Ub,k.Vb,k.Zb]=B;let Z=k.Mb;k.jsepRegisterBuffer=(ae,we,qe,$t)=>Z.registerBuffer(ae,we,qe,$t),k.jsepGetBuffer=ae=>Z.getBuffer(ae),k.jsepCreateDownloader=(ae,we,qe)=>Z.createDownloader(ae,we,qe),k.jsepOnReleaseSession=ae=>{Z.onReleaseSession(ae)},k.jsepOnRunStart=ae=>Z.onRunStart(ae)}};var me,Be,je=Object.assign({},k),et="./this.program",Ot=(b,B)=>{throw B},It="";(re||ue)&&(ue?It=self.location.href:typeof document<"u"&&document.currentScript&&(It=document.currentScript.src),jt&&(It=jt),It=It.startsWith("blob:")?"":It.substr(0,It.replace(/[?#].*/,"").lastIndexOf("/")+1),ue&&(Be=b=>{var B=new XMLHttpRequest;return B.open("GET",b,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),me=(b,B,Z)=>{var ae=new XMLHttpRequest;ae.open("GET",b,!0),ae.responseType="arraybuffer",ae.onload=()=>{ae.status==200||ae.status==0&&ae.response?B(ae.response):Z()},ae.onerror=Z,ae.send(null)});var Kt,yn=console.log.bind(console),_n=console.error.bind(console),Zn=yn,Gn=_n;if(Object.assign(k,je),je=null,ie){let b=function(B){try{var Z=B.data,ae=Z.cmd;if(ae==="load"){let we=[];self.onmessage=qe=>we.push(qe),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let qe of we)b(qe);self.onmessage=b};for(let qe of Z.handlers)k[qe]&&!k[qe].proxy||(k[qe]=(...$t)=>{postMessage({Lb:"callHandler",kc:qe,args:$t})},qe=="print"&&(Zn=k[qe]),qe=="printErr"&&(Gn=k[qe]));ir=Z.wasmMemory,Ts(),lr(Z.wasmModule)}else if(ae==="run"){z_(Z.pthread_ptr,0,0,1,0,0),P_(Z.pthread_ptr),pC(),L1(),_r||(Db(),_r=!0);try{mC(Z.start_routine,Z.arg)}catch(we){if(we!="unwind")throw we}}else ae==="cancel"?xc()&&sm(-1):Z.target!=="setimmediate"&&(ae==="checkMailbox"?_r&&Qp():ae&&(Gn(`worker: received unknown command ${ae}`),Gn(Z)))}catch(we){throw zb(),we}};var lr,_r=!1;Gn=function(...B){B=B.join(" "),console.error(B)},self.alert=function(...B){postMessage({Lb:"alert",text:B.join(" "),mc:xc()})},k.instantiateWasm=(B,Z)=>new Promise(ae=>{lr=we=>{we=new WebAssembly.Instance(we,F1()),Z(we),ae()}}),self.onunhandledrejection=B=>{throw B.reason||B},self.onmessage=b}k.wasmBinary&&(Kt=k.wasmBinary);var ir,On,yr,Pr,Nn,ur,Rt,ln,Jn,Br,Nr,Qs,xo,Ds=!1;function Ts(){var b=ir.buffer;k.HEAP8=Pr=new Int8Array(b),k.HEAP16=ur=new Int16Array(b),k.HEAPU8=Nn=new Uint8Array(b),k.HEAPU16=Rt=new Uint16Array(b),k.HEAP32=ln=new Int32Array(b),k.HEAPU32=Jn=new Uint32Array(b),k.HEAPF32=Br=new Float32Array(b),k.HEAPF64=xo=new Float64Array(b),k.HEAP64=Nr=new BigInt64Array(b),k.HEAPU64=Qs=new BigUint64Array(b)}if(!ie){if(!((ir=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof Ae))throw Gn("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");Ts()}var Zi=[],Ni=[],sl=[],ol=0,iu=null;function C1(){if(--ol==0&&iu){var b=iu;iu=null,b()}}function vc(b){throw Gn(b="Aborted("+b+")"),Ds=!0,yr=1,b=new WebAssembly.RuntimeError(b+". Build with -sASSERTIONS for more info."),Q(b),b}var __,P1=b=>b.startsWith("data:application/octet-stream;base64,"),A1=b=>b.startsWith("file://");function $1(b){if(b==__&&Kt)return new Uint8Array(Kt);if(Be)return Be(b);throw"both async and sync fetching of the wasm failed"}function I1(b,B,Z){return function(ae){if(!Kt&&(re||ue)){if(typeof fetch=="function"&&!A1(ae))return fetch(ae,{credentials:"same-origin"}).then(we=>{if(!we.ok)throw`failed to load wasm binary file at '${ae}'`;return we.arrayBuffer()}).catch(()=>$1(ae));if(me)return new Promise((we,qe)=>{me(ae,$t=>we(new Uint8Array($t)),qe)})}return Promise.resolve().then(()=>$1(ae))}(b).then(ae=>WebAssembly.instantiate(ae,B)).then(Z,ae=>{Gn(`failed to asynchronously prepare wasm: ${ae}`),vc(ae)})}function F1(){return{a:{M:hC,za:fC,b:_C,$:V1,z:G1,pa:q1,X:K1,Z:X1,qa:Q1,na:Y1,ga:Z1,ma:J1,J:eb,Y:tb,V:nb,oa:rb,W:ib,va:yC,D:vC,P:wC,O:xC,C:TC,s:SC,p:kC,E:EC,y:OC,Q:DC,ta:zC,ja:RC,T:LC,aa:BC,F:NC,ia:P_,sa:jC,u:VC,B:GC,o:qC,m:KC,c:E_,n:XC,k:ZC,Aa:JC,r:eP,g:tP,v:nP,l:rP,f:iP,i:sP,j:oP,h:aP,e:lP,da:uP,ea:cP,fa:dP,ba:yb,ca:vb,S:fP,d:hP,N:pP,G:mP,K:gP,w:_P,ra:yP,U:vP,t:bb,x:wP,L:bP,R:xP,ya:MP,xa:TP,ka:Tb,la:Sb,_:x_,A:kb,I:Eb,ha:Cb,H:Pb,a:ir,wa:b_,ua:Ib,q:EP}}}var y_={858916:(b,B,Z,ae)=>{if(k===void 0||!k.Fb)return 1;if((b=Oi(b>>>0)).startsWith("./")&&(b=b.substring(2)),!(b=k.Fb.get(b)))return 2;if(ae>>>=0,(B>>>=0)+(Z>>>=0)>b.byteLength)return 3;try{return u().set(b.subarray(B,B+Z),ae>>>0),0}catch{return 4}},859417:()=>{k.Ub()},859448:()=>{k.Vb()},859477:()=>{k.Zb()},859502:b=>k.Tb(b),859535:b=>k.Xb(b),859567:(b,B,Z)=>{k.Nb(b,B,Z,!0)},859606:(b,B,Z)=>{k.Nb(b,B,Z)},859639:()=>typeof wasmOffsetConverter<"u",859696:b=>{k.jb("Abs",b,void 0)},859747:b=>{k.jb("Neg",b,void 0)},859798:b=>{k.jb("Floor",b,void 0)},859851:b=>{k.jb("Ceil",b,void 0)},859903:b=>{k.jb("Reciprocal",b,void 0)},859961:b=>{k.jb("Sqrt",b,void 0)},860013:b=>{k.jb("Exp",b,void 0)},860064:b=>{k.jb("Erf",b,void 0)},860115:b=>{k.jb("Sigmoid",b,void 0)},860170:(b,B,Z)=>{k.jb("HardSigmoid",b,{alpha:B,beta:Z})},860249:b=>{k.jb("Log",b,void 0)},860300:b=>{k.jb("Sin",b,void 0)},860351:b=>{k.jb("Cos",b,void 0)},860402:b=>{k.jb("Tan",b,void 0)},860453:b=>{k.jb("Asin",b,void 0)},860505:b=>{k.jb("Acos",b,void 0)},860557:b=>{k.jb("Atan",b,void 0)},860609:b=>{k.jb("Sinh",b,void 0)},860661:b=>{k.jb("Cosh",b,void 0)},860713:b=>{k.jb("Asinh",b,void 0)},860766:b=>{k.jb("Acosh",b,void 0)},860819:b=>{k.jb("Atanh",b,void 0)},860872:b=>{k.jb("Tanh",b,void 0)},860924:b=>{k.jb("Not",b,void 0)},860975:(b,B,Z)=>{k.jb("Clip",b,{min:B,max:Z})},861044:b=>{k.jb("Clip",b,void 0)},861096:(b,B)=>{k.jb("Elu",b,{alpha:B})},861154:b=>{k.jb("Gelu",b,void 0)},861206:b=>{k.jb("Relu",b,void 0)},861258:(b,B)=>{k.jb("LeakyRelu",b,{alpha:B})},861322:(b,B)=>{k.jb("ThresholdedRelu",b,{alpha:B})},861392:(b,B)=>{k.jb("Cast",b,{to:B})},861450:b=>{k.jb("Add",b,void 0)},861501:b=>{k.jb("Sub",b,void 0)},861552:b=>{k.jb("Mul",b,void 0)},861603:b=>{k.jb("Div",b,void 0)},861654:b=>{k.jb("Pow",b,void 0)},861705:b=>{k.jb("Equal",b,void 0)},861758:b=>{k.jb("Greater",b,void 0)},861813:b=>{k.jb("GreaterOrEqual",b,void 0)},861875:b=>{k.jb("Less",b,void 0)},861927:b=>{k.jb("LessOrEqual",b,void 0)},861986:(b,B,Z,ae,we)=>{k.jb("ReduceMean",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},862145:(b,B,Z,ae,we)=>{k.jb("ReduceMax",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},862303:(b,B,Z,ae,we)=>{k.jb("ReduceMin",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},862461:(b,B,Z,ae,we)=>{k.jb("ReduceProd",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},862620:(b,B,Z,ae,we)=>{k.jb("ReduceSum",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},862778:(b,B,Z,ae,we)=>{k.jb("ReduceL1",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},862935:(b,B,Z,ae,we)=>{k.jb("ReduceL2",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},863092:(b,B,Z,ae,we)=>{k.jb("ReduceLogSum",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},863253:(b,B,Z,ae,we)=>{k.jb("ReduceSumSquare",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},863417:(b,B,Z,ae,we)=>{k.jb("ReduceLogSumExp",b,{keepDims:!!B,noopWithEmptyAxes:!!Z,axes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},863581:b=>{k.jb("Where",b,void 0)},863634:(b,B,Z)=>{k.jb("Transpose",b,{perm:B?Array.from(g().subarray(B>>>0,Z>>>0)):[]})},863742:(b,B,Z,ae)=>{k.jb("DepthToSpace",b,{blocksize:B,mode:Oi(Z),format:ae?"NHWC":"NCHW"})},863875:(b,B,Z,ae)=>{k.jb("DepthToSpace",b,{blocksize:B,mode:Oi(Z),format:ae?"NHWC":"NCHW"})},864008:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt,dr)=>{k.jb("ConvTranspose",b,{format:dn?"NHWC":"NCHW",autoPad:B,dilations:[Z],group:ae,kernelShape:[we],pads:[qe,$t],strides:[Nt],wIsConst:()=>!!s()[gn>>>0],outputPadding:$n?Array.from(g().subarray($n>>>0,fr>>>0)):[],outputShape:Sr?Array.from(g().subarray(Sr>>>0,Tt>>>0)):[],activation:Oi(dr)})},864409:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt)=>{k.jb("ConvTranspose",b,{format:Nt?"NHWC":"NCHW",autoPad:B,dilations:Array.from(g().subarray(Z>>>0,2+(Z>>>0)>>>0)),group:ae,kernelShape:Array.from(g().subarray(we>>>0,2+(we>>>0)>>>0)),pads:Array.from(g().subarray(qe>>>0,4+(qe>>>0)>>>0)),strides:Array.from(g().subarray($t>>>0,2+($t>>>0)>>>0)),wIsConst:()=>!!s()[dn>>>0],outputPadding:gn?Array.from(g().subarray(gn>>>0,$n>>>0)):[],outputShape:fr?Array.from(g().subarray(fr>>>0,Sr>>>0)):[],activation:Oi(Tt)})},864974:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt,dr)=>{k.jb("ConvTranspose",b,{format:dn?"NHWC":"NCHW",autoPad:B,dilations:[Z],group:ae,kernelShape:[we],pads:[qe,$t],strides:[Nt],wIsConst:()=>!!s()[gn>>>0],outputPadding:$n?Array.from(g().subarray($n>>>0,fr>>>0)):[],outputShape:Sr?Array.from(g().subarray(Sr>>>0,Tt>>>0)):[],activation:Oi(dr)})},865375:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt)=>{k.jb("ConvTranspose",b,{format:Nt?"NHWC":"NCHW",autoPad:B,dilations:Array.from(g().subarray(Z>>>0,2+(Z>>>0)>>>0)),group:ae,kernelShape:Array.from(g().subarray(we>>>0,2+(we>>>0)>>>0)),pads:Array.from(g().subarray(qe>>>0,4+(qe>>>0)>>>0)),strides:Array.from(g().subarray($t>>>0,2+($t>>>0)>>>0)),wIsConst:()=>!!s()[dn>>>0],outputPadding:gn?Array.from(g().subarray(gn>>>0,$n>>>0)):[],outputShape:fr?Array.from(g().subarray(fr>>>0,Sr>>>0)):[],activation:Oi(Tt)})},865940:(b,B)=>{k.jb("GlobalAveragePool",b,{format:B?"NHWC":"NCHW"})},866031:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt)=>{k.jb("AveragePool",b,{format:Tt?"NHWC":"NCHW",auto_pad:B,ceil_mode:Z,count_include_pad:ae,storage_order:we,dilations:qe?Array.from(g().subarray(qe>>>0,$t>>>0)):[],kernel_shape:Nt?Array.from(g().subarray(Nt>>>0,dn>>>0)):[],pads:gn?Array.from(g().subarray(gn>>>0,$n>>>0)):[],strides:fr?Array.from(g().subarray(fr>>>0,Sr>>>0)):[]})},866446:(b,B)=>{k.jb("GlobalAveragePool",b,{format:B?"NHWC":"NCHW"})},866537:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt)=>{k.jb("AveragePool",b,{format:Tt?"NHWC":"NCHW",auto_pad:B,ceil_mode:Z,count_include_pad:ae,storage_order:we,dilations:qe?Array.from(g().subarray(qe>>>0,$t>>>0)):[],kernel_shape:Nt?Array.from(g().subarray(Nt>>>0,dn>>>0)):[],pads:gn?Array.from(g().subarray(gn>>>0,$n>>>0)):[],strides:fr?Array.from(g().subarray(fr>>>0,Sr>>>0)):[]})},866952:(b,B)=>{k.jb("GlobalMaxPool",b,{format:B?"NHWC":"NCHW"})},867039:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt)=>{k.jb("MaxPool",b,{format:Tt?"NHWC":"NCHW",auto_pad:B,ceil_mode:Z,count_include_pad:ae,storage_order:we,dilations:qe?Array.from(g().subarray(qe>>>0,$t>>>0)):[],kernel_shape:Nt?Array.from(g().subarray(Nt>>>0,dn>>>0)):[],pads:gn?Array.from(g().subarray(gn>>>0,$n>>>0)):[],strides:fr?Array.from(g().subarray(fr>>>0,Sr>>>0)):[]})},867450:(b,B)=>{k.jb("GlobalMaxPool",b,{format:B?"NHWC":"NCHW"})},867537:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt)=>{k.jb("MaxPool",b,{format:Tt?"NHWC":"NCHW",auto_pad:B,ceil_mode:Z,count_include_pad:ae,storage_order:we,dilations:qe?Array.from(g().subarray(qe>>>0,$t>>>0)):[],kernel_shape:Nt?Array.from(g().subarray(Nt>>>0,dn>>>0)):[],pads:gn?Array.from(g().subarray(gn>>>0,$n>>>0)):[],strides:fr?Array.from(g().subarray(fr>>>0,Sr>>>0)):[]})},867948:(b,B,Z,ae,we)=>{k.jb("Gemm",b,{alpha:B,beta:Z,transA:ae,transB:we})},868052:b=>{k.jb("MatMul",b,void 0)},868106:(b,B,Z,ae)=>{k.jb("ArgMax",b,{keepDims:!!B,selectLastIndex:!!Z,axis:ae})},868214:(b,B,Z,ae)=>{k.jb("ArgMin",b,{keepDims:!!B,selectLastIndex:!!Z,axis:ae})},868322:(b,B)=>{k.jb("Softmax",b,{axis:B})},868385:(b,B)=>{k.jb("Concat",b,{axis:B})},868445:(b,B,Z,ae,we)=>{k.jb("Split",b,{axis:B,numOutputs:Z,splitSizes:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},868585:b=>{k.jb("Expand",b,void 0)},868639:(b,B)=>{k.jb("Gather",b,{axis:Number(B)})},868710:(b,B)=>{k.jb("GatherElements",b,{axis:Number(B)})},868789:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n)=>{k.jb("Resize",b,{antialias:B,axes:Z?Array.from(g().subarray(Z>>>0,ae>>>0)):[],coordinateTransformMode:Oi(we),cubicCoeffA:qe,excludeOutside:$t,extrapolationValue:Nt,keepAspectRatioPolicy:Oi(dn),mode:Oi(gn),nearestMode:Oi($n)})},869135:(b,B,Z,ae,we,qe,$t)=>{k.jb("Slice",b,{starts:B?Array.from(g().subarray(B>>>0,Z>>>0)):[],ends:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[],axes:qe?Array.from(g().subarray(qe>>>0,$t>>>0)):[]})},869351:b=>{k.jb("Tile",b,void 0)},869403:(b,B,Z)=>{k.jb("InstanceNormalization",b,{epsilon:B,format:Z?"NHWC":"NCHW"})},869517:(b,B,Z)=>{k.jb("InstanceNormalization",b,{epsilon:B,format:Z?"NHWC":"NCHW"})},869631:b=>{k.jb("Range",b,void 0)},869684:(b,B)=>{k.jb("Einsum",b,{equation:Oi(B)})},869765:(b,B,Z,ae,we)=>{k.jb("Pad",b,{mode:B,value:Z,pads:ae?Array.from(g().subarray(ae>>>0,we>>>0)):[]})},869892:(b,B,Z,ae,we,qe)=>{k.jb("BatchNormalization",b,{epsilon:B,momentum:Z,spatial:!!we,trainingMode:!!ae,format:qe?"NHWC":"NCHW"})},870061:(b,B,Z,ae,we,qe)=>{k.jb("BatchNormalization",b,{epsilon:B,momentum:Z,spatial:!!we,trainingMode:!!ae,format:qe?"NHWC":"NCHW"})},870230:(b,B,Z)=>{k.jb("CumSum",b,{exclusive:Number(B),reverse:Number(Z)})},870327:(b,B,Z)=>{k.jb("DequantizeLinear",b,{axis:B,blockSize:Z})},870417:(b,B,Z,ae,we,qe,$t,Nt,dn)=>{k.jb("Attention",b,{numHeads:B,isUnidirectional:Z,maskFilterValue:ae,scale:we,doRotary:qe,qkvHiddenSizes:$t?Array.from(g().subarray(Number(Nt)>>>0,Number(Nt)+$t>>>0)):[],pastPresentShareBuffer:!!dn})},870689:b=>{k.jb("BiasAdd",b,void 0)},870744:b=>{k.jb("BiasSplitGelu",b,void 0)},870805:b=>{k.jb("FastGelu",b,void 0)},870861:(b,B,Z,ae,we,qe,$t,Nt,dn,gn,$n,fr,Sr,Tt,dr,Zr)=>{k.jb("Conv",b,{format:fr?"NHWC":"NCHW",auto_pad:B,dilations:Z?Array.from(g().subarray(Z>>>0,ae>>>0)):[],group:we,kernel_shape:qe?Array.from(g().subarray(qe>>>0,$t>>>0)):[],pads:Nt?Array.from(g().subarray(Nt>>>0,dn>>>0)):[],strides:gn?Array.from(g().subarray(gn>>>0,$n>>>0)):[],w_is_const:()=>!!s()[Sr>>>0],activation:Oi(Tt),activation_params:dr?Array.from(A().subarray(dr>>>0,Zr>>>0)):[]})},871357:b=>{k.jb("Gelu",b,void 0)},871409:(b,B,Z,ae)=>{k.jb("GroupQueryAttention",b,{numHeads:B,kvNumHeads:Z,scale:ae})},871522:(b,B,Z,ae)=>{k.jb("LayerNormalization",b,{axis:B,epsilon:Z,simplified:!!ae})},871633:(b,B,Z,ae)=>{k.jb("LayerNormalization",b,{axis:B,epsilon:Z,simplified:!!ae})},871744:(b,B,Z,ae,we,qe)=>{k.jb("MatMulNBits",b,{k:B,n:Z,accuracyLevel:ae,bits:we,blockSize:qe})},871871:(b,B,Z,ae,we,qe)=>{k.jb("MultiHeadAttention",b,{numHeads:B,isUnidirectional:Z,maskFilterValue:ae,scale:we,doRotary:qe})},872030:(b,B)=>{k.jb("QuickGelu",b,{alpha:B})},872094:(b,B,Z,ae,we)=>{k.jb("RotaryEmbedding",b,{interleaved:!!B,numHeads:Z,rotaryEmbeddingDim:ae,scale:we})},872233:(b,B,Z)=>{k.jb("SkipLayerNormalization",b,{epsilon:B,simplified:!!Z})},872335:(b,B,Z)=>{k.jb("SkipLayerNormalization",b,{epsilon:B,simplified:!!Z})},872437:(b,B,Z,ae)=>{k.jb("GatherBlockQuantized",b,{gatherAxis:B,quantizeAxis:Z,blockSize:ae})},872558:b=>{k.Yb(b)},872592:(b,B)=>k.$b(b,B,k.Eb.bc,k.Eb.errors)};function fC(b,B,Z){return hb(async()=>{await k.Wb(b,B,Z)})}function hC(){return typeof wasmOffsetConverter<"u"}function v_(b){this.name="ExitStatus",this.message=`Program terminated with exit(${b})`,this.status=b}var w_=b=>{b.terminate(),b.onmessage=()=>{}},O1=b=>{al.length==0&&(N1(),B1(al[0]));var B=al.pop();if(!B)return 6;ou.push(B),Xo[b.Ab]=B,B.Ab=b.Ab;var Z={cmd:"run",start_routine:b.cc,arg:b.Pb,pthread_ptr:b.Ab};return B.postMessage(Z,b.ic),0},su=0,Kr=(b,B,...Z)=>{for(var ae=2*Z.length,we=B_(),qe=L_(8*ae),$t=qe>>>3,Nt=0;Nt>>0]=dn)}return b=Rb(b,0,ae,qe,B),om(we),b};function b_(b){if(ie)return Kr(0,1,b);if(yr=b,!(0{if(yr=b,ie)throw D1(b),"unwind";b_(b)},al=[],ou=[],z1=[],Xo={},R1=b=>{var B=b.Ab;delete Xo[B],al.push(b),ou.splice(ou.indexOf(b),1),b.Ab=0,R_(B)};function L1(){z1.forEach(b=>b())}var B1=b=>new Promise(B=>{b.onmessage=we=>{var qe=(we=we.data).cmd;if(we.targetThread&&we.targetThread!=xc()){var $t=Xo[we.targetThread];$t?$t.postMessage(we,we.transferList):Gn(`Internal error! Worker sent a message "${qe}" to target pthread ${we.targetThread}, but that thread no longer exists!`)}else qe==="checkMailbox"?Qp():qe==="spawnThread"?O1(we):qe==="cleanupThread"?R1(Xo[we.thread]):qe==="killThread"?(we=we.thread,qe=Xo[we],delete Xo[we],w_(qe),R_(we),ou.splice(ou.indexOf(qe),1),qe.Ab=0):qe==="cancelThread"?Xo[we.thread].postMessage({cmd:"cancel"}):qe==="loaded"?(b.loaded=!0,B(b)):qe==="alert"?alert(`Thread ${we.threadId}: ${we.text}`):we.target==="setimmediate"?b.postMessage(we):qe==="callHandler"?k[we.handler](...we.args):qe&&Gn(`worker sent an unknown command ${qe}`)},b.onerror=we=>{throw Gn(`worker sent an error! ${we.filename}:${we.lineno}: ${we.message}`),we};var Z,ae=[];for(Z of[])k.hasOwnProperty(Z)&&ae.push(Z);b.postMessage({cmd:"load",handlers:ae,wasmMemory:ir,wasmModule:On})});function N1(){var b=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});al.push(b)}var Xp=b=>{for(;0{var b=xc(),B=y()[b+52>>>2>>>0];b=y()[b+56>>>2>>>0],Bb(B,B-b),om(B)},mC=(b,B)=>{su=0,b=Nb(b,B),0>>=0);throw B>>>=0,Z>>>=0,y()[ae.Ib+16>>>2>>>0]=0,y()[ae.Ib+4>>>2>>>0]=B,y()[ae.Ib+8>>>2>>>0]=Z,b}function j1(b,B,Z,ae){return ie?Kr(2,1,b,B,Z,ae):V1(b,B,Z,ae)}function V1(b,B,Z,ae){if(b>>>=0,B>>>=0,Z>>>=0,ae>>>=0,Ae===void 0)return Gn("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var we=[];return ie&&we.length===0?j1(b,B,Z,ae):(b={cc:Z,Ab:b,Pb:ae,ic:we},ie?(b.Lb="spawnThread",postMessage(b,we),0):O1(b))}var U1=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,W1=(b,B,Z)=>{var ae=(B>>>=0)+Z;for(Z=B;b[Z]&&!(Z>=ae);)++Z;if(16(we=(240&we)==224?(15&we)<<12|qe<<6|$t:(7&we)<<18|qe<<12|$t<<6|63&b[B++])?ae+=String.fromCharCode(we):(we-=65536,ae+=String.fromCharCode(55296|we>>10,56320|1023&we))}}else ae+=String.fromCharCode(we)}return ae},Oi=(b,B)=>(b>>>=0)?W1(u(),b,B):"";function G1(b,B,Z){return ie?Kr(3,1,b,B,Z):0}function q1(b,B){if(ie)return Kr(4,1,b,B)}var M_=b=>{for(var B=0,Z=0;Z=ae?B++:2047>=ae?B+=2:55296<=ae&&57343>=ae?(B+=4,++Z):B+=3}return B},H1=(b,B,Z,ae)=>{if(!(0>>=0;ae=Z+ae-1;for(var qe=0;qe=$t&&($t=65536+((1023&$t)<<10)|1023&b.charCodeAt(++qe)),127>=$t){if(Z>=ae)break;B[Z++>>>0]=$t}else{if(2047>=$t){if(Z+1>=ae)break;B[Z++>>>0]=192|$t>>6}else{if(65535>=$t){if(Z+2>=ae)break;B[Z++>>>0]=224|$t>>12}else{if(Z+3>=ae)break;B[Z++>>>0]=240|$t>>18,B[Z++>>>0]=128|$t>>12&63}B[Z++>>>0]=128|$t>>6&63}B[Z++>>>0]=128|63&$t}}return B[Z>>>0]=0,Z-we},wc=(b,B,Z)=>H1(b,u(),B,Z);function K1(b,B){if(ie)return Kr(5,1,b,B)}function X1(b,B,Z){if(ie)return Kr(6,1,b,B,Z)}function Q1(b,B,Z){return ie?Kr(7,1,b,B,Z):0}function Y1(b,B){if(ie)return Kr(8,1,b,B)}function Z1(b,B,Z){if(ie)return Kr(9,1,b,B,Z)}function J1(b,B,Z,ae){if(ie)return Kr(10,1,b,B,Z,ae)}function eb(b,B,Z,ae){if(ie)return Kr(11,1,b,B,Z,ae)}function tb(b,B,Z,ae){if(ie)return Kr(12,1,b,B,Z,ae)}function nb(b){if(ie)return Kr(13,1,b)}function rb(b,B){if(ie)return Kr(14,1,b,B)}function ib(b,B,Z){if(ie)return Kr(15,1,b,B,Z)}var sb,ll,yC=()=>{vc("")},Qo=b=>{for(var B="";u()[b>>>0];)B+=sb[u()[b++>>>0]];return B},T_={},S_={};function Ta(b,B,Z={}){if(!("argPackAdvance"in B))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(ae,we,qe={}){var $t=we.name;if(!ae)throw new ll(`type "${$t}" must have a positive integer typeid pointer`);if(S_.hasOwnProperty(ae)){if(qe.Rb)return;throw new ll(`Cannot register type '${$t}' twice`)}S_[ae]=we,T_.hasOwnProperty(ae)&&(we=T_[ae],delete T_[ae],we.forEach(Nt=>Nt()))}(b,B,Z)}var ob=(b,B,Z)=>{switch(B){case 1:return Z?ae=>s()[ae>>>0]:ae=>u()[ae>>>0];case 2:return Z?ae=>p()[ae>>>1>>>0]:ae=>m()[ae>>>1>>>0];case 4:return Z?ae=>g()[ae>>>2>>>0]:ae=>y()[ae>>>2>>>0];case 8:return Z?ae=>Nr[ae>>>3]:ae=>Qs[ae>>>3];default:throw new TypeError(`invalid integer width (${B}): ${b}`)}};function vC(b,B,Z){Z>>>=0,Ta(b>>>=0,{name:B=Qo(B>>>0),fromWireType:ae=>ae,toWireType:function(ae,we){if(typeof we!="bigint"&&typeof we!="number")throw we=we===null?"null":(ae=typeof we)=="object"||ae==="array"||ae==="function"?we.toString():""+we,new TypeError(`Cannot convert "${we}" to ${this.name}`);return typeof we=="number"&&(we=BigInt(we)),we},argPackAdvance:ul,readValueFromPointer:ob(B,Z,B.indexOf("u")==-1),Db:null})}var ul=8;function wC(b,B,Z,ae){Ta(b>>>=0,{name:B=Qo(B>>>0),fromWireType:function(we){return!!we},toWireType:function(we,qe){return qe?Z:ae},argPackAdvance:ul,readValueFromPointer:function(we){return this.fromWireType(u()[we>>>0])},Db:null})}var k_=[],Sa=[];function E_(b){9<(b>>>=0)&&--Sa[b+1]==0&&(Sa[b]=void 0,k_.push(b))}var Ys=b=>{if(!b)throw new ll("Cannot use deleted val. handle = "+b);return Sa[b]},Zs=b=>{switch(b){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let B=k_.pop()||Sa.length;return Sa[B]=b,Sa[B+1]=1,B}};function C_(b){return this.fromWireType(y()[b>>>2>>>0])}var bC={name:"emscripten::val",fromWireType:b=>{var B=Ys(b);return E_(b),B},toWireType:(b,B)=>Zs(B),argPackAdvance:ul,readValueFromPointer:C_,Db:null};function xC(b){return Ta(b>>>0,bC)}var MC=(b,B)=>{switch(B){case 4:return function(Z){return this.fromWireType(A()[Z>>>2>>>0])};case 8:return function(Z){return this.fromWireType(I()[Z>>>3>>>0])};default:throw new TypeError(`invalid float width (${B}): ${b}`)}};function TC(b,B,Z){Z>>>=0,Ta(b>>>=0,{name:B=Qo(B>>>0),fromWireType:ae=>ae,toWireType:(ae,we)=>we,argPackAdvance:ul,readValueFromPointer:MC(B,Z),Db:null})}function SC(b,B,Z,ae,we){if(b>>>=0,Z>>>=0,B=Qo(B>>>0),we===-1&&(we=4294967295),we=Nt=>Nt,ae===0){var qe=32-8*Z;we=Nt=>Nt<>>qe}var $t=B.includes("unsigned")?function(Nt,dn){return dn>>>0}:function(Nt,dn){return dn};Ta(b,{name:B,fromWireType:we,toWireType:$t,argPackAdvance:ul,readValueFromPointer:ob(B,Z,ae!==0),Db:null})}function kC(b,B,Z){function ae(qe){var $t=y()[qe>>>2>>>0];return qe=y()[qe+4>>>2>>>0],new we(s().buffer,qe,$t)}var we=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][B];Ta(b>>>=0,{name:Z=Qo(Z>>>0),fromWireType:ae,argPackAdvance:ul,readValueFromPointer:ae},{Rb:!0})}function EC(b,B){b>>>=0;var Z=(B=Qo(B>>>0))==="std::string";Ta(b,{name:B,fromWireType:function(ae){var we=y()[ae>>>2>>>0],qe=ae+4;if(Z)for(var $t=qe,Nt=0;Nt<=we;++Nt){var dn=qe+Nt;if(Nt==we||u()[dn>>>0]==0){if($t=Oi($t,dn-$t),gn===void 0)var gn=$t;else gn+="\0",gn+=$t;$t=dn+1}}else{for(gn=Array(we),Nt=0;Nt>>0]);gn=gn.join("")}return Zo(ae),gn},toWireType:function(ae,we){we instanceof ArrayBuffer&&(we=new Uint8Array(we));var qe=typeof we=="string";if(!(qe||we instanceof Uint8Array||we instanceof Uint8ClampedArray||we instanceof Int8Array))throw new ll("Cannot pass non-string to std::string");var $t=Z&&qe?M_(we):we.length,Nt=im(4+$t+1),dn=Nt+4;if(y()[Nt>>>2>>>0]=$t,Z&&qe)wc(we,dn,$t+1);else if(qe)for(qe=0;qe<$t;++qe){var gn=we.charCodeAt(qe);if(255>>0]=gn}else for(qe=0;qe<$t;++qe)u()[dn+qe>>>0]=we[qe];return ae!==null&&ae.push(Zo,Nt),Nt},argPackAdvance:ul,readValueFromPointer:C_,Db(ae){Zo(ae)}})}var ab=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,CC=(b,B)=>{for(var Z=b>>1,ae=Z+B/2;!(Z>=ae)&&m()[Z>>>0];)++Z;if(32<(Z<<=1)-b&&ab)return ab.decode(u().slice(b,Z));for(Z="",ae=0;!(ae>=B/2);++ae){var we=p()[b+2*ae>>>1>>>0];if(we==0)break;Z+=String.fromCharCode(we)}return Z},PC=(b,B,Z)=>{if(Z??=2147483647,2>Z)return 0;var ae=B;Z=(Z-=2)<2*b.length?Z/2:b.length;for(var we=0;we>>1>>>0]=qe,B+=2}return p()[B>>>1>>>0]=0,B-ae},AC=b=>2*b.length,$C=(b,B)=>{for(var Z=0,ae="";!(Z>=B/4);){var we=g()[b+4*Z>>>2>>>0];if(we==0)break;++Z,65536<=we?(we-=65536,ae+=String.fromCharCode(55296|we>>10,56320|1023&we)):ae+=String.fromCharCode(we)}return ae},IC=(b,B,Z)=>{if(B>>>=0,Z??=2147483647,4>Z)return 0;var ae=B;Z=ae+Z-4;for(var we=0;we=qe&&(qe=65536+((1023&qe)<<10)|1023&b.charCodeAt(++we)),g()[B>>>2>>>0]=qe,(B+=4)+4>Z)break}return g()[B>>>2>>>0]=0,B-ae},FC=b=>{for(var B=0,Z=0;Z=ae&&++Z,B+=4}return B};function OC(b,B,Z){if(b>>>=0,B>>>=0,Z=Qo(Z>>>=0),B===2)var ae=CC,we=PC,qe=AC,$t=Nt=>m()[Nt>>>1>>>0];else B===4&&(ae=$C,we=IC,qe=FC,$t=Nt=>y()[Nt>>>2>>>0]);Ta(b,{name:Z,fromWireType:Nt=>{for(var dn,gn=y()[Nt>>>2>>>0],$n=Nt+4,fr=0;fr<=gn;++fr){var Sr=Nt+4+fr*B;fr!=gn&&$t(Sr)!=0||($n=ae($n,Sr-$n),dn===void 0?dn=$n:(dn+="\0",dn+=$n),$n=Sr+B)}return Zo(Nt),dn},toWireType:(Nt,dn)=>{if(typeof dn!="string")throw new ll(`Cannot pass non-string to C++ string type ${Z}`);var gn=qe(dn),$n=im(4+gn+B);return y()[$n>>>2>>>0]=gn/B,we(dn,$n+4,gn+B),Nt!==null&&Nt.push(Zo,$n),$n},argPackAdvance:ul,readValueFromPointer:C_,Db(Nt){Zo(Nt)}})}function DC(b,B){Ta(b>>>=0,{Sb:!0,name:B=Qo(B>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var zC=()=>1;function RC(b){z_(b>>>0,!ue,1,!re,131072,!1),L1()}var lb=b=>{if(!Ds)try{if(b(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(g(),b>>>2,b).value.then(Qp),b+=128,Atomics.store(g(),b>>>2,1))}var Qp=()=>{var b=xc();b&&(P_(b),lb(Lb))};function LC(b,B){(b>>>=0)==B>>>0?setTimeout(Qp):ie?postMessage({targetThread:b,cmd:"checkMailbox"}):(b=Xo[b])&&b.postMessage({cmd:"checkMailbox"})}var A_=[];function BC(b,B,Z,ae,we){for(B>>>=0,ae/=2,A_.length=ae,Z=we>>>0>>>3,we=0;we>>0];return(B?y_[B]:CP[b])(...A_)}function NC(b){b>>>=0,ie?postMessage({cmd:"cleanupThread",thread:b}):R1(Xo[b])}function jC(b){}var $_=(b,B)=>{var Z=S_[b];if(Z===void 0)throw b=Ob(b),Z=Qo(b),Zo(b),new ll(`${B} has unknown type ${Z}`);return Z},ub=(b,B,Z)=>{var ae=[];return b=b.toWireType(ae,Z),ae.length&&(y()[B>>>2>>>0]=Zs(ae)),b};function VC(b,B,Z){return B>>>=0,Z>>>=0,b=Ys(b>>>0),B=$_(B,"emval::as"),ub(B,Z,b)}var Yp=b=>{try{b()}catch(B){vc(B)}},cl=0,Yo=null,cb=0,Zp=[],db={},fb={},UC=0,I_=null,WC=[];function hb(b){return function(B){if(!Ds){if(cl===0){var Z=!1,ae=!1;B((we=0)=>{if(!Ds&&(cb=we,Z=!0,ae)){cl=2,Yp(()=>Ub(Yo)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),we=!1;try{var qe=function(){var dn=g()[Yo+8>>>2>>>0];return dn=Pn[fb[dn]],--su,dn()}()}catch(dn){qe=dn,we=!0}var $t=!1;if(!Yo){var Nt=I_;Nt&&(I_=null,(we?Nt.reject:Nt.resolve)(qe),$t=!0)}if(we&&!$t)throw qe}}),ae=!0,Z||(cl=1,Yo=function(){var we=im(65548),qe=we+12;y()[we>>>2>>>0]=qe,y()[we+4>>>2>>>0]=qe+65536,qe=Zp[0];var $t=db[qe];return $t===void 0&&($t=UC++,db[qe]=$t,fb[$t]=qe),qe=$t,g()[we+8>>>2>>>0]=qe,we}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),Yp(()=>jb(Yo)))}else cl===2?(cl=0,Yp(Wb),Zo(Yo),Yo=null,WC.forEach(lb)):vc(`invalid state: ${cl}`);return cb}}(B=>{b().then(B)})}function GC(b){return b>>>=0,hb(()=>(b=Ys(b)).then(Zs))}var Jp=[];function qC(b,B,Z,ae){return Z>>>=0,ae>>>=0,(b=Jp[b>>>0])(null,B=Ys(B>>>0),Z,ae)}var HC={},em=b=>{var B=HC[b];return B===void 0?Qo(b):B};function KC(b,B,Z,ae,we){return Z>>>=0,ae>>>=0,we>>>=0,(b=Jp[b>>>0])(B=Ys(B>>>0),B[Z=em(Z)],ae,we)}var pb=()=>typeof globalThis=="object"?globalThis:Function("return this")();function XC(b){return(b>>>=0)==0?Zs(pb()):(b=em(b),Zs(pb()[b]))}var QC=b=>{var B=Jp.length;return Jp.push(b),B},YC=(b,B)=>{for(var Z=Array(b),ae=0;ae>>2>>>0],"parameter "+ae);return Z},mb=(b,B)=>Object.defineProperty(B,"name",{value:b});function ZC(b,B,Z){var ae=(B=YC(b,B>>>0)).shift();b--;var we=`return function (obj, func, destructorsRef, args) { `,qe=0,$t=[];Z===0&&$t.push("obj");for(var Nt=["retType"],dn=[ae],gn=0;gn$n.name).join(", ")}) => ${ae.name}>`,QC(mb(Z,b))}function JC(b){return b=em(b>>>0),Zs(k[b])}function eP(b,B){return B>>>=0,b=Ys(b>>>0),B=Ys(B),Zs(b[B])}function tP(b){9<(b>>>=0)&&(Sa[b+1]+=1)}function nP(){return Zs([])}function rP(b){b=Ys(b>>>0);for(var B=Array(b.length),Z=0;Z>>0))}function sP(){return Zs({})}function oP(b){for(var B=Ys(b>>>=0);B.length;){var Z=B.pop();B.pop()(Z)}E_(b)}function aP(b,B,Z){B>>>=0,Z>>>=0,b=Ys(b>>>0),B=Ys(B),Z=Ys(Z),b[B]=Z}function lP(b,B){return B>>>=0,b=(b=$_(b>>>0,"_emval_take_value")).readValueFromPointer(B),Zs(b)}function uP(b,B){b=-9007199254740992>b||9007199254740992>>=0,b=new Date(1e3*b),g()[B>>>2>>>0]=b.getUTCSeconds(),g()[B+4>>>2>>>0]=b.getUTCMinutes(),g()[B+8>>>2>>>0]=b.getUTCHours(),g()[B+12>>>2>>>0]=b.getUTCDate(),g()[B+16>>>2>>>0]=b.getUTCMonth(),g()[B+20>>>2>>>0]=b.getUTCFullYear()-1900,g()[B+24>>>2>>>0]=b.getUTCDay(),b=(b.getTime()-Date.UTC(b.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,g()[B+28>>>2>>>0]=b}var bc=b=>b%4==0&&(b%100!=0||b%400==0),gb=[0,31,60,91,121,152,182,213,244,274,305,335],_b=[0,31,59,90,120,151,181,212,243,273,304,334];function cP(b,B){b=-9007199254740992>b||9007199254740992>>=0,b=new Date(1e3*b),g()[B>>>2>>>0]=b.getSeconds(),g()[B+4>>>2>>>0]=b.getMinutes(),g()[B+8>>>2>>>0]=b.getHours(),g()[B+12>>>2>>>0]=b.getDate(),g()[B+16>>>2>>>0]=b.getMonth(),g()[B+20>>>2>>>0]=b.getFullYear()-1900,g()[B+24>>>2>>>0]=b.getDay();var Z=(bc(b.getFullYear())?gb:_b)[b.getMonth()]+b.getDate()-1|0;g()[B+28>>>2>>>0]=Z,g()[B+36>>>2>>>0]=-60*b.getTimezoneOffset(),Z=new Date(b.getFullYear(),6,1).getTimezoneOffset();var ae=new Date(b.getFullYear(),0,1).getTimezoneOffset();b=0|(Z!=ae&&b.getTimezoneOffset()==Math.min(ae,Z)),g()[B+32>>>2>>>0]=b}function dP(b){b>>>=0;var B=new Date(g()[b+20>>>2>>>0]+1900,g()[b+16>>>2>>>0],g()[b+12>>>2>>>0],g()[b+8>>>2>>>0],g()[b+4>>>2>>>0],g()[b>>>2>>>0],0),Z=g()[b+32>>>2>>>0],ae=B.getTimezoneOffset(),we=new Date(B.getFullYear(),6,1).getTimezoneOffset(),qe=new Date(B.getFullYear(),0,1).getTimezoneOffset(),$t=Math.min(qe,we);return 0>Z?g()[b+32>>>2>>>0]=+(we!=qe&&$t==ae):0>>2>>>0]=B.getDay(),Z=(bc(B.getFullYear())?gb:_b)[B.getMonth()]+B.getDate()-1|0,g()[b+28>>>2>>>0]=Z,g()[b>>>2>>>0]=B.getSeconds(),g()[b+4>>>2>>>0]=B.getMinutes(),g()[b+8>>>2>>>0]=B.getHours(),g()[b+12>>>2>>>0]=B.getDate(),g()[b+16>>>2>>>0]=B.getMonth(),g()[b+20>>>2>>>0]=B.getYear(),b=B.getTime(),BigInt(isNaN(b)?-1:b/1e3)}function yb(b,B,Z,ae,we,qe,$t){return ie?Kr(16,1,b,B,Z,ae,we,qe,$t):-52}function vb(b,B,Z,ae,we,qe){if(ie)return Kr(17,1,b,B,Z,ae,we,qe)}function fP(b,B,Z,ae){b>>>=0,B>>>=0,Z>>>=0,ae>>>=0;var we=new Date().getFullYear(),qe=new Date(we,0,1),$t=new Date(we,6,1);we=qe.getTimezoneOffset();var Nt=$t.getTimezoneOffset(),dn=Math.max(we,Nt);y()[b>>>2>>>0]=60*dn,g()[B>>>2>>>0]=+(we!=Nt),qe=(b=gn=>gn.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(qe),$t=b($t),Nt{F_.length=0;for(var Z;Z=u()[b++>>>0];){var ae=Z!=105;B+=(ae&=Z!=112)&&B%8?4:0,F_.push(Z==112?y()[B>>>2>>>0]:Z==106?Nr[B>>>3]:Z==105?g()[B>>>2>>>0]:I()[B>>>3>>>0]),B+=ae?8:4}return F_};function hP(b,B,Z){return b>>>=0,B=wb(B>>>0,Z>>>0),y_[b](...B)}function pP(b,B,Z){return b>>>=0,B=wb(B>>>0,Z>>>0),y_[b](...B)}var mP=()=>{},gP=()=>Date.now();function _P(b,B){return Gn(Oi(b>>>0,B>>>0))}var bb,yP=()=>{throw su+=1,"unwind"};function vP(){return 4294901760}bb=()=>performance.timeOrigin+performance.now();var wP=()=>navigator.hardwareConcurrency;function bP(){return vc("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function xP(b){b>>>=0;var B=u().length;if(b<=B||4294901760=Z;Z*=2){var ae=B*(1+.2/Z);ae=Math.min(ae,b+100663296);var we=Math;ae=Math.max(b,ae);e:{we=(we.min.call(we,4294901760,ae+(65536-ae%65536)%65536)-ir.buffer.byteLength+65535)/65536;try{ir.grow(we),Ts();var qe=1;break e}catch{}qe=void 0}if(qe)return!0}return!1}var tm=()=>(vc("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Hf={},xb=b=>{b.forEach(B=>{tm()})};function MP(){var b=Error().stack.toString().split(` `);return b[0]=="Error"&&b.shift(),xb(b),Hf.Ob=tm(),Hf.ac=b,Hf.Ob}function TP(b,B,Z){if(b>>>=0,B>>>=0,Hf.Ob==b)var ae=Hf.ac;else(ae=Error().stack.toString().split(` `))[0]=="Error"&&ae.shift(),xb(ae);for(var we=3;ae[we]&&tm()!=b;)++we;for(b=0;b>>2>>>0]=tm();return b}var O_,D_={},Mb=()=>{if(!O_){var b,B={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",_:et};for(b in D_)D_[b]===void 0?delete B[b]:B[b]=D_[b];var Z=[];for(b in B)Z.push(`${b}=${B[b]}`);O_=Z}return O_};function Tb(b,B){if(ie)return Kr(18,1,b,B);b>>>=0,B>>>=0;var Z=0;return Mb().forEach((ae,we)=>{var qe=B+Z;for(we=y()[b+4*we>>>2>>>0]=qe,qe=0;qe>>0]=ae.charCodeAt(qe);s()[we>>>0]=0,Z+=ae.length+1}),0}function Sb(b,B){if(ie)return Kr(19,1,b,B);b>>>=0,B>>>=0;var Z=Mb();y()[b>>>2>>>0]=Z.length;var ae=0;return Z.forEach(we=>ae+=we.length+1),y()[B>>>2>>>0]=ae,0}function kb(b){return ie?Kr(20,1,b):52}function Eb(b,B,Z,ae){return ie?Kr(21,1,b,B,Z,ae):52}function Cb(b,B,Z,ae){return ie?Kr(22,1,b,B,Z,ae):70}var SP=[null,[],[]];function Pb(b,B,Z,ae){if(ie)return Kr(23,1,b,B,Z,ae);B>>>=0,Z>>>=0,ae>>>=0;for(var we=0,qe=0;qe>>2>>>0],Nt=y()[B+4>>>2>>>0];B+=8;for(var dn=0;dn>>0],$n=SP[b];gn===0||gn===10?((b===1?Zn:Gn)(W1($n,0)),$n.length=0):$n.push(gn)}we+=Nt}return y()[ae>>>2>>>0]=we,0}var Ab=[31,29,31,30,31,30,31,31,30,31,30,31],$b=[31,28,31,30,31,30,31,31,30,31,30,31],kP=(b,B)=>{s().set(b,B>>>0)};function Ib(b,B,Z,ae){function we(Tt,dr,Zr){for(Tt=typeof Tt=="number"?Tt.toString():Tt||"";Tt.lengthqb?-1:0au-Tt.getDate())){Tt.setDate(Tt.getDate()+dr);break}dr-=au-Tt.getDate()+1,Tt.setDate(1),11>Zr?Tt.setMonth(Zr+1):(Tt.setMonth(0),Tt.setFullYear(Tt.getFullYear()+1))}return Zr=new Date(Tt.getFullYear()+1,0,4),dr=Nt(new Date(Tt.getFullYear(),0,4)),Zr=Nt(Zr),0>=$t(dr,Tt)?0>=$t(Zr,Tt)?Tt.getFullYear()+1:Tt.getFullYear():Tt.getFullYear()-1}b>>>=0,B>>>=0,Z>>>=0,ae>>>=0;var gn=y()[ae+40>>>2>>>0];for(var $n in ae={fc:g()[ae>>>2>>>0],ec:g()[ae+4>>>2>>>0],Gb:g()[ae+8>>>2>>>0],Kb:g()[ae+12>>>2>>>0],Hb:g()[ae+16>>>2>>>0],Cb:g()[ae+20>>>2>>>0],ub:g()[ae+24>>>2>>>0],Bb:g()[ae+28>>>2>>>0],nc:g()[ae+32>>>2>>>0],dc:g()[ae+36>>>2>>>0],hc:gn?Oi(gn):""},Z=Oi(Z),gn={"%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"})Z=Z.replace(new RegExp($n,"g"),gn[$n]);var fr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Sr="January February March April May June July August September October November December".split(" ");for($n in gn={"%a":Tt=>fr[Tt.ub].substring(0,3),"%A":Tt=>fr[Tt.ub],"%b":Tt=>Sr[Tt.Hb].substring(0,3),"%B":Tt=>Sr[Tt.Hb],"%C":Tt=>qe((Tt.Cb+1900)/100|0,2),"%d":Tt=>qe(Tt.Kb,2),"%e":Tt=>we(Tt.Kb,2," "),"%g":Tt=>dn(Tt).toString().substring(2),"%G":dn,"%H":Tt=>qe(Tt.Gb,2),"%I":Tt=>((Tt=Tt.Gb)==0?Tt=12:12{for(var dr=0,Zr=0;Zr<=Tt.Hb-1;dr+=(bc(Tt.Cb+1900)?Ab:$b)[Zr++]);return qe(Tt.Kb+dr,3)},"%m":Tt=>qe(Tt.Hb+1,2),"%M":Tt=>qe(Tt.ec,2),"%n":()=>` `,"%p":Tt=>0<=Tt.Gb&&12>Tt.Gb?"AM":"PM","%S":Tt=>qe(Tt.fc,2),"%t":()=>" ","%u":Tt=>Tt.ub||7,"%U":Tt=>qe(Math.floor((Tt.Bb+7-Tt.ub)/7),2),"%V":Tt=>{var dr=Math.floor((Tt.Bb+7-(Tt.ub+6)%7)/7);if(2>=(Tt.ub+371-Tt.Bb-2)%7&&dr++,dr)dr==53&&((Zr=(Tt.ub+371-Tt.Bb)%7)==4||Zr==3&&bc(Tt.Cb)||(dr=1));else{dr=52;var Zr=(Tt.ub+7-Tt.Bb-1)%7;(Zr==4||Zr==5&&bc(Tt.Cb%400-1))&&dr++}return qe(dr,2)},"%w":Tt=>Tt.ub,"%W":Tt=>qe(Math.floor((Tt.Bb+7-(Tt.ub+6)%7)/7),2),"%y":Tt=>(Tt.Cb+1900).toString().substring(2),"%Y":Tt=>Tt.Cb+1900,"%z":Tt=>{var dr=0<=(Tt=Tt.dc);return Tt=Math.abs(Tt)/60,(dr?"+":"-")+("0000"+(Tt/60*100+Tt%60)).slice(-4)},"%Z":Tt=>Tt.hc,"%%":()=>"%"},Z=Z.replace(/%%/g,"\0\0"),gn)Z.includes($n)&&(Z=Z.replace(new RegExp($n,"g"),gn[$n](ae)));return $n=function(Tt){var dr=Array(M_(Tt)+1);return H1(Tt,dr,0,dr.length),dr}(Z=Z.replace(/\0\0/g,"%")),$n.length>B?0:(kP($n,b),$n.length-1)}function EP(b,B,Z,ae){return Ib(b>>>0,B>>>0,Z>>>0,ae>>>0)}ie||function(){for(var b=k.numThreads-1;b--;)N1();Zi.unshift(()=>{ol++,function(B){ie?B():Promise.all(al.map(B1)).then(B)}(()=>C1())})}();for(var Fb=Array(256),nm=0;256>nm;++nm)Fb[nm]=String.fromCharCode(nm);sb=Fb,ll=k.BindingError=class extends Error{constructor(b){super(b),this.name="BindingError"}},k.InternalError=class extends Error{constructor(b){super(b),this.name="InternalError"}},Sa.push(0,1,void 0,1,null,1,!0,1,!1,1),k.count_emval_handles=()=>Sa.length/2-5-k_.length;var CP=[b_,D1,j1,G1,q1,K1,X1,Q1,Y1,Z1,J1,eb,tb,nb,rb,ib,yb,vb,Tb,Sb,kb,Eb,Cb,Pb],Pn=function(){function b(Z,ae){return Pn=Z.exports,Pn=function(){var we=Pn,qe={};for(let[$t,Nt]of Object.entries(we))qe[$t]=typeof Nt=="function"?(...dn)=>{Zp.push($t);try{return Nt(...dn)}finally{Ds||(Zp.pop(),Yo&&cl===1&&Zp.length===0&&(cl=0,su+=1,Yp(Vb),typeof Fibers<"u"&&Fibers.oc()))}}:Nt;return qe}(),Pn=function(){var we=Pn,qe=Nt=>dn=>Nt(dn)>>>0,$t=Nt=>()=>Nt()>>>0;return(we=Object.assign({},we)).Ca=qe(we.Ca),we.fb=$t(we.fb),we.gb=qe(we.gb),we.emscripten_main_runtime_thread_id=$t(we.emscripten_main_runtime_thread_id),we.sb=qe(we.sb),we.tb=$t(we.tb),we}(),z1.push(Pn.ib),Ni.unshift(Pn.Ba),On=ae,C1(),Pn}var B=F1();if(ol++,k.instantiateWasm)try{return k.instantiateWasm(B,b)}catch(Z){Gn(`Module.instantiateWasm callback failed with error: ${Z}`),Q(Z)}return __||=k.locateFile?P1("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":k.locateFile?k.locateFile("ort-wasm-simd-threaded.jsep.wasm",It):It+"ort-wasm-simd-threaded.jsep.wasm":new URL(n("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),n.b).href,function(Z,ae){var we=__;return Kt||typeof WebAssembly.instantiateStreaming!="function"||P1(we)||A1(we)||typeof fetch!="function"?I1(we,Z,ae):fetch(we,{credentials:"same-origin"}).then(qe=>WebAssembly.instantiateStreaming(qe,Z).then(ae,function($t){return Gn(`wasm streaming compile failed: ${$t}`),Gn("falling back to ArrayBuffer instantiation"),I1(we,Z,ae)}))}(B,function(Z){b(Z.instance,Z.module)}).catch(Q),{}}(),Ob=b=>(Ob=Pn.Ca)(b),Db=()=>(Db=Pn.Da)();k._OrtInit=(b,B)=>(k._OrtInit=Pn.Ea)(b,B),k._OrtGetLastError=(b,B)=>(k._OrtGetLastError=Pn.Fa)(b,B),k._OrtCreateSessionOptions=(b,B,Z,ae,we,qe,$t,Nt,dn,gn)=>(k._OrtCreateSessionOptions=Pn.Ga)(b,B,Z,ae,we,qe,$t,Nt,dn,gn),k._OrtAppendExecutionProvider=(b,B)=>(k._OrtAppendExecutionProvider=Pn.Ha)(b,B),k._OrtAddFreeDimensionOverride=(b,B,Z)=>(k._OrtAddFreeDimensionOverride=Pn.Ia)(b,B,Z),k._OrtAddSessionConfigEntry=(b,B,Z)=>(k._OrtAddSessionConfigEntry=Pn.Ja)(b,B,Z),k._OrtReleaseSessionOptions=b=>(k._OrtReleaseSessionOptions=Pn.Ka)(b),k._OrtCreateSession=(b,B,Z)=>(k._OrtCreateSession=Pn.La)(b,B,Z),k._OrtReleaseSession=b=>(k._OrtReleaseSession=Pn.Ma)(b),k._OrtGetInputOutputCount=(b,B,Z)=>(k._OrtGetInputOutputCount=Pn.Na)(b,B,Z),k._OrtGetInputName=(b,B)=>(k._OrtGetInputName=Pn.Oa)(b,B),k._OrtGetOutputName=(b,B)=>(k._OrtGetOutputName=Pn.Pa)(b,B),k._OrtFree=b=>(k._OrtFree=Pn.Qa)(b),k._OrtCreateTensor=(b,B,Z,ae,we,qe)=>(k._OrtCreateTensor=Pn.Ra)(b,B,Z,ae,we,qe),k._OrtGetTensorData=(b,B,Z,ae,we)=>(k._OrtGetTensorData=Pn.Sa)(b,B,Z,ae,we),k._OrtReleaseTensor=b=>(k._OrtReleaseTensor=Pn.Ta)(b),k._OrtCreateRunOptions=(b,B,Z,ae)=>(k._OrtCreateRunOptions=Pn.Ua)(b,B,Z,ae),k._OrtAddRunConfigEntry=(b,B,Z)=>(k._OrtAddRunConfigEntry=Pn.Va)(b,B,Z),k._OrtReleaseRunOptions=b=>(k._OrtReleaseRunOptions=Pn.Wa)(b),k._OrtCreateBinding=b=>(k._OrtCreateBinding=Pn.Xa)(b),k._OrtBindInput=(b,B,Z)=>(k._OrtBindInput=Pn.Ya)(b,B,Z),k._OrtBindOutput=(b,B,Z,ae)=>(k._OrtBindOutput=Pn.Za)(b,B,Z,ae),k._OrtClearBoundOutputs=b=>(k._OrtClearBoundOutputs=Pn._a)(b),k._OrtReleaseBinding=b=>(k._OrtReleaseBinding=Pn.$a)(b),k._OrtRunWithBinding=(b,B,Z,ae,we)=>(k._OrtRunWithBinding=Pn.ab)(b,B,Z,ae,we),k._OrtRun=(b,B,Z,ae,we,qe,$t,Nt)=>(k._OrtRun=Pn.bb)(b,B,Z,ae,we,qe,$t,Nt),k._OrtEndProfiling=b=>(k._OrtEndProfiling=Pn.cb)(b),k._JsepOutput=(b,B,Z)=>(k._JsepOutput=Pn.db)(b,B,Z),k._JsepGetNodeName=b=>(k._JsepGetNodeName=Pn.eb)(b);var rm,xc=()=>(xc=Pn.fb)(),im=k._malloc=b=>(im=k._malloc=Pn.gb)(b),Zo=k._free=b=>(Zo=k._free=Pn.hb)(b),z_=(b,B,Z,ae,we,qe)=>(z_=Pn.kb)(b,B,Z,ae,we,qe),zb=()=>(zb=Pn.lb)(),Rb=(b,B,Z,ae,we)=>(Rb=Pn.mb)(b,B,Z,ae,we),R_=b=>(R_=Pn.nb)(b),sm=b=>(sm=Pn.ob)(b),Lb=()=>(Lb=Pn.pb)(),Bb=(b,B)=>(Bb=Pn.qb)(b,B),om=b=>(om=Pn.rb)(b),L_=b=>(L_=Pn.sb)(b),B_=()=>(B_=Pn.tb)(),Nb=k.dynCall_ii=(b,B)=>(Nb=k.dynCall_ii=Pn.vb)(b,B),jb=b=>(jb=Pn.wb)(b),Vb=()=>(Vb=Pn.xb)(),Ub=b=>(Ub=Pn.yb)(b),Wb=()=>(Wb=Pn.zb)();function Gb(){0B_(),k.stackRestore=b=>om(b),k.stackAlloc=b=>L_(b),k.UTF8ToString=Oi,k.stringToUTF8=wc,k.lengthBytesUTF8=M_,iu=function b(){rm||Gb(),rm||(iu=b)},Gb(),J}),en=it,globalThis.self?.name==="em-pthread"&&it()}),xt,hn,fn,Tn,bn,mn,Sn,An,In=c(()=>{kt(),xt=import.meta.url??(typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0),hn=typeof location>"u"?void 0:location.origin,fn=(r,s)=>{try{let u=s??xt;return(u?new URL(r,u):new URL(r)).origin===hn}catch{return!1}},Tn=async r=>{let s=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(s)},bn=(mt(),_(ve)).default,mn=async()=>{if(!xt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(fn(xt))return[void 0,bn()];let r=await Tn(xt);return[r,bn(r)]},Sn=(Vt(),_(At)).default,An=async(r,s,u)=>[void 0,Sn]}),Mn,Et,Ht,un,zr,os,ao,vr,Qr=c(()=>{In(),Et=!1,Ht=!1,un=!1,zr=()=>{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}},os=()=>{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}},ao=async r=>{if(Et)return Promise.resolve();if(Ht)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(un)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ht=!0;let s=r.initTimeout,u=r.numThreads;if(!os())throw new Error("WebAssembly SIMD is not supported in the current environment.");let p=zr();u>1&&!p&&(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 m=r.wasmPaths,g=typeof m=="string"?m:void 0,y=m?.mjs,A=y?.href??y,I=m?.wasm,O=I?.href??I,Q=r.wasmBinary,[k,J]=await An(A,g,u>1),re=!1,ue=[];if(s>0&&ue.push(new Promise(ie=>{setTimeout(()=>{re=!0,ie()},s)})),ue.push(new Promise((ie,Ae)=>{let $e={numThreads:u};Q?$e.wasmBinary=Q:(O||g)&&($e.locateFile=(me,Be)=>O??(g??Be)+me),J($e).then(me=>{Ht=!1,Et=!0,Mn=me,ie(),k&&URL.revokeObjectURL(k)},me=>{Ht=!1,un=!0,Ae(me)})})),await Promise.race(ue),re)throw new Error(`WebAssembly backend initializing failed due to timeout: ${s}ms`)},vr=()=>{if(Et&&Mn)return Mn;throw new Error("WebAssembly is not initialized yet.")}}),br,as,kr,mi=c(()=>{Qr(),br=(r,s)=>{let u=vr(),p=u.lengthBytesUTF8(r)+1,m=u._malloc(p);return u.stringToUTF8(r,m,p),s.push(m),m},as=(r,s,u,p)=>{if(typeof r=="object"&&r!==null){if(u.has(r))throw new Error("Circular reference in options");u.add(r)}Object.entries(r).forEach(([m,g])=>{let y=s?s+m:m;if(typeof g=="object")as(g,y+".",u,p);else if(typeof g=="string"||typeof g=="number")p(y,g.toString());else if(typeof g=="boolean")p(y,g?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof g}`)})},kr=r=>{let s=vr(),u=s.stackSave();try{let p=s.stackAlloc(8);s._OrtGetLastError(p,p+4);let m=s.HEAP32[p/4],g=s.HEAPU32[p/4+1],y=g?s.UTF8ToString(g):"";throw new Error(`${r} ERROR_CODE: ${m}, ERROR_MESSAGE: ${y}`)}finally{s.stackRestore(u)}}}),ls,us=c(()=>{Qr(),mi(),ls=r=>{let s=vr(),u=0,p=[],m=r||{};try{if(r?.logSeverityLevel===void 0)m.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?.logVerbosityLevel===void 0)m.logVerbosityLevel=0;else if(typeof r.logVerbosityLevel!="number"||!Number.isInteger(r.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${r.logVerbosityLevel}`);r?.terminate===void 0&&(m.terminate=!1);let g=0;return r?.tag!==void 0&&(g=br(r.tag,p)),u=s._OrtCreateRunOptions(m.logSeverityLevel,m.logVerbosityLevel,!!m.terminate,g),u===0&&kr("Can't create run options."),r?.extra!==void 0&&as(r.extra,"",new WeakSet,(y,A)=>{let I=br(y,p),O=br(A,p);s._OrtAddRunConfigEntry(u,I,O)!==0&&kr(`Can't set a run config entry: ${y} - ${A}.`)}),[u,p]}catch(g){throw u!==0&&s._OrtReleaseRunOptions(u),p.forEach(y=>s._free(y)),g}}}),lo,Ws,Ar,Gi,li,$o=c(()=>{Qr(),mi(),lo=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}`)}},Ws=r=>{switch(r){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${r}`)}},Ar=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)},Gi=(r,s,u)=>{for(let p of s){let m=typeof p=="string"?p:p.name;switch(m){case"webnn":if(m="WEBNN",typeof p!="string"){let y=p?.deviceType;if(y){let A=br("deviceType",u),I=br(y,u);vr()._OrtAddSessionConfigEntry(r,A,I)!==0&&kr(`Can't set a session config entry: 'deviceType' - ${y}.`)}}break;case"webgpu":if(m="JS",typeof p!="string"){let y=p;if(y?.preferredLayout){if(y.preferredLayout!=="NCHW"&&y.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${y.preferredLayout}`);let A=br("preferredLayout",u),I=br(y.preferredLayout,u);vr()._OrtAddSessionConfigEntry(r,A,I)!==0&&kr(`Can't set a session config entry: 'preferredLayout' - ${y.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${m}`)}let g=br(m,u);vr()._OrtAppendExecutionProvider(r,g)!==0&&kr(`Can't append execution provider: ${m}.`)}},li=r=>{let s=vr(),u=0,p=[],m=r||{};Ar(m);try{let g=lo(m.graphOptimizationLevel??"all"),y=Ws(m.executionMode??"sequential"),A=typeof m.logId=="string"?br(m.logId,p):0,I=m.logSeverityLevel??2;if(!Number.isInteger(I)||I<0||I>4)throw new Error(`log serverity level is not valid: ${I}`);let O=m.logVerbosityLevel??0;if(!Number.isInteger(O)||O<0||O>4)throw new Error(`log verbosity level is not valid: ${O}`);let Q=typeof m.optimizedModelFilePath=="string"?br(m.optimizedModelFilePath,p):0;if(u=s._OrtCreateSessionOptions(g,!!m.enableCpuMemArena,!!m.enableMemPattern,y,!!m.enableProfiling,0,A,I,O,Q),u===0&&kr("Can't create session options."),m.executionProviders&&Gi(u,m.executionProviders,p),m.enableGraphCapture!==void 0){if(typeof m.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${m.enableGraphCapture}`);let k=br("enableGraphCapture",p),J=br(m.enableGraphCapture.toString(),p);s._OrtAddSessionConfigEntry(u,k,J)!==0&&kr(`Can't set a session config entry: 'enableGraphCapture' - ${m.enableGraphCapture}.`)}if(m.freeDimensionOverrides)for(let[k,J]of Object.entries(m.freeDimensionOverrides)){if(typeof k!="string")throw new Error(`free dimension override name must be a string: ${k}`);if(typeof J!="number"||!Number.isInteger(J)||J<0)throw new Error(`free dimension override value must be a non-negative integer: ${J}`);let re=br(k,p);s._OrtAddFreeDimensionOverride(u,re,J)!==0&&kr(`Can't set a free dimension override: ${k} - ${J}.`)}return m.extra!==void 0&&as(m.extra,"",new WeakSet,(k,J)=>{let re=br(k,p),ue=br(J,p);s._OrtAddSessionConfigEntry(u,re,ue)!==0&&kr(`Can't set a session config entry: ${k} - ${J}.`)}),[u,p]}catch(g){throw u!==0&&s._OrtReleaseSessionOptions(u),p.forEach(y=>s._free(y)),g}}}),qi,Si,cs,Hi,ki,Gs,vs,En=c(()=>{qi=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}`)}},Si=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}`)}},cs=(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],p=typeof s=="number"?s:s.reduce((m,g)=>m*g,1);return u>0?Math.ceil(p*u):void 0},Hi=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}`)}},ki=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}`)}},Gs=r=>r==="float32"||r==="float16"||r==="int32"||r==="int64"||r==="uint32"||r==="uint8"||r==="bool"||r==="uint4"||r==="int4",vs=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}`)}}}),Xn,uo=c(()=>{kt(),Xn=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"),p=u?parseInt(u,10):0;if(p<1073741824)return new Uint8Array(await s.arrayBuffer());{if(!s.body)throw new Error(`failed to load external data file: ${r}, no response body.`);let m=s.body.getReader(),g;try{g=new ArrayBuffer(p)}catch(A){if(A instanceof RangeError){let I=Math.ceil(p/65536);g=new WebAssembly.Memory({initial:I,maximum:I}).buffer}else throw A}let y=0;for(;;){let{done:A,value:I}=await m.read();if(A)break;let O=I.byteLength;new Uint8Array(g,y,O).set(I),y+=O}return new Uint8Array(g,0,p)}}else return r instanceof Blob?new Uint8Array(await r.arrayBuffer()):r instanceof Uint8Array?r:new Uint8Array(r)}}),co,qs,mr,ws,ds,fs,xr,wi=c(()=>{En(),co=["V","I","W","E","F"],qs=(r,s)=>{console.log(`[${co[r]},${new Date().toISOString()}]${s}`)},ds=(r,s)=>{mr=r,ws=s},fs=(r,s)=>{let u=ki(r),p=ki(mr);u>=p&&qs(u,typeof s=="function"?s():s)},xr=(...r)=>{ws&&fs(...r)}}),nt,q=c(()=>{En(),nt=(r,s)=>new(Hi(s))(r)}),ye=c(()=>{}),Le,De,ct,Pt,tn,zt,nn,Qt,nr,Cn=c(()=>{wi(),ye(),Le=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]]),De=[],ct=r=>Math.ceil(r/16)*16,Pt=r=>{for(let s=0;stn++,nn=async(r,s,u,p)=>{let m=ct(u),g=r.device.createBuffer({size:m,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let y=r.getCommandEncoder();r.endComputePass(),y.copyBufferToBuffer(s,0,g,0,m),r.flush(),await g.mapAsync(GPUMapMode.READ);let A=g.getMappedRange();if(p){let I=p();return I.set(new Uint8Array(A,0,u)),I}else return new Uint8Array(A.slice(0,u))}finally{g.destroy()}},Qt=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 Le)De.push(s),this.freeBuffers.set(s,[]),this.freeUniformBuffers.set(s,[])}upload(r,s){let u=s.buffer,p=s.byteOffset,m=s.byteLength,g=ct(m),y=this.storageCache.get(r);if(!y)throw new Error("gpu data for uploading does not exist");if(y.originalSize!==m)throw new Error(`inconsistent data size. gpu data size=${y.originalSize}, data size=${m}`);let A=this.backend.device.createBuffer({mappedAtCreation:!0,size:g,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),I=A.getMappedRange();new Uint8Array(I).set(new Uint8Array(u,p,m)),A.unmap();let O=this.backend.getCommandEncoder();this.backend.endComputePass(),O.copyBufferToBuffer(A,0,y.gpuData.buffer,0,g),xr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${r})`),this.buffersForUploadingPending.push(A)}memcpy(r,s){let u=this.storageCache.get(r);if(!u)throw new Error("source gpu data for memcpy does not exist");let p=this.storageCache.get(s);if(!p)throw new Error("destination gpu data for memcpy does not exist");if(u.originalSize!==p.originalSize)throw new Error("inconsistent source and destination gpu data size");let m=ct(u.originalSize),g=this.backend.getCommandEncoder();this.backend.endComputePass(),g.copyBufferToBuffer(u.gpuData.buffer,0,p.gpuData.buffer,0,m)}registerExternalBuffer(r,s,u){let p;if(u){if(p=this.externalBuffers.get(u),p===void 0)throw new Error("previous buffer is not registered");if(r===u)return xr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${s}) => id=${p}, buffer is the same, skip.`),p;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 p=zt();return this.storageCache.set(p,{gpuData:{id:p,type:0,buffer:r},originalSize:s}),this.externalBuffers.set(r,p),xr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${s}) => id=${p}, registered.`),p}unregisterExternalBuffer(r){let s=this.externalBuffers.get(r);s!==void 0&&(this.storageCache.delete(s),this.externalBuffers.delete(r),xr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${s}`))}create(r,s=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let u=Pt(r),p,m=(s&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,g=(s&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(m||g){let A=(m?this.freeBuffers:this.freeUniformBuffers).get(u);A?A.length>0?p=A.pop():p=this.backend.device.createBuffer({size:u,usage:s}):p=this.backend.device.createBuffer({size:u,usage:s})}else p=this.backend.device.createBuffer({size:u,usage:s});let y={id:zt(),type:0,buffer:p};return this.storageCache.set(y.id,{gpuData:y,originalSize:r}),xr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${r}) => id=${y.id}`),y}get(r){return this.storageCache.get(r)?.gpuData}release(r){let s=this.storageCache.get(r);if(!s)throw new Error("releasing data does not exist");return xr("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 nn(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=Le.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))}},nr=(...r)=>new Qt(...r)}),qn,kn,Qn=c(()=>{qn=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}},kn=r=>new qn(r)}),Ei,Mr,yt,Yr,er,Dr,ui,xn=c(()=>{Ei=class{static calcMatMulShape(r,s){return r[1]!==s[0]?void 0:[r[0],s[1]]}},Mr=class{static calcShape(r,s,u=!1){let p=r.length,m=s.length;if(p===0)return s;if(m===0)return r;let g=Math.max(r.length,s.length),y=new Array(g);if(u){if(p<2||m<2)return;let A=Ei.calcMatMulShape([r[p-2],r[p-1]],[s[m-2],s[m-1]]);if(A===void 0)return;[y[g-2],y[g-1]]=A}for(let A=u?3:1;A<=g;A++){let I=p-A<0?1:r[p-A],O=m-A<0?1:s[m-A];if(I!==O&&I>1&&O>1)return;let Q=Math.max(I,O);if(I&&O)y[g-A]=Math.max(I,O);else{if(Q>1)return;y[g-A]=0}}return y}static isValidBroadcast(r,s){let u=r.length,p=s.length;if(u>p)return!1;for(let m=1;m<=u;m++)if(r[u-m]!==1&&r[u-m]!==s[p-m])return!1;return!0}},yt=class jm{static size(s){return jm.getSizeFromDimensionRange(s,0,s.length)}static convertShape(s,u=4){let p=s.length;if(p===0)return[];let m=new Array(p),g=p-1;for(;g>=0;){if(s[g]%u===0){m[g]=s[g]/u;break}if(u%s[g]!==0)throw new Error("cannot convert shape");m[g]=1,u/=s[g],g--}for(g--;g>=0;g--)m[g]=s[g];return m}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 jm.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 jm.getSizeFromDimensionRange(s,0,u)}static getSizeFromDimensionRange(s,u,p){let m=1;for(let g=u;g=0;--m)p[m]=p[m+1]*s[m+1];return p}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(p=>this.normalizeAxis(p,u??s.length))}static sortBasedOnPerm(s,u){return u?u.map(p=>s[p]):s.slice().reverse()}static padShape(s,u){let p=s.length;return s.map((m,g)=>m+u[g]+u[g+p])}static areEqual(s,u){return s.length!==u.length?!1:s.every((p,m)=>p===u[m])}},Yr=class lh{static adjustPoolAttributes(s,u,p,m,g,y){if(!s&&p.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 A=0;A=p.length?p.push(u[A+2]):p[A]=u[A+2];for(let A=0;A=p[A]||y[A+p.length]>=p[A])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(s,u,p,m,g,y,A){if(A){if(g.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(m.length!==s.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let I=0;I{En(),xn(),Ci=64,$r=(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}`)}},or=(r,s=1)=>{let u=$r(r,s);return typeof u=="string"?u:u[0]},ar=(r,s=1)=>{let u=$r(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:yt.computeStrides(u)})}),s},tr=r=>r%4===0?4:r%2===0?2:1,pr=(r="f32",s,u="0")=>!s||s===1?`${r}(${u})`:`vec${s}<${r}>(${u})`,Ir=(r,s,u)=>r==="f32"?u:s===1?`f32(${u})`:`vec${s}(${u})`,Pi=(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,pn=(r,s,u,p)=>r.startsWith("uniforms.")&&u>4?typeof s=="string"?p==="f16"?`${r}[(${s}) / 8][(${s}) % 8 / 4][(${s}) % 8 % 4]`:`${r}[(${s}) / 4][(${s}) % 4]`:p==="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,la=(r,s,u,p,m)=>{let g=typeof u=="number",y=g?u:u.length,A=[...new Array(y).keys()],I=y<2?"u32":y<=4?`vec${y}`:`array`,O=$r(s,m),Q=typeof O=="string"?O:O[1],k=typeof O=="string"?O:O[0],J={indices:I,value:Q,storage:k,tensor:s},re=Rt=>typeof Rt=="string"?Rt:`${Rt}u`,ue={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},ie=g?"uniforms.":"",Ae=`${ie}${r}_shape`,$e=`${ie}${r}_strides`,me="";for(let Rt=0;Rt ${J.indices} { var indices: ${J.indices}; var current = offset; ${me} return indices; }`,je=Rt=>(ue.offsetToIndices=!0,y<2?Rt:`o2i_${r}(${Rt})`),et=[];if(y>=2)for(let Rt=y-1;Rt>=0;Rt--)et.push(`${pn($e,Rt,y)} * (indices[${Rt}])`);let Ot=y<2?"":` fn i2o_${r}(indices: ${J.indices}) -> u32 { return ${et.join("+")}; }`,It=Rt=>(ue.indicesToOffset=!0,y<2?Rt:`i2o_${r}(${Rt})`),Kt=(...Rt)=>y===0?"0u":`${J.indices}(${Rt.map(re).join(",")})`,yn=(Rt,ln)=>y<2?`${Rt}`:`${pn(Rt,ln,y)}`,_n=(Rt,ln,Jn)=>y<2?`${Rt}=${Jn};`:`${pn(Rt,ln,y)}=${Jn};`,Zn={},Gn=(Rt,ln)=>{ue.broadcastedIndicesToOffset=!0;let Jn=`${ln.name}broadcastedIndicesTo${r}Offset`;if(Jn in Zn)return`${Jn}(${Rt})`;let Br=[];for(let Nr=y-1;Nr>=0;Nr--){let Qs=ln.indicesGet("outputIndices",Nr+ln.rank-y);Br.push(`${yn($e,Nr)} * (${Qs} % ${yn(Ae,Nr)})`)}return Zn[Jn]=`fn ${Jn}(outputIndices: ${ln.type.indices}) -> u32 { return ${Br.length>0?Br.join("+"):"0u"}; }`,`${Jn}(${Rt})`},lr=(Rt,ln)=>(()=>{if(J.storage===J.value)return`${r}[${Rt}]=${ln};`;if(J.storage==="vec2"&&J.value==="i32")return`${r}[${Rt}]=vec2(u32(${ln}), select(0u, 0xFFFFFFFFu, ${ln} < 0));`;if(J.storage==="vec2"&&J.value==="u32")return`${r}[${Rt}]=vec2(u32(${ln}), 0u);`;if(J.storage==="u32"&&J.value==="vec4")return`${r}[${Rt}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ln}));`;throw new Error(`not supported combination of storage type ${J.storage} and value type ${J.value} yet`)})(),_r=Rt=>(()=>{if(J.storage===J.value)return`${r}[${Rt}]`;if(J.storage==="vec2"&&J.value==="i32")return`i32(${r}[${Rt}].x)`;if(J.storage==="vec2"&&J.value==="u32")return`u32(${r}[${Rt}].x)`;if(J.storage==="u32"&&J.value==="vec4")return`vec4(bool(${r}[${Rt}] & 0xFFu), bool(${r}[${Rt}] & 0xFF00u), bool(${r}[${Rt}] & 0xFF0000u), bool(${r}[${Rt}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${J.storage} and value type ${J.value} yet`)})(),ir=y<2?"":` fn get_${r}ByIndices(indices: ${J.indices}) -> ${Q} { return ${_r(`i2o_${r}(indices)`)}; }`,On=y<2?"":(()=>{let Rt=A.map(Jn=>`d${Jn}: u32`).join(", "),ln=A.map(Jn=>`d${Jn}`).join(", ");return` fn get_${r}(${Rt}) -> ${Q} { return get_${r}ByIndices(${Kt(ln)}); }`})(),yr=(...Rt)=>{if(Rt.length!==y)throw new Error(`indices length must be ${y}`);let ln=Rt.map(re).join(",");return y===0?_r("0u"):y===1?_r(ln[0]):(ue.get=!0,ue.getByIndices=!0,ue.indicesToOffset=!0,`get_${r}(${ln})`)},Pr=Rt=>y<2?_r(Rt):(ue.getByIndices=!0,ue.indicesToOffset=!0,`get_${r}ByIndices(${Rt})`),Nn=y<2?"":` fn set_${r}ByIndices(indices: ${J.indices}, value: ${Q}) { ${lr(`i2o_${r}(indices)`,"value")} }`,ur=y<2?"":(()=>{let Rt=A.map(Jn=>`d${Jn}: u32`).join(", "),ln=A.map(Jn=>`d${Jn}`).join(", ");return` fn set_${r}(${Rt}, value: ${Q}) { set_${r}ByIndices(${Kt(ln)}, value); }`})();return{impl:()=>{let Rt=[],ln=!1;return ue.offsetToIndices&&(Rt.push(Be),ln=!0),ue.indicesToOffset&&(Rt.push(Ot),ln=!0),ue.broadcastedIndicesToOffset&&(Object.values(Zn).forEach(Jn=>Rt.push(Jn)),ln=!0),ue.set&&(Rt.push(ur),ln=!0),ue.setByIndices&&(Rt.push(Nn),ln=!0),ue.get&&(Rt.push(On),ln=!0),ue.getByIndices&&(Rt.push(ir),ln=!0),!g&&ln&&Rt.unshift(`const ${Ae} = ${J.indices}(${u.join(",")});`,`const ${$e} = ${J.indices}(${yt.computeStrides(u).join(",")});`),Rt.join(` `)},type:J,offsetToIndices:je,indicesToOffset:It,broadcastedIndicesToOffset:Gn,indices:Kt,indicesGet:yn,indicesSet:_n,set:(...Rt)=>{if(Rt.length!==y+1)throw new Error(`indices length must be ${y}`);let ln=Rt[y];if(typeof ln!="string")throw new Error("value must be string");let Jn=Rt.slice(0,y).map(re).join(",");return y===0?lr("0u",ln):y===1?lr(Jn[0],ln):(ue.set=!0,ue.setByIndices=!0,ue.indicesToOffset=!0,`set_${r}(${Jn}, ${ln})`)},setByOffset:lr,setByIndices:(Rt,ln)=>y<2?lr(Rt,ln):(ue.setByIndices=!0,ue.indicesToOffset=!0,`set_${r}ByIndices(${Rt}, ${ln});`),get:yr,getByOffset:_r,getByIndices:Pr,usage:p,name:r,strides:$e,shape:Ae,rank:y}},Lt=(r,s,u,p=1)=>la(r,s,u,"input",p),vn=(r,s,u,p=1)=>la(r,s,u,"output",p),fo=(r,s,u,p=1)=>la(r,s,u,"internal",p),Io=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=Ci){let s=typeof r=="number"?r:r[0],u=typeof r=="number"?1:r[1],p=typeof r=="number"?1:r[2];if(s>this.limits.maxComputeWorkgroupSizeX||u>this.limits.maxComputeWorkgroupSizeY||p>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${s}, ${u}, ${p}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(s*u*p>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${s}, ${u}, ${p}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let m=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,g=m?`@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`,y=m?"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*p}u + local_idx;`;return`@compute @workgroup_size(${s}, ${u}, ${p}) fn main(${g}) { ${y} `}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",p=r.type.storage;return`@group(0) @binding(${s}) var ${r.name}: array<${p}>;`}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:p}of this.uniforms)if(p&&p>4)u==="f16"?r.push(`@align(16) ${s}:array, ${Math.ceil(p/8)}>`):r.push(`${s}:array, ${Math.ceil(p/4)}>`);else{let m=p==null||p===1?u:`vec${p}<${u}>`;r.push(`${s}:${m}`)}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])}},zl=(r,s)=>new Io(r,s),ho=(r,s)=>{let u=r.length,p=[];for(let m=0;m1&&y===1&&p.unshift(g)}return p}}),ua,Fo,po,Oo,Ai,Do,ca,mo=c(()=>{En(),xn(),Qn(),Ln(),ua=r=>{if(!r||r.length!==1)throw new Error("Transpose requires 1 input.")},Fo=(r,s)=>s&&s.length!==r?[...new Array(r).keys()].reverse():s,po=(r,s)=>yt.sortBasedOnPerm(r,Fo(r.length,s)),Oo=(r,s,u,p)=>{let m=[];m.push(`fn perm(i: ${p.type.indices}) -> ${u.type.indices} { var a: ${u.type.indices};`);for(let g=0;g{let u=r.dataType,p=r.dims.length,m=Fo(p,s),g=po(r.dims,m),y=vn("output",u,g.length),A=Lt("a",u,p),I;if(m.length===2&&m[0]===1&&m[1]===0){let O=y.type.value,Q=[16,16,1];I=k=>` ${k.registerUniform("output_size","u32").declareVariables(A,y)} var tile : array, ${Q[0]}>; ${k.mainStart(Q)} var x = workgroup_id.x * ${Q[0]}u + local_id.x; var y = workgroup_id.y * ${Q[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] = ${A.getByOffset("y * width + x")}; } workgroupBarrier(); x = workgroup_id.y * ${Q[0]}u + local_id.x; y = workgroup_id.x * ${Q[0]}u + local_id.y; if (x < height && y < width) { ${y.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} } }`}else I=O=>` ${O.registerUniform("output_size","u32").declareVariables(A,y)} ${Oo(m,p,A,y)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${y.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${y.setByOffset("global_idx",A.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>{let O=yt.size(g);return{outputs:[{dims:g,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},...sn(r.dims,g)]}},getShaderSource:I}},Do=(r,s)=>{ua(r.inputs),r.compute(Ai(r.inputs[0],s.perm))},ca=r=>kn({perm:r.perm})}),zo,da,fa,ha,Ro,ci,go,Hs,Wa,Lo,$i,Ga,Bo,No,$s,pa,jo,Vo,ma,ga,Rl,qa=c(()=>{En(),xn(),Ln(),Go(),mo(),zo={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"},da={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"},fa={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},ha={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ro=(r,s)=>{let u=[];for(let p=s-r;p{let u=[],p=r.length;for(let g=0;gr[g]);return[u,m]},go=(r,s)=>{let u=r.length+s.length,p=[],m=0;for(let g=0;g{for(let u=0;u{let u=[];if(!Hs(r,s)){for(let p=0;pu.push(p))}return u},Lo=(r,s,u,p,m,g,y)=>{let A=u[0].dims,I=yt.size(g),O=yt.size(y),Q=Lt("_A",u[0].dataType,A),k=vn("output",m,g),J=32,re=` var aBestValues : array; `;return{name:r,shaderCache:s,getShaderSource:ue=>` ${ue.registerUniform("reduceSize","u32").declareVariables(Q,k)} ${re} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${ue.mainStart(J)} let outputIndex = global_idx / ${J}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${fa[p]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${J}) { let candidate = f32(${Q.getByOffset("offset + k")}); bestValue = ${zo[p]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${J}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 = ${da[p]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${k.setByOffset("outputIndex",`${p==="mean"?`${k.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${k.type.storage}(${ha[p]})`}`)}; } }`,getRunData:()=>({outputs:[{dims:g,dataType:m}],dispatchGroup:{x:I},programUniforms:[{type:12,data:O}]})}},$i=(r,s,u,p)=>{let m=r.inputs.length===1?u:yo(r.inputs,u),g=m.axes;g.length===0&&!m.noopWithEmptyAxes&&(g=r.inputs[0].dims.map((re,ue)=>ue));let y=yt.normalizeAxes(g,r.inputs[0].dims.length),A=y,I=r.inputs[0],O=Wa(A,r.inputs[0].dims.length);O.length>0&&(I=r.compute(Ai(r.inputs[0],O),{inputs:[0],outputs:[-1]})[0],A=Ro(A.length,I.dims.length));let[Q,k]=ci(I.dims,A),J=Q;m.keepDims&&(J=go(Q,y)),r.compute(Lo(s,{hint:m.cacheKey,inputDependencies:["type"]},[I],p,r.inputs[0].dataType,J,k),{inputs:[I]})},Ga=(r,s)=>{$i(r,"ReduceMeanShared",s,"mean")},Bo=(r,s)=>{$i(r,"ReduceL1Shared",s,"l1")},No=(r,s)=>{$i(r,"ReduceL2Shared",s,"l2")},$s=(r,s)=>{$i(r,"ReduceLogSumExpShared",s,"logSumExp")},pa=(r,s)=>{$i(r,"ReduceMaxShared",s,"max")},jo=(r,s)=>{$i(r,"ReduceMinShared",s,"min")},Vo=(r,s)=>{$i(r,"ReduceProdShared",s,"prod")},ma=(r,s)=>{$i(r,"ReduceSumShared",s,"sum")},ga=(r,s)=>{$i(r,"ReduceSumSquareShared",s,"sumSquare")},Rl=(r,s)=>{$i(r,"ReduceLogSumShared",s,"logSum")}}),gi,Ll,_o,yo,Ki,Ha,Ka,Xa,Qa,Ya,Za,_a,ya,Ja,Bl,Ri,Nl,Uo,Xi,Rr,Wo,bi,jl,va,wa,Is,Go=c(()=>{En(),xn(),Qn(),Ln(),qa(),gi=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.")},Ll=r=>["","",`var value = ${r.getByIndices("input_indices")};`,""],_o=(r,s,u,p,m,g,y=!1,A=!1)=>{let I=[],O=u[0].dims,Q=O.length,k=yt.normalizeAxes(m,Q),J=!A&&k.length===0;O.forEach((ie,Ae)=>{J||k.indexOf(Ae)>=0?y&&I.push(1):I.push(ie)});let re=I.length,ue=yt.size(I);return{name:r,shaderCache:s,getShaderSource:ie=>{let Ae=[],$e=Lt("_A",u[0].dataType,Q),me=vn("output",g,re),Be=p($e,me,k),je=Be[2];for(let et=0,Ot=0;et=0?(y&&Ot++,je=`for(var j${et}: u32 = 0; j${et} < ${O[et]}; j${et}++) { ${Be[2].includes("last_index")?`let last_index = j${et};`:""} ${$e.indicesSet("input_indices",et,`j${et}`)} ${je} }`):(Ae.push(`${$e.indicesSet("input_indices",et,me.indicesGet("output_indices",Ot))};`),Ot++);return` ${ie.registerUniform("output_size","u32").declareVariables($e,me)} ${ie.mainStart()} ${ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${$e.type.indices}; let output_indices = ${me.offsetToIndices("global_idx")}; ${Ae.join(` `)} ${Be[0]} // init ops for reduce max/min ${Be[1]} ${je} ${Be[3]} ${Be.length===4?me.setByOffset("global_idx","value"):Be.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:I,dataType:g}],dispatchGroup:{x:Math.ceil(ue/64)},programUniforms:[{type:12,data:ue},...sn(O,I)]})}},yo=(r,s)=>{let u=[];return r[1].dims[0]>0&&r[1].getBigInt64Array().forEach(p=>u.push(Number(p))),kn({axes:u,keepDims:s.keepDims,noopWithEmptyAxes:s.noopWithEmptyAxes})},Ki=(r,s,u,p)=>{let m=r.inputs,g=m.length===1?u:yo(m,u);r.compute(_o(s,{hint:g.cacheKey,inputDependencies:["rank"]},[m[0]],g.noopWithEmptyAxes&&g.axes.length===0?Ll:p,g.axes,m[0].dataType,g.keepDims,g.noopWithEmptyAxes),{inputs:[0]})},Ha=(r,s)=>{gi(r.inputs),Ki(r,"ReduceLogSum",s,(u,p)=>[`var value = ${p.type.storage}(0);`,"",`value += ${u.getByIndices("input_indices")};`,"value = log(value);"])},Ka=(r,s)=>{gi(r.inputs),Ki(r,"ReduceL1",s,(u,p)=>[`var value = ${p.type.storage}(0);`,"",`value += abs(${u.getByIndices("input_indices")});`,""])},Xa=(r,s)=>{gi(r.inputs),Ki(r,"ReduceL2",s,(u,p)=>[`var t = ${p.type.value}(0); var value = ${p.type.value}(0);`,"",`t = ${u.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Qa=(r,s)=>{gi(r.inputs),Ki(r,"ReduceLogSumExp",s,(u,p)=>[`var value = ${p.type.storage}(0);`,"",`value += exp(${u.getByIndices("input_indices")});`,"value = log(value);"])},Ya=(r,s)=>{gi(r.inputs),Ki(r,"ReduceMax",s,(u,p,m)=>{let g=[];for(let y=0;y=0||m.length===0)&&g.push(u.indicesSet("input_indices",y,0));return[`${g.join(` `)}`,`var value = ${u.getByIndices("input_indices")};`,`value = max(value, ${u.getByIndices("input_indices")});`,""]})},Za=(r,s)=>{gi(r.inputs),Ki(r,"ReduceMean",s,(u,p,m)=>{let g=1;for(let y=0;y=0||m.length===0)&&(g*=r.inputs[0].dims[y]);return["var sum = f32(0);","",`sum += f32(${u.getByIndices("input_indices")});`,`let value = ${p.type.value}(sum / ${g});`]})},_a=(r,s)=>{gi(r.inputs),Ki(r,"ReduceMin",s,(u,p,m)=>{let g=[];for(let y=0;y=0||m.length===0)&&g.push(`input_indices[${y}] = 0;`);return[`${g.join(` `)}`,`var value = ${u.getByIndices("input_indices")};`,`value = min(value, ${u.getByIndices("input_indices")});`,""]})},ya=(r,s)=>{gi(r.inputs),Ki(r,"ReduceProd",s,(u,p)=>[`var value = ${p.type.storage}(1);`,"",`value *= ${u.getByIndices("input_indices")};`,""])},Ja=(r,s)=>{gi(r.inputs),Ki(r,"ReduceSum",s,(u,p)=>[`var value = ${p.type.storage}(0);`,"",`value += ${u.getByIndices("input_indices")};`,""])},Bl=(r,s)=>{gi(r.inputs),Ki(r,"ReduceSumSquare",s,(u,p)=>[`var t = ${p.type.value}(0); var value = ${p.type.value}(0);`,"",`t = ${u.getByIndices("input_indices")}; value += t * t;`,""])},Ri=(r,s,u)=>{if(s.length===0)return u;let p=1,m=1;for(let g=0;g1024},Nl=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Za(r,s):Ga(r,s)},Uo=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Ka(r,s):Bo(r,s)},Xi=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Xa(r,s):No(r,s)},Rr=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Qa(r,s):$s(r,s)},Wo=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Ya(r,s):pa(r,s)},bi=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?_a(r,s):jo(r,s)},jl=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?ya(r,s):Vo(r,s)},va=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Ja(r,s):ma(r,s)},wa=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Bl(r,s):ga(r,s)},Is=(r,s)=>{Ri(r.inputs[0].dims,s.axes,s.noopWithEmptyAxes)?Ha(r,s):Rl(r,s)}}),bs,xs,el,f,v=c(()=>{En(),Qn(),Go(),bs=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.")},xs=(r,s)=>{bs(r.inputs);let u=(p,m,g)=>{let y=[];for(let A=0;A=0||g.length===0)&&y.push(`input_indices[${A}] = 0;`);return[`${y.join(` `)}`,`var value = ${p.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${p.getByIndices("input_indices")} ${s.selectLastIndex>0?"<=":"<"} value) { value = ${p.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",m.setByOffset("global_idx","best_index")]};r.compute(_o("ArgMin",{hint:s.cacheKey,inputDependencies:["rank"]},[r.inputs[0]],u,[s.axis],7,s.keepDims),{inputs:[0]})},el=(r,s)=>{bs(r.inputs);let u=(p,m,g)=>{let y=[];for(let A=0;A=0||g.length===0)&&y.push(`input_indices[${A}] = 0;`);return[`${y.join(` `)}`,`var value = ${p.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${p.getByIndices("input_indices")} ${s.selectLastIndex>0?">=":">"} value) { value = ${p.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",m.setByOffset("global_idx","best_index")]};r.compute(_o("argMax",{hint:s.cacheKey,inputDependencies:["rank"]},[r.inputs[0]],u,[s.axis],7,s.keepDims),{inputs:[0]})},f=r=>kn(r)}),$,U,Y,le,Me,ze,Ke,Ge=c(()=>{En(),xn(),ye(),Ln(),$=(r,s)=>{let u=r[0],p=r[1],m=r[2],g=r[3],y=r[4],A=r[5];if(y&&A)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 I=u.dims[0],O=u.dims[1],Q=u.dims[2];if(m.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(p.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(p.dims[0]!==Q)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(m.dims[0]!==p.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let k=m.dims[0]/3,J=k,re=J;if(s.qkvHiddenSizes.length>0){if(s.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let Be of s.qkvHiddenSizes)if(Be%s.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");k=s.qkvHiddenSizes[0],J=s.qkvHiddenSizes[1],re=s.qkvHiddenSizes[2]}let ue=O;if(k!==J)throw new Error("qkv_hidden_sizes first element should be same as the second");if(m.dims[0]!==k+J+re)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let ie=0;if(y){if(J!==re)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(y.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(y.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(y.dims[1]!==I)throw new Error('Input "past" second dimension must be batch_size');if(y.dims[2]!==s.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(y.dims[4]!==J/s.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');s.pastPresentShareBuffer||(ie=y.dims[3])}let Ae=ue+ie,$e=-1,me=0;if(g)throw new Error("Mask not supported");if(y)throw new Error("past is not supported");if(A){if(A.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(A.dims[0]!==I||A.dims[1]!==s.numHeads||A.dims[2]!==O||A.dims[3]!==Ae)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:I,sequenceLength:O,pastSequenceLength:ie,kvSequenceLength:ue,totalSequenceLength:Ae,maxSequenceLength:$e,inputHiddenSize:Q,hiddenSize:k,vHiddenSize:re,headSize:Math.floor(k/s.numHeads),vHeadSize:Math.floor(re/s.numHeads),numHeads:s.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:s.maskFilterValue,maskType:me,scale:s.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},U=(r,s,u)=>{let p=tr(u),m=64,g=u/p;g{let re=vn("x",r.dataType,r.dims,p),ue=ar(r.dataType),ie=[{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; ${J.registerUniforms(ie).declareVariables(re)} ${J.mainStart([m,1,1])} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${m}) * 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(p){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: ${p}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${m}; 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(p){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: ${p}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${m}; 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] = ${re.type.value}(${ue}(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] = ${re.type.value}(exp(f32input - max_value) / sum); } } }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${m};${I};${p}`,inputDependencies:Q},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:s},programUniforms:A})}},Y=(r,s,u,p,m,g,y,A)=>{let I=A+g.kvSequenceLength,O=[g.batchSize,g.numHeads,g.sequenceLength,I],Q=g.kvNumHeads===void 0&&r>1&&p,k=Q?[g.batchSize,g.numHeads,I,g.headSize]:void 0,J=y.scale===0?1/Math.sqrt(g.headSize):y.scale,re=tr(g.headSize),ue=g.headSize/re,ie=12,Ae={x:Math.ceil(I/ie),y:Math.ceil(g.sequenceLength/ie),z:g.batchSize*g.numHeads},$e=[{type:12,data:g.sequenceLength},{type:12,data:ue},{type:12,data:I},{type:12,data:g.numHeads},{type:1,data:J},{type:12,data:A},{type:12,data:g.kvSequenceLength}],me=Q&&p&&yt.size(p.dims)>0,Be=["type","type"];me&&Be.push("type"),m&&Be.push("type");let je=[{dims:O,dataType:s.dataType,gpuDataType:0}];Q&&je.push({dims:k,dataType:s.dataType,gpuDataType:0});let et=Ot=>{let It=Lt("q",s.dataType,s.dims,re),Kt=Lt("key",u.dataType,u.dims,re),yn=[It,Kt];if(me){let _r=Lt("past_key",p.dataType,p.dims,re);yn.push(_r)}m&&yn.push(Lt("attention_bias",m.dataType,m.dims));let _n=vn("output",s.dataType,O),Zn=[_n];Q&&Zn.push(vn("present_key",s.dataType,k,re));let Gn=ar(1,re),lr=[{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 = ${ie}u; var tileQ: array<${It.type.storage}, ${ie*ie}>; var tileK: array<${It.type.storage}, ${ie*ie}>; ${Ot.registerUniforms(lr).declareVariables(...yn,...Zn)} ${Ot.mainStart([ie,ie,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; ${me&&Q?` 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;`} ${Q?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} var value = ${Gn}(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; ${me&&Q?` 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];"} ${Q?"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 += ${Gn}(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(re){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: ${re}`)}})()}; output[outputIdx] = ${_n.type.value} (sum * uniforms.alpha) + ${m?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${re};${m!==void 0};${p!==void 0};${r}`,inputDependencies:Be},getRunData:()=>({outputs:je,dispatchGroup:Ae,programUniforms:$e}),getShaderSource:et}},le=(r,s,u,p,m,g)=>{let y=g+m.kvSequenceLength,A=m.nReps?m.nReps:1,I=m.vHiddenSize*A,O=m.kvNumHeads==null&&r>1&&p,Q=O?[m.batchSize,m.numHeads,y,m.headSize]:void 0,k=[m.batchSize,m.sequenceLength,I],J=12,re={x:Math.ceil(m.vHeadSize/J),y:Math.ceil(m.sequenceLength/J),z:m.batchSize*m.numHeads},ue=[{type:12,data:m.sequenceLength},{type:12,data:y},{type:12,data:m.vHeadSize},{type:12,data:m.numHeads},{type:12,data:I},{type:12,data:g},{type:12,data:m.kvSequenceLength}],ie=O&&p&&yt.size(p.dims)>0,Ae=["type","type"];ie&&Ae.push("type");let $e=[{dims:k,dataType:s.dataType,gpuDataType:0}];O&&$e.push({dims:Q,dataType:s.dataType,gpuDataType:0});let me=Be=>{let je=Lt("probs",s.dataType,s.dims),et=Lt("v",u.dataType,u.dims),Ot=[je,et];ie&&Ot.push(Lt("past_value",p.dataType,p.dims));let It=[vn("output",s.dataType,k)];O&&It.push(vn("present_value",s.dataType,Q));let Kt=[{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 = ${J}u; var tileQ: array<${je.type.value}, ${J*J}>; var tileK: array<${je.type.value}, ${J*J}>; ${Be.registerUniforms(Kt).declareVariables(...Ot,...It)} ${Be.mainStart([J,J,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; ${ie&&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 = ${je.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; ${ie&&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:`${p!==void 0};${r}`,inputDependencies:Ae},getRunData:()=>({outputs:$e,dispatchGroup:re,programUniforms:ue}),getShaderSource:me}},Me=(r,s,u,p,m,g,y,A,I,O,Q)=>{let k=Math.min(r.outputCount,1+(y?1:0)+(A?1:0)),J=O.kvNumHeads!==void 0||k>1?O.pastSequenceLength:0,re=J+O.kvSequenceLength,ue=I&&yt.size(I.dims)>0?I:void 0,ie=[s,u];O.kvNumHeads===void 0&&k>1&&y&&yt.size(y.dims)>0&&ie.push(y),ue&&ie.push(ue);let Ae=r.compute(Y(k,s,u,y,ue,O,Q,J),{inputs:ie,outputs:O.kvNumHeads===void 0&&k>1?[-1,1]:[-1]})[0];r.compute(U(Ae,O.batchSize*O.numHeads*O.sequenceLength,re),{inputs:[Ae],outputs:[]});let $e=[Ae,p];O.kvNumHeads===void 0&&k>1&&A&&yt.size(A.dims)>0&&$e.push(A),r.compute(le(k,Ae,p,A,O,J),{inputs:$e,outputs:O.kvNumHeads===void 0&&k>1?[0,2]:[0]})},ze=(r,s)=>{let u=[s.batchSize,s.numHeads,s.sequenceLength,s.headSize],p=s.sequenceLength,m=s.inputHiddenSize,g=s.headSize,y=12,A={x:Math.ceil(s.headSize/y),y:Math.ceil(s.sequenceLength/y),z:s.batchSize*s.numHeads},I=[r.inputs[0],r.inputs[1],r.inputs[2]],O=[{type:12,data:p},{type:12,data:m},{type:12,data:g},{type:12,data:s.numHeads},{type:12,data:s.headSize},{type:12,data:s.hiddenSize},{type:12,data:s.hiddenSize+s.hiddenSize+s.vHiddenSize}],Q=k=>{let J=vn("output_q",I[0].dataType,u),re=vn("output_k",I[0].dataType,u),ue=vn("output_v",I[0].dataType,u),ie=Lt("input",I[0].dataType,I[0].dims),Ae=Lt("weight",I[1].dataType,I[1].dims),$e=Lt("bias",I[2].dataType,I[2].dims),me=ie.type.storage,Be=[{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 = ${y}u; var tileInput: array<${me}, ${y*y}>; var tileWeightQ: array<${me}, ${y*y}>; var tileWeightK: array<${me}, ${y*y}>; var tileWeightV: array<${me}, ${y*y}>; ${k.registerUniforms(Be).declareVariables(ie,Ae,$e,J,re,ue)} ${k.mainStart([y,y,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 = ${me}(0); var valueK = ${me}(0); var valueV = ${me}(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:A,programUniforms:O}),getShaderSource:Q},{inputs:I,outputs:[-1,-1,-1]})},Ke=(r,s)=>{let u=$(r.inputs,s),[p,m,g]=ze(r,u);return Me(r,p,m,g,r.inputs[4],void 0,void 0,void 0,r.inputs[5],u,s)}}),st,We,ot,He,tt=c(()=>{Jt(),En(),xn(),Qn(),Ln(),st=(r,s)=>{if(!r||r.length!==5)throw new Error("BatchNormalization requires 5 inputs");let u=(p,m,g)=>{let y=m.length;if(y!==p.length)throw new Error(`${g}: num dimensions != ${y}`);m.forEach((A,I)=>{if(A!==p[I])throw new Error(`${g}: dim[${I}] do not match`)})};if(r[0].dims.length>1){let p=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,p,"Invalid input scale"),u(r[2].dims,p,"Invalid input B"),u(r[3].dims,p,"Invalid input mean"),u(r[4].dims,p,"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")},We=(r,s)=>{let{epsilon:u,spatial:p,format:m}=s,g=r[0].dims,y=p?tr(g[g.length-1]):1,A=m==="NHWC"&&g.length>1?y:1,I=yt.size(g)/y,O=p,Q=O?g.length:g,k=Lt("x",r[0].dataType,r[0].dims,y),J=Lt("scale",r[1].dataType,r[1].dims,A),re=Lt("bias",r[2].dataType,r[2].dims,A),ue=Lt("inputMean",r[3].dataType,r[3].dims,A),ie=Lt("inputVar",r[4].dataType,r[4].dims,A),Ae=vn("y",r[0].dataType,Q,y),$e=()=>{let Be="";if(p)Be=`let cOffset = ${g.length===1?"0u":m==="NHWC"?`outputIndices[${g.length-1}] / ${y}`:"outputIndices[1]"};`;else if(m==="NCHW")Be=` ${Ae.indicesSet("outputIndices","0","0")} let cOffset = ${Ae.indicesToOffset("outputIndices")};`;else{Be=`var cIndices = ${J.type.indices}(0); cIndices[0] = outputIndices[${g.length-1}];`;for(let je=1;je` const epsilon = ${u}; ${Be.registerUniform("outputSize","u32").declareVariables(k,J,re,ue,ie,Ae)} ${Be.mainStart()} ${Be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${Ae.offsetToIndices(`global_idx * ${y}`)}; ${$e()} let scale = ${J.getByOffset("cOffset")}; let bias = ${re.getByOffset("cOffset")}; let inputMean = ${ue.getByOffset("cOffset")}; let inputVar = ${ie.getByOffset("cOffset")}; let x = ${k.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${Ae.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${s.epsilon}_${s.format}_${p}_${y}`,inputDependencies:O?["rank","type","type","type","type"]:void 0},getShaderSource:me,getRunData:()=>({outputs:[{dims:r[0].dims,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:O?[{type:12,data:I},...sn(g)]:[{type:12,data:I}]})}},ot=r=>kn(r),He=(r,s)=>{let{inputs:u,outputCount:p}=r,m=ot({...s,outputCount:p});if(V.webgpu.validateInputContent&&st(u,m),s.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");r.compute(We(u,m))}}),at,Je,gt,vt=c(()=>{xn(),Ln(),at=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")},Je=r=>{let s=r[0].dims,u=r[0].dims[2],p=yt.size(s)/4,m=r[0].dataType,g=Lt("input",m,s,4),y=Lt("bias",m,[u],4),A=Lt("residual",m,s,4),I=vn("output",m,s,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)}}),getShaderSource:O=>` const channels = ${u}u / 4; ${O.declareVariables(g,y,A,I)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes(p)} let value = ${g.getByOffset("global_idx")} + ${y.getByOffset("global_idx % channels")} + ${A.getByOffset("global_idx")}; ${I.setByOffset("global_idx","value")} }`}},gt=r=>{at(r.inputs),r.compute(Je(r.inputs))}}),wt,_t,Gt,on,Wt,rn,an,Ut,Bn,jn,Hn,Kn,Li,Un,ii,si,Fs,oi,hs,qo,ud,cd,dd,Cu,fd,hd,pd,Pu,md,gd,Au,_d,yd,$u,vd,Iu,Fu,Ou,Du,zu,wd,bd,xd,Md,Vl,Ru=c(()=>{En(),xn(),Qn(),Ln(),wt=(r,s,u,p,m,g)=>{let y=Math.ceil(s/4),A="";typeof m=="string"?A=`${m}(a)`:A=m("a");let I=Lt("inputData",u,[y],4),O=vn("outputData",p,[y],4);return` ${r.registerUniform("vec_size","u32").declareVariables(I,O)} ${g??""} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${I.getByOffset("global_idx")}; ${O.setByOffset("global_idx",A)} }`},_t=(r,s,u,p,m,g=r.dataType)=>({name:s,shaderCache:{hint:m,inputDependencies:["type"]},getShaderSource:y=>wt(y,yt.size(r.dims),r.dataType,g,u,p),getRunData:y=>({outputs:[{dims:r.dims,dataType:g}],dispatchGroup:{x:Math.ceil(yt.size(y[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(yt.size(r.dims)/4)}]})}),Gt=r=>{r.compute(_t(r.inputs[0],"Abs","abs"))},on=r=>{r.compute(_t(r.inputs[0],"Acos","acos"))},Wt=r=>{r.compute(_t(r.inputs[0],"Acosh","acosh"))},rn=r=>{r.compute(_t(r.inputs[0],"Asin","asin"))},an=r=>{r.compute(_t(r.inputs[0],"Asinh","asinh"))},Ut=r=>{r.compute(_t(r.inputs[0],"Atan","atan"))},Bn=r=>{r.compute(_t(r.inputs[0],"Atanh","atanh"))},jn=r=>kn(r),Hn=(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(_t(r.inputs[0],"Cast",u,void 0,s.cacheKey,s.to))},Kn=r=>{let s=r.length>=2&&r[1].data!==0?r[1].getFloat32Array()[0]:Dr,u=r.length>=3&&r[2].data!==0?r[2].getFloat32Array()[0]:ui;return kn({min:s,max:u})},Li=(r,s)=>{let u=r.inputs.length===1?s:Kn(r.inputs),p=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"Clip",m=>`clamp(${m}, clip_min_, clip_max_)`,` const clip_min_: vec4<${p}> = vec4(${p}(${u.min})); const clip_max_: vec4<${p}> = vec4(${p}(${u.max})); `,u.cacheKey),{inputs:[0]})},Un=r=>{r.compute(_t(r.inputs[0],"Ceil","ceil"))},ii=r=>{r.compute(_t(r.inputs[0],"Cos","cos"))},si=r=>{r.compute(_t(r.inputs[0],"Cosh","cosh"))},Fs=r=>kn(r),oi=(r,s)=>{let u=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"Elu",p=>`elu_vf32(${p})`,` 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))},hs=(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)); }`,qo=r=>{let s=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"Erf",u=>`erf_vf32(${u})`,hs(s)))},ud=r=>{r.compute(_t(r.inputs[0],"Exp","exp"))},cd=r=>{r.compute(_t(r.inputs[0],"Floor","floor"))},dd=r=>{let s=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"Gelu",u=>`0.5 * ${u} * (1.0 + erf_vf32(${u} * 0.7071067811865475))`,hs(s)))},Cu=(r,s)=>{let u=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"LeakyRelu",p=>`select(leaky_relu_alpha_ * ${p}, ${p}, ${p} >= vec4<${u}>(0.0))`,`const leaky_relu_alpha_ = ${u}(${s.alpha});`,s.cacheKey))},fd=r=>{r.compute(_t(r.inputs[0],"Not",s=>`!${s}`))},hd=r=>{r.compute(_t(r.inputs[0],"Neg",s=>`-${s}`))},pd=r=>{r.compute(_t(r.inputs[0],"Reciprocal",s=>`1.0/${s}`))},Pu=r=>{let s=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"Relu",u=>`select(vec4<${s}>(0.0), ${u}, ${u} > vec4<${s}>(0.0))`))},md=r=>{r.compute(_t(r.inputs[0],"Sigmoid",s=>`(1.0 / (1.0 + exp(-${s})))`))},gd=r=>kn(r),Au=(r,s)=>{let u=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"HardSigmoid",p=>`max(vec4<${u}>(0.0), min(vec4<${u}>(1.0), ${s.alpha} * ${p} + vec4<${u}>(${s.beta})))`,void 0,s.cacheKey))},_d=r=>{r.compute(_t(r.inputs[0],"Sin","sin"))},yd=r=>{r.compute(_t(r.inputs[0],"Sinh","sinh"))},$u=r=>{r.compute(_t(r.inputs[0],"Sqrt","sqrt"))},vd=r=>{r.compute(_t(r.inputs[0],"Tan","tan"))},Iu=r=>`sign(${r}) * (1 - exp(-2 * abs(${r}))) / (1 + exp(-2 * abs(${r})))`,Fu=r=>{r.compute(_t(r.inputs[0],"Tanh",Iu))},Ou=(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 ${Iu("v")}; } `,Du=r=>`(fast_gelu_a + fast_gelu_a * tanh_v(${r} * (fast_gelu_c * ${r} * ${r} + fast_gelu_b))) * ${r}`,zu=r=>{let s=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"FastGelu",Du,Ou(s),void 0,r.inputs[0].dataType))},wd=(r,s)=>{let u=ar(r.inputs[0].dataType);return r.compute(_t(r.inputs[0],"ThresholdedRelu",p=>`select(vec4<${u}>(0.0), ${p}, ${p} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${u}>(${s.alpha});`,s.cacheKey)),0},bd=r=>{r.compute(_t(r.inputs[0],"Log","log"))},xd=(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; } `,Md=r=>`quick_gelu_impl(${r})`,Vl=(r,s)=>{let u=ar(r.inputs[0].dataType);r.compute(_t(r.inputs[0],"QuickGelu",Md,xd(u,s.alpha),s.cacheKey,r.inputs[0].dataType))}}),Td,Sd,Lu,rp=c(()=>{xn(),Ln(),Ru(),Td=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")},Sd=r=>{let s=r[0].dims.slice();s[2]=s[2]/2;let u=Lt("input",r[0].dataType,r[0].dims,4),p=Lt("bias",r[0].dataType,[r[0].dims[2]],4),m=vn("output",r[0].dataType,s,4),g=yt.size(s)/4,y=or(r[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)}}),getShaderSource:A=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${r[0].dims[2]/4/2}u; ${A.declareVariables(u,p,m)} ${hs(y)} ${A.mainStart()} ${A.guardAgainstOutOfBoundsWorkgroupSizes(g)} 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); ${m.setByOffset("global_idx","valueLeft * geluRight")} }`}},Lu=r=>{Td(r.inputs),r.compute(Sd(r.inputs))}}),kd,Ed,Ms,Bu,Cd,Pd,Nu,Ad,$d,ju,Id,Fd,Vu,ip=c(()=>{En(),xn(),Ln(),kd=(r,s,u,p,m,g,y,A,I,O,Q,k)=>{let J,re;typeof A=="string"?J=re=(me,Be)=>`${A}((${me}),(${Be}))`:typeof A=="function"?J=re=A:(J=A.scalar,re=A.vector);let ue=vn("outputData",Q,p.length,4),ie=Lt("aData",I,s.length,4),Ae=Lt("bData",O,u.length,4),$e;if(m)if(g){let me=yt.size(s)===1,Be=yt.size(u)===1,je=s.length>0&&s[s.length-1]%4===0,et=u.length>0&&u[u.length-1]%4===0;me||Be?$e=ue.setByOffset("global_idx",re(me?`${ie.type.value}(${ie.getByOffset("0")}.x)`:ie.getByOffset("global_idx"),Be?`${Ae.type.value}(${Ae.getByOffset("0")}.x)`:Ae.getByOffset("global_idx"))):$e=` let outputIndices = ${ue.offsetToIndices("global_idx * 4u")}; let offsetA = ${ie.broadcastedIndicesToOffset("outputIndices",ue)}; let offsetB = ${Ae.broadcastedIndicesToOffset("outputIndices",ue)}; ${ue.setByOffset("global_idx",re(y||je?ie.getByOffset("offsetA / 4u"):`${ie.type.value}(${ie.getByOffset("offsetA / 4u")}[offsetA % 4u])`,y||et?Ae.getByOffset("offsetB / 4u"):`${Ae.type.value}(${Ae.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else $e=ue.setByOffset("global_idx",re(ie.getByOffset("global_idx"),Ae.getByOffset("global_idx")));else{if(!g)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let me=(Be,je,et="")=>{let Ot=`aData[indexA${je}][componentA${je}]`,It=`bData[indexB${je}][componentB${je}]`;return` let outputIndices${je} = ${ue.offsetToIndices(`global_idx * 4u + ${je}u`)}; let offsetA${je} = ${ie.broadcastedIndicesToOffset(`outputIndices${je}`,ue)}; let offsetB${je} = ${Ae.broadcastedIndicesToOffset(`outputIndices${je}`,ue)}; let indexA${je} = offsetA${je} / 4u; let indexB${je} = offsetB${je} / 4u; let componentA${je} = offsetA${je} % 4u; let componentB${je} = offsetB${je} % 4u; ${Be}[${je}] = ${et}(${J(Ot,It)}); `};Q===9?$e=` var data = vec4(0); ${me("data",0,"u32")} ${me("data",1,"u32")} ${me("data",2,"u32")} ${me("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:$e=` ${me("outputData[global_idx]",0)} ${me("outputData[global_idx]",1)} ${me("outputData[global_idx]",2)} ${me("outputData[global_idx]",3)} `}return` ${r.registerUniform("vec_size","u32").declareVariables(ie,Ae,ue)} ${k??""} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${$e} }`},Ed=(r,s,u,p,m,g,y=u.dataType)=>{let A=!yt.areEqual(u.dims,p.dims),I=u.dims,O=yt.size(u.dims),Q=!1,k=!1,J=[A];if(A){let re=Mr.calcShape(u.dims,p.dims,!1);if(!re)throw new Error("Can't perform binary op on the given tensors");I=re,O=yt.size(I);let ue=yt.size(u.dims)===1,ie=yt.size(p.dims)===1,Ae=u.dims.length>0&&u.dims[u.dims.length-1]%4===0,$e=p.dims.length>0&&p.dims[p.dims.length-1]%4===0;J.push(ue),J.push(ie),J.push(Ae),J.push($e);let me=1;for(let Be=1;Bere.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:re=>kd(re,u.dims,p.dims,I,Q,A,k,m,u.dataType,p.dataType,y,g),getRunData:()=>({outputs:[{dims:I,dataType:y}],dispatchGroup:{x:Math.ceil(O/64/4)},programUniforms:[{type:12,data:Math.ceil(yt.size(I)/4)},...sn(u.dims,p.dims,I)]})}},Ms=(r,s,u,p,m,g)=>{r.compute(Ed(s,m??"",r.inputs[0],r.inputs[1],u,p,g))},Bu=r=>{Ms(r,"Add",(s,u)=>`${s}+${u}`)},Cd=r=>{Ms(r,"Div",(s,u)=>`${s}/${u}`)},Pd=r=>{Ms(r,"Equal",{scalar:(s,u)=>`u32(${s}==${u})`,vector:(s,u)=>`vec4(${s}==${u})`},void 0,void 0,9)},Nu=r=>{Ms(r,"Mul",(s,u)=>`${s}*${u}`)},Ad=r=>{let s=Lt("input",r.inputs[0].dataType,r.inputs[0].dims).type.value;Ms(r,"Pow",{scalar:(u,p)=>`pow_custom(${u},${p})`,vector:(u,p)=>`pow_vector_custom(${u},${p})`},` 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)); } `)},$d=r=>{Ms(r,"Sub",(s,u)=>`${s}-${u}`)},ju=r=>{Ms(r,"Greater",{scalar:(s,u)=>`u32(${s}>${u})`,vector:(s,u)=>`vec4(${s}>${u})`},void 0,void 0,9)},Id=r=>{Ms(r,"Less",{scalar:(s,u)=>`u32(${s}<${u})`,vector:(s,u)=>`vec4(${s}<${u})`},void 0,void 0,9)},Fd=r=>{Ms(r,"GreaterOrEqual",{scalar:(s,u)=>`u32(${s}>=${u})`,vector:(s,u)=>`vec4(${s}>=${u})`},void 0,void 0,9)},Vu=r=>{Ms(r,"LessOrEqual",{scalar:(s,u)=>`u32(${s}<=${u})`,vector:(s,u)=>`vec4(${s}<=${u})`},void 0,void 0,9)}}),Od,Dd,zd,Rd,Ld,Uu,sp=c(()=>{En(),xn(),Qn(),Ln(),Od=(r,s)=>{if(!r||r.length<1)throw new Error("too few inputs");let u=0,p=r[u],m=p.dataType,g=p.dims.length;r.forEach((y,A)=>{if(A!==u){if(y.dataType!==m)throw new Error("input tensors should be one type");if(y.dims.length!==g)throw new Error("input tensors should have the same shape");y.dims.forEach((I,O)=>{if(O!==s&&I!==p.dims[O])throw new Error("non concat dimensions must match")})}})},Dd=(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; }`,zd=(r,s)=>{let u=r.length,p=[];for(let m=0;m{let m=yt.size(u),g=new Array(r.length),y=new Array(r.length),A=0,I=[],O=[],Q=[{type:12,data:m}];for(let ie=0;ie`uniforms.sizeInConcatAxis${ie}`).join(","),ue=ie=>` ${(()=>{ie.registerUniform("outputSize","u32");for(let Ae=0;Ae(${re}); ${J} -= sizeInConcatAxis[inputIndex - 1u]; } ${zd(y,k)} }`;return{name:"Concat",shaderCache:{hint:`${s}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:u,dataType:p}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:Q}),getShaderSource:ue}},Ld=(r,s)=>{let u=r.inputs,p=u[0].dims,m=yt.normalizeAxis(s.axis,p.length);Od(u,m);let g=p.slice();g[m]=u.reduce((A,I)=>A+(I.dims.length>m?I.dims[m]:0),0);let y=u.filter(A=>yt.size(A.dims)>0);r.compute(Rd(y,m,g,u[0].dataType),{inputs:y})},Uu=r=>kn({axis:r.axis})}),vo,Ks,wo,Wu,Bi=c(()=>{En(),xn(),vo=(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}`)}},Ks=(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})},wo=(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"})},Wu=r=>{let s=r?.activation||"";if(s==="HardSigmoid"){let[u,p]=r?.activation_params||[.2,.5];return{activation:s,alpha:u,beta:p}}else if(s==="Clip"){let[u,p]=r?.activation_params||[Dr,ui];return{activation:s,clipMax:p,clipMin:u}}else if(s==="LeakyRelu"){let[u]=r?.activation_params||[.01];return{activation:s,alpha:u}}return{activation:s}}}),xi,Gu,Ul=c(()=>{xi=(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.`)}},Gu=r=>` ${r?"value = value + getBiasByOutputCoords(coords);":""} `}),qu,Hu=c(()=>{qu=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)); } `}),Bd,Nd,Wl,Ku,Gl,ql,jd,Xu,Ho=c(()=>{En(),xn(),Ln(),Bi(),Ul(),Bd=(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":""}); `,Nd=(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];"} }`,Wl=(r,s,u="f32",p,m=!1,g=32,y=!1,A=32)=>{let I=s[1]*r[1],O=s[0]*r[0],Q=m?I:g,k=m?g:I,J=Q/s[0],re=g/s[1];if(!((m&&J===4&&r[1]===4||!m&&(J===3||J===4))&&Q%s[0]===0&&g%s[1]===0&&r[0]===4))throw new Error(`If transposeA ${m} is true, innerElementSize ${J} and workPerThread[1] ${r[1]} must be 4. Otherwise, innerElementSize ${J} must be 3 or 4. tileAWidth ${Q} must be divisible by workgroupSize[0]${s[0]}. tileInner ${g} must be divisible by workgroupSize[1] ${s[1]}. colPerThread ${r[0]} must be 4.`);return` var mm_Asub: array, ${Q/J}>, ${k}>; var mm_Bsub: array, ${O/r[0]}>, ${g}>; const rowPerThread = ${r[1]}; const colPerThread = ${r[0]}; const innerElementSize = ${J}; const tileInner = ${g}; @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 = ${y?"0":"i32(globalId.z)"}; ${p?`let batchIndices = ${p.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${I}; let num_tiles = ${y?`${Math.ceil(A/g)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${y?`i32(globalId.z) * ${A}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${re}; 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; ${Bd(m,p)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${re}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${p?", 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]; ${J===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Nd(m,J)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Ku=(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":""}); `,Gl=r=>r?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ql=(r,s,u="f32",p,m=!1,g=32,y=!1,A=32,I=!1)=>{let O=r[1]*s[1],Q=r[0]*s[0],k=m?O:g,J=m?g:O;if(!(J%s[1]===0&&k%s[0]===0&&g%s[1]===0))throw new Error(`tileAHight ${J} must be divisible by workgroupSize[1]${s[1]}, tileAWidth ${k} must be divisible by workgroupSize[0]${s[0]}, tileInner ${g} must be divisible by workgroupSize[1]${s[1]}`);let re=J/s[1],ue=k/s[0],ie=g/s[1],Ae=I?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${O}; let globalColStart = i32(workgroupId.x) * ${Q}; // 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 < ${J}; inputRow = inputRow + ${s[1]}) { for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${s[0]}) { ${Ku(m,p)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${g}; inputRow = inputRow + ${s[1]}) { for (var inputCol = localCol; inputCol < ${Q}; inputCol = inputCol + ${s[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${p?", 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 = ${m?`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) * ${re}; let tileColA = i32(localId.x) * ${ue}; let tileRowB = i32(localId.y) * ${ie}; // 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 < ${re}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${ue}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Ku(m,p)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${ie}; 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${p?", 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) { ${Gl(m)} 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, ${J}>; var mm_Bsub : array, ${g}>; const rowPerThread = ${r[1]}; const colPerThread = ${r[0]}; const tileInner = ${g}; @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 = ${y?"0":"i32(globalId.z)"}; ${p?`let batchIndices = ${p.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${y?`${Math.ceil(A/g)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${y?`i32(globalId.z) * ${A}`:"0"}; var acc : array, rowPerThread>; ${Ae} } `},jd=(r,s,u,p,m,g=!1)=>{let[y,A,I]=m,[O,Q,k,J]=p,re=ho(y,I),ue=ho(A,I),ie=or(p[0].type.tensor),Ae=()=>{let me=Q.rank,Be=O.rank,je=`var aIndices: ${Q.type.indices};`;for(let et=me-2-1,Ot=Be-1;et>=0;et--,Ot--)je+=` aIndices[${et}] = ${Be>1?`batchIndices[${Ot}]`:"batchIndices"};`;return re.forEach(et=>{je+=` aIndices[${et}] = 0;`}),je+=` aIndices[${me-2}] = u32(row); aIndices[${me-1}] = u32(colIn);`,je},$e=()=>{let me=k.rank,Be=O.rank,je=`var bIndices: ${k.type.indices};`;for(let et=me-2-1,Ot=Be-1;et>=0;et--,Ot--)je+=` bIndices[${et}] = ${Be>1?`batchIndices[${Ot}]`:"batchIndices"};`;return ue.forEach(et=>{je+=` bIndices[${et}] = 0;`}),je+=` bIndices[${me-2}] = u32(row); bIndices[${me-1}] = u32(colIn);`,je};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${O.type.indices}) -> ${xi(r,ie)} { var value = ${xi(r,ie)}(0.0); let col = colIn * ${r}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${Ae()} value = ${Q.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${O.type.indices}) -> ${xi(r,ie)} { var value = ${xi(r,ie)}(0.0); let col = colIn * ${r}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${$e()} value = ${k.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${xi(r,ie)}) { 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 + ${g?"bias[colIn]":`${xi(r,ie)}(bias[row])`};`:""} ${u} ${J.setByIndices("vec3(coords)","value")} } } `},Xu=(r,s,u,p,m=!1,g)=>{let y=r[0].dims,A=r[1].dims,I=y.slice(0,-2),O=A.slice(0,-2),Q=p?p.slice(0,-2):u.slice(0,-2),k=yt.size(Q),J=y[y.length-2],re=y[y.length-1],ue=A[A.length-1],ie=re%4===0&&ue%4===0,Ae=J<=8?[4,1,1]:[4,4,1],$e=[8,8,1],me=[Math.ceil(ue/$e[0]/Ae[0]),Math.ceil(J/$e[1]/Ae[1]),Math.ceil(k/$e[2]/Ae[2])],Be=ie?4:1,je=[...I,J,re/Be],et=je.length,Ot=[...O,re,ue/Be],It=Ot.length,Kt=[k,J,ue/Be],yn=[{type:6,data:J},{type:6,data:ue},{type:6,data:re}];Ks(s,yn),yn.push(...sn(Q,je,Ot));let _n=["rank","rank"],Zn=r.length>2;Zn&&(yn.push(...sn(r[2].dims)),_n.push("rank")),yn.push(...sn(Kt));let Gn=lr=>{let _r=Q.length,ir=fo("batchDims",r[0].dataType,_r,1),On=or(r[0].dataType),yr=Lt("a",r[0].dataType,et,Be),Pr=Lt("b",r[1].dataType,It,Be),Nn=vn("result",r[0].dataType,Kt.length,Be),ur=[yr,Pr];if(Zn){let Nr=m?Be:1;ur.push(Lt("bias",r[2].dataType,r[2].dims.length,Nr))}let Rt=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];wo(s,Rt);let ln=or(Nn.type.tensor),Jn=vo(s,Nn.type.value,ln),Br=jd(Be,Zn,Jn,[ir,yr,Pr,Nn],[I,O,Q],m);return` ${lr.registerUniforms(Rt).registerInternalVariables(ir).declareVariables(...ur,Nn)} ${Br} ${ie?Wl(Ae,$e,On,ir):ql(Ae,$e,On,ir)} `};return{name:"MatMul",shaderCache:{hint:`${Ae};${s.activation};${ie};${m}`,inputDependencies:_n},getRunData:()=>({outputs:[{dims:g?g(u):u,dataType:r[0].dataType}],dispatchGroup:{x:me[0],y:me[1],z:me[2]},programUniforms:yn}),getShaderSource:Gn}}}),Vd,Ud,op=c(()=>{En(),wi(),Ln(),Bi(),Ul(),Hu(),Ho(),Vd=(r,s,u,p,m=!1,g,y=4,A=4,I=4,O="f32")=>{let Q=yn=>{switch(yn){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 ${yn} is not supported.`)}},k=yn=>{switch(yn){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 ${yn} is not supported.`)}},J=r?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,re=r?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,ue=r?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",ie=r?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Ae=r?"row":"col",$e=r?"col":"row",me=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${Ae} / outWidth; let outCol = ${Ae} % outWidth; let WRow = ${$e} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${$e} / 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 = ${$e} % inChannels; var resData = ${xi(y,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 < ${ue} && xCol >= 0 && xCol < ${ie}) { ${J} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${Q(y)} } return resData;`,Be=r?s&&p?` let col = colIn * ${y}; ${me}`:` let col = colIn * ${y}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${me} } return ${xi(y,O)}(0.0);`:p&&u?` let col = colIn * ${y}; ${me}`:` let col = colIn * ${y}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${me} } return ${xi(y,O)}(0.0);`,je=`${k(A)}`,et=xi(I,O),Ot=xi(r?y:A,O),It=xi(r?A:y,O),Kt=vo(g,et,O);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ot} { ${r?Be:je} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${It} { ${r?je:Be} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${et}) { let col = colIn * ${I}; 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])"}; ${re} ${Gu(m)} ${Kt} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Ud=(r,s,u,p,m,g,y,A,I)=>{let O=s.format==="NHWC",Q=O?r[0].dims[3]:r[0].dims[1],k=u[0],J=O?u[2]:u[3],re=O?u[1]:u[2],ue=O?u[3]:u[1],ie=O&&(Q%4===0||Q%3===0)&&ue%4===0,Ae=O?ue:J*re,$e=O?J*re:ue,me=[8,8,1],Be=p<=8?[4,1,1]:[4,4,1],je=[Math.ceil(Ae/me[0]/Be[0]),Math.ceil($e/me[1]/Be[1]),Math.ceil(k/me[2]/Be[2])];xr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${je}`);let et=ie?O&&Q%4!==0?3:4:1,Ot=me[1]*Be[1],It=me[0]*Be[0],Kt=Math.max(me[0]*et,me[1]),yn=p%Ot===0,_n=m%It===0,Zn=g%Kt===0,Gn=ie?[et,4,4]:[1,1,1],lr=[{type:6,data:p},{type:6,data:m},{type:6,data:g},{type:6,data:[s.pads[0],s.pads[1]]},{type:6,data:s.strides},{type:6,data:s.dilations}];Ks(s,lr),lr.push(...sn(r[0].dims,r[1].dims));let _r=["rank","rank"];y&&(lr.push(...sn(r[2].dims)),_r.push("rank")),lr.push(...sn(u));let ir=On=>{let yr=[{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}];wo(s,yr);let Pr=ie?4:1,Nn=or(r[0].dataType),ur=` fn setOutputAtIndex(flatIndex : i32, value : ${ie?`vec4<${Nn}>`:Nn}) { result[flatIndex] = ${ie?`vec4<${Nn}>`:Nn}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${ie?`vec4<${Nn}>`:Nn}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${ie?"/ 4":""}, value); }`,Rt=Lt("x",r[0].dataType,r[0].dims.length,et===3?1:et),ln=Lt("w",r[1].dataType,r[1].dims.length,Pr),Jn=[Rt,ln],Br=vn("result",r[0].dataType,u.length,Pr);if(y){let Nr=Lt("bias",r[2].dataType,r[2].dims.length,Pr);Jn.push(Nr),ur+=` fn getBiasByOutputCoords(coords : vec4) -> ${ie?`vec4<${Nn}>`:Nn} { return bias[coords.${O?"w":"y"}${ie?"/ 4":""}]; }`}return` ${qu("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 }; ${On.registerUniforms(yr).declareVariables(...Jn,Br)} ${ur} ${Vd(O,yn,_n,Zn,y,s,Gn[0],Gn[1],Gn[2],Nn)} ${ie?Wl(Be,me,Nn,void 0,!O,Kt):ql(Be,me,Nn,void 0,!O,Kt,!1,void 0,A)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${s.cacheKey};${et};${ie};${yn};${_n};${Zn};${Ot};${It};${Kt}`,inputDependencies:_r},getRunData:()=>({outputs:[{dims:I?I(u):u,dataType:r[0].dataType}],dispatchGroup:{x:je[0],y:je[1],z:je[2]},programUniforms:lr}),getShaderSource:ir}}}),Wd,tl,nl,Gd,Qu,ap,qd,Hd,lp=c(()=>{En(),wi(),xn(),Ln(),Bi(),Ul(),Wd=r=>{let s=1;for(let u=0;utypeof r=="number"?[r,r,r]:r,nl=(r,s)=>s<=1?r:r+(r-1)*(s-1),Gd=(r,s,u,p=1)=>{let m=nl(s,p);return Math.floor((r[0]*(u-1)-u+m)/2)},Qu=(r,s,u,p,m)=>{m==null&&(m=Gd(r,s[0],p[0]));let g=[0,0,0,u];for(let y=0;y<3;y++)r[y]+2*m>=s[y]&&(g[y]=Math.trunc((r[y]-s[y]+2*m)/p[y]+1));return g},ap=(r,s,u,p,m,g,y,A,I,O)=>{let Q,k,J,re;if(r==="VALID"&&(r=0),typeof r=="number"){Q={top:r,bottom:r,left:r,right:r,front:r,back:r};let ue=Qu([s,u,p,1],[A,I,O],1,[m,g,y],r);k=ue[0],J=ue[1],re=ue[2]}else if(Array.isArray(r)){if(!r.every((ie,Ae,$e)=>ie===$e[0]))throw Error(`Unsupported padding parameter: ${r}`);Q={top:r[0],bottom:r[1],left:r[2],right:r[3],front:r[4],back:r[5]};let ue=Qu([s,u,p,1],[A,I,O],1,[m,g,y],r[0]);k=ue[0],J=ue[1],re=ue[2]}else if(r==="SAME_UPPER"){k=Math.ceil(s/m),J=Math.ceil(u/g),re=Math.ceil(p/y);let ue=(k-1)*m+A-s,ie=(J-1)*g+I-u,Ae=(re-1)*y+O-p,$e=Math.floor(ue/2),me=ue-$e,Be=Math.floor(ie/2),je=ie-Be,et=Math.floor(Ae/2),Ot=Ae-et;Q={top:Be,bottom:je,left:et,right:Ot,front:$e,back:me}}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:Q,outDepth:k,outHeight:J,outWidth:re}},qd=(r,s,u,p,m,g=!1,y="channelsLast")=>{let A,I,O,Q,k;if(y==="channelsLast")[A,I,O,Q,k]=r;else if(y==="channelsFirst")[A,k,I,O,Q]=r;else throw new Error(`Unknown dataFormat ${y}`);let[J,,re,ue,ie]=s,[Ae,$e,me]=tl(u),[Be,je,et]=tl(p),Ot=nl(re,Be),It=nl(ue,je),Kt=nl(ie,et),{padInfo:yn,outDepth:_n,outHeight:Zn,outWidth:Gn}=ap(m,I,O,Q,Ae,$e,me,Ot,It,Kt),lr=g?J*k:J,_r=[0,0,0,0,0];return y==="channelsFirst"?_r=[A,lr,_n,Zn,Gn]:y==="channelsLast"&&(_r=[A,_n,Zn,Gn,lr]),{batchSize:A,dataFormat:y,inDepth:I,inHeight:O,inWidth:Q,inChannels:k,outDepth:_n,outHeight:Zn,outWidth:Gn,outChannels:lr,padInfo:yn,strideDepth:Ae,strideHeight:$e,strideWidth:me,filterDepth:re,filterHeight:ue,filterWidth:ie,effectiveFilterDepth:Ot,effectiveFilterHeight:It,effectiveFilterWidth:Kt,dilationDepth:Be,dilationHeight:je,dilationWidth:et,inShape:r,outShape:_r,filterShape:s}},Hd=(r,s,u,p,m,g)=>{let y=g==="channelsLast";y?r[0].dims[3]:r[0].dims[1];let A=[64,1,1],I={x:u.map((Ae,$e)=>$e)},O=[Math.ceil(Wd(I.x.map(Ae=>u[Ae]))/A[0]),1,1];xr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${O}`);let Q=1,k=yt.size(u),J=[{type:12,data:k},{type:12,data:p},{type:12,data:m},{type:12,data:s.strides},{type:12,data:s.dilations}];Ks(s,J),J.push(...sn(r[0].dims,r[1].dims));let re=["rank","rank"],ue=r.length===3;ue&&(J.push(...sn(r[2].dims)),re.push("rank")),J.push(...sn(u));let ie=Ae=>{let $e=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:p.length},{name:"pads",type:"u32",length:m.length},{name:"strides",type:"u32",length:s.strides.length},{name:"dilations",type:"u32",length:s.dilations.length}];wo(s,$e);let me=1,Be=or(r[0].dataType),je=Lt("x",r[0].dataType,r[0].dims.length,Q),et=Lt("W",r[1].dataType,r[1].dims.length,me),Ot=[je,et],It=vn("result",r[0].dataType,u.length,me),Kt="";if(ue){let Zn=Lt("bias",r[2].dataType,r[2].dims.length,me);Ot.push(Zn),Kt+=` fn getBiasByOutputCoords(coords : array) -> ${Be} { return bias[${y?pn("coords",4,5):pn("coords",1,5)}]; }`}let yn=xi(Q,Be),_n=vo(s,yn,Be);return` ${Kt} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${je.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${et.getByIndices("aIndices")}; } ${Ae.registerUniforms($e).declareVariables(...Ot,It)} ${Ae.mainStart()} ${Ae.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${It.offsetToIndices("global_idx")}; let batch = ${pn("coords",0,je.rank)}; let d2 = ${y?pn("coords",je.rank-1,je.rank):pn("coords",1,je.rank)}; let xFRCCorner = vec3(${y?pn("coords",1,je.rank):pn("coords",2,je.rank)}, ${y?pn("coords",2,je.rank):pn("coords",3,je.rank)}, ${y?pn("coords",3,je.rank):pn("coords",4,je.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${y?pn("uniforms.x_shape",1,je.rank):pn("uniforms.x_shape",2,je.rank)}; let xShapeZ = ${y?pn("uniforms.x_shape",2,je.rank):pn("uniforms.x_shape",3,je.rank)}; let xShapeW = ${y?pn("uniforms.x_shape",3,je.rank):pn("uniforms.x_shape",4,je.rank)}; let xShapeU = ${y?pn("uniforms.x_shape",4,je.rank):pn("uniforms.x_shape",1,je.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) { ${y?`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) { ${y?`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) { ${y?`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) { ${y?`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); } } } } ${ue?"value = value + getBiasByOutputCoords(coords)":""}; ${_n} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${s.cacheKey};${y};${Q};${ue}`,inputDependencies:re},getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:O[0],y:O[1],z:O[2]},programUniforms:J}),getShaderSource:ie}}}),ba,Kd,up=c(()=>{En(),xn(),Ln(),rc(),Bi(),ba=(r,s,u)=>{let p=r.length>2,m=p?"value += b[output_channel];":"",g=r[0].dims,y=r[1].dims,A=y[0]/s.group,I=s.format==="NHWC",O=Zu(g,y,s.dilations,s.pads,s.strides,I),Q=yt.size(O),k=[{type:12,data:Q},{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:A}];Ks(s,k),k.push(...sn(g,y));let J=["rank","rank"];p&&(k.push(...sn(r[2].dims)),J.push("rank")),k.push(...sn(O));let re=ue=>{let ie=vn("output",r[0].dataType,O.length),Ae=or(ie.type.tensor),$e=vo(s,ie.type.value,Ae),me=Lt("x",r[0].dataType,g.length),Be=Lt("w",r[1].dataType,y.length),je=[me,Be];p&&je.push(Lt("b",r[2].dataType,r[2].dims.length));let et=[{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 wo(s,et),` ${ue.registerUniforms(et).declareVariables(...je,ie)} ${ue.mainStart()} ${ue.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${ie.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${I?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${I?1:2}], outputIndices[${I?2:3}]) * uniforms.strides - uniforms.pads; let group_id: u32 = output_channel / uniforms.output_channels_per_group; var value: ${ie.type.value} = ${ie.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[${I?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[${I?2:3}]) { continue; } let xVal = ${I?me.get("batch","xHeight","xWidth","input_channel"):me.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${Be.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${m} ${$e} ${ie.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:s.cacheKey,inputDependencies:J},getRunData:()=>({outputs:[{dims:u?u(O):O,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(Q/64)},programUniforms:k}),getShaderSource:re}},Kd=(r,s,u,p)=>{let m=r.length>2,g=tr(u[3]),y=tr(u[2]),A=yt.size(u)/g/y,I=[r[0].dims[0],r[0].dims[1],r[0].dims[2],r[0].dims[3]/g],O=[r[1].dims[0],r[1].dims[1],r[1].dims[2],r[1].dims[3]/g],Q=[u[0],u[1],u[2],u[3]/g],k=[{type:12,data:A},{type:6,data:[s.strides[0],s.strides[1]]},{type:6,data:[s.pads[0],s.pads[1]]}];Ks(s,k),k.push(...sn(I,O,Q));let J=(y-1)*s.strides[1]+O[1],re=ue=>{let ie=vn("output",r[0].dataType,Q.length,g),Ae=or(ie.type.tensor),$e=vo(s,ie.type.value,Ae),me=Lt("x",r[0].dataType,I.length,g),Be=Lt("w",r[1].dataType,O.length,g),je=[me,Be];m&&je.push(Lt("b",r[2].dataType,r[2].dims,g));let et=m?"value += b[output_channel];":"",Ot=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return wo(s,Ot),` ${ue.registerUniforms(Ot).declareVariables(...je,ie)} ${ue.mainStart()} ${ue.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] / ${y}u; let col = (index1 % width1) * ${y}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<${me.type.value}, ${J}>; var values: array<${ie.type.value}, ${y}>; 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 < ${J}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${me.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${me.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${O[1]}; w_width++) { let w_val = ${Be.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${y}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${y}u; i++) { var value = values[i]; ${et} ${$e} ${ie.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${s.cacheKey};${g};${y};${J};${O[0]};${O[1]}`,inputDependencies:m?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:p?p(u):u,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:k}),getShaderSource:re}}}),Yu,Xd,Qd,Hl=c(()=>{En(),xn(),Ho(),Ln(),Bi(),Yu=(r,s,u,p,m=!1,g)=>{let y=r[0].dims,A=r[1].dims,I=y[y.length-2],O=A[A.length-1],Q=y[y.length-1],k=tr(O),J=tr(Q),re=tr(I),ue=yt.size(u)/k/re,ie=r.length>2,Ae=p?p.slice(0,-2):u.slice(0,-2),$e=[yt.size(Ae),I,O],me=[{type:12,data:ue},{type:12,data:I},{type:12,data:O},{type:12,data:Q}];Ks(s,me),me.push(...sn(Ae,y,A)),ie&&me.push(...sn(r[2].dims)),me.push(...sn($e));let Be=je=>{let et=fo("batch_dims",r[0].dataType,Ae.length),Ot=Lt("a",r[0].dataType,y.length,J),It=Lt("b",r[1].dataType,A.length,k),Kt=vn("output",r[0].dataType,$e.length,k),yn=or(Kt.type.tensor),_n=vo(s,Kt.type.value,yn),Zn=[Ot,It],Gn="";if(ie){let ur=m?k:1;Zn.push(Lt("bias",r[2].dataType,r[2].dims.length,ur)),Gn=`${m?`value += bias[col / ${ur}];`:`value += ${Kt.type.value}(bias[row + i]);`}`}let lr=y.slice(0,-2),_r=A.slice(0,-2),ir=ho(lr,Ae),On=ho(_r,Ae),yr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];wo(s,yr);let Pr=(ur,Rt)=>{let ln=ur.rank,Jn=ur.name;if(ln===2)return`var ${Jn}_indices = ${ur.type.indices}(0u, 0u);`;let Br=et.rank,Nr=`var ${Jn}_indices: ${ur.type.indices};`;for(let Qs=ln-2-1,xo=Br-1;Qs>=0;Qs--,xo--)Nr+=` ${Jn}_indices[${Qs}] = ${Br>1?`batch_indices[${xo}]`:"batch_indices"};`;return Rt.forEach(Qs=>{Nr+=` ${Jn}_indices[${Qs}] = 0;`}),Nr+=`${Jn}_indices[${ln-2}] = 0u; ${Jn}_indices[${ln-1}] = 0u;`,Nr},Nn=()=>{let ur=`var a_data: ${Ot.type.value};`;for(let Rt=0;Rt; for (var k: u32 = 0u; k < uniforms.K; k = k + ${J}) { ${Nn()} } for (var i = 0u; i < ${re}u; i++) { var value = values[i]; ${Gn} ${_n} let cur_indices = ${Kt.type.indices}(batch, row + i, col); let offset = ${Kt.indicesToOffset("cur_indices")}; ${Kt.setByOffset(`offset / ${k}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${s.activation};${k};${J};${re};${m}`,inputDependencies:ie?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:g?g(u):u,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(ue/64)},programUniforms:me}),getShaderSource:Be}},Xd=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.")},Qd=r=>{Xd(r.inputs);let s=Mr.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],p=r.inputs[0].dims[r.inputs[0].dims.length-1];u<8&&p<8?r.compute(Yu(r.inputs,{activation:""},s)):r.compute(Xu(r.inputs,{activation:""},s))}}),Zu,Kl,Yd,Xl,Ju,ec,tc,Zd,nc,rc=c(()=>{xn(),op(),lp(),Ho(),up(),Bi(),Hl(),mo(),Zu=(r,s,u,p,m,g)=>{let y=r[0],A=r.slice(g?1:2,g?3:4),I=A.length,O=s[0],Q=s.slice(2).map((J,re)=>J+(J-1)*(u[re]-1)),k=A.map((J,re)=>J+p[re]+p[re+I]).map((J,re)=>Math.floor((J-Q[re]+m[re])/m[re]));return k.splice(0,0,y),k.splice(g?3:1,0,O),k},Kl=[2,3,1,0],Yd=(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],p=r[1].dims[1]*s.group;if(u!==p)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 m=r[0].dims.length-2;if(s.dilations.length!==m)throw new Error(`dilations should be ${m}D`);if(s.strides.length!==m)throw new Error(`strides should be ${m}D`);if(s.pads.length!==m*2)throw new Error(`pads should be ${m*2}D`);if(s.kernelShape.length!==0&&s.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape")},Xl=(r,s)=>{let u=r.kernelShape.slice();for(let g=2;g{let s=Wu(r),u=r.format,p=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][r.auto_pad],m=r.dilations,g=r.group,y=r.kernel_shape,A=r.pads,I=r.strides,O=r.w_is_const();return{autoPad:p,format:u,dilations:m,group:g,kernelShape:y,pads:A,strides:I,wIsConst:O,...s,cacheKey:`${r.format};${s.activation};`}},ec=(r,s,u,p)=>{let m=u.format==="NHWC";if(u.group!==1){if(!r.adapterInfo.isArchitecture("ampere")&&m&&s[1].dims[0]===u.group&&s[1].dims[1]===1&&u.dilations[0]===1&&u.dilations[1]===1){let Ot=Zu(s[0].dims,s[1].dims,u.dilations,u.pads,u.strides,m),It=r.kernelCustomData.wT??r.compute(Ai(s[1],Kl),{inputs:[1],outputs:[u.wIsConst?-2:-1]})[0];u.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=It);let Kt=[s[0],It];s.length===3&&Kt.push(s[2]),r.compute(Kd(Kt,u,Ot,p),{inputs:Kt})}else r.compute(ba(s,u,p));return}let g=s.length===3,y=s[0].dims[m?1:2],A=s[0].dims[m?2:3],I=s[0].dims[m?3:1],O=s[1].dims[2],Q=s[1].dims[3],k=Zu(s[0].dims,s[1].dims,u.dilations,u.pads,u.strides,m),J=k[m?1:2],re=k[m?2:3],ue=k[m?3:1],ie=m&&O===y&&Q===A&&u.pads[0]===0&&u.pads[1]===0;if(ie||O===1&&Q===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 Ot=k[0],It,Kt,yn,_n=[];if(m){let lr=r.kernelCustomData.wT??r.compute(Ai(s[1],Kl),{inputs:[1],outputs:[u.wIsConst?-2:-1]})[0];if(u.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=lr),ie){let _r=y*A*I;It=s[0].reshape([1,Ot,_r]),Kt=lr.reshape([1,_r,ue]),yn=[1,Ot,ue]}else It=s[0].reshape([Ot,y*A,I]),Kt=lr.reshape([1,I,ue]),yn=[Ot,J*re,ue];_n.push(It),_n.push(Kt)}else It=s[0].reshape([Ot,I,y*A]),Kt=s[1].reshape([1,ue,I]),yn=[Ot,ue,J*re],_n.push(Kt),_n.push(It);g&&_n.push(s[2]);let Zn=yn[2],Gn=_n[0].dims[_n[0].dims.length-1];Zn<8&&Gn<8?r.compute(Yu(_n,u,k,yn,m,p),{inputs:_n}):r.compute(Xu(_n,u,k,yn,m,p),{inputs:_n});return}let Ae=!0,$e=r.kernelCustomData.wT??r.compute(Ai(s[1],Kl),{inputs:[1],outputs:[u.wIsConst?-2:-1]})[0];u.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=$e);let me=[s[0],$e];g&&me.push(s[2]);let Be=m?J*re:ue,je=m?ue:J*re,et=O*Q*I;r.compute(Ud(me,u,k,Be,je,et,g,Ae,p),{inputs:me})},tc=(r,s)=>{let u=s.format==="NHWC",p=[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&&p.push(r.inputs[2]);let m=[0,s.pads[0],0,s.pads[1]],g=[1].concat(s.strides),y=[1].concat(s.dilations),A=[1].concat(s.kernelShape),I=Xl({...s,pads:m,strides:g,dilations:y,kernelShape:A},p);ec(r,p,I,O=>u?[O[0],O[2],O[3]]:[O[0],O[1],O[3]])},Zd=(r,s,u)=>{let p=u.format==="NHWC"?"channelsLast":"channelsFirst",m=Xl(u,s),g=u.autoPad==="NOTSET"?u.pads:u.autoPad,y=qd(s[0].dims,s[1].dims,u.strides,u.dilations,g,!1,p);r.compute(Hd(s,m,y.outShape,[y.filterDepth,y.filterHeight,y.filterWidth],[y.padInfo.front,y.padInfo.top,y.padInfo.left],p))},nc=(r,s)=>{if(Yd(r.inputs,s),r.inputs[0].dims.length===3)tc(r,s);else if(r.inputs[0].dims.length===5)Zd(r,r.inputs,s);else{let u=Xl(s,r.inputs);ec(r,r.inputs,u)}}}),Jd,ef,tf=c(()=>{En(),wi(),Ln(),Bi(),Ul(),Hu(),Ho(),Jd=(r,s=!1,u,p,m=4)=>{let g=Ae=>{switch(Ae){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 ${p}(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${Ae} is not supported.`)}},y=r?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,A=r?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,I=r?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",O=r?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Q=r?"row":"col",k=r?"col":"row",J=` 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 = ${Q} / outWidth; let outCol = ${Q} % outWidth; let WRow = ${k} / (uniforms.filter_dims[1] * inChannels); let WCol = ${k} / 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(${I}) || fract(xR) > 0.0) { return ${p}(0.0); } if (xC < 0.0 || xC >= f32(${O}) || fract(xC) > 0.0) { return ${p}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${k} % inChannels; ${y} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${m}];`,re=r?` let col = colIn * ${m}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${J} } return ${p}(0.0);`:` let col = colIn * ${m}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${J} } return ${p}(0.0);`,ue=` let col = colIn * ${m}; 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); ${g(m)} } return ${p}(0.0); `,ie=vo(u,p);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${p} { ${r?re:ue} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${p} { ${r?ue:re} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${p}) { let col = colIn * ${m}; 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])"}; ${A} ${Gu(s)} ${ie} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${m}] = value; } }`},ef=(r,s,u,p,m,g,y,A)=>{let I=s.format==="NHWC",O=I?r[0].dims[3]:r[0].dims[1],Q=u[0],k=I?u[2]:u[3],J=I?u[1]:u[2],re=I?u[3]:u[1],ue=I&&O%4===0&&O%3&&re%4===0,ie=I?re:k*J,Ae=I?k*J:re,$e=[8,8,1],me=p<=8?[4,1,1]:[4,4,1],Be=[Math.ceil(ie/$e[0]/me[0]),Math.ceil(Ae/$e[1]/me[1]),Math.ceil(Q/$e[2]/me[2])];xr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${Be}`);let je=ue?4:1,et=Math.max($e[0]*je,$e[1]),Ot=ue?4:1,It=[s.kernelShape[I?1:2],s.kernelShape[I?2:3]],Kt=[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))],yn=[Kt[0]-1-Math.floor((s.pads[0]+s.pads[2])/2),Kt[1]-1-Math.floor((s.pads[1]+s.pads[3])/2)],_n=[{type:6,data:p},{type:6,data:m},{type:6,data:g},{type:6,data:s.strides},{type:6,data:s.dilations},{type:6,data:It},{type:6,data:yn}];Ks(s,_n),_n.push(...sn(r[0].dims,r[1].dims));let Zn=["rank","rank"];y&&(_n.push(...sn(r[2].dims)),Zn.push("rank")),_n.push(...sn(u));let Gn=lr=>{let _r=Lt("x",r[0].dataType,r[0].dims.length,Ot),ir=Lt("w",r[1].dataType,r[1].dims.length,1),On=vn("result",r[0].dataType,u.length,Ot),yr=[_r,ir],Pr="";if(y){let Rt=Lt("bias",r[2].dataType,r[2].dims.length,Ot);yr.push(Rt),Pr+=` fn getBiasByOutputCoords(coords : vec4) -> ${Rt.type.value} { return bias[coords.${I?"w":"y"}${ue?"/ 4":""}]; }`}let Nn=[{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:yn.length}];wo(s,Nn);let ur=or(r[0].dataType,1);if(ur!=="f16"&&ur!=="f32")throw new Error(`elemType ${ur} is not supported.`);return` ${qu("uniforms.result_strides")} ${lr.registerUniforms(Nn).declareVariables(...yr,On)}; ${Pr} ${Jd(I,y,s,_r.type.value,je)} ${ue?Wl(me,$e,ur,void 0,!I,et):ql(me,$e,ur,void 0,!I,et,!1,void 0,A)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${s.cacheKey};${me};${$e};${ue}`,inputDependencies:Zn},getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:Be[0],y:Be[1],z:Be[2]},programUniforms:_n}),getShaderSource:Gn}}}),nf,ic,sc=c(()=>{En(),wi(),xn(),Ln(),nf=(r,s,u,p,m,g=!1,y,A,I=!1)=>{let O=I?1:2,Q=I?2:3,k=I?3:1,J=g?2:1,re=` fn setOutputAtIndex(flatIndex : u32, value : ${g?`vec4<${y}>`:y}) { result[flatIndex] = ${g?`vec4<${y}>`:y}(value); }`;p&&(re+=` fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${y}>`:y} { return bias[coords.${I?"w":"y"}${g?"/ 4":""}]; }`);let ue=g?4:1,ie=Lt("W",s[1].dataType,s[1].dims.length,ue),Ae=Lt("Dy",s[0].dataType,s[0].dims.length,ue),$e=[Ae,ie];p&&$e.push(Lt("bias",s[2].dataType,[u[k]].length,ue));let me=vn("result",s[0].dataType,u.length,ue),Be=`{ let batch: u32 = ${m?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; let r = ${m?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; let c = ${m?"global_id.y":"workgroup_id.y"} * ${J}; let d1: u32 = ${m?"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, ${J}>; for (var i = 0; i < ${J}; i++) { dotProd[i] = vec4<${y}>(0.0); } for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { var dyR = (${y}(dyCorner.x) + ${y}(wR)) / ${y}(uniforms.strides.x); let wRPerm = uniforms.filter_dims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${y}(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 = (${y}(dyCorner.y) + ${y}(wC)) / ${y}(uniforms.strides.y); let dyC2 = (${y}(dyCorner.y) + 1.0 + ${y}(wC)) / ${y}(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 >= ${y}(uniforms.Dy_shape[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${y}(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 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${Ae.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${y}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${Ae.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${y}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = uniforms.Dy_shape[${k}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${Ae.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${y}>(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 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${ie.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${Ae.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${y}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${J}; i = i + 1) { let value = dotProd[i] + ${p?"bias[c+i]":`vec4<${y}>(0.0)`}; ${me.set("batch","r","c + i","d1","value")}; } }`,je=` let outputIndices = ${me.offsetToIndices("global_idx")}; let batch = ${me.indicesGet("outputIndices",0)}; let d1 = ${me.indicesGet("outputIndices",k)}; let r = ${me.indicesGet("outputIndices",O)}; let c = ${me.indicesGet("outputIndices",Q)}; 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 = ${y}(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 = (${y}(dyRCorner) + ${y}(wR)) / ${y}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${y}(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 = (${y}(dyCCorner) + ${y}(wC)) / ${y}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${y}(uniforms.Dy_shape[${Q}]) || 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 = ${I?Ae.get("batch","idyR","idyC","inputChannel"):Ae.get("batch","inputChannel","idyR","idyC")}; let wValue = ${ie.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${p?"bias[d1]":`${y}(0.0)`}; ${me.setByOffset("global_idx","value")}; `;return` ${r.registerUniforms(A).declareVariables(...$e,me)} ${re} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${g?Be:je}}`},ic=(r,s,u)=>{let p=r.length>2,m=s.outputShape,g=yt.size(m),y=[Math.ceil(g/64),1,1];xr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${y}`);let A=s.format==="NHWC",I=["rank","rank"],O=[s.strides[0],s.strides[1]],Q=[s.kernelShape[A?1:2],s.kernelShape[A?2:3]],k=[s.dilations[0],s.dilations[1]],J=[Q[0]+(s.dilations[0]<=1?0:(s.kernelShape[A?1:2]-1)*(s.dilations[0]-1)),Q[1]+(s.dilations[1]<=1?0:(s.kernelShape[A?2:3]-1)*(s.dilations[1]-1))],re=[J[0]-1-Math.floor((s.pads[0]+s.pads[2])/2),J[1]-1-Math.floor(s.pads[1]+s.pads[3])/2],ue=!1,ie=s.group,Ae=r[1].dims,$e=Ae[0]/ie,me=Ae[1],Be=[{type:12,data:g},{type:12,data:O},{type:12,data:Q},{type:12,data:k},{type:12,data:J},{type:6,data:re},{type:12,data:$e},{type:12,data:me},...sn(r[0].dims,r[1].dims)];p&&(Be.push(...sn(r[2].dims)),I.push("rank")),Be.push(...sn(m));let je=y[1]===1&&y[2]===1,et=Ot=>{let It=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:O.length},{name:"filter_dims",type:"u32",length:Q.length},{name:"dilations",type:"u32",length:Q.length},{name:"effective_filter_dims",type:"u32",length:J.length},{name:"pads",type:"i32",length:re.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Kt=or(r[0].dataType);return`${nf(Ot,r,m,p,je,ue,Kt,It,A)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${s.cacheKey};`,inputDependencies:I},getRunData:()=>({dispatchGroup:{x:y[0],y:y[1],z:y[2]},outputs:[{dims:u?u(m):m,dataType:r[0].dataType}],programUniforms:Be}),getShaderSource:et}}}),rf,sf,of,oc,ac,Ql,cp,af,lf,lc,dp=c(()=>{tf(),sc(),Bi(),mo(),rf=(r,s,u,p,m,g)=>(r-1)*s+u+(p-1)*m+1-g,sf=(r,s,u,p,m)=>{let g=Math.floor(r/2);s==="SAME_UPPER"?(u[p]=g,u[m]=r-g):s==="SAME_LOWER"&&(u[p]=r-g,u[m]=g)},of=(r,s,u,p,m,g,y,A,I,O)=>{let Q=r.length-2,k=O.length===0;if(I.length===0)for(let ue=0;ue{let u=r.kernelShape.slice();if(r.kernelShape.length===0||r.kernelShape.reduce((k,J)=>k*J,1)===0){u.length=0;for(let k=2;kk+J,0)===0){let k=s[0].dims.length-2;I=new Array(k).fill(1)}let O=r.strides.slice();if(O.reduce((k,J)=>k+J,0)===0){let k=s[0].dims.length-2;O=new Array(k).fill(1)}of(A,u,I,r.autoPad,r.group,m,O,p,y,g);let Q=Object.assign({},r);return Object.assign(Q,{kernelShape:u,pads:m,outputPadding:y,outputShape:g,dilations:I,strides:O}),Q},ac=r=>{let s=Wu(r),u=r.format,p=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof r.autoPad>"u"?0:r.autoPad],m=r.dilations,g=r.group,y=r.kernelShape,A=r.pads,I=r.strides,O=r.wIsConst(),Q=r.outputPadding,k=r.outputShape;return{autoPad:p,format:u,dilations:m,group:g,kernelShape:y,outputPadding:Q,outputShape:k,pads:A,strides:I,wIsConst:O,...s,cacheKey:`${r.format};${s.activation};`}},Ql=(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],p=r[1].dims[0];if(u!==p)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let m=r[1].dims[1]*s.group;if(r.length===3&&(r[2].dims.length!==1||r[2].dims[0]!==m))throw new Error("invalid bias");let g=r[0].dims.length-2;if(s.dilations.reduce((y,A)=>y+A,0)>0&&s.dilations.length!==g)throw new Error(`dilations should be ${g}D`);if(s.strides.reduce((y,A)=>y+A,0)>0&&s.strides.length!==g)throw new Error(`strides should be ${g}D`);if(s.pads.reduce((y,A)=>y+A,0)>0&&s.pads.length!==g*2)throw new Error(`pads should be ${g*2}D`);if(s.outputPadding.length!==g&&s.outputPadding.length!==0)throw new Error(`output_padding should be ${g}D`);if(s.kernelShape.reduce((y,A)=>y+A,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")},cp=[2,3,1,0],af=(r,s,u)=>{let p=oc(u,s),m=u.format==="NHWC",g=p.outputShape,y=g[m?3:1],A=s[0].dims[m?3:1];if(p.group!==1||y===1&&A===1){r.compute(ic(s,p));return}let I=g[m?1:2],O=g[m?2:3],Q=s[1].dims[2],k=s[1].dims[3],J=m?I*O:y,re=m?y:I*O,ue=Q*k*A,ie=!0,Ae=r.kernelCustomData.wT??r.compute(Ai(s[1],cp),{inputs:[1],outputs:[u.wIsConst?-2:-1]})[0];u.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=Ae);let $e=[s[0],Ae],me=s.length===3;me&&(!m&&s[2].dims.length===1?$e.push(s[2].reshape([s[2].dims[0],1,1])):$e.push(s[2])),r.compute(ef($e,p,g,J,re,ue,me,ie),{inputs:$e})},lf=(r,s)=>{let u=s.format==="NHWC",p=[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&&p.push(r.inputs[2]);let m=s.kernelShape;(m.length===0||m[0]===0)&&(m=[r.inputs[1].dims[2]]);let g=s.dilations;(g.length===0||g[0]===0)&&(g=[1]);let y=s.strides;(y.length===0||y[0]===0)&&(y=[1]);let A=s.pads;A.length===0&&(A=[0,0]),A=[0,A[0],0,A[1]],y=[1].concat(y),g=[1].concat(g),m=[1].concat(m);let I=oc({...s,pads:A,strides:y,dilations:g,kernelShape:m},p);r.compute(ic(p,I,O=>u?[O[0],O[2],O[3]]:[O[0],O[1],O[3]]))},lc=(r,s)=>{Ql(r.inputs,s),r.inputs[0].dims.length===3?lf(r,s):af(r,r.inputs,s)}}),uf,uc,cf,fp=c(()=>{En(),xn(),Qn(),Ln(),uf=(r,s,u,p)=>{let m=yt.size(s),g=s.length,y=Lt("input",r,g),A=vn("output",r,g),I=u.dataType===6?u.getInt32Array()[0]:Number(u.getBigInt64Array()[0]),O=yt.normalizeAxis(I,g),Q=k=>{let J=` i32(${y.indicesGet("inputIndices","uniforms.axis")}) `,re=pn("uniforms.input_shape","uniforms.axis",g),ue=p.reverse?J+(p.exclusive?" + 1":""):"0",ie=p.reverse?re:J+(p.exclusive?"":" + 1");return` ${k.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(y,A)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${A.offsetToIndices("global_idx")}; var sum = ${A.type.value}(0); let first : i32 = ${ue}; let last : i32 = ${ie}; for (var i : i32 = first; i < last; i++) { ${y.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${y.getByIndices("inputIndices")}; } ${A.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:p.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},{type:12,data:O},...sn(s,s)]}),getShaderSource:Q}},uc=(r,s)=>{let u=r.inputs[0].dims,p=r.inputs[0].dataType,m=r.inputs[1];r.compute(uf(p,u,m,s),{inputs:[0]})},cf=r=>{let s=r.exclusive===1,u=r.reverse===1;return kn({exclusive:s,reverse:u})}}),cc,hp,pp,dc,fc,mp=c(()=>{En(),xn(),Qn(),Ln(),cc=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.")},hp=(r,s,u,p)=>{let m=[];m.push(`fn perm(i: ${p.type.indices}) -> ${u.type.indices} { var a: ${u.type.indices};`);for(let g=0;g{let u,p,m,g,y,A,I=s.format==="NHWC",O=s.blocksize,Q=s.mode==="DCR";I?([u,p,m,g]=r.dims,y=Q?[u,p,m,O,O,g/O**2]:[u,p,m,g/O**2,O,O],A=Q?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([u,p,m,g]=[r.dims[0],r.dims[2],r.dims[3],r.dims[1]],y=Q?[u,O,O,g/O**2,p,m]:[u,g/O**2,O,O,p,m],A=Q?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let k=r.reshape(y),J=k.dims.length,re=r.dataType,ue=Lt("a",re,J),ie=vn("output",re,J),Ae=$e=>` ${$e.registerUniform("output_size","u32").declareVariables(ue,ie)} ${hp(A,J,ue,ie)} ${$e.mainStart()} ${$e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${ie.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${ie.setByOffset("global_idx",ue.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${r.dims};${s.blocksize};${s.mode}`,inputDependencies:["rank"]},getRunData:$e=>{let me=I?[u,p*O,m*O,g/O**2]:[u,g/O**2,p*O,m*O],Be=yt.size(me),je=k.dims,et=yt.sortBasedOnPerm(je,A);return{outputs:[{dims:me,dataType:$e[0].dataType}],dispatchGroup:{x:Math.ceil(Be/64)},programUniforms:[{type:12,data:Be},...sn(je,et)]}},getShaderSource:Ae}},dc=(r,s)=>{cc(r.inputs),r.compute(pp(r.inputs[0],s))},fc=r=>kn({blocksize:r.blocksize,mode:r.mode,format:r.format})}),Yl,xa,hc,df,pc,ff,hf,Zl,pf,mf,Er,Zg=c(()=>{En(),xn(),Qn(),Ln(),Yl="[a-zA-Z]|\\.\\.\\.",xa="("+Yl+")+",hc="^"+xa+"$",df="("+xa+",)*"+xa,pc="^"+df+"$",ff=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)}},hf=class{constructor(r,s){this.equation=s,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[u,p]=s.includes("->")?s.split("->",2):[s,""];if(!u.match(RegExp(pc)))throw new Error("Invalid LHS term");if(u.split(",").forEach((m,g)=>{let y=r[g].dims.slice();if(!m.match(RegExp(hc)))throw new Error("Invalid LHS term");let A=this.processTerm(m,!0,y,g);this.lhs.push(A)}),p==="")p+=[...this.symbolToInfo.entries()].filter(([m,g])=>g.count===1||m==="...").map(([m])=>m).join("");else if(!p.match(RegExp(xa)))throw new Error("Invalid RHS");p.match(RegExp(Yl,"g"))?.forEach(m=>{if(m==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let g=this.symbolToInfo.get(m);if(g===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(g.dimValue)}}),this.rhs=this.processTerm(p,!1,this.outputDims)}addSymbol(r,s,u){let p=this.symbolToInfo.get(r);if(p!==void 0){if(p.dimValue!==s&&p.count!==1)throw new Error("Dimension mismatch");p.count++,p.inputIndices.push(u)}else p={count:1,dimValue:s,inputIndices:[u]};this.symbolToInfo.set(r,p)}processTerm(r,s,u,p=-1){let m=u.length,g=!1,y=[],A=0;if(!r.match(RegExp(hc))&&!s&&r!=="")throw new Error("Invalid LHS term");let I=r.match(RegExp(Yl,"g")),O=new ff(p);return I?.forEach((Q,k)=>{if(Q==="..."){if(g)throw new Error("Only one ellipsis is allowed per input term");g=!0;let J=m-I.length+1;if(J<0)throw new Error("Ellipsis out of bounds");if(y=u.slice(A,A+J),this.hasEllipsis){if(this.ellipsisDims.length!==y.length||this.ellipsisDims.toString()!==y.toString())throw new Error("Ellipsis dimensions mismatch")}else if(s)this.hasEllipsis=!0,this.ellipsisDims=y;else throw new Error("Ellipsis must be specified in the LHS");for(let re=0;rer+"_max",pf=(r,s,u,p)=>{let m=r.map(O=>O.length).map((O,Q)=>Lt(`input${Q}`,s,O)),g=yt.size(p),y=vn("output",s,p.length),A=[...u.symbolToInfo.keys()].filter(O=>!u.rhs.symbolToIndices.has(O)),I=O=>{let Q=[],k="var prod = 1.0;",J="var sum = 0.0;",re="sum += prod;",ue=[],ie=[],Ae=[],$e=[],me=u.symbolToInfo.size===u.rhs.symbolToIndices.size;u.symbolToInfo.forEach((je,et)=>{if(u.rhs.symbolToIndices.has(et)){let Ot=u.rhs.symbolToIndices.get(et)?.[0];Ot!==void 0&&u.lhs.forEach((It,Kt)=>{if(je.inputIndices.includes(Kt)){let yn=It.symbolToIndices.get(et);if(yn===void 0)throw new Error("Invalid symbol error");yn.forEach(_n=>{Q.push(`${m[Kt].indicesSet(`input${Kt}Indices`,_n,y.indicesGet("outputIndices",Ot))}`)})}})}else u.lhs.forEach((Ot,It)=>{if(je.inputIndices.includes(It)){let Kt=Ot.symbolToIndices.get(et);if(Kt===void 0)throw new Error("Invalid symbol error");Kt.forEach(yn=>{ue.push(`${m[It].indicesSet(`input${It}Indices`,yn,`${et}`)}`)}),$e.push(`prod *= ${m[It].getByIndices(`input${It}Indices`)};`)}}),ie.push(`for(var ${et}: u32 = 0; ${et} < uniforms.${Zl(et)}; ${et}++) {`),Ae.push("}")});let Be=me?[...Q,`let sum = ${m.map((je,et)=>je.getByIndices(`input${et}Indices`)).join(" * ")};`]:[...Q,J,...ie,...ue,k,...$e,re,...Ae];return` ${O.registerUniforms(A.map(je=>({name:`${Zl(je)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...m,y)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${y.offsetToIndices("global_idx")}; ${m.map((je,et)=>`var input${et}Indices: ${m[et].type.indices};`).join(` `)} ${Be.join(` `)}; ${y.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:u.equation,inputDependencies:r.map(()=>"rank")},getRunData:()=>{let O=A.filter(k=>u.symbolToInfo.has(k)).map(k=>({type:12,data:u.symbolToInfo.get(k)?.dimValue||0}));O.push({type:12,data:g});let Q=r.map((k,J)=>[...sn(k)]).reduce((k,J)=>k.concat(J),O);return Q.push(...sn(p)),{outputs:[{dims:p,dataType:s}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:Q}},getShaderSource:I}},mf=(r,s)=>{let u=new hf(r.inputs,s.equation),p=u.outputDims,m=r.inputs.map((g,y)=>g.dims);r.compute(pf(m,r.inputs[0].dataType,u,p))},Er=r=>{let s=r.equation.replace(/\s+/g,"");return kn({equation:s})}}),gp,gf,mc,_f,yf,_p=c(()=>{En(),xn(),Ln(),gp=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),p=u.length{let u=r.length-s.length,p=[];for(let m=0;mr.length>s.length?gf(r,s):gf(s,r),_f=r=>{let s=r[0].dims,u=Array.from(r[1].getBigInt64Array(),Number),p=mc(s,u),m=r[0].dataType,g=m===9?4:1,y=Math.ceil(yt.size(p)/g),A=O=>{let Q=Lt("input",m,s.length,g),k=vn("output",m,p.length,g),J;if(m===9){let re=(ue,ie,Ae="")=>` let outputIndices${ie} = ${k.offsetToIndices(`outputOffset + ${ie}u`)}; let offset${ie} = ${Q.broadcastedIndicesToOffset(`outputIndices${ie}`,k)}; let index${ie} = offset${ie} / 4u; let component${ie} = offset${ie} % 4u; ${ue}[${ie}] = ${Ae}(${Q.getByOffset(`index${ie}`)}[component${ie}]); `;J=` let outputOffset = global_idx * ${g}; var data = vec4(0); ${re("data",0,"u32")} ${re("data",1,"u32")} ${re("data",2,"u32")} ${re("data",3,"u32")} ${k.setByOffset("global_idx","data")} }`}else J=` let outputIndices = ${k.offsetToIndices("global_idx")}; let inputOffset = ${Q.broadcastedIndicesToOffset("outputIndices",k)}; ${k.setByOffset("global_idx",Q.getByOffset("inputOffset"))} }`;return` ${O.registerUniform("vec_size","u32").declareVariables(Q,k)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${J}`},I=[{type:12,data:y},...sn(s,p)];return{name:"Expand",shaderCache:{hint:`${p.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[{dims:p,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:I})}},yf=r=>{gp(r.inputs),r.compute(_f(r.inputs),{inputs:[0]})}}),vf,gc,wf=c(()=>{En(),xn(),Ln(),Ru(),vf=r=>{let s=r[0].dataType,u=yt.size(r[0].dims),p=yt.size(r[1].dims),m=p%4===0,g=y=>{let A=Lt("x",s,[1],4),I=Lt("bias",s,[1],4),O=vn("y",s,[1],4),Q=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],k=re=>` let bias${re}_offset: u32 = (global_idx * 4 + ${re}) % uniforms.bias_size; let bias${re} = ${I.getByOffset(`bias${re}_offset / 4`)}[bias${re}_offset % 4];`,J=m?` let bias = ${I.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${k(0)}${k(1)}${k(2)}${k(3)} let bias = ${A.type.value}(bias0, bias1, bias2, bias3);`;return`${y.registerUniforms(Q).declareVariables(A,I,O)} ${Ou(ar(s))} ${y.mainStart(Ci)} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${A.getByOffset("global_idx")}; ${J} let x_in = x + bias; ${O.setByOffset("global_idx",Du("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${m}`,inputDependencies:["type","type"]},getShaderSource:g,getRunData:y=>({outputs:[{dims:y[0].dims,dataType:y[0].dataType}],programUniforms:[{type:12,data:Math.ceil(u/4)},{type:12,data:p}],dispatchGroup:{x:Math.ceil(u/Ci/4)}})}},gc=r=>{r.inputs.length<2||yt.size(r.inputs[1].dims)===0?zu(r):r.compute(vf(r.inputs))}}),bf,xf,_c,yp,Jg=c(()=>{En(),xn(),Qn(),Ln(),bf=r=>{if(!r||r.length!==2)throw new Error("Gather requires 2 inputs.")},xf=(r,s)=>{let u=r[0].dims,p=r[1].dims,m=u.length,g=yt.normalizeAxis(s.axis,m),y=u.slice(0);y.splice(g,1,...p);let A=u[g],I=r[0].dataType===9?4:1,O=Math.ceil(yt.size(y)/I),Q=[{type:12,data:O},{type:6,data:A},{type:12,data:g},...sn(r[0].dims,r[1].dims,y)],k=J=>{let re=Lt("data",r[0].dataType,r[0].dims.length,I),ue=Lt("inputIndices",r[1].dataType,r[1].dims.length),ie=vn("output",r[0].dataType,y.length,I),Ae=me=>{let Be=p.length,je=`var indicesIndices${me} = ${ue.type.indices}(0);`;for(let et=0;et1?`indicesIndices${me}[${et}]`:`indicesIndices${me}`} = ${y.length>1?`outputIndices${me}[uniforms.axis + ${et}]`:`outputIndices${me}`};`;je+=` var idx${me} = ${ue.getByIndices(`indicesIndices${me}`)}; if (idx${me} < 0) { idx${me} = idx${me} + uniforms.axisDimLimit; } var dataIndices${me} : ${re.type.indices}; `;for(let et=0,Ot=0;et1?`dataIndices${me}[${et}]`:`dataIndices${me}`} = u32(idx${me});`,Ot+=Be):(je+=`${m>1?`dataIndices${me}[${et}]`:`dataIndices${me}`} = ${y.length>1?`outputIndices${me}[${Ot}]`:`outputIndices${me}`};`,Ot++);return je},$e;if(r[0].dataType===9){let me=(Be,je,et="")=>` let outputIndices${je} = ${ie.offsetToIndices(`outputOffset + ${je}u`)}; ${Ae(je)}; let offset${je} = ${re.indicesToOffset(`dataIndices${je}`)}; let index${je} = offset${je} / 4u; let component${je} = offset${je} % 4u; ${Be}[${je}] = ${et}(${re.getByOffset(`index${je}`)}[component${je}]); `;$e=` let outputOffset = global_idx * ${I}; var value = vec4(0); ${me("value",0,"u32")} ${me("value",1,"u32")} ${me("value",2,"u32")} ${me("value",3,"u32")} ${ie.setByOffset("global_idx","value")} `}else $e=` let outputIndices = ${ie.offsetToIndices("global_idx")}; ${Ae("")}; let value = ${re.getByIndices("dataIndices")}; ${ie.setByOffset("global_idx","value")}; `;return` ${J.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(re,ue,ie)} ${J.mainStart()} ${J.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${$e} }`};return{name:"Gather",shaderCache:{hint:s.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:y,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:Q}),getShaderSource:k}},_c=r=>kn({axis:r.axis}),yp=(r,s)=>{let u=r.inputs;bf(u),r.compute(xf(r.inputs,s))}}),Mf,Tf,Sf,kf,vp=c(()=>{En(),xn(),Qn(),Ln(),Mf=(r,s)=>{if(r.length<3||r.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let u=yt.normalizeAxis(s.quantizeAxis,r[0].dims.length),p=s.blockSize,m=r[0],g=r[2],y=r.length===4?r[3]:void 0;if(g.dims.length!==m.dims.length||!m.dims.map((A,I)=>I===u?Math.ceil(A/p)===g.dims[I]:A===g.dims[I]).reduce((A,I)=>A&&I,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(y){if(y.dataType!==m.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(y.dims.length!==g.dims.length||!y.dims.map((A,I)=>A===g.dims[I]).reduce((A,I)=>A&&I,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Tf=(r,s)=>{let u=r[0].dims,p=r[1].dims,m=u.length,g=yt.normalizeAxis(s.gatherAxis,m),y=yt.normalizeAxis(s.quantizeAxis,m),A=u.slice(0);A.splice(g,1,...p);let I=yt.size(A),O=r[2].dataType,Q=r[0].dataType===22,k=[{type:12,data:I},{type:12,data:y},{type:12,data:g},{type:12,data:s.blockSize},...sn(...r.map((re,ue)=>re.dims),A)],J=re=>{let ue=Lt("data",r[0].dataType,r[0].dims.length),ie=Lt("inputIndices",r[1].dataType,r[1].dims.length),Ae=Lt("scales",r[2].dataType,r[2].dims.length),$e=r.length>3?Lt("zeroPoint",r[3].dataType,r[3].dims.length):void 0,me=vn("output",O,A.length),Be=[ue,ie,Ae];$e&&Be.push($e);let je=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${re.registerUniforms(je).declareVariables(...Be,me)} ${re.mainStart()} let output_indices = ${me.offsetToIndices("global_idx")}; var indices_indices = ${ie.type.indices}(0); ${p.length>1?` for (var i: u32 = 0; i < ${p.length}; i++) { let index = ${me.indicesGet("output_indices","uniforms.gather_axis + i")}; ${ie.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${me.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${ue.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${me.indicesGet("output_indices","i")}; ${ue.indicesSet("data_indices","i","index")}; } var index_from_indices = ${ie.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${u[g]}; } ${ue.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${A.length}; i++) { let index = ${me.indicesGet("output_indices",`i + ${p.length} - 1`)}; ${ue.indicesSet("data_indices","i","index")}; } let data_offset = ${ue.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${ue.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${Q?"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 = ${Ae.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${Ae.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${Ae.getByIndices("scale_indices")}; ${$e?` let zero_point_indices = scale_indices; let zero_point_offset = ${$e.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${$e.getByOffset("zero_point_offset / 8")}; let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; let zero_point_vec = ${Q?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${ar(O)}(quantized_data - zero_point) * scale; ${me.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${s.cacheKey};${r.filter((re,ue)=>ue!==1).map(re=>re.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:r.length},(re,ue)=>"rank")},getRunData:()=>({outputs:[{dims:A,dataType:O}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:k}),getShaderSource:J}},Sf=(r,s)=>{let u=r.inputs;Mf(u,s),r.compute(Tf(r.inputs,s))},kf=r=>kn({blockSize:r.blockSize,gatherAxis:r.gatherAxis,quantizeAxis:r.quantizeAxis})}),Ef,Cf,Pf,Af,wp=c(()=>{En(),xn(),Qn(),Ln(),Ef=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.`)},Cf=(r,s)=>{let u=r[0].dims,p=r[0].dataType,m=u.length,g=r[1].dims,y=r[1].dataType,A=yt.normalizeAxis(s.axis,m),I=u[A],O=g.slice(0),Q=yt.size(O),k=Lt("input",p,m),J=Lt("indicesInput",y,g.length),re=vn("output",p,O.length),ue=[{type:12,data:Q},{type:6,data:I},{type:12,data:A}];return ue.push(...sn(u,g,O)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:O,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(Q/64)},programUniforms:ue}),getShaderSource:ie=>` ${ie.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(k,J,re)} ${ie.mainStart()} ${ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${re.offsetToIndices("global_idx")}; var idx = ${J.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${k.type.indices}(outputIndices); ${k.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${k.getByIndices("inputIndices")}; ${re.setByOffset("global_idx","value")}; }`}},Pf=r=>kn({axis:r.axis}),Af=(r,s)=>{let u=r.inputs;Ef(u),r.compute(Cf(r.inputs,s))}}),$f,If,Ff,Of,bp=c(()=>{En(),xn(),Ln(),$f=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")},If=(r,s)=>{let u=r[0].dims.slice(),p=r[1].dims.slice(),[m,g,y]=er.getShapeOfGemmResult(u,s.transA,p,s.transB,r.length===3?r[2].dims:void 0),A=[m,g];if(!A)throw new Error("Can't use gemm on the given tensors");let I=yt.size(A),O=[{type:12,data:I},{type:12,data:m},{type:12,data:g},{type:12,data:y},{type:1,data:s.alpha},{type:1,data:s.beta}],Q=["type","type"];r.length===3&&(O.push(...sn(r[2].dims)),Q.push("rank")),O.push(...sn(A));let k=J=>{let re="";s.transA&&s.transB?re="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":s.transA&&!s.transB?re="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!s.transA&&s.transB?re="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!s.transA&&!s.transB&&(re="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let ue=s.alpha===1?"":"value *= uniforms.alpha;",ie=Lt("a",r[0].dataType,r[0].dims),Ae=Lt("b",r[1].dataType,r[1].dims),$e=ie.type.value,me=null,Be=[ie,Ae];r.length===3&&(me=Lt("c",r[2].dataType,r[2].dims.length),Be.push(me));let je=vn("output",r[0].dataType,A.length);Be.push(je);let et=[{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` ${J.registerUniforms(et).declareVariables(...Be)} ${J.mainStart()} ${J.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${$e}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${re} } ${ue} ${me!=null?`let cOffset = ${me.broadcastedIndicesToOffset("vec2(m, n)",je)}; value += ${$e}(uniforms.beta) * ${me.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${s.cacheKey}`,inputDependencies:Q},getRunData:()=>({outputs:[{dims:A,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:O}),getShaderSource:k}},Ff=r=>{let s=r.transA,u=r.transB,p=r.alpha,m=r.beta;return{transA:s,transB:u,alpha:p,beta:m,cacheKey:`${r.transA};${r.transB};${r.alpha===1}`}},Of=(r,s)=>{$f(r.inputs),r.compute(If(r.inputs,s))}}),Ii,xp,Mp,Df,Tp,Jl,Sp,kp=c(()=>{En(),xn(),Qn(),ye(),Ge(),Ln(),mo(),Ii=(r,s)=>r.length>s&&r[s].dims.length>0?r[s]:void 0,xp=(r,s)=>{let u=r[0],p=Ii(r,1),m=Ii(r,2),g=Ii(r,3),y=Ii(r,4),A=Ii(r,5),I=Ii(r,6),O=Ii(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 Q=u.dims[0],k=u.dims[1],J=u.dims.length===3?u.dims[2]:s.numHeads*u.dims[4],re=k,ue=0,ie=0,Ae=Math.floor(J/s.numHeads);if(I&&O&&yt.size(I.dims)&&yt.size(O.dims)){if(I.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(I.dims[0]!==Q||I.dims[1]!==s.numHeads||I.dims[3]!==Ae)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(O.dims[0]!==Q||O.dims[1]!==s.numHeads||O.dims[3]!==Ae)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(I.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');ue=I.dims[2],ie=I.dims[2]}else if(I&&yt.size(I.dims)||O&&yt.size(O.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let $e;if(p&&yt.size(p.dims)>0){if(u.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(p.dims.length<3||p.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(u.dims[0]!==p.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(p.dims.length===3){if(p.dims[2]!==u.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');$e=2,re=p.dims[1]}else if(p.dims.length===5){if(p.dims[2]!==s.numHeads||p.dims[3]!==2||p.dims[4]!==Ae)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(m)throw new Error('Expect "value" be none when "key" has packed kv format.');$e=5,re=p.dims[1]}else{if(p.dims[1]!==s.numHeads||p.dims[3]!==Ae)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$e=0,re=p.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');$e=3}if(g&&yt.size(g.dims)>0){if(g.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(p&&p.dims.length===5&&p.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let me=ue+re,Be=0;if(y&&yt.size(y.dims)>0){Be=8;let It=y.dims;throw It.length===1?It[0]===Q?Be=1:It[0]===3*Q+2&&(Be=3):It.length===2&&It[0]===Q&&It[1]===me&&(Be=5),Be===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let je=!1,et=J;if(m&&yt.size(m.dims)>0){if(m.dims.length!==3&&m.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(u.dims[0]!==m.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(m.dims.length===3){if(re!==m.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');et=m.dims[2]}else{if(re!==m.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');et=m.dims[1]*m.dims[3],je=!0}}let Ot=!1;if(y&&yt.size(y.dims)>0)throw new Error("Key padding mask is not supported");if(A&&yt.size(A.dims)>0){if(A.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(A.dims[0]!==Q||A.dims[1]!==s.numHeads||A.dims[2]!==k||A.dims[3]!==me)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:Q,sequenceLength:k,pastSequenceLength:ue,kvSequenceLength:re,totalSequenceLength:me,maxSequenceLength:ie,inputHiddenSize:0,hiddenSize:J,vHiddenSize:et,headSize:Ae,vHeadSize:Math.floor(et/s.numHeads),numHeads:s.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:s.maskFilterValue,maskType:Be,scale:s.scale,broadcastResPosBias:Ot,passPastInKv:je,qkvFormat:$e}},Mp=r=>kn({...r}),Df=kn({perm:[0,2,1,3]}),Tp=(r,s,u,p,m,g,y)=>{let A=[p,m,g],I=yt.size(A),O=[{type:12,data:I},{type:12,data:y},{type:12,data:g}],Q=k=>{let J=vn("qkv_with_bias",s.dataType,A),re=Lt("qkv",s.dataType,A),ue=Lt("bias",u.dataType,A),ie=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${k.registerUniforms(ie).declareVariables(re,ue,J)} ${k.mainStart()} ${k.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:A,dataType:s.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:O}),getShaderSource:Q},{inputs:[s,u],outputs:[-1]})[0]},Jl=(r,s,u,p,m,g,y,A)=>{let I=g;if(y&&yt.size(y.dims)>0){if(p===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return I=Tp(r,g,y,s,p,u*m,A),I=I.reshape([s,p,u,m]),r.compute(Ai(I,Df.perm),{inputs:[I],outputs:[-1]})[0]}else return g.dims.length===3&&(I=g.reshape([s,p,u,m])),r.compute(Ai(I,Df.perm),{inputs:[I],outputs:[-1]})[0]},Sp=(r,s)=>{let u=xp(r.inputs,s),p=r.inputs[0],m=Ii(r.inputs,1),g=Ii(r.inputs,2),y=Ii(r.inputs,3),A=Ii(r.inputs,4),I=Ii(r.inputs,5),O=Ii(r.inputs,6),Q=Ii(r.inputs,7);if(p.dims.length===5)throw new Error("Packed QKV is not implemented");if(m?.dims.length===5)throw new Error("Packed KV is not implemented");let k=m&&g&&m.dims.length===4&&g.dims.length===4,J=Jl(r,u.batchSize,u.numHeads,u.sequenceLength,u.headSize,p,y,0);if(k)return Me(r,J,m,g,A,void 0,O,Q,I,u,s);if(!m||!g)throw new Error("key and value must be provided");let re=Jl(r,u.batchSize,u.numHeads,u.kvSequenceLength,u.headSize,m,y,u.hiddenSize),ue=Jl(r,u.batchSize,u.numHeads,u.kvSequenceLength,u.vHeadSize,g,y,2*u.hiddenSize);Me(r,J,re,ue,A,void 0,O,Q,I,u,s)}}),zf,Ep,Cp,Rf,Pp,Ap=c(()=>{En(),xn(),Ln(),zf=r=>Array.from(r.getBigInt64Array(),Number),Ep=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(zf(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")},Cp=(r,s)=>{let u=[];for(let p=0;p{let u=r[0].dims,p=s??zf(r[1]),m=Cp(u,p),g=yt.size(m),y=r[0].dataType,A=Lt("input",y,u.length),I=vn("output",y,m.length),O=Q=>` const inputShape = ${A.indices(...u)}; ${Q.registerUniform("output_size","u32").declareVariables(A,I)} ${Q.mainStart()} ${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${I.offsetToIndices("global_idx")}; var input_indices: ${A.type.indices}; for (var i = 0; i < ${u.length}; i++) { let input_dim_i = ${A.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${I.indicesGet("output_indices","i")} % input_dim_i; ${A.indicesSet("input_indices","i","input_dim_value")} } ${I.setByOffset("global_idx",A.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${p}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:m,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...sn(r[0].dims,m)]}),getShaderSource:O}},Pp=r=>{Ep(r.inputs),r.compute(Rf(r.inputs),{inputs:[0]})}}),$p,Lf,Ip,Fp,Bf,Op,e_=c(()=>{En(),xn(),Qn(),Ge(),Ln(),kp(),Ap(),mo(),$p=(r,s)=>{let u=r[0],p=r[1],m=r[2],g=r[3],y=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 A=!1,I=u.dims[0],O=u.dims[1],Q=u.dims.length===3?A?u.dims[2]/3:u.dims[2]:s.numHeads*u.dims[4],k=O,J=0,re=0,ue=Math.floor(Q/s.numHeads),ie=g&&g.dims.length!==0,Ae=y&&y.dims.length!==0,$e=!0;if(ie&&Ae){if(g.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(y.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');J=g.dims[1],re=g.dims[1]}else if(ie||Ae)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let me;if(p){if(u.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(p.dims.length<3||p.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(u.dims[0]!==p.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(p.dims.length===3){if(u.dims[2]%p.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');me=2,k=p.dims[1]}else if(p.dims.length===5){if(p.dims[2]!==s.numHeads||p.dims[3]!==2||p.dims[4]!==ue)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(m)throw new Error('Expect "value" be none when "key" has packed kv format.');me=5,k=p.dims[1]}else{if(p.dims[1]!==s.numHeads||p.dims[3]!==ue)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');me=0,k=p.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');me=3}let Be=0,je=!1,et=Q;if(m){if(m.dims.length!==3&&m.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(u.dims[0]!==m.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(m.dims.length===3){if(k!==m.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');et=m.dims[2]}else{if(k!==m.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');et=m.dims[1]*m.dims[3],je=!0}}let Ot=J+k;return{batchSize:I,sequenceLength:O,pastSequenceLength:J,kvSequenceLength:k,totalSequenceLength:Ot,maxSequenceLength:re,inputHiddenSize:0,hiddenSize:Q,vHiddenSize:et,headSize:ue,vHeadSize:Math.floor(et/s.kvNumHeads),numHeads:s.numHeads,kvNumHeads:s.kvNumHeads,nReps:s.numHeads/s.kvNumHeads,pastPresentShareBuffer:!1,maskType:Be,scale:s.scale,broadcastResPosBias:!1,passPastInKv:je,qkvFormat:me,isPastkvBSNH:$e}},Lf=(r,s,u,p)=>{let m=[p.batchSize,p.totalSequenceLength,p.kvNumHeads,p.headSize],g=4,y=yt.size(m)/g,A=p.totalSequenceLength,I=vn("present_kv",u,m.length,g),O=Lt("new_kv",r.dataType,r.dims.length,g),Q=s?Lt("past_kv",s.dataType,s.dims.length,g):void 0,k=Math.ceil(p.headSize/g),J={x:A,y:r.dims[0],z:1},re=s?["rank","rank"]:["rank"],ue=[{type:12,data:y},{type:12,data:p.pastSequenceLength},{type:12,data:p.kvSequenceLength},{type:12,data:p.totalSequenceLength}],ie=[O];Q?(ue.push(...sn(r.dims),...sn(s.dims),...sn(m)),ie.push(Q)):ue.push(...sn(r.dims),...sn(m));let Ae=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],$e=` 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];`,me=` 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];`,Be=s?`if (s < past_seqlen) { ${$e} } else if (s < past_seqlen + uniforms.new_seqlen) { ${me} }`:`if (s < past_seqlen + uniforms.new_seqlen) { ${me} }`,je=et=>` ${et.registerUniforms(Ae).declareVariables(...ie,I)} ${et.mainStart([k,p.kvNumHeads,1])} ${et.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var indices = ${I.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 = ${p.kvNumHeads}u; let H = ${k}u; let present_seqlen = uniforms.present_seqlen; let present_batch_stride = present_seqlen * num_heads * H; var row_stride = H; let is_bsnh = ${p.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; ${Be} }`;return{name:"ConcatPastNew",shaderCache:{hint:`${p.kvNumHeads}${k}${!!s}`,inputDependencies:re},getRunData:()=>({outputs:[{dims:m,dataType:u}],dispatchGroup:J,programUniforms:ue}),getShaderSource:je}},Ip=r=>kn({...r}),Fp=kn({perm:[0,2,1,3]}),Bf=(r,s,u,p,m)=>{let g=s,y=p.kvNumHeads,A=p.nReps;return s.dims.length===3&&p.kvSequenceLength!==0&&(g=s.reshape([p.batchSize,p.kvSequenceLength,y,p.headSize])),u?g=r.compute(Lf(g,u,g.dataType,p),{inputs:[g,u],outputs:[p.isPastkvBSNH?m:-1]})[0]:g=r.compute(Lf(g,void 0,g.dataType,p),{inputs:[g],outputs:[p.isPastkvBSNH?m:-1]})[0],A!==1&&(g=r.compute(Rf([g],[1,1,1,A]),{inputs:[g],outputs:[-1]})[0],g=g.reshape([p.batchSize,p.totalSequenceLength,y*A,p.headSize])),r.compute(Ai(g,Fp.perm),{inputs:[g],outputs:[-1]})[0]},Op=(r,s)=>{let u=$p(r.inputs,s);if(r.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(r.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let p=Jl(r,u.batchSize,u.numHeads,u.sequenceLength,u.headSize,r.inputs[0],void 0,0),m=r.inputs[3]&&r.inputs[3].dims.length!==0?r.inputs[3]:void 0,g=r.inputs[4]&&r.inputs[4].dims.length!==0?r.inputs[4]:void 0,y=Bf(r,r.inputs[1],m,u,1),A=Bf(r,r.inputs[2],g,u,2);Me(r,p,y,A,void 0,void 0,void 0,void 0,void 0,u,s)}}),Dp,zp,Rp,Lp,t_=c(()=>{En(),xn(),Ln(),Dp=(r,s)=>{let u=r[0].dims,p=u,m=2,g=yt.sizeToDimension(u,m),y=yt.sizeFromDimension(u,m),A=tr(y),I=y/A,O=[u[0],u[1],I],Q=["rank","type","type"],k=[{type:12,data:y},{type:12,data:I}];k.push(...sn(O,O));let J=re=>{let ue=Lt("x",r[0].dataType,O.length,A),ie=Lt("scale",r[1].dataType,r[1].dims),Ae=Lt("bias",r[2].dataType,r[2].dims),$e=vn("output",r[0].dataType,O.length,A),me=[ue,ie,Ae,$e],Be=ue.type.value,je=A===1?"f32":`vec${A}`,et=64,Ot=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${je}, ${et}>; const workgroupSize = ${et}u; ${re.registerUniforms(Ot).declareVariables(...me)} ${re.mainStart(et)} 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 = ${je}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${je}(${ue.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 = ${Pi("workgroupShared[0]",A)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${je}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${je}(${ue.get("batch","channel","h")}) - ${je}(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 = ${Pi("workgroupShared[0]",A)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${s.epsilon})); let channelScale = invStdDev * f32(${ie.getByOffset("channel")}); let channelShift = f32(${Ae.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${ue.get("batch","channel","h")} * ${Be}(${je}(channelScale)) + ${Be}(${je}(channelShift)); ${$e.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${s.epsilon};${A}`,inputDependencies:Q},getRunData:()=>({outputs:[{dims:p,dataType:r[0].dataType}],dispatchGroup:{x:g},programUniforms:k}),getShaderSource:J}},zp=(r,s,u,p,m,g,y,A)=>{let I=tr(y),O=64,Q=I===1?"vec2f":`mat2x${I}f`,k=I===1?"f32":`vec${I}f`,J=(Ot,It)=>`${Q}(${Ot}, ${It})`,re=m*y/I,ue=Math.ceil(g/O),ie=["type"],Ae=[{type:12,data:ue},{type:12,data:g},{type:12,data:Math.floor(y/I)},{type:12,data:Math.floor(g*y/I)}],$e=Ot=>{let It=Lt("input",s.dataType,s.dims,I);return` ${Ot.declareVariables(It)} @group(0) @binding(1) var output : array<${Q}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${Ot.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 = ${pr("f32",I)}; var squaredSum = ${pr("f32",I)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${k}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${J("sum","squaredSum")}; }`},me=r.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${I}`,inputDependencies:ie},getRunData:()=>({outputs:[{dims:[m,y,O,2],dataType:1}],dispatchGroup:{x:m*y/I},programUniforms:Ae}),getShaderSource:$e},{inputs:[s],outputs:[-1]})[0],Be=[{type:12,data:re},{type:12,data:g},{type:12,data:Math.floor(y/I)},{type:12,data:Math.floor(O*y/I)}],je=["type","type","type"],et=Ot=>{let It=Lt("scale",u.dataType,u.dims,I),Kt=Lt("bias",p.dataType,p.dims,I);return` @group(0) @binding(0) var input : array<${Q}>; @group(0) @binding(1) var scale : array<${It.type.storage}>; @group(0) @binding(2) var bias : array<${Kt.type.storage}>; @group(0) @binding(3) var output : array<${Q}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${Ot.mainStart()} ${Ot.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 = ${pr("f32",I)}; var squaredSum = ${pr("f32",I)}; 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(${A})); let channelScale = invStdDev * ${k}(scale[currentChannelNumber]); let channelShift = ${k}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${J("channelScale","channelShift")}; }`};return r.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${I};${A}`,inputDependencies:je},getRunData:()=>({outputs:[{dims:[m,y,2],dataType:1}],dispatchGroup:{x:Math.ceil(re/64)},programUniforms:Be}),getShaderSource:et},{inputs:[me,u,p],outputs:[-1]})[0]},Rp=(r,s,u)=>{let p=s[0].dims,m=p,g=p[0],y=p[p.length-1],A=yt.sizeFromDimension(p,1)/y,I=tr(y),O=yt.size(m)/I,Q=[{type:12,data:A},{type:12,data:Math.floor(y/I)}],k=["type","type"],J=zp(r,s[0],s[1],s[2],g,A,y,u.epsilon),re=ue=>{let ie=or(s[0].dataType),Ae=I===1?"vec2f":`mat2x${I}f`,$e=I===1?ie:`vec${I}<${ie}>`,me=Lt("input",s[0].dataType,s[0].dims,I),Be=vn("output",s[0].dataType,m,I);return` @group(0) @binding(0) var input : array<${me.type.storage}>; @group(0) @binding(1) var scaleInput : array<${Ae}>; @group(0) @binding(2) var output : array<${Be.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${ue.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], ${$e}(scale[0]), ${$e}(scale[1])); }`};r.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${I}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:m,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:Q}),getShaderSource:re},{inputs:[s[0],J]})},Lp=(r,s)=>{s.format==="NHWC"?Rp(r,r.inputs,s):r.compute(Dp(r.inputs,s))}}),Bp,Np,jp,n_=c(()=>{En(),xn(),Ln(),Bp=r=>{if(!r||r.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Np=(r,s,u)=>{let p=s.simplified,m=r[0].dims,g=r[1],y=!p&&r[2],A=m,I=yt.normalizeAxis(s.axis,m.length),O=yt.sizeToDimension(m,I),Q=yt.sizeFromDimension(m,I),k=yt.size(g.dims),J=y?yt.size(y.dims):0;if(k!==Q||y&&J!==Q)throw new Error(`Size of X.shape()[axis:] == ${Q}. Size of scale and bias (if provided) must match this. Got scale size of ${k} and bias size of ${J}`);let re=[];for(let et=0;et1,me=u>2,Be=et=>{let Ot=or(r[0].dataType),It=[Lt("x",r[0].dataType,r[0].dims,ue),Lt("scale",g.dataType,g.dims,ue)];y&&It.push(Lt("bias",y.dataType,y.dims,ue)),It.push(vn("output",r[0].dataType,A,ue)),$e&&It.push(vn("mean_data_output",1,re)),me&&It.push(vn("inv_std_output",1,re));let Kt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${et.registerUniforms(Kt).declareVariables(...It)} ${et.mainStart()} ${et.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${pr("f32",ue)}; var mean_square_vector = ${pr("f32",ue)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Ir(Ot,ue,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Pi("mean_vector",ue)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Pi("mean_square_vector",ue)} / uniforms.norm_size ${p?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Ir(Ot,ue,"x[j + offset]")}; let f32scale = ${Ir(Ot,ue,"scale[j]")}; output[j + offset] = ${It[0].type.value}((f32input ${p?"":"- mean"}) * inv_std_dev * f32scale ${y?`+ ${Ir(Ot,ue,"bias[j]")}`:""} ); } ${$e?"mean_data_output[global_idx] = mean":""}; ${me?"inv_std_output[global_idx] = inv_std_dev":""}; }`},je=[{dims:A,dataType:r[0].dataType}];return $e&&je.push({dims:re,dataType:1}),me&&je.push({dims:re,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${ue};${u};${p}`,inputDependencies:ie},getRunData:()=>({outputs:je,dispatchGroup:{x:Math.ceil(O/64)},programUniforms:Ae}),getShaderSource:Be}},jp=(r,s)=>{Bp(r.inputs),r.compute(Np(r.inputs,s,r.outputCount))}}),Yn,Nf,di,_i,Fi=c(()=>{En(),xn(),Qn(),Ln(),Yn=(r,s)=>{if(r.length<3||r.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let u=r[0],p=u.dims.length;if(u.dims[p-1]!==s.k)throw new Error("The last dim of input shape does not match the k value");let m=Math.floor((s.k+s.blockSize-1)/s.blockSize),g=s.blockSize/8*s.bits,y=r[1];if(!yt.areEqual(y.dims,[s.n,m,g]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let A=r[2].dims;if(yt.size(A)!==s.n*m)throw new Error("scales input size error.");if(r.length===4){let I=r[3].dims,O=s.bits>4?s.n*m:s.n*Math.floor((m+1)/2);if(yt.size(I)!==O)throw new Error("zeroPoints input size error.")}},Nf=(r,s)=>{let u=r[0].dims,p=u.length,m=u[p-2],g=s.k,y=s.n,A=u.slice(0,p-2),I=yt.size(A),O=r[1].dims[2]/4,Q=r[0].dataType,k=tr(s.k),J=tr(O),re=tr(y),ue=A.concat([m,y]),ie=m>1&&y/re%2===0?2:1,Ae=yt.size(ue)/re/ie,$e=64,me=[],Be=[I,m,g/k],je=yt.convertShape(r[1].dims).slice();je.splice(-1,1,O/J),me.push(...sn(Be)),me.push(...sn(je)),me.push(...sn(r[2].dims)),r.length===4&&me.push(...sn(yt.convertShape(r[3].dims)));let et=[I,m,y/re];me.push(...sn(et));let Ot=It=>{let Kt=Be.length,yn=Lt("a",r[0].dataType,Kt,k),_n=Lt("b",12,je.length,J),Zn=Lt("scales",r[2].dataType,r[2].dims.length),Gn=[yn,_n,Zn],lr=r.length===4?Lt("zero_points",12,r[3].dims.length):void 0;lr&&Gn.push(lr);let _r=et.length,ir=vn("output",r[0].dataType,_r,re),On=or(r[0].dataType),yr=(()=>{switch(k){case 1:return`array<${On}, 8>`;case 2:return`mat4x2<${On}>`;case 4:return`mat2x4<${On}>`;default:throw new Error(`${k}-component is not supported.`)}})(),Pr=()=>{let Rt=` // reuse a data var input_offset = ${yn.indicesToOffset(`${yn.type.indices}(batch, row, word_offset)`)}; var a_data: ${yr}; for (var j: u32 = 0; j < ${8/k}; j++) { a_data[j] = ${yn.getByOffset("input_offset")}; input_offset++; } `;for(let ln=0;ln> 4) & b_mask); b_quantized_values = ${yr}(${Array.from({length:4},(Jn,Br)=>`${On}(b_value_lower[${Br}]), ${On}(b_value_upper[${Br}])`).join(", ")}); b_dequantized_values = ${k===1?`${yr}(${Array.from({length:8},(Jn,Br)=>`(b_quantized_values[${Br}] - ${lr?`zero_point${ln}`:"zero_point"}) * scale${ln}`).join(", ")});`:`(b_quantized_values - ${yr}(${Array(8).fill(`${lr?`zero_point${ln}`:"zero_point"}`).join(",")})) * scale${ln};`}; workgroup_shared[local_id.x * ${ie} + ${Math.floor(ln/re)}]${re>1?`[${ln%re}]`:""} += ${Array.from({length:8/k},(Jn,Br)=>`${k===1?`a_data[${Br}] * b_dequantized_values[${Br}]`:`dot(a_data[${Br}], b_dequantized_values[${Br}])`}`).join(" + ")}; `;return Rt},Nn=()=>{let Rt=` var col_index = col * ${re}; ${lr?` 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 = ${On}(8);`} `;for(let ln=0;ln> 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 = ${lr.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${ln} = ${On}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return Rt},ur=()=>{let Rt=`col_index = col * ${re};`;for(let ln=0;ln; var b_value_upper: vec4; var b_quantized_values: ${yr}; var b_dequantized_values: ${yr};`,Rt};return` var workgroup_shared: array<${ir.type.value}, ${ie*$e}>; ${It.declareVariables(...Gn,ir)} ${It.mainStart([$e,1,1])} let output_indices = ${ir.offsetToIndices(`(global_idx / ${$e}) * ${ie}`)}; 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 += ${$e}) { //process one block var word_offset: u32 = block * ${s.blockSize/k}; ${Nn()} for (var word: u32 = 0; word < ${O}; word += ${J}) { ${ur()} for (var i: u32 = 0; i < ${J}; i++) { ${Pr()} word_offset += ${8/k}; } } } workgroupBarrier(); if (local_id.x < ${ie}) { var output_value: ${ir.type.value} = ${ir.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${$e}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${ie}; } ${ir.setByIndices(`${ir.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${s.blockSize};${s.bits};${k};${J};${re};${ie};${$e}`,inputDependencies:Array(r.length).fill("rank")},getRunData:()=>({outputs:[{dims:ue,dataType:Q}],dispatchGroup:{x:Ae},programUniforms:me}),getShaderSource:Ot}},di=(r,s)=>{Yn(r.inputs,s),r.compute(Nf(r.inputs,s))},_i=r=>kn(r)}),Ko,Vp,jf,Vf,X,R,be,Ue,Ct,Bt=c(()=>{En(),xn(),Ln(),Ko=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].")}},Vp=(r,s,u)=>{let p="";for(let m=s-1;m>=0;--m)p+=` k = i32(${r.indicesGet("indices",m)}) - ${pn("uniforms.pads",m,u)}; if (k < 0) { break; } if (k >= i32(${pn("uniforms.x_shape",m,s)})) { break; } offset += k * i32(${pn("uniforms.x_strides",m,s)}); `;return` value = ${r.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${p} value = x[offset]; } `},jf=(r,s,u)=>{let p="";for(let m=s-1;m>=0;--m)p+=` k = i32(${r.indicesGet("indices",m)}) - ${pn("uniforms.pads",m,u)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${pn("uniforms.x_shape",m,s)}) - 1); k = k % _2n_1; if(k >= i32(${pn("uniforms.x_shape",m,s)})) { k = _2n_1 - k; } } offset += k * i32(${pn("uniforms.x_strides",m,s)}); `;return` var offset = 0; var k = 0; ${p} value = x[offset]; `},Vf=(r,s,u)=>{let p="";for(let m=s-1;m>=0;--m)p+=` k = i32(${r.indicesGet("indices",m)}) - ${pn("uniforms.pads",m,u)}; if (k < 0) { k = 0; } if (k >= i32(${pn("uniforms.x_shape",m,s)})) { k = i32(${pn("uniforms.x_shape",m,s)}) - 1; } offset += k * i32(${pn("uniforms.x_strides",m,s)}); `;return` var offset = 0; var k = 0; ${p} value = x[offset]; `},X=(r,s,u)=>{let p="";for(let m=s-1;m>=0;--m)p+=` k = i32(${r.indicesGet("indices",m)}) - ${pn("uniforms.pads",m,u)}; if (k < 0) { k += i32(${pn("uniforms.x_shape",m,s)}]); } if (k >= i32(${pn("uniforms.x_shape",m,s)})) { k -= i32(${pn("uniforms.x_shape",m,s)}); } offset += k * i32(${pn("uniforms.x_strides",m,s)}); `;return` var offset = 0; var k = 0; ${p} value = x[offset]; `},R=(r,s,u)=>{switch(u.mode){case 0:return Vp(r,s,u.pads.length);case 1:return jf(r,s,u.pads.length);case 2:return Vf(r,s,u.pads.length);case 3:return X(r,s,u.pads.length);default:throw new Error("Invalid mode")}},be=(r,s)=>{let u=yt.padShape(r[0].dims.slice(),s.pads),p=r[0].dims,m=yt.size(u),g=[{type:12,data:m},{type:6,data:s.pads}],y=r.length>=3&&r[2].data;s.mode===0&&g.push({type:y?r[2].dataType:1,data:s.value}),g.push(...sn(r[0].dims,u));let A=["rank"],I=O=>{let Q=vn("output",r[0].dataType,u.length),k=Lt("x",r[0].dataType,p.length),J=k.type.value,re=R(Q,p.length,s),ue=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:s.pads.length}];return s.mode===0&&ue.push({name:"constant_value",type:y?J:"f32"}),` ${O.registerUniforms(ue).declareVariables(k,Q)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${Q.offsetToIndices("global_idx")}; var value = ${J}(0); ${re} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${s.mode}${y}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(yt.size(u)/64)},programUniforms:g}),getShaderSource:I}},Ue=(r,s)=>{if(r.length>1){let u=r[1].getBigInt64Array(),p=r.length>=3&&r[2].data?r[2].dataType===10?r[2].getUint16Array()[0]:r[2].getFloat32Array()[0]:0,m=r[0].dims.length,g=new Int32Array(2*m).fill(0);if(r.length>=4){let A=r[3].getBigInt64Array();for(let I=0;Ig[Number(I)]=Number(A));let y=[];return g.forEach(A=>y.push(A)),{mode:s.mode,value:p,pads:y}}else return s},Ct=(r,s)=>{Ko(r.inputs);let u=Ue(r.inputs,s);r.compute(be(r.inputs,u),{inputs:[0]})}}),qt,cn,Fn,sr,gr,Tr,rr,zn,Cr,Wn,cr,Wr,fi,bo,ps,Qi,Hr,Yi,eu,tu=c(()=>{Jt(),En(),xn(),Ln(),qt=r=>{if(V.webgpu.validateInputContent&&(!r||r.length!==1))throw new Error("Pool ops requires 1 input.")},cn=(r,s,u)=>{let p=s.format==="NHWC",m=r.dims.slice();p&&m.splice(1,0,m.pop());let g=Object.hasOwnProperty.call(s,"dilations"),y=s.kernelShape.slice(),A=s.strides.slice(),I=g?s.dilations.slice():[],O=s.pads.slice();Yr.adjustPoolAttributes(u,m,y,A,I,O);let Q=Yr.computePoolOutputShape(u,m,A,I,y,O,s.autoPad),k=Object.assign({},s);g?Object.assign(k,{kernelShape:y,strides:A,pads:O,dilations:I,cacheKey:s.cacheKey}):Object.assign(k,{kernelShape:y,strides:A,pads:O,cacheKey:s.cacheKey});let J=Q.slice();return J.push(J.splice(1,1)[0]),[k,p?J:Q]},Fn=(r,s)=>{let u=s.format==="NHWC",p=yt.size(r),m=yt.size(s.kernelShape),g=[{type:12,data:p},{type:12,data:m}],y=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(s.kernelShape.length<=2){let A=s.kernelShape[s.kernelShape.length-1],I=s.strides[s.strides.length-1],O=s.pads[s.pads.length/2-1],Q=s.pads[s.pads.length-1],k=!!(O+Q);g.push({type:12,data:A},{type:12,data:I},{type:12,data:O},{type:12,data:Q}),y.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let J=!1;if(s.kernelShape.length===2){let re=s.kernelShape[s.kernelShape.length-2],ue=s.strides[s.strides.length-2],ie=s.pads[s.pads.length/2-2],Ae=s.pads[s.pads.length-2];J=!!(ie+Ae),g.push({type:12,data:re},{type:12,data:ue},{type:12,data:ie},{type:12,data:Ae}),y.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[g,y,!0,k,J]}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let A=yt.computeStrides(s.kernelShape);g.push({type:12,data:A},{type:12,data:s.pads},{type:12,data:s.strides}),y.push({name:"kernelStrides",type:"u32",length:A.length},{name:"pads",type:"u32",length:s.pads.length},{name:"strides",type:"u32",length:s.strides.length});let I=s.pads.reduce((O,Q)=>O+Q);return[g,y,!!I,!1,!1]}},sr=(r,s,u,p,m,g,y,A,I,O,Q,k)=>{let J=m.format==="NHWC",re=s.type.value,ue=vn("output",s.type.tensor,p);if(m.kernelShape.length<=2){let ie="",Ae="",$e="",me=u-(J?2:1);if(Q?ie=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${me}] = indices[${me}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${me}] < 0 || xIndices[${me}] >= uniforms.x_shape[${me}]) { pad++; continue; } let x_val = x[${s.indicesToOffset("xIndices")}]; ${g} }`:ie=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${me}] = indices[${me}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${s.indicesToOffset("xIndices")}]; ${g} }`,m.kernelShape.length===2){let Be=u-(J?3:2);k?Ae=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${Be}] = indices[${Be}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${Be}] < 0 || xIndices[${Be}] >= uniforms.x_shape[${Be}]) { pad += i32(uniforms.kw); continue; } `:Ae=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${Be}] = indices[${Be}] * uniforms.sh - uniforms.phStart + j; `,$e=` } `}return` ${r.registerUniforms(I).declareVariables(s,ue)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${ue.offsetToIndices("global_idx")}; var xIndices = ${ue.offsetToIndices("global_idx")}; var value = ${re}(${A}); var pad = 0; ${Ae} ${ie} ${$e} ${y} output[global_idx] = value; }`}else{if(J)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let ie=m.kernelShape.length,Ae=m.pads.length,$e="";return O?$e=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${s.indicesToOffset("xIndices")}]; ${g} }`:$e=` } let x_val = x[${s.indicesToOffset("xIndices")}]; ${g} `,` ${r.registerUniforms(I).declareVariables(s,ue)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${ue.offsetToIndices("global_idx")}; var xIndices = ${ue.offsetToIndices("global_idx")}; var offsets: array; var value = ${re}(${A}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${ie-1}u; j++) { offsets[j] = offset / ${pn("uniforms.kernelStrides","j",ie)}; offset -= offsets[j] * ${pn("uniforms.kernelStrides","j",ie)}; } offsets[${ie-1}] = offset; isPad = false; for (var j = ${u-ie}u; j < ${u}u; j++) { xIndices[j] = indices[j] * ${pn("uniforms.strides",`j - ${u-ie}u`,ie)} + offsets[j - ${u-ie}u] - ${pn("uniforms.pads","j - 2u",Ae)}; ${$e} } ${y} output[global_idx] = value; }`}},gr=r=>`${r.format};${r.ceilMode};${r.autoPad};${r.kernelShape.length}`,Tr=r=>`${gr(r)};${r.countIncludePad}`,rr=r=>`${gr(r)};${r.storageOrder};${r.dilations}`,zn=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}),Cr=(r,s,u,p)=>{let[m,g]=cn(s,p,u),y=Lt("x",s.dataType,s.dims.length),A=y.type.value,I="value += x_val;",O="";m.countIncludePad?O+=`value /= ${A}(uniforms.kernelSize);`:O+=`value /= ${A}(i32(uniforms.kernelSize) - pad);`;let[Q,k,J,re,ue]=Fn(g,m);Q.push(...sn(s.dims,g));let ie=["rank"];return{name:r,shaderCache:{hint:`${p.cacheKey};${J};${re};${ue}`,inputDependencies:ie},getRunData:()=>({outputs:[{dims:g,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(yt.size(g)/64)},programUniforms:Q}),getShaderSource:Ae=>sr(Ae,y,s.dims.length,g.length,m,I,O,0,k,J,re,ue)}},Wn=r=>{let s=r.count_include_pad!==0,u=zn(r);if(u.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let p={countIncludePad:s,...u,cacheKey:""};return{...p,cacheKey:Tr(p)}},cr=(r,s)=>{qt(r.inputs),r.compute(Cr("AveragePool",r.inputs[0],!1,s))},Wr={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},fi=r=>{let s=r.format;return{format:s,...Wr,cacheKey:s}},bo=(r,s)=>{qt(r.inputs),r.compute(Cr("GlobalAveragePool",r.inputs[0],!0,s))},ps=(r,s,u,p)=>{let[m,g]=cn(s,p,u),y=` value = max(x_val, value); `,A="",I=Lt("x",s.dataType,s.dims.length),O=["rank"],[Q,k,J,re,ue]=Fn(g,m);return Q.push(...sn(s.dims,g)),{name:r,shaderCache:{hint:`${p.cacheKey};${J};${re};${ue}`,inputDependencies:O},getRunData:()=>({outputs:[{dims:g,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(yt.size(g)/64)},programUniforms:Q}),getShaderSource:ie=>sr(ie,I,s.dims.length,g.length,m,y,A,s.dataType===10?-65504:-1e5,k,J,re,ue)}},Qi=(r,s)=>{qt(r.inputs),r.compute(ps("MaxPool",r.inputs[0],!1,s))},Hr=r=>{let s=r.storage_order,u=r.dilations,p=zn(r);if(s!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(p.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let m={storageOrder:s,dilations:u,...p,cacheKey:""};return{...m,cacheKey:rr(m)}},Yi=r=>{let s=r.format;return{format:s,...Wr,cacheKey:s}},eu=(r,s)=>{qt(r.inputs),r.compute(ps("GlobalMaxPool",r.inputs[0],!0,s))}}),r_,Os,Ma,Up,i_=c(()=>{En(),xn(),Qn(),Ln(),r_=(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,p)=>u===r[2].dims[p]).reduce((u,p)=>u&&p,!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((m,g)=>g===s.axis||m===r[0].dims[g]).reduce((m,g)=>m&&g,!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],p=r[1].dims[s.axis];if(s.blockSizeMath.ceil(u/(p-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Os=(r,s)=>{let u=yt.normalizeAxis(s.axis,r[0].dims.length),p=r[0].dataType,m=p===3,g=r[0].dims,y=r[1].dataType,A=yt.size(g),I=p===3||p===2,O=I?[Math.ceil(yt.size(r[0].dims)/4)]:r[0].dims,Q=r[1].dims,k=r.length>2?r[2]:void 0,J=k?I?[Math.ceil(yt.size(k.dims)/4)]:k.dims:void 0,re=Q.length===0||Q.length===1&&Q[0]===1,ue=re===!1&&Q.length===1,ie=tr(A),Ae=re&&(!I||ie===4),$e=Ae?ie:1,me=Ae&&!I?ie:1,Be=Lt("input",I?12:p,O.length,me),je=Lt("scale",y,Q.length),et=k?Lt("zero_point",I?12:p,J.length):void 0,Ot=vn("output",y,g.length,$e),It=[Be,je];et&&It.push(et);let Kt=[O,Q];k&&Kt.push(J);let yn=[{type:12,data:A/$e},{type:12,data:u},{type:12,data:s.blockSize},...sn(...Kt,g)],_n=Zn=>{let Gn=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${Zn.registerUniforms(Gn).declareVariables(...It,Ot)} ${Zn.mainStart()} ${Zn.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${Ot.offsetToIndices("global_idx")}; // Set input x ${I?` let input = ${Be.getByOffset("global_idx / 4")}; let x_vec = ${m?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${$e===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${Be.getByOffset("global_idx")};`}; // Set scale input ${re?`let scale_value= ${je.getByOffset("0")}`:ue?` let scale_index = ${Ot.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${je.getByOffset("scale_index")};`:` var scale_indices: ${je.type.indices} = output_indices; let index = ${je.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${je.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${je.getByIndices("scale_indices")};`}; // Set zero-point input ${et?re?I?` let zero_point_input = ${et.getByOffset("0")}; let zero_point_vec = ${m?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${et.getByOffset("0")}`:ue?I?` let zero_point_index = ${Ot.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${et.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${m?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${Ot.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${et.getByOffset("zero_point_index")};`:I?` let zero_point_offset = ${je.indicesToOffset("scale_indices")}; let zero_point_input = ${et.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${m?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${et.getByIndices("scale_indices")};`:`let zero_point_value = ${I?m?"i32":"u32":Be.type.value}(0);`}; // Compute and write output ${Ot.setByOffset("global_idx",`${Ot.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:s.cacheKey,inputDependencies:et?["rank","rank","rank"]:["rank","rank"]},getShaderSource:_n,getRunData:()=>({outputs:[{dims:g,dataType:y}],dispatchGroup:{x:Math.ceil(A/$e/64),y:1,z:1},programUniforms:yn})}},Ma=(r,s)=>{r_(r.inputs,s),r.compute(Os(r.inputs,s))},Up=r=>kn({axis:r.axis,blockSize:r.blockSize})}),Wp,Uf,cw,XE=c(()=>{Jt(),En(),Ln(),Wp=(r,s,u)=>{let p=r===s,m=rs&&u>0;if(p||m||g)throw new Error("Range these inputs' contents are invalid.")},Uf=(r,s,u,p)=>{let m=Math.abs(Math.ceil((s-r)/u)),g=[m],y=m,A=[{type:12,data:y},{type:p,data:r},{type:p,data:u},...sn(g)],I=O=>{let Q=vn("output",p,g.length),k=Q.type.value,J=[{name:"outputSize",type:"u32"},{name:"start",type:k},{name:"delta",type:k}];return` ${O.registerUniforms(J).declareVariables(Q)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${k}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${p}`},getShaderSource:I,getRunData:()=>({outputs:[{dims:g,dataType:p}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:A})}},cw=r=>{let s=0,u=0,p=0;r.inputs[0].dataType===6?(s=r.inputs[0].getInt32Array()[0],u=r.inputs[1].getInt32Array()[0],p=r.inputs[2].getInt32Array()[0]):r.inputs[0].dataType===1&&(s=r.inputs[0].getFloat32Array()[0],u=r.inputs[1].getFloat32Array()[0],p=r.inputs[2].getFloat32Array()[0]),V.webgpu.validateInputContent&&Wp(s,u,p),r.compute(Uf(s,u,p,r.inputs[0].dataType),{inputs:[]})}}),dw,fw,hw,pw,mw,gw,_w,yw,vw,ww,bw,s_,xw,Mw,Tw,Sw,kw,Ew,Cw,QE=c(()=>{En(),xn(),Qn(),Ln(),dw=(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")}},fw=(r,s,u)=>{s.every(m=>m>=0&&m{throw new Error("Resize requires axes input values to be positive and less than rank")}));let p=new Array(u).fill(1);return s.forEach((m,g)=>p[m]=r[g]),p},hw=(r,s,u,p,m,g)=>{let[y,A,I]=u>10?[1,2,3]:[-1,r.length>1?1:-1,-1],O=r[0].dims.length;if(y>0&&r.length>y&&r[y].dims.length>0)r[y].getFloat32Array().forEach(Q=>g.push(Q));else if(s.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(A>0&&r.length>A&&r[A].dims.length>0){if(r[A].getFloat32Array().forEach(Q=>p.push(Q)),p.length!==0&&p.length!==O&&u>=18&&p.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");dw(p,s),s.axes.length>0&&fw(p,s.axes,O).forEach((Q,k)=>p[k]=Q)}if(I>0&&r.length>I&&(r[I].getBigInt64Array().forEach(Q=>m.push(Number(Q))),m.length!==O||u>=18&&m.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(p.length!==s.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(m.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 p<"u"&&typeof m<"u"&&p.length>0&&m.length>O)throw new Error("Resize requires only of scales or sizes to be specified")},pw=(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`)}})()+"}",mw=(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`)}})()+"}",gw=(r,s,u)=>{let p=new Array(u).fill(0).concat(new Array(u).fill(1)),m=r.length===0?p:r.slice();return s.length>0?(s.forEach((g,y)=>{p[g]=m[y],p[y+u]=m[s.length+y]}),p):m},_w=(r,s,u,p)=>{let m=[];if(u.length>0)if(p.length>0){if(r.forEach(g=>m.push(g)),Math.max(...p)>r.length)throw new Error("axes is out of bound");p.forEach((g,y)=>m[g]=u[y])}else u.forEach(g=>m.push(g));else{if(s.length===0)throw new Error("Resize requires either scales or sizes.");m=r.map((g,y)=>Math.round(g*s[y]))}return m},yw=(r,s,u)=>{let p=(()=>{switch(u.keepAspectRatioPolicy){case"not_larger":return u.axes.length>0?Math.min(...u.axes.map(g=>s[g]),Number.MAX_VALUE):Math.min(...s,Number.MAX_VALUE);case"not_smaller":return u.axes.length>0?Math.max(...u.axes.map(g=>s[g]),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 m=r.slice();return u.axes.length>0?(u.axes.forEach(g=>s[g]=p),u.axes.forEach(g=>m[g]=Math.round(r[g]*s[g]))):(s.fill(p,0,s.length),m.forEach((g,y)=>m[y]=Math.round(g*s[y]))),m},vw=(r,s,u,p,m)=>` 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 = ${pn("uniforms.scales","i",p)}; var roi_low = ${pn("uniforms.roi","i",m)}; var roi_hi = ${pn("uniforms.roi",`i + ${s.length}`,m)}; if (scale == 1.0) { original_indices[i] = ${r.type.value}(output_index); } else { var input_shape_i = ${pn("uniforms.input_shape","i",s.length)}; var output_shape_i = ${pn("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; }`,ww=(r,s,u,p,m,g,y)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${s.type.indices}) -> ${r.type.indices} { var input_indices: ${r.type.indices}; for (var i:u32 = 0; i < ${p.length}; i++) { var output_index = ${s.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${pn("uniforms.scales","i",m)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${pn("uniforms.roi","i",g)}; var roi_hi = ${pn("uniforms.roi",`i + ${u.length}`,g)}; var input_shape_i = ${pn("uniforms.input_shape","i",u.length)}; var output_shape_i = ${pn("uniforms.output_shape","i",p.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${y} || (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; }`,bw=(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 >= ${pn("uniforms.input_shape","i",s.length)}) { return false; } } return true; }`,s_=(r,s,u,p)=>r.rank>p?` ${r.indicesSet("input_indices",s,"channel")}; ${r.indicesSet("input_indices",u,"batch")}; `:"",xw=(r,s,u,p,m)=>{let[g,y,A,I]=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",y,`max(0, min(row, ${u[y]} - 1))`)}; ${r.indicesSet("input_indices",A,`max(0, min(col, ${u[A]} - 1))`)}; ${s_(r,I,g,2)} return ${r.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${s.type.indices}) -> ${O} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${O} = originalIndices[${y}]; var col:${O} = originalIndices[${A}]; ${p?`if (row < 0 || row > (${u[y]} - 1) || col < 0 || col > (${u[A]} - 1)) { return ${m}; }`:""}; row = max(0, min(row, ${u[y]} - 1)); col = max(0, min(col, ${u[A]} - 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[${I}])`:"0"}; var batch: u32 = ${u.length>2?`u32(originalIndices[${g}])`:"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); }`},Mw=(r,s,u,p,m,g,y,A,I,O)=>{let Q=u.length===2,[k,J]=Q?[0,1]:[2,3],re=r.type.value,ue=ie=>{let Ae=ie===k?"row":"col";return` fn ${Ae}CubicInterpolation(input_indices: ${r.type.indices}, output_indices: ${s.type.indices}) -> ${re} { var output_index = ${s.indicesGet("output_indices",ie)}; var originalIdx: ${re} = getOriginalCoordinateFromResizedCoordinate(output_index, ${m[ie]}, ${p[ie]}, ${u[ie]}, ${g[ie]}, ${g[ie]} + ${u.length}); var fractOriginalIdx: ${re} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${A} && (originalIdx < 0 || originalIdx > (${u[ie]} - 1))) { return ${I}; } var data: array<${re}, 4> = array<${re}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${Ae}: ${re} = originalIdx + ${re}(i); if (${Ae} < 0 || ${Ae} >= ${u[ie]}) { ${O?`coefs[i + 1] = 0.0; continue;`:A?`return ${I};`:`${Ae} = max(0, min(${Ae}, ${u[ie]} - 1));`}; } var input_indices_copy: ${r.type.indices} = input_indices; ${r.indicesSet("input_indices_copy",ie,`u32(${Ae})`)}; data[i + 1] = ${ie===k?r.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${ue(k)}; ${ue(J)}; fn getCubicInterpolationCoefs(s: ${re}) -> array<${re}, 4> { var absS = abs(s); var coeffs: array<${re}, 4> = array<${re}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${re} = 1.0 - absS; var twoMinusAbsS: ${re} = 2.0 - absS; var onePlusAbsS: ${re} = 1.0 + absS; coeffs[0] = ((${y} * onePlusAbsS - 5 * ${y}) * onePlusAbsS + 8 * ${y}) * onePlusAbsS - 4 * ${y}; coeffs[1] = ((${y} + 2) * absS - (${y} + 3)) * absS * absS + 1; coeffs[2] = ((${y} + 2) * oneMinusAbsS - (${y} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${y} * twoMinusAbsS - 5 * ${y}) * twoMinusAbsS + 8 * ${y}) * twoMinusAbsS - 4 * ${y}; return coeffs; } fn cubicInterpolation1D(x: array<${re}, 4>, coefs: array<${re}, 4>) -> ${re} { var coefsSum: ${re} = 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}) -> ${re} { var input_indices: ${r.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},Tw=(r,s,u,p,m)=>{let[g,y,A,I,O]=u.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],Q=r.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${Q} { var input_indices: ${r.type.indices}; ${r.indicesSet("input_indices",y,`max(0, min(depth, ${u[y]} - 1))`)}; ${r.indicesSet("input_indices",A,`max(0, min(height, ${u[A]} - 1))`)}; ${r.indicesSet("input_indices",I,`max(0, min(width, ${u[I]} - 1))`)}; ${s_(r,O,g,3)} return ${r.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${s.type.indices}) -> ${Q} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${Q} = originalIndices[${y}]; var height:${Q} = originalIndices[${A}]; var width:${Q} = originalIndices[${I}]; ${p?`if (depth < 0 || depth > (${u[y]} - 1) || height < 0 || height > (${u[A]} - 1) || width < 0 || (width > ${u[I]} - 1)) { return ${m}; }`:""}; depth = max(0, min(depth, ${u[y]} - 1)); height = max(0, min(height, ${u[A]} - 1)); width = max(0, min(width, ${u[I]} - 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[${g}])`:"0"}; var x111: ${Q} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${Q} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${Q} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${Q} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${Q} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${Q} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${Q} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${Q} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${Q} = abs(depth - ${Q}(depth1)); var dx2: ${Q} = abs(${Q}(depth2) - depth); var dy1: ${Q} = abs(height - ${Q}(height1)); var dy2: ${Q} = abs(${Q}(height2) - height); var dz1: ${Q} = abs(width - ${Q}(width1)); var dz2: ${Q} = abs(${Q}(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); }`},Sw=(r,s,u,p,m,g)=>{let y=r.dims,A=gw(g,s.axes,y.length),I=_w(y,p,m,s.axes),O=p.slice();p.length===0&&(O=y.map((me,Be)=>me===0?1:I[Be]/me),s.keepAspectRatioPolicy!=="stretch"&&(I=yw(y,O,s)));let Q=vn("output",r.dataType,I.length),k=Lt("input",r.dataType,y.length),J=yt.size(I),re=y.length===I.length&&y.every((me,Be)=>me===I[Be]),ue=s.coordinateTransformMode==="tf_crop_and_resize",ie=s.extrapolationValue,Ae=k.type.value,$e=me=>` ${re?"":` ${pw(s.coordinateTransformMode,Ae)}; ${(()=>{switch(s.mode){case"nearest":return` ${bw(k,y)}; ${mw(s.nearestMode,u,Ae)}; ${ww(k,Q,y,I,O.length,A.length,ue)}; `;case"linear":return` ${vw(Q,y,I,O.length,A.length)}; ${(()=>{if(y.length===2||y.length===4)return`${xw(k,Q,y,ue,ie)}`;if(y.length===3||y.length===5)return`${Tw(k,Q,y,ue,ie)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(y.length===2||y.length===4)return`${Mw(k,Q,y,I,O,A,s.cubicCoeffA,ue,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")}})()}; `} ${me.registerUniform("output_size","u32").registerUniform("scales","f32",O.length).registerUniform("roi","f32",A.length).declareVariables(k,Q)} ${me.mainStart()} ${me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${re?"output[global_idx] = input[global_idx];":` let output_indices = ${Q.offsetToIndices("global_idx")}; var input_indices: ${k.type.indices}; ${(()=>{switch(s.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${k.getByIndices("input_indices")}; } else { output[global_idx] = ${s.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${y.length===2||y.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:""}|${m.length>0?m:""}|${A.length>0?A:""}|${re}|${y}`,inputDependencies:["rank"]},getShaderSource:$e,getRunData:()=>({outputs:[{dims:I,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(J/64)},programUniforms:[{type:12,data:J},{type:1,data:O},{type:1,data:A},...sn(y,I)]})}},kw=r=>{let s=r.customDataBuffer;return new Uint32Array(s,s.byteOffset,1)[0]},Ew=(r,s)=>{let u=[],p=[],m=[],g=kw(r);if(s.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");hw(r.inputs,s,g,u,p,m),r.compute(Sw(r.inputs[0],s,g,u,p,m),{inputs:[0]})},Cw=r=>{let s=r.antialias,u=r.axes,p=r.coordinateTransformMode,m=r.cubicCoeffA,g=r.excludeOutside!==0,y=r.extrapolationValue,A=r.keepAspectRatioPolicy,I=r.mode,O=r.nearestMode===""?"simple":r.nearestMode;return kn({antialias:s,axes:u,coordinateTransformMode:p,cubicCoeffA:m,excludeOutside:g,extrapolationValue:y,keepAspectRatioPolicy:A,mode:I,nearestMode:O})}}),Pw,Aw,$w,YE=c(()=>{En(),xn(),Qn(),Ln(),Pw=(r,s)=>{let[u,p,m,g]=r,{numHeads:y,rotaryEmbeddingDim:A}=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(!yt.areEqual(p.dims,[])&&!yt.areEqual(p.dims,[1])&&p.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${p.dims.length}`);if(m.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${m.dims.length}`);if(g.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${g.dims.length}`);if(!yt.areEqual(m.dims,g.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(A>0&&y===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let I=u.dims[0],O=u.dims[u.dims.length-2],Q=m.dims[0],k=yt.sizeFromDimension(u.dims,1)/O,J=A===0?m.dims[1]*2:k/y;if(A>J)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(p.dims.length===2){if(I!==p.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${p.dims[0]}`);if(O!==p.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${p.dims[1]}`)}if(J/2!==m.dims[1]&&A/2!==m.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${m.dims[1]}`);if(O>Q)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Aw=(r,s)=>{let{interleaved:u,numHeads:p,rotaryEmbeddingDim:m,scale:g}=s,y=r[0].dims[0],A=yt.sizeFromDimension(r[0].dims,1),I=r[0].dims[r[0].dims.length-2],O=A/I,Q=r[2].dims[1],k=m===0?Q*2:O/p,J=new Array(y,I,O/k,k-Q),re=yt.computeStrides(J),ue=[{type:1,data:g},{type:12,data:J},{type:12,data:re},...r[0].dims.length===3?new Array({type:12,data:[A,O,k,1]}):[],...r[0].dims.length===4?new Array({type:12,data:[A,k,I*k,1]}):[],...sn(r[0].dims,r[1].dims,r[2].dims,r[3].dims,r[0].dims)],ie=Ae=>{let $e=Lt("input",r[0].dataType,r[0].dims.length),me=Lt("position_ids",r[1].dataType,r[1].dims.length),Be=Lt("cos_cache",r[2].dataType,r[2].dims.length),je=Lt("sin_cache",r[3].dataType,r[3].dims.length),et=vn("output",r[0].dataType,r[0].dims.length);return Ae.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:J.length},{name:"global_strides",type:"u32",length:re.length},{name:"input_output_strides",type:"u32",length:re.length}]),` ${Ae.declareVariables($e,me,Be,je,et)} ${Ae.mainStart(Ci)} let half_rotary_emb_dim = uniforms.${Be.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${Ae.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${me.broadcastedIndicesToOffset("bsnh.xy",vn("",me.type.tensor,2))}; let position_id = u32(${me.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 = ${$e.getByOffset("i")} * ${Be.get("position_id","bsnh[3]")} - ${$e.getByOffset("j")} * ${je.get("position_id","bsnh[3]")}; ${et.setByOffset("i","re")} let im = ${$e.getByOffset("i")} * ${je.get("position_id","bsnh[3]")} + ${$e.getByOffset("j")} * ${Be.get("position_id","bsnh[3]")}; ${et.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${et.setByOffset("k",$e.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:kn({interleaved:u}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:ie,getRunData:()=>({outputs:[{dims:r[0].dims,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(yt.size(J)/Ci)},programUniforms:ue})}},$w=(r,s)=>{Pw(r.inputs,s),r.compute(Aw(r.inputs,s))}}),Iw,Fw,Ow,ZE=c(()=>{En(),xn(),Ln(),Iw=r=>{if(!r||r.length<3)throw new Error("layerNorm requires at least 3 inputs.");let s=r[0],u=r[1],p=r[2];if(s.dataType!==u.dataType||s.dataType!==p.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 m=s.dims[s.dims.length-1],g=s.dims[s.dims.length-2];if(u.dims[u.dims.length-1]!==m)throw new Error("Skip must have the same hidden size as input");if(u.dims[u.dims.length-2]!==g)throw new Error("Skip must have the same sequence length as input");if(p.dims.length!==1)throw new Error("Gamma must be 1D");if(p.dims[p.dims.length-1]!==m)throw new Error("Gamma must have the same hidden size as input");if(r.length>3){let y=r[3];if(y.dims.length!==1)throw new Error("Beta must be 1D");if(y.dims[y.dims.length-1]!==m)throw new Error("Beta must have the same hidden size as input")}if(r.length>4){let y=r[4];if(y.dims.length!==1)throw new Error("Bias must be 1D");if(y.dims[y.dims.length-1]!==m)throw new Error("Bias must have the same hidden size as input")}},Fw=(r,s,u,p)=>{let m=s.simplified,g=r[0].dims,y=yt.size(g),A=g,I=y,O=g.slice(-1)[0],Q=p?g.slice(0,-1).concat(1):[],k=!m&&r.length>3,J=r.length>4,re=p&&u>1,ue=p&&u>2,ie=u>3,Ae=64,$e=tr(O),me=[{type:12,data:I},{type:12,data:$e},{type:12,data:O},{type:1,data:s.epsilon}],Be=et=>{let Ot=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],It=[Lt("x",r[0].dataType,r[0].dims,$e),Lt("skip",r[1].dataType,r[1].dims,$e),Lt("gamma",r[2].dataType,r[2].dims,$e)];k&&It.push(Lt("beta",r[3].dataType,r[3].dims,$e)),J&&It.push(Lt("bias",r[4].dataType,r[4].dims,$e)),It.push(vn("output",r[0].dataType,A,$e)),re&&It.push(vn("mean_output",1,Q)),ue&&It.push(vn("inv_std_output",1,Q)),ie&&It.push(vn("input_skip_bias_sum",r[0].dataType,A,$e));let Kt=or(r[0].dataType),yn=or(1,$e);return` ${et.registerUniforms(Ot).declareVariables(...It)} var sum_shared : array<${yn}, ${Ae}>; var sum_squared_shared : array<${yn}, ${Ae}>; ${et.mainStart([Ae,1,1])} let ix = local_id.x; let iy = global_id.x / ${Ae}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${Ae}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${Ae-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${J?"bias[offset1d + i]":Kt+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${ie?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Ir(Kt,$e,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${Ae}; 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 = ${Pi("sum",$e)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Pi("square_sum",$e)} / f32(uniforms.hidden_size) ${m?"":"- mean * mean"} + uniforms.epsilon); ${re?"mean_output[global_idx] = mean;":""} ${ue?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${m?"":`- ${Kt}(mean)`}) * ${Kt}(inv_std_dev) * gamma[offset1d + i] ${k?"+ beta[offset1d + i]":""}; } }`},je=[{dims:A,dataType:r[0].dataType}];return u>1&&je.push({dims:Q,dataType:1}),u>2&&je.push({dims:Q,dataType:1}),u>3&&je.push({dims:g,dataType:r[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${$e};${re};${ue};${ie}`,inputDependencies:r.map((et,Ot)=>"type")},getShaderSource:Be,getRunData:()=>({outputs:je,dispatchGroup:{x:Math.ceil(I/O)},programUniforms:me})}},Ow=(r,s)=>{Iw(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(Fw(r.inputs,s,r.outputCount,!1),{outputs:u})}}),Dw,Wf,zw,o_,Rw,Lw,Bw,Nw,JE=c(()=>{En(),xn(),Qn(),Ln(),Dw=(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,p)=>{if(r[p+1].dataType!==6&&r[p+1].dataType!==7)throw new Error(`Input ${p} must be an array of int32 or int64`)})},Wf=(r,s)=>{let u=[];if(r.length>s)if(r[s].dataType===7)r[s].getBigInt64Array().forEach(p=>u.push(Number(p)));else if(r[s].dataType===6)r[s].getInt32Array().forEach(p=>u.push(Number(p)));else throw new Error(`Input ${s} must be an array of int32 or int64`);return u},zw=(r,s)=>{if(r.length>1){let u=Wf(r,1),p=Wf(r,2),m=Wf(r,3);return m.length===0&&(m=[...Array(r[0].dims.length).keys()]),kn({starts:u,ends:p,axes:m})}else return s},o_=(r,s,u,p,m)=>{let g=r;return r<0&&(g+=u[p[s]]),m[s]<0?Math.max(0,Math.min(g,u[p[s]]-1)):Math.max(0,Math.min(g,u[p[s]]))},Rw=(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 = ${pn("uniforms.input_shape","i",u.length)}; let steps_i = ${pn("uniforms.steps","i",u.length)}; let signs_i = ${pn("uniforms.signs","i",u.length)}; let starts_i = ${pn("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; }`,Lw=(r,s)=>{let u=r[0].dims,p=yt.size(u),m=s.axes.length>0?yt.normalizeAxes(s.axes,u.length):[...Array(u.length).keys()],g=Wf(r,4);g.forEach($e=>$e!==0||(()=>{throw new Error("step cannot be 0")})),g.length===0&&(g=Array(m.length).fill(1));let y=s.starts.map(($e,me)=>o_($e,me,u,m,g)),A=s.ends.map(($e,me)=>o_($e,me,u,m,g));if(m.length!==y.length||m.length!==A.length)throw new Error("start, ends and axes should have the same number of elements");if(m.length!==u.length)for(let $e=0;$eMath.sign($e));g.forEach(($e,me,Be)=>{if($e<0){let je=(A[me]-y[me])/$e,et=y[me],Ot=et+je*g[me];y[me]=Ot,A[me]=et,Be[me]=-$e}});let O=u.slice(0);m.forEach(($e,me)=>{O[$e]=Math.ceil((A[$e]-y[$e])/g[$e])});let Q={dims:O,dataType:r[0].dataType},k=vn("output",r[0].dataType,O.length),J=Lt("input",r[0].dataType,r[0].dims.length),re=yt.size(O),ue=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:y.length},{name:"signs",type:"i32",length:I.length},{name:"steps",type:"u32",length:g.length}],ie=[{type:12,data:re},{type:12,data:y},{type:6,data:I},{type:12,data:g},...sn(r[0].dims,O)],Ae=$e=>` ${$e.registerUniforms(ue).declareVariables(J,k)} ${Rw(J,k,u)} ${$e.mainStart()} ${$e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${k.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${k.setByOffset("global_idx",J.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${I.length}_${y.length}_${g.length}`,inputDependencies:["rank"]},getShaderSource:Ae,getRunData:()=>({outputs:[Q],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:ie})}},Bw=(r,s)=>{Dw(r.inputs,s);let u=zw(r.inputs,s);r.compute(Lw(r.inputs,u),{inputs:[0]})},Nw=r=>{let s=r.starts,u=r.ends,p=r.axes;return kn({starts:s,ends:u,axes:p})}}),jw,Vw,Uw,Ww,eC=c(()=>{En(),xn(),Qn(),Ln(),jw=r=>{if(!r||r.length!==1)throw new Error("Softmax op requires 1 input.")},Vw=(r,s)=>{let u=r.dims,p=yt.size(u),m=64,g=s.axis;if(g<0&&(g=u.length+g),g$e===4?`max(max(${Ae}.x, ${Ae}.y), max(${Ae}.z, ${Ae}.w))`:$e===2?`max(${Ae}.x, ${Ae}.y)`:$e===3?`max(max(${Ae}.x, ${Ae}.y), ${Ae}.z)`:Ae,k=Lt("x",r.dataType,r.dims,I),J=vn("result",r.dataType,r.dims,I),re=k.type.value,ue=or(r.dataType)==="f32"?`var threadMax = ${re}(-3.402823e+38f);`:`var threadMax = ${re}(-65504.0h);`,ie=Ae=>` var rowMaxShared : ${re}; var rowSumShared : ${re}; var threadShared : array<${re}, ${m}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${re} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${re}) { let index = row * row_stride + col; result[index] = value; } ${Ae.registerUniform("packedCols","i32").declareVariables(k,J)} ${Ae.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${m}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${ue} 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 = ${re}(${Q("threadShared[0]",I)}); } workgroupBarrier(); // find the rows sum var threadSum = ${re}(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 = ${re}(${Pi("threadShared[0]",I)}); } 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:`${I}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:u,dataType:r.dataType}],dispatchGroup:{x:A},programUniforms:[{type:6,data:O}]}),getShaderSource:ie}},Uw=(r,s)=>{jw(r.inputs),r.compute(Vw(r.inputs[0],s))},Ww=r=>kn({axis:r.axis})}),Gw,qw,Hw,Kw,Xw,Qw,Yw,tC=c(()=>{En(),xn(),Qn(),Ln(),Gw=r=>{if(!r||r.length<1)throw new Error("too few inputs")},qw=(r,s)=>{let u=[],p=s.numOutputs;return r[1].dims[0]>0&&(r[1].getBigInt64Array().forEach(m=>u.push(Number(m))),p=u.length),kn({numOutputs:p,axis:s.axis,splitSizes:u})},Hw=r=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${r}u; i += 1u ) { if (index < ${pn("uniforms.size_in_split_axis","i",r)}) { return i; } } return ${r}u; }`,Kw=r=>{let s=r.length,u=[];for(let p=0;p{let u=r[0].dims,p=yt.size(u),m=r[0].dataType,g=yt.normalizeAxis(s.axis,u.length),y=new Array(s.numOutputs),A=Lt("input",m,u.length),I=new Array(s.numOutputs),O=[],Q=[],k=0,J=[{type:12,data:p}];for(let ue=0;ue` ${ue.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",I.length).declareVariables(A,...y)} ${Hw(I.length)} ${Kw(y)} ${ue.mainStart()} ${ue.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${A.offsetToIndices("global_idx")}; var index = ${A.indicesGet("indices",g)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${pn("uniforms.size_in_split_axis","output_number - 1u",I.length)}; ${A.indicesSet("indices",g,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getShaderSource:re,getRunData:()=>({outputs:O,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:J})}},Qw=(r,s)=>{Gw(r.inputs);let u=r.inputs.length===1?s:qw(r.inputs,s);r.compute(Xw(r.inputs,u),{inputs:[0]})},Yw=r=>{let s=r.axis,u=r.splitSizes,p=r.numOutputs<0?u.length:r.numOutputs;if(p!==u.length)throw new Error("numOutputs and splitSizes lengh must be equal");return kn({axis:s,numOutputs:p,splitSizes:u})}}),Zw,Jw,e1,nC=c(()=>{En(),xn(),Ln(),Zw=(r,s,u,p,m)=>{let g=vn("output_data",m,u.length,4),y=Lt("a_data",s[1].dataType,s[1].dims.length,4),A=Lt("b_data",s[2].dataType,s[2].dims.length,4),I=Lt("c_data",s[0].dataType,s[0].dims.length,4),O,Q=(k,J,re)=>`select(${J}, ${k}, ${re})`;if(!p)O=g.setByOffset("global_idx",Q(y.getByOffset("global_idx"),A.getByOffset("global_idx"),I.getByOffset("global_idx")));else{let k=(J,re,ue="")=>{let ie=`a_data[index_a${re}][component_a${re}]`,Ae=`b_data[index_b${re}][component_b${re}]`,$e=`bool(c_data[index_c${re}] & (0xffu << (component_c${re} * 8)))`;return` let output_indices${re} = ${g.offsetToIndices(`global_idx * 4u + ${re}u`)}; let offset_a${re} = ${y.broadcastedIndicesToOffset(`output_indices${re}`,g)}; let offset_b${re} = ${A.broadcastedIndicesToOffset(`output_indices${re}`,g)}; let offset_c${re} = ${I.broadcastedIndicesToOffset(`output_indices${re}`,g)}; let index_a${re} = offset_a${re} / 4u; let index_b${re} = offset_b${re} / 4u; let index_c${re} = offset_c${re} / 4u; let component_a${re} = offset_a${re} % 4u; let component_b${re} = offset_b${re} % 4u; let component_c${re} = offset_c${re} % 4u; ${J}[${re}] = ${ue}(${Q(ie,Ae,$e)}); `};m===9?O=` var data = vec4(0); ${k("data",0,"u32")} ${k("data",1,"u32")} ${k("data",2,"u32")} ${k("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:O=` ${k("output_data[global_idx]",0)} ${k("output_data[global_idx]",1)} ${k("output_data[global_idx]",2)} ${k("output_data[global_idx]",3)} `}return` ${r.registerUniform("vec_size","u32").declareVariables(I,y,A,g)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${O} }`},Jw=r=>{let s=r[1].dims,u=r[2].dims,p=r[0].dims,m=r[1].dataType,g=!(yt.areEqual(s,u)&&yt.areEqual(u,p)),y=s,A=yt.size(s);if(g){let O=Mr.calcShape(Mr.calcShape(s,u,!1),p,!1);if(!O)throw new Error("Can't perform where op on the given tensors");y=O,A=yt.size(y)}let I=Math.ceil(A/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:O=>Zw(O,r,y,g,m),getRunData:()=>({outputs:[{dims:y,dataType:m}],dispatchGroup:{x:Math.ceil(A/64/4)},programUniforms:[{type:12,data:I},...sn(p,s,u,y)]})}},e1=r=>{r.compute(Jw(r.inputs))}}),t1,rC=c(()=>{v(),Ge(),tt(),vt(),rp(),ip(),sp(),rc(),dp(),fp(),mp(),Zg(),_p(),wf(),Jg(),vp(),wp(),bp(),e_(),t_(),n_(),Hl(),Fi(),kp(),Bt(),tu(),i_(),XE(),Go(),QE(),YE(),ZE(),JE(),eC(),tC(),Ap(),mo(),Ru(),nC(),t1=new Map([["Abs",[Gt]],["Acos",[on]],["Acosh",[Wt]],["Add",[Bu]],["ArgMax",[el,f]],["ArgMin",[xs,f]],["Asin",[rn]],["Asinh",[an]],["Atan",[Ut]],["Atanh",[Bn]],["Attention",[Ke]],["AveragePool",[cr,Wn]],["BatchNormalization",[He]],["BiasAdd",[gt]],["BiasSplitGelu",[Lu]],["Cast",[Hn,jn]],["Ceil",[Un]],["Clip",[Li]],["Concat",[Ld,Uu]],["Conv",[nc,Ju]],["ConvTranspose",[lc,ac]],["Cos",[ii]],["Cosh",[si]],["CumSum",[uc,cf]],["DepthToSpace",[dc,fc]],["DequantizeLinear",[Ma,Up]],["Div",[Cd]],["Einsum",[mf,Er]],["Elu",[oi,Fs]],["Equal",[Pd]],["Erf",[qo]],["Exp",[ud]],["Expand",[yf]],["FastGelu",[gc]],["Floor",[cd]],["FusedConv",[nc,Ju]],["Gather",[yp,_c]],["GatherElements",[Af,Pf]],["GatherBlockQuantized",[Sf,kf]],["Gelu",[dd]],["Gemm",[Of,Ff]],["GlobalAveragePool",[bo,fi]],["GlobalMaxPool",[eu,Yi]],["Greater",[ju]],["GreaterOrEqual",[Fd]],["GroupQueryAttention",[Op,Ip]],["HardSigmoid",[Au,gd]],["InstanceNormalization",[Lp]],["LayerNormalization",[jp]],["LeakyRelu",[Cu,Fs]],["Less",[Id]],["LessOrEqual",[Vu]],["Log",[bd]],["MatMul",[Qd]],["MatMulNBits",[di,_i]],["MaxPool",[Qi,Hr]],["Mul",[Nu]],["MultiHeadAttention",[Sp,Mp]],["Neg",[hd]],["Not",[fd]],["Pad",[Ct]],["Pow",[Ad]],["QuickGelu",[Vl,Fs]],["Range",[cw]],["Reciprocal",[pd]],["ReduceMin",[bi]],["ReduceMean",[Nl]],["ReduceMax",[Wo]],["ReduceSum",[va]],["ReduceProd",[jl]],["ReduceL1",[Uo]],["ReduceL2",[Xi]],["ReduceLogSum",[Is]],["ReduceLogSumExp",[Rr]],["ReduceSumSquare",[wa]],["Relu",[Pu]],["Resize",[Ew,Cw]],["RotaryEmbedding",[$w]],["Sigmoid",[md]],["Sin",[_d]],["Sinh",[yd]],["Slice",[Bw,Nw]],["SkipLayerNormalization",[Ow]],["Split",[Qw,Yw]],["Sqrt",[$u]],["Softmax",[Uw,Ww]],["Sub",[$d]],["Tan",[vd]],["Tanh",[Fu]],["ThresholdedRelu",[wd,Fs]],["Tile",[Pp]],["Transpose",[Do,ca]],["Where",[e1]]])}),n1,iC=c(()=>{Jt(),wi(),Ln(),n1=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,p,m){bt(r.programInfo.name);let g=this.backend.device,y=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let A=[];for(let O of s)A.push({binding:A.length,resource:{buffer:O.buffer}});for(let O of u)A.push({binding:A.length,resource:{buffer:O.buffer}});m&&A.push({binding:A.length,resource:m});let I=g.createBindGroup({layout:r.computePipeline.getBindGroupLayout(0),entries:A,label:r.programInfo.name});if(this.backend.sessionStatus==="capturing"){let O={kernelId:this.backend.currentKernelId,computePipeline:r.computePipeline,bindGroup:I,dispatchGroup:p};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(O)}y.setPipeline(r.computePipeline),y.setBindGroup(0,I),y.dispatchWorkgroups(...p),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){bt(r.name);let u=this.backend.device,p=[];u.features.has("shader-f16")&&p.push("enable f16;");let m=zl(s,this.backend.device.limits),g=r.getShaderSource(m),y=`${p.join(` `)} ${m.additionalImplementations} ${g}`,A=u.createShaderModule({code:y,label:r.name});xr("verbose",()=>`[WebGPU] ${r.name} shader code: ${y}`);let I=u.createComputePipeline({compute:{module:A,entryPoint:"main"},layout:"auto",label:r.name});return z(r.name),{programInfo:r,computePipeline:I,uniformVariablesInfo:m.variablesInfo}}normalizeDispatchGroupSize(r){let s=typeof r=="number"?r:r.x,u=typeof r=="number"?1:r.y||1,p=typeof r=="number"?1:r.z||1,m=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(s<=m&&u<=m&&p<=m)return[s,u,p];let g=s*u*p,y=Math.ceil(Math.sqrt(g));if(y>m){if(y=Math.ceil(Math.cbrt(g)),y>m)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[y,y,y]}else return[y,y,1]}}}),r1,i1,s1,o1,sC=c(()=>{Jt(),En(),wi(),q(),Cn(),rC(),iC(),r1=(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 p=0;p{let p=r.name;return r.shaderCache?.hint&&(p+="["+r.shaderCache.hint+"]"),p+=":"+u+`:${r1(s,r.shaderCache?.inputDependencies??new Array(s.length).fill("dims"))}`,p},s1=class{constructor(r){r&&(this.architecture=r.architecture,this.vendor=r.vendor)}isArchitecture(r){return this.architecture===r}isVendor(r){return this.vendor===r}},o1=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=[],p={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(p),this.adapterInfo=new s1(s.info||await s.requestAdapterInfo()),this.gpuDataManager=nr(this),this.programManager=new n1(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ds(r.logLevel,!!r.debug),this.device.onuncapturederror=m=>{m.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${m.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;bt(),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(()=>{let s=new BigUint64Array(r.getMappedRange()),u=this.pendingQueries.get(r);for(let p=0;p"u"&&(this.queryTimeBase=J);let ue=Number(J-this.queryTimeBase),ie=Number(re-this.queryTimeBase);if(!Number.isSafeInteger(ue)||!Number.isSafeInteger(ie))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:Q.map(Ae=>({dims:Ae.dims,dataType:Si(Ae.dataType)})),outputsMetadata:k.map(Ae=>({dims:Ae.dims,dataType:Si(Ae.dataType)})),kernelId:g,kernelType:A,kernelName:I,programName:O,startTime:ue,endTime:ie});else{let Ae="";Q.forEach((me,Be)=>{Ae+=`input[${Be}]: [${me.dims}] | ${Si(me.dataType)}, `});let $e="";k.forEach((me,Be)=>{$e+=`output[${Be}]: [${me.dims}] | ${Si(me.dataType)}, `}),console.log(`[profiling] kernel "${g}|${A}|${I}|${O}" ${Ae}${$e}execution time: ${ie-ue} ns`)}lt("GPU",`${O}::${J}::${re}`)}r.unmap(),this.pendingQueries.delete(r)}),z()}run(r,s,u,p,m,g){bt(r.name);let y=[];for(let me=0;meBe):u;if(Q.length!==A.length)throw new Error(`Output size ${Q.length} must be equal to ${A.length}.`);let k=[],J=[];for(let me=0;me=g)throw new Error(`Invalid output index: ${Q[me]}`);if(Q[me]===-3)continue;let Be=Q[me]===-1,je=Q[me]===-2,et=Be||je?m(A[me].dataType,A[me].dims):p(Q[me],A[me].dataType,A[me].dims);if(k.push(et),et.data===0)continue;let Ot=this.gpuDataManager.get(et.data);if(!Ot)throw new Error(`no GPU data for output: ${et.data}`);if(Be&&this.temporaryData.push(Ot),je){let It=this.kernelPersistentData.get(this.currentKernelId);It||(It=[],this.kernelPersistentData.set(this.currentKernelId,It)),It.push(Ot)}J.push(Ot)}if(y.length!==s.length||J.length!==k.length){if(J.length===0)return z(r.name),k;throw new Error(`Program ${r.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let re;if(O){let me=0,Be=[];O.forEach(It=>{let Kt=typeof It.data=="number"?[It.data]:It.data;if(Kt.length===0)return;let yn=It.type===10?2:4,_n,Zn;It.type===10?(Zn=Kt.length>4?16:Kt.length>2?8:Kt.length*yn,_n=Kt.length>4?16:yn*Kt.length):(Zn=Kt.length<=2?Kt.length*yn:16,_n=16),me=Math.ceil(me/Zn)*Zn,Be.push(me);let Gn=It.type===10?8:4;me+=Kt.length>4?Math.ceil(Kt.length/Gn)*_n:Kt.length*yn});let je=16;me=Math.ceil(me/je)*je;let et=new ArrayBuffer(me);O.forEach((It,Kt)=>{let yn=Be[Kt],_n=typeof It.data=="number"?[It.data]:It.data;if(It.type===6)new Int32Array(et,yn,_n.length).set(_n);else if(It.type===12)new Uint32Array(et,yn,_n.length).set(_n);else if(It.type===10)new Uint16Array(et,yn,_n.length).set(_n);else if(It.type===1)new Float32Array(et,yn,_n.length).set(_n);else throw new Error(`Unsupported uniform type: ${Si(It.type)}`)});let Ot=this.gpuDataManager.create(me,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ot.buffer,0,et,0,me),this.gpuDataManager.release(Ot.id),re={offset:0,size:me,buffer:Ot.buffer}}let ue=this.programManager.normalizeDispatchGroupSize(I),ie=ue[1]===1&&ue[2]===1,Ae=i1(r,s,ie),$e=this.programManager.getArtifact(Ae);if($e||($e=this.programManager.build(r,ue),this.programManager.setArtifact(Ae,$e),xr("info",()=>`[artifact] key: ${Ae}, programName: ${r.name}`)),O&&$e.uniformVariablesInfo){if(O.length!==$e.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${$e.uniformVariablesInfo.length}, got ${O.length} in program "${$e.programInfo.name}".`);for(let me=0;me`[ProgramManager] run "${r.name}" (key=${Ae}) with ${ue[0]}x${ue[1]}x${ue[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let me={kernelId:this.currentKernelId,programName:$e.programInfo.name,inputTensorViews:s,outputTensorViews:k};this.pendingKernels.push(me),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(me)}return this.programManager.run($e,y,J,ue,re),z(r.name),k}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,p){let m=t1.get(r);if(!m)throw new Error(`kernel not implemented: ${r}`);let g={kernelType:r,kernelName:p,kernelEntry:m[0],attributes:[m[1],u]};this.kernels.set(s,g)}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 p=this.kernels.get(r);if(!p)throw new Error(`kernel not created: ${r}`);let m=p.kernelType,g=p.kernelName,y=p.kernelEntry,A=p.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${m}] ${g}" is not allowed to be called recursively`);this.currentKernelId=r,A[0]&&(A[1]=A[0](A[1]),A[0]=void 0),xr("info",()=>`[WebGPU] Start to run kernel "[${m}] ${g}"...`);let I=this.env.debug;this.temporaryData=[];try{return I&&this.device.pushErrorScope("validation"),y(s,A[1]),0}catch(O){return u.push(Promise.resolve(`[WebGPU] Kernel "[${m}] ${g}" failed. ${O}`)),1}finally{I&&u.push(this.device.popErrorScope().then(O=>O?`GPU validation error for kernel "[${m}] ${g}": ${O.message}`:null));for(let O of this.temporaryData)this.gpuDataManager.release(O.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(r,s,u,p){let m=this.sessionExternalDataMapping.get(r);m||(m=new Map,this.sessionExternalDataMapping.set(r,m));let g=m.get(s),y=this.gpuDataManager.registerExternalBuffer(u,p,g?.[1]);return m.set(s,[y,u]),y}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 p=await nn(this,r,s);return nt(p.buffer,u)}}writeTimestamp(r){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,r)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.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(){xr("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(){xr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){xr("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 p=0;p=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()}}}),a1={};h(a1,{init:()=>u1});var Gp,l1,u1,oC=c(()=>{En(),sC(),wi(),xn(),Gp=class uk{constructor(s,u,p,m){this.module=s,this.dataType=u,this.data=p,this.dims=m}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let s=yt.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=yt.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=yt.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=yt.size(this.dims);return s===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,s)}reshape(s){if(yt.size(s)!==yt.size(this.dims))throw new Error("Invalid new shape");return new uk(this.module,this.dataType,this.data,s)}},l1=class{constructor(r,s,u){this.module=r,this.backend=s,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=s.adapterInfo;let p=r.HEAPU32,m=u>>>2;this.opKernelContext=p[m++];let g=p[m++];this.outputCount=p[m++],this.customDataOffset=p[m++],this.customDataSize=p[m++];let y=[];for(let A=0;Atypeof y=="number"?this.inputs[y]:y)??this.inputs,p=s?.outputs??[],m=(y,A,I)=>new Gp(this.module,A,this.output(y,I),I),g=(y,A)=>{let I=cs(y,A);if(!I)throw new Error(`Unsupported data type: ${y}`);let O=I>0?this.backend.gpuDataManager.create(I).id:0;return new Gp(this.module,y,O,A)};return this.backend.run(r,u,p,m,g,this.outputCount)}output(r,s){let u=this.module.stackSave();try{let p=this.module.stackAlloc((1+s.length)*4),m=p>>2;this.module.HEAPU32[m++]=s.length;for(let g=0;g{let m=s.jsepInit;if(!m)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(r==="webgpu"){let g=new o1;await g.initialize(u,p),m("webgpu",[g,y=>g.alloc(y),y=>g.free(y),(y,A,I,O=!1)=>{if(O)xr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${y}, dst=${A}, size=${I}`),g.memcpy(y,A);else{xr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${y}, gpuDataId=${A}, size=${I}`);let Q=s.HEAPU8.subarray(y>>>0,(y>>>0)+I);g.upload(A,Q)}},async(y,A,I)=>{xr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${y}, dataOffset=${A}, size=${I}`),await g.download(y,()=>s.HEAPU8.subarray(A>>>0,(A>>>0)+I))},(y,A,I)=>g.createKernel(y,A,I,s.UTF8ToString(s._JsepGetNodeName(A))),y=>g.releaseKernel(y),(y,A,I,O)=>{xr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${I}, kernel=${y}, contextDataOffset=${A}`);let Q=new l1(s,g,A);return g.computeKernel(y,Q,O)},()=>g.captureBegin(),()=>g.captureEnd(),()=>g.replay()])}else m("webnn")}}),c1,a_,l_,rl,d1,qp,u_,c_,d_,f_,h_,p_,f1=c(()=>{us(),$o(),En(),Qr(),mi(),uo(),c1=(r,s)=>{vr()._OrtInit(r,s)!==0&&kr("Can't initialize onnxruntime.")},a_=async r=>{c1(r.wasm.numThreads,ki(r.logLevel))},l_=async(r,s)=>{{let u=(oC(),_(a1)).init;if(s==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let p=r.webgpu.adapter;if(p){if(typeof p.limits!="object"||typeof p.features!="object"||typeof p.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let m=r.webgpu.powerPreference;if(m!==void 0&&m!=="low-power"&&m!=="high-performance")throw new Error(`Invalid powerPreference setting: "${m}"`);let g=r.webgpu.forceFallbackAdapter;if(g!==void 0&&typeof g!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${g}"`);if(p=await navigator.gpu.requestAdapter({powerPreference:m,forceFallbackAdapter:g}),!p)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",vr(),r,p)}if(s==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await u("webnn",vr(),r)}}},rl=new Map,d1=r=>{let s=vr(),u=s.stackSave();try{let p=s.stackAlloc(8);return s._OrtGetInputOutputCount(r,p,p+4)!==0&&kr("Can't get session input/output count."),[s.HEAP32[p/4],s.HEAP32[p/4+1]]}finally{s.stackRestore(u)}},qp=r=>{let s=vr(),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]},u_=async(r,s)=>{let u,p,m=vr();Array.isArray(r)?[u,p]=r:r.buffer===m.HEAPU8.buffer?[u,p]=[r.byteOffset,r.byteLength]:[u,p]=qp(r);let g=0,y=0,A=0,I=[],O=[],Q=[];try{if([y,I]=li(s),s?.externalData&&m.mountExternalData){let me=[];for(let Be of s.externalData){let je=typeof Be=="string"?Be:Be.path;me.push(Xn(typeof Be=="string"?Be:Be.data).then(et=>{m.mountExternalData(je,et)}))}await Promise.all(me)}for(let me of s?.executionProviders??[])if((typeof me=="string"?me:me.name)==="webnn"){if(m.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof me!="string"){let Be=me,je=Be?.context,et=Be?.gpuDevice,Ot=Be?.deviceType,It=Be?.numThreads,Kt=Be?.powerPreference;je?m.currentContext=je:et?m.currentContext=await navigator.ml.createContext(et):m.currentContext=await navigator.ml.createContext({deviceType:Ot,numThreads:It,powerPreference:Kt})}else m.currentContext=await navigator.ml.createContext();break}g=await m._OrtCreateSession(u,p,y),g===0&&kr("Can't create a session."),m.currentContext&&(m.currentContext=void 0);let[k,J]=d1(g),re=!!s?.enableGraphCapture,ue=[],ie=[],Ae=[];for(let me=0;meme==="gpu-buffer")&&(A=m._OrtCreateBinding(g),A===0&&kr("Can't create IO binding."),$e={handle:A,outputPreferredLocations:Ae,outputPreferredLocationsEncoded:Ae.map(me=>vs(me))}),rl.set(g,[g,O,Q,$e,re,!1]),[g,ue,ie]}catch(k){throw O.forEach(J=>m._OrtFree(J)),Q.forEach(J=>m._OrtFree(J)),A!==0&&m._OrtReleaseBinding(A),g!==0&&m._OrtReleaseSession(g),k}finally{m._free(u),y!==0&&m._OrtReleaseSessionOptions(y),I.forEach(k=>m._free(k)),m.unmountExternalData?.()}},c_=r=>{let s=vr(),u=rl.get(r);if(!u)throw new Error(`cannot release session. invalid session id: ${r}`);let[p,m,g,y,A]=u;y&&(A&&s._OrtClearBoundOutputs(y.handle),s._OrtReleaseBinding(y.handle)),s.jsepOnReleaseSession?.(r),m.forEach(I=>s._OrtFree(I)),g.forEach(I=>s._OrtFree(I)),s._OrtReleaseSession(p),rl.delete(r)},d_=(r,s,u,p,m,g=!1)=>{if(!r){s.push(0);return}let y=vr(),A=r[0],I=r[1],O=r[3],Q,k;if(A==="string"&&O==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(g&&O!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${m} when enableGraphCapture is true.`);if(O==="gpu-buffer"){let ue=r[2].gpuBuffer;k=cs(qi(A),I);let ie=y.jsepRegisterBuffer;if(!ie)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Q=ie(p,m,ue,k)}else{let ue=r[2];if(Array.isArray(ue)){k=4*ue.length,Q=y._malloc(k),u.push(Q);let ie=Q/4;for(let Ae=0;Aey.HEAP32[ue++]=Ae);let ie=y._OrtCreateTensor(qi(A),Q,k,re,I.length,vs(O));ie===0&&kr(`Can't create tensor for input/output. session=${p}, index=${m}.`),s.push(ie)}finally{y.stackRestore(J)}},f_=async(r,s,u,p,m,g)=>{let y=vr(),A=rl.get(r);if(!A)throw new Error(`cannot run inference. invalid session id: ${r}`);let I=A[0],O=A[1],Q=A[2],k=A[3],J=A[4],re=A[5],ue=s.length,ie=p.length,Ae=0,$e=[],me=[],Be=[],je=[],et=y.stackSave(),Ot=y.stackAlloc(ue*4),It=y.stackAlloc(ue*4),Kt=y.stackAlloc(ie*4),yn=y.stackAlloc(ie*4);try{[Ae,$e]=ls(g);for(let On=0;OnZi*Ni,1);Rt=Si(Br);let Ts=k?.outputPreferredLocations[p[On]];if(Rt==="string"){if(Ts==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Zi=[],Ni=ln/4;for(let sl=0;sl0){let Zi=y.jsepGetBuffer;if(!Zi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ni=Zi(ln),sl=cs(Br,Ds);if(sl===void 0||!Gs(Rt))throw new Error(`Unsupported data type: ${Rt}`);ur=!0,ir.push([Rt,xo,{gpuBuffer:Ni,download:y.jsepCreateDownloader(Ni,sl,Rt),dispose:()=>{y._OrtReleaseTensor(yr)}},"gpu-buffer"])}else{let Zi=Hi(Rt),Ni=new Zi(Ds);new Uint8Array(Ni.buffer,Ni.byteOffset,Ni.byteLength).set(y.HEAPU8.subarray(ln,ln+Ni.byteLength)),ir.push([Rt,xo,Ni,"cpu"])}}finally{y.stackRestore(Pr),Rt==="string"&&ln&&y._free(ln),ur||y._OrtReleaseTensor(yr)}}return k&&!J&&(y._OrtClearBoundOutputs(k.handle),rl.set(r,[I,O,Q,k,J,!1])),ir}finally{y.stackRestore(et),me.forEach(_n=>y._OrtReleaseTensor(_n)),Be.forEach(_n=>y._OrtReleaseTensor(_n)),je.forEach(_n=>y._free(_n)),Ae!==0&&y._OrtReleaseRunOptions(Ae),$e.forEach(_n=>y._free(_n))}},h_=r=>{let s=vr(),u=rl.get(r);if(!u)throw new Error("invalid session id");let p=u[0],m=s._OrtEndProfiling(p);m===0&&kr("Can't get an profile file name."),s._OrtFree(m)},p_=r=>{let s=[];for(let u of r){let p=u[2];!Array.isArray(p)&&"buffer"in p&&s.push(p.buffer)}return s}}),il,Xs,yc,Gf,qf,Hp,m_,Kp,nu,ru,h1,p1,m1,g1,_1,y1,v1,w1,b1=c(()=>{Jt(),f1(),Qr(),In(),il=()=>!!V.wasm.proxy&&typeof document<"u",yc=!1,Gf=!1,qf=!1,Kp=new Map,nu=(r,s)=>{let u=Kp.get(r);u?u.push(s):Kp.set(r,[s])},ru=()=>{if(yc||!Gf||qf||!Xs)throw new Error("worker not ready")},h1=r=>{switch(r.data.type){case"init-wasm":yc=!1,r.data.err?(qf=!0,m_[1](r.data.err)):(Gf=!0,m_[0]()),Hp&&(URL.revokeObjectURL(Hp),Hp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let s=Kp.get(r.data.type);r.data.err?s.shift()[1](r.data.err):s.shift()[0](r.data.out);break}}},p1=async()=>{if(!Gf){if(yc)throw new Error("multiple calls to 'initWasm()' detected.");if(qf)throw new Error("previous call to 'initWasm()' failed.");if(yc=!0,il())return new Promise((r,s)=>{Xs?.terminate(),mn().then(([u,p])=>{try{Xs=p,Xs.onerror=g=>s(g),Xs.onmessage=h1,m_=[r,s];let m={type:"init-wasm",in:V};Xs.postMessage(m),Hp=u}catch(m){s(m)}},s)});try{await ao(V.wasm),await a_(V),Gf=!0}catch(r){throw qf=!0,r}finally{yc=!1}}},m1=async r=>{if(il())return ru(),new Promise((s,u)=>{nu("init-ep",[s,u]);let p={type:"init-ep",in:{epName:r,env:V}};Xs.postMessage(p)});await l_(V,r)},g1=async r=>il()?(ru(),new Promise((s,u)=>{nu("copy-from",[s,u]);let p={type:"copy-from",in:{buffer:r}};Xs.postMessage(p,[r.buffer])})):qp(r),_1=async(r,s)=>{if(il()){if(s?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ru(),new Promise((u,p)=>{nu("create",[u,p]);let m={type:"create",in:{model:r,options:{...s}}},g=[];r instanceof Uint8Array&&g.push(r.buffer),Xs.postMessage(m,g)})}else return u_(r,s)},y1=async r=>{if(il())return ru(),new Promise((s,u)=>{nu("release",[s,u]);let p={type:"release",in:r};Xs.postMessage(p)});c_(r)},v1=async(r,s,u,p,m,g)=>{if(il()){if(u.some(y=>y[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(m.some(y=>y))throw new Error("pre-allocated output tensor is not supported for proxy.");return ru(),new Promise((y,A)=>{nu("run",[y,A]);let I=u,O={type:"run",in:{sessionId:r,inputIndices:s,inputs:I,outputIndices:p,options:g}};Xs.postMessage(O,p_(I))})}else return f_(r,s,u,p,m,g)},w1=async r=>{if(il())return ru(),new Promise((s,u)=>{nu("end-profiling",[s,u]);let p={type:"end-profiling",in:r};Xs.postMessage(p)});h_(r)}}),g_,x1,M1,aC=c(()=>{Jt(),b1(),En(),kt(),uo(),g_=(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()}`)}},x1=r=>{switch(r[3]){case"cpu":return new Ve(r[0],r[2],r[1]);case"gpu-buffer":{let s=r[0];if(!Gs(s))throw new Error(`not supported data type: ${s} for deserializing GPU tensor`);let{gpuBuffer:u,download:p,dispose:m}=r[2];return Ve.fromGpuBuffer(u,{dataType:s,dims:r[1],download:p,dispose:m})}default:throw new Error(`invalid data location: ${r[3]}`)}},M1=class{async fetchModelAndCopyToWasmMemory(r){return g1(await Xn(r))}async loadModel(r,s){bt();let u;typeof r=="string"?u=await this.fetchModelAndCopyToWasmMemory(r):u=r,[this.sessionId,this.inputNames,this.outputNames]=await _1(u,s),z()}async dispose(){return y1(this.sessionId)}async run(r,s,u){bt();let p=[],m=[];Object.entries(r).forEach(k=>{let J=k[0],re=k[1],ue=this.inputNames.indexOf(J);if(ue===-1)throw new Error(`invalid input '${J}'`);p.push(re),m.push(ue)});let g=[],y=[];Object.entries(s).forEach(k=>{let J=k[0],re=k[1],ue=this.outputNames.indexOf(J);if(ue===-1)throw new Error(`invalid output '${J}'`);g.push(re),y.push(ue)});let A=p.map((k,J)=>g_(k,()=>`input "${this.inputNames[m[J]]}"`)),I=g.map((k,J)=>k?g_(k,()=>`output "${this.outputNames[y[J]]}"`):null),O=await v1(this.sessionId,m,A,y,I,u),Q={};for(let k=0;k{Jt(),b1(),aC(),In(),T1=()=>{if((typeof V.wasm.initTimeout!="number"||V.wasm.initTimeout<0)&&(V.wasm.initTimeout=0),V.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 V.wasm.proxy!="boolean"&&(V.wasm.proxy=!1),typeof V.wasm.trace!="boolean"&&(V.wasm.trace=!1),typeof V.wasm.numThreads!="number"||!Number.isInteger(V.wasm.numThreads)||V.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)V.wasm.numThreads=1;else{let r=typeof navigator>"u"?d("node:os").cpus().length:navigator.hardwareConcurrency;V.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},S1=class{async init(r){T1(),await p1(),await m1(r)}async createInferenceSessionHandler(r,s){let u=new M1;return await u.loadModel(r,s),Promise.resolve(u)}}}),k1={};h(k1,{wasmBackend:()=>E1});var E1,uC=c(()=>{lC(),E1=new S1});Jt(),Jt(),Jt();var cC="1.20.0-dev.20240827-1d059b8702",dC=Dt;{let r=(uC(),_(k1)).wasmBackend;F("webgpu",r,5),F("webnn",r,5),F("cpu",r,10),F("wasm",r,10)}Object.defineProperty(V.versions,"web",{value:cC,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:()=>T,isONNXProxy:()=>S,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"}}),h=[];let w,_;if(o.apis.IS_NODE_ENV){switch(_=a??(i||(i=n.t(a,2))),process.platform){case"win32":h.push("dml");break;case"linux":process.arch==="x64"&&h.push("cuda");break}h.push("cpu"),w=["cpu"]}else _=l,o.apis.IS_WEBNN_AVAILABLE&&h.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&h.push("webgpu"),h.push("wasm"),w=["wasm"];const M=_.InferenceSession;function T(P=null){if(!P)return w;switch(P){case"auto":return h;case"gpu":return h.filter(j=>["webgpu","cuda","dml","webnn-gpu"].includes(j))}if(h.includes(P))return[c[P]??P];throw new Error(`Unsupported device: "${P}". Should be one of: ${h.join(", ")}.`)}let F=null;async function C(P,j){F&&await F;const L=M.create(P,j);return F??=L,await L}function E(P){return P instanceof _.Tensor}const x=_?.env;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?.webgpu&&(x.webgpu.powerPreference="high-performance");function S(){return x?.wasm?.proxy}o.env.backends.onnx=x},"./src/configs.js":(e,t,n)=>{n.r(t),n.d(t,{AutoConfig:()=>h,PretrainedConfig:()=>c,getKeyValueShapes:()=>d});var i=n("./src/utils/core.js"),o=n("./src/utils/hub.js");async function a(w,_){return await(0,o.getModelJSON)(w,"config.json",!0,_)}function l(w){const _={};let M={};switch(w.model_type){case"llava":case"paligemma":case"florence2":M=l(w.text_config);break;case"moondream1":M=l(w.phi_config);break;case"musicgen":M=l(w.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 F=l(w.decoder),C="num_decoder_layers"in F,E=(0,i.pick)(w,["model_type","is_encoder_decoder"]);return C?(E.num_decoder_layers=F.num_decoder_layers,E.num_decoder_heads=F.num_decoder_heads,E.decoder_hidden_size=F.decoder_hidden_size,E.num_encoder_layers=F.num_encoder_layers,E.num_encoder_heads=F.num_encoder_heads,E.encoder_hidden_size=F.encoder_hidden_size):(E.num_layers=F.num_layers,E.num_heads=F.num_heads,E.hidden_size=F.hidden_size),E}const T={...M,...(0,i.pick)(w,["model_type","multi_query","is_encoder_decoder"])};for(const F in _)T[F]=w[_[F]];return T}function d(w,{prefix:_="past_key_values"}={}){const M={},T=w.normalized_config,F=1;if(T.is_encoder_decoder&&"num_encoder_heads"in T&&"num_decoder_heads"in T){const C=T.encoder_dim_kv??T.encoder_hidden_size/T.num_encoder_heads,E=T.decoder_dim_kv??T.decoder_hidden_size/T.num_decoder_heads,x=[F,T.num_encoder_heads,0,C],S=[F,T.num_decoder_heads,0,E];for(let P=0;P{n.r(t),n.d(t,{apis:()=>E,env:()=>N});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",h=d&&"caches"in self,w=typeof navigator<"u"&&"gpu"in navigator,_=typeof navigator<"u"&&"ml"in navigator,M=typeof process<"u",T=M&&process?.release?.name==="node",F=!W(i),C=!W(o),E=Object.freeze({IS_BROWSER_ENV:d,IS_WEBWORKER_ENV:c,IS_WEB_CACHE_AVAILABLE:h,IS_WEBGPU_AVAILABLE:w,IS_WEBNN_AVAILABLE:_,IS_PROCESS_AVAILABLE:M,IS_NODE_ENV:T,IS_FS_AVAILABLE:F,IS_PATH_AVAILABLE:C}),x=F&&C,S=x?o.dirname(o.dirname(a.fileURLToPath(import.meta.url))):"./",P=x?o.join(S,"/.cache/"):null,j="/models/",L=x?o.join(S,j):j,N={version:l,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co./",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!d,localModelPath:L,useFS:F,useBrowserCache:h,useFSCache:F,cacheDir:P,useCustomCache:!1,customCache:null};function W(V){return Object.keys(V).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{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(l){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:()=>h,LogitsProcessor:()=>a,LogitsProcessorList:()=>d,LogitsWarper:()=>l,MinLengthLogitsProcessor:()=>F,MinNewTokensLengthLogitsProcessor:()=>C,NoBadWordsLogitsProcessor:()=>E,NoRepeatNGramLogitsProcessor:()=>M,RepetitionPenaltyLogitsProcessor:()=>T,SuppressTokensAtBeginLogitsProcessor:()=>w,TemperatureLogitsWarper:()=>S,TopKLogitsWarper:()=>j,TopPLogitsWarper:()=>P,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(N,W){throw Error("`_call` should be implemented in a subclass")}}class l extends i.Callable{_call(N,W){throw Error("`_call` should be implemented in a subclass")}}class d extends i.Callable{constructor(){super(),this.processors=[]}push(N){this.processors.push(N)}extend(N){this.processors.push(...N)}_call(N,W){let V=W;for(const ce of this.processors)V=ce(N,V);return V}[Symbol.iterator](){return this.processors.values()}}class c extends a{constructor(N){super(),this.bos_token_id=N}_call(N,W){for(let V=0;V=1&&ge[ge.length-1]>=this.timestamp_begin,oe=ge.length<2||ge[ge.length-2]>=this.timestamp_begin;if(Re&&(oe?ce.subarray(this.timestamp_begin).fill(-1/0):ce.subarray(0,this.eos_token_id).fill(-1/0)),N[V].length===this.begin_index&&this.max_initial_timestamp_index!==null){const pt=this.timestamp_begin+this.max_initial_timestamp_index;ce.subarray(pt+1).fill(-1/0)}const Se=(0,o.log_softmax)(ce),G=Math.log(Se.subarray(this.timestamp_begin).map(Math.exp).reduce((pt,Te)=>pt+Te)),Ce=(0,o.max)(Se.subarray(0,this.timestamp_begin))[0];G>Ce&&ce.subarray(0,this.timestamp_begin).fill(-1/0)}return W}}class M extends a{constructor(N){super(),this.no_repeat_ngram_size=N}getNgrams(N){const W=N.length,V=[];for(let ge=0;ge1 to use the classifier free guidance processor, got guidance scale ${N}.`);this.guidance_scale=N}_call(N,W){if(W.dims[0]!==2*N.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 ${N.length} for the input ids.`);const V=N.length,ce=W.slice([0,V],null),ge=W.slice([V,W.dims[0]],null);for(let Re=0;Re1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${N}`);if(!Number.isInteger(V)||V<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${V}`);this.top_p=N,this.filter_value=W,this.min_tokens_to_keep=V}}class j extends l{constructor(N,{filter_value:W=-1/0,min_tokens_to_keep:V=1}={}){if(super(),!Number.isInteger(N)||N<0)throw new Error(`\`top_k\` must be a positive integer, but is ${N}`);this.top_k=Math.max(N,V),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(_,M){let T=_.dims.at(-1),F=_.data;if(M===-1)F=F.slice(-T);else{let C=M*T;F=F.slice(C,C+T)}return F}randomSelect(_){let M=0;for(let F=0;F<_.length;++F)M+=_[F];let T=Math.random()*M;for(let F=0;F<_.length;++F)if(T-=_[F],T<=0)return F;return 0}static getSampler(_){if(_.do_sample)return new c(_);if(_.num_beams>1)return new h(_);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 M=(0,a.max)(_.data)[1];return[[BigInt(M),0]]}}class c extends l{async sample(_){let M=_.dims.at(-1);this.generation_config.top_k>0&&(M=Math.min(this.generation_config.top_k,M));const[T,F]=await(0,o.topk)(_,M),C=(0,a.softmax)(T.data);return Array.from({length:this.generation_config.num_beams},()=>{const E=this.randomSelect(C);return[F.data[E],Math.log(C[E])]})}}class h extends l{async sample(_){let M=_.dims.at(-1);this.generation_config.top_k>0&&(M=Math.min(this.generation_config.top_k,M));const[T,F]=await(0,o.topk)(_,M),C=(0,a.softmax)(T.data);return Array.from({length:this.generation_config.num_beams},(E,x)=>[F.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(w,_){throw Error("StoppingCriteria needs to be subclassed")}}class a extends i.Callable{constructor(){super(),this.criteria=[]}push(w){this.criteria.push(w)}extend(w){w instanceof a?w=w.criteria:w instanceof o&&(w=[w]),this.criteria.push(...w)}_call(w,_){const M=new Array(w.length).fill(!1);for(const T of this.criteria){const F=T(w,_);for(let C=0;C_.length>=this.max_length)}}class d extends o{constructor(w){super(),Array.isArray(w)||(w=[w]),this.eos_token_id=w}_call(w,_){return w.map(M=>{const T=M.at(-1);return this.eos_token_id.some(F=>T==F)})}}class c extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(w,_){return new Array(w.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,t,n)=>{n.r(t),n.d(t,{BaseStreamer:()=>l,TextStreamer:()=>c,WhisperTextStreamer:()=>h});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?w=>process.stdout.write(w):w=>console.log(w);class c extends l{constructor(_,{skip_prompt:M=!1,callback_function:T=null,token_callback_function:F=null,decode_kwargs:C={},...E}={}){super(),this.tokenizer=_,this.skip_prompt=M,this.callback_function=T??d,this.token_callback_function=F,this.decode_kwargs={...C,...E},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(_){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 M=_[0];this.token_callback_function?.(M),this.token_cache=(0,i.mergeArrays)(this.token_cache,M);const T=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let F;T.endsWith(` `)?(F=T.slice(this.print_len),this.token_cache=[],this.print_len=0):T.length>0&&(0,o.is_chinese_char)(T.charCodeAt(T.length-1))?(F=T.slice(this.print_len),this.print_len+=F.length):(F=T.slice(this.print_len,T.lastIndexOf(" ")+1),this.print_len+=F.length),this.on_finalized_text(F,!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(_,M){_.length>0&&this.callback_function?.(_),M&&this.callback_function===d&&a.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}}class h extends c{constructor(_,{skip_prompt:M=!1,callback_function:T=null,token_callback_function:F=null,on_chunk_start:C=null,on_chunk_end:E=null,on_finalize:x=null,time_precision:S=.02,skip_special_tokens:P=!0,decode_kwargs:j={}}={}){super(_,{skip_prompt:M,callback_function:T,token_callback_function:F,decode_kwargs:{skip_special_tokens:P,...j}}),this.timestamp_begin=_.timestamp_begin,this.on_chunk_start=C,this.on_chunk_end=E,this.on_finalize=x,this.time_precision=S,this.waiting_for_timestamp=!1}put(_){if(_.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const M=_[0];if(M.length===1){const T=Number(M[0])-this.timestamp_begin;if(T>=0){const F=T*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(F):this.on_chunk_start?.(F),this.waiting_for_timestamp=!this.waiting_for_timestamp,_=[[]]}}return super.put(_)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(e,t,n)=>{n.r(t),n.d(t,{ASTForAudioClassification:()=>la,ASTModel:()=>pn,ASTPreTrainedModel:()=>Pi,AlbertForMaskedLM:()=>En,AlbertForQuestionAnswering:()=>vs,AlbertForSequenceClassification:()=>Gs,AlbertModel:()=>ki,AlbertPreTrainedModel:()=>Hi,AutoModel:()=>Mp,AutoModelForAudioClassification:()=>e_,AutoModelForAudioFrameClassification:()=>zp,AutoModelForCTC:()=>Op,AutoModelForCausalLM:()=>Ep,AutoModelForDepthEstimation:()=>Bp,AutoModelForDocumentQuestionAnswering:()=>Rp,AutoModelForImageClassification:()=>Ap,AutoModelForImageFeatureExtraction:()=>jp,AutoModelForImageMatting:()=>Lp,AutoModelForImageSegmentation:()=>$p,AutoModelForImageToImage:()=>t_,AutoModelForMaskGeneration:()=>Bf,AutoModelForMaskedLM:()=>Cp,AutoModelForNormalEstimation:()=>Np,AutoModelForObjectDetection:()=>Ip,AutoModelForQuestionAnswering:()=>Rf,AutoModelForSemanticSegmentation:()=>Lf,AutoModelForSeq2SeqLM:()=>Jl,AutoModelForSequenceClassification:()=>Df,AutoModelForSpeechSeq2Seq:()=>Sp,AutoModelForTextToSpectrogram:()=>kp,AutoModelForTextToWaveform:()=>zf,AutoModelForTokenClassification:()=>Tp,AutoModelForVision2Seq:()=>Pp,AutoModelForXVector:()=>Dp,AutoModelForZeroShotObjectDetection:()=>Fp,BartForConditionalGeneration:()=>q,BartForSequenceClassification:()=>ye,BartModel:()=>nt,BartPretrainedModel:()=>wi,BaseModelOutput:()=>ht,BeitForImageClassification:()=>Li,BeitModel:()=>Kn,BeitPreTrainedModel:()=>Hn,BertForMaskedLM:()=>ut,BertForQuestionAnswering:()=>Ve,BertForSequenceClassification:()=>Mt,BertForTokenClassification:()=>Ft,BertModel:()=>Ze,BertPreTrainedModel:()=>Qe,BlenderbotForConditionalGeneration:()=>Qt,BlenderbotModel:()=>nn,BlenderbotPreTrainedModel:()=>zt,BlenderbotSmallForConditionalGeneration:()=>qn,BlenderbotSmallModel:()=>Cn,BlenderbotSmallPreTrainedModel:()=>nr,BloomForCausalLM:()=>$,BloomModel:()=>v,BloomPreTrainedModel:()=>f,CLIPModel:()=>Oo,CLIPPreTrainedModel:()=>po,CLIPSegForImageSegmentation:()=>go,CLIPSegModel:()=>ci,CLIPSegPreTrainedModel:()=>Ro,CLIPTextModelWithProjection:()=>Ai,CLIPVisionModelWithProjection:()=>Do,CamembertForMaskedLM:()=>ve,CamembertForQuestionAnswering:()=>Ye,CamembertForSequenceClassification:()=>Ne,CamembertForTokenClassification:()=>rt,CamembertModel:()=>kt,CamembertPreTrainedModel:()=>Jt,CausalLMOutput:()=>Ko,CausalLMOutputWithPast:()=>Vp,ChineseCLIPModel:()=>ha,ChineseCLIPPreTrainedModel:()=>fa,ClapAudioModelWithProjection:()=>of,ClapModel:()=>rf,ClapPreTrainedModel:()=>sc,ClapTextModelWithProjection:()=>sf,CodeGenForCausalLM:()=>Ha,CodeGenModel:()=>Ki,CodeGenPreTrainedModel:()=>yo,CohereForCausalLM:()=>_a,CohereModel:()=>Za,CoherePreTrainedModel:()=>Ya,ConvBertForMaskedLM:()=>H,ConvBertForQuestionAnswering:()=>_e,ConvBertForSequenceClassification:()=>se,ConvBertForTokenClassification:()=>K,ConvBertModel:()=>Ee,ConvBertPreTrainedModel:()=>de,ConvNextForImageClassification:()=>Pd,ConvNextModel:()=>Cd,ConvNextPreTrainedModel:()=>Bu,ConvNextV2ForImageClassification:()=>$d,ConvNextV2Model:()=>Ad,ConvNextV2PreTrainedModel:()=>Nu,DPTForDepthEstimation:()=>bd,DPTModel:()=>wd,DPTPreTrainedModel:()=>zu,DebertaForMaskedLM:()=>jt,DebertaForQuestionAnswering:()=>Vt,DebertaForSequenceClassification:()=>it,DebertaForTokenClassification:()=>en,DebertaModel:()=>At,DebertaPreTrainedModel:()=>mt,DebertaV2ForMaskedLM:()=>fn,DebertaV2ForQuestionAnswering:()=>mn,DebertaV2ForSequenceClassification:()=>Tn,DebertaV2ForTokenClassification:()=>bn,DebertaV2Model:()=>hn,DebertaV2PreTrainedModel:()=>xt,DeiTForImageClassification:()=>gd,DeiTModel:()=>md,DeiTPreTrainedModel:()=>Pu,DepthAnythingForDepthEstimation:()=>Md,DepthAnythingPreTrainedModel:()=>xd,DetrForObjectDetection:()=>si,DetrForSegmentation:()=>Fs,DetrModel:()=>ii,DetrObjectDetectionOutput:()=>oi,DetrPreTrainedModel:()=>Un,DetrSegmentationOutput:()=>hs,Dinov2ForImageClassification:()=>Fd,Dinov2Model:()=>Id,Dinov2PreTrainedModel:()=>ju,DistilBertForMaskedLM:()=>Ht,DistilBertForQuestionAnswering:()=>Et,DistilBertForSequenceClassification:()=>In,DistilBertForTokenClassification:()=>Mn,DistilBertModel:()=>An,DistilBertPreTrainedModel:()=>Sn,DonutSwinModel:()=>Ms,DonutSwinPreTrainedModel:()=>Ed,EfficientNetForImageClassification:()=>fp,EfficientNetModel:()=>cf,EfficientNetPreTrainedModel:()=>uc,ElectraForMaskedLM:()=>Xe,ElectraForQuestionAnswering:()=>Dt,ElectraForSequenceClassification:()=>St,ElectraForTokenClassification:()=>ft,ElectraModel:()=>Ie,ElectraPreTrainedModel:()=>pe,EsmForMaskedLM:()=>os,EsmForSequenceClassification:()=>ao,EsmForTokenClassification:()=>vr,EsmModel:()=>zr,EsmPreTrainedModel:()=>un,FalconForCausalLM:()=>ic,FalconModel:()=>nf,FalconPreTrainedModel:()=>tf,FastViTForImageClassification:()=>tt,FastViTModel:()=>He,FastViTPreTrainedModel:()=>ot,Florence2ForConditionalGeneration:()=>Fo,Florence2PreTrainedModel:()=>ua,GLPNForDepthEstimation:()=>kd,GLPNModel:()=>rp,GLPNPreTrainedModel:()=>Lu,GPT2LMHeadModel:()=>Lo,GPT2Model:()=>Wa,GPT2PreTrainedModel:()=>Hs,GPTBigCodeForCausalLM:()=>_o,GPTBigCodeModel:()=>Ll,GPTBigCodePreTrainedModel:()=>gi,GPTJForCausalLM:()=>qa,GPTJModel:()=>Rl,GPTJPreTrainedModel:()=>ga,GPTNeoForCausalLM:()=>pa,GPTNeoModel:()=>$s,GPTNeoPreTrainedModel:()=>No,GPTNeoXForCausalLM:()=>ma,GPTNeoXModel:()=>Vo,GPTNeoXPreTrainedModel:()=>jo,Gemma2ForCausalLM:()=>Uo,Gemma2Model:()=>Nl,Gemma2PreTrainedModel:()=>Ri,GemmaForCausalLM:()=>Bl,GemmaModel:()=>Ja,GemmaPreTrainedModel:()=>ya,HubertForCTC:()=>Hd,HubertForSequenceClassification:()=>lp,HubertModel:()=>qd,HubertPreTrainedModel:()=>ap,ImageMattingOutput:()=>jf,JAISLMHeadModel:()=>Bo,JAISModel:()=>Ga,JAISPreTrainedModel:()=>$i,LlamaForCausalLM:()=>Qa,LlamaModel:()=>Xa,LlamaPreTrainedModel:()=>Ka,LlavaForConditionalGeneration:()=>ho,LlavaPreTrainedModel:()=>zl,LongT5ForConditionalGeneration:()=>ws,LongT5Model:()=>mr,LongT5PreTrainedModel:()=>qs,M2M100ForConditionalGeneration:()=>Wu,M2M100Model:()=>wo,M2M100PreTrainedModel:()=>Ks,MBartForCausalLM:()=>tn,MBartForConditionalGeneration:()=>ct,MBartForSequenceClassification:()=>Pt,MBartModel:()=>De,MBartPreTrainedModel:()=>Le,MPNetForMaskedLM:()=>lo,MPNetForQuestionAnswering:()=>Gi,MPNetForSequenceClassification:()=>Ws,MPNetForTokenClassification:()=>Ar,MPNetModel:()=>us,MPNetPreTrainedModel:()=>ls,MT5ForConditionalGeneration:()=>xr,MT5Model:()=>fs,MT5PreTrainedModel:()=>ds,MarianMTModel:()=>vo,MarianModel:()=>sp,MarianPreTrainedModel:()=>Uu,MaskedLMOutput:()=>_i,MistralForCausalLM:()=>nc,MistralModel:()=>Zd,MistralPreTrainedModel:()=>tc,MobileBertForMaskedLM:()=>as,MobileBertForQuestionAnswering:()=>mi,MobileBertForSequenceClassification:()=>kr,MobileBertModel:()=>br,MobileBertPreTrainedModel:()=>Qr,MobileNetV1ForImageClassification:()=>Yl,MobileNetV1Model:()=>mp,MobileNetV1PreTrainedModel:()=>fc,MobileNetV2ForImageClassification:()=>df,MobileNetV2Model:()=>hc,MobileNetV2PreTrainedModel:()=>xa,MobileNetV3ForImageClassification:()=>hf,MobileNetV3Model:()=>ff,MobileNetV3PreTrainedModel:()=>pc,MobileNetV4ForImageClassification:()=>mf,MobileNetV4Model:()=>pf,MobileNetV4PreTrainedModel:()=>Zl,MobileViTForImageClassification:()=>wt,MobileViTModel:()=>vt,MobileViTPreTrainedModel:()=>gt,MobileViTV2ForImageClassification:()=>on,MobileViTV2Model:()=>Gt,MobileViTV2PreTrainedModel:()=>_t,ModelOutput:()=>xe,Moondream1ForConditionalGeneration:()=>Ln,MptForCausalLM:()=>le,MptModel:()=>Y,MptPreTrainedModel:()=>U,MusicgenForCausalLM:()=>pp,MusicgenForConditionalGeneration:()=>dc,MusicgenModel:()=>hp,MusicgenPreTrainedModel:()=>cc,NomicBertModel:()=>lt,NomicBertPreTrainedModel:()=>ke,OPTForCausalLM:()=>Ke,OPTModel:()=>ze,OPTPreTrainedModel:()=>Me,OpenELMForCausalLM:()=>Wo,OpenELMModel:()=>Rr,OpenELMPreTrainedModel:()=>Xi,OwlViTForObjectDetection:()=>an,OwlViTModel:()=>rn,OwlViTPreTrainedModel:()=>Wt,Owlv2ForObjectDetection:()=>jn,Owlv2Model:()=>Bn,Owlv2PreTrainedModel:()=>Ut,Phi3ForCausalLM:()=>el,Phi3Model:()=>xs,Phi3PreTrainedModel:()=>bs,PhiForCausalLM:()=>Go,PhiModel:()=>Is,PhiPreTrainedModel:()=>wa,PreTrainedModel:()=>ne,PretrainedMixin:()=>Er,PyAnnoteForAudioFrameClassification:()=>Nd,PyAnnoteModel:()=>Bd,PyAnnotePreTrainedModel:()=>Hu,QuestionAnsweringModelOutput:()=>Fi,Qwen2ForCausalLM:()=>va,Qwen2Model:()=>jl,Qwen2PreTrainedModel:()=>bi,RTDetrForObjectDetection:()=>cd,RTDetrModel:()=>ud,RTDetrObjectDetectionOutput:()=>dd,RTDetrPreTrainedModel:()=>qo,ResNetForImageClassification:()=>yd,ResNetModel:()=>_d,ResNetPreTrainedModel:()=>Au,RoFormerForMaskedLM:()=>z,RoFormerForQuestionAnswering:()=>he,RoFormerForSequenceClassification:()=>Fe,RoFormerForTokenClassification:()=>Oe,RoFormerModel:()=>bt,RoFormerPreTrainedModel:()=>dt,RobertaForMaskedLM:()=>Ei,RobertaForQuestionAnswering:()=>Yr,RobertaForSequenceClassification:()=>Mr,RobertaForTokenClassification:()=>yt,RobertaModel:()=>Qn,RobertaPreTrainedModel:()=>kn,SamImageSegmentationOutput:()=>Ld,SamModel:()=>Rd,SamPreTrainedModel:()=>zd,SapiensForDepthEstimation:()=>Td,SapiensForNormalEstimation:()=>Sd,SapiensForSemanticSegmentation:()=>Ru,SapiensPreTrainedModel:()=>Vl,SegformerForImageClassification:()=>af,SegformerForSemanticSegmentation:()=>lf,SegformerModel:()=>cp,SegformerPreTrainedModel:()=>Ql,Seq2SeqLMOutput:()=>n_,SequenceClassifierOutput:()=>Yn,SiglipModel:()=>mo,SiglipPreTrainedModel:()=>ca,SiglipTextModel:()=>zo,SiglipVisionModel:()=>da,SpeechT5ForSpeechToText:()=>Kl,SpeechT5ForTextToSpeech:()=>Yd,SpeechT5HifiGan:()=>Xl,SpeechT5Model:()=>Zu,SpeechT5PreTrainedModel:()=>Hl,SqueezeBertForMaskedLM:()=>qi,SqueezeBertForQuestionAnswering:()=>cs,SqueezeBertForSequenceClassification:()=>Si,SqueezeBertModel:()=>$o,SqueezeBertPreTrainedModel:()=>li,StableLmForCausalLM:()=>uf,StableLmModel:()=>dp,StableLmPreTrainedModel:()=>lc,Starcoder2ForCausalLM:()=>ef,Starcoder2Model:()=>Jd,Starcoder2PreTrainedModel:()=>rc,Swin2SRForImageSuperResolution:()=>Du,Swin2SRModel:()=>Ou,Swin2SRPreTrainedModel:()=>Fu,SwinForImageClassification:()=>Iu,SwinModel:()=>vd,SwinPreTrainedModel:()=>$u,T5ForConditionalGeneration:()=>co,T5Model:()=>uo,T5PreTrainedModel:()=>Xn,TableTransformerForObjectDetection:()=>hd,TableTransformerModel:()=>fd,TableTransformerObjectDetectionOutput:()=>pd,TableTransformerPreTrainedModel:()=>Cu,TokenClassifierOutput:()=>di,TrOCRForCausalLM:()=>ec,TrOCRPreTrainedModel:()=>Ju,UniSpeechForCTC:()=>jd,UniSpeechForSequenceClassification:()=>Xu,UniSpeechModel:()=>ql,UniSpeechPreTrainedModel:()=>Gl,UniSpeechSatForAudioFrameClassification:()=>Wd,UniSpeechSatForCTC:()=>Ud,UniSpeechSatForSequenceClassification:()=>op,UniSpeechSatModel:()=>Vd,UniSpeechSatPreTrainedModel:()=>Ho,ViTForImageClassification:()=>We,ViTModel:()=>st,ViTPreTrainedModel:()=>Ge,VisionEncoderDecoderModel:()=>Io,VitMatteForImageMatting:()=>Je,VitMattePreTrainedModel:()=>at,VitsModel:()=>ac,VitsModelOutput:()=>Vf,VitsPreTrainedModel:()=>oc,Wav2Vec2BertForCTC:()=>Gd,Wav2Vec2BertForSequenceClassification:()=>Qu,Wav2Vec2BertModel:()=>nl,Wav2Vec2BertPreTrainedModel:()=>tl,Wav2Vec2ForAudioFrameClassification:()=>qu,Wav2Vec2ForCTC:()=>Gu,Wav2Vec2ForSequenceClassification:()=>Ul,Wav2Vec2Model:()=>xi,Wav2Vec2PreTrainedModel:()=>Bi,WavLMForAudioFrameClassification:()=>Qd,WavLMForCTC:()=>up,WavLMForSequenceClassification:()=>Yu,WavLMForXVector:()=>Xd,WavLMModel:()=>Kd,WavLMPreTrainedModel:()=>ba,WeSpeakerResNetModel:()=>Ku,WeSpeakerResNetPreTrainedModel:()=>Wl,WhisperForConditionalGeneration:()=>fo,WhisperModel:()=>vn,WhisperPreTrainedModel:()=>Lt,XLMForQuestionAnswering:()=>$r,XLMForSequenceClassification:()=>xn,XLMForTokenClassification:()=>Ci,XLMModel:()=>Dr,XLMPreTrainedModel:()=>er,XLMRobertaForMaskedLM:()=>sn,XLMRobertaForQuestionAnswering:()=>Ir,XLMRobertaForSequenceClassification:()=>tr,XLMRobertaForTokenClassification:()=>pr,XLMRobertaModel:()=>ar,XLMRobertaPreTrainedModel:()=>or,XLMWithLMHeadModel:()=>ui,XVectorOutput:()=>Nf,YolosForObjectDetection:()=>Od,YolosModel:()=>ip,YolosObjectDetectionOutput:()=>Dd,YolosPreTrainedModel:()=>Vu});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"),h=n("./src/generation/logits_process.js"),w=n("./src/generation/configuration_utils.js"),_=n("./src/utils/tensor.js"),M=n("./src/utils/maths.js"),T=n("./src/generation/stopping_criteria.js"),F=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 S={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},P=new Map,j=new Map,L=new Map;async function N(X,R,be){let Ue=be.device;Ue&&typeof Ue!="string"&&(Ue.hasOwnProperty(R)?Ue=Ue[R]:(console.warn(`device not specified for "${R}". Using the default device.`),Ue=null));const Ct=Ue??(C.apis.IS_NODE_ENV?"cpu":"wasm"),Bt=(0,o.deviceToExecutionProviders)(Ct);let qt=be.dtype;typeof qt!="string"&&(qt&&qt.hasOwnProperty(R)?qt=qt[R]:(qt=a.DEFAULT_DEVICE_DTYPE_MAPPING[Ct]??a.DATA_TYPES.fp32,console.warn(`dtype not specified for "${R}". Using the default dtype (${qt}) for this device (${Ct}).`)));const cn=qt;if(a.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(cn)){if(cn===a.DATA_TYPES.fp16&&Ct==="webgpu"&&!await(0,a.isWebGpuFp16Supported)())throw new Error(`The device (${Ct}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${cn}. Should be one of: ${Object.keys(a.DATA_TYPES).join(", ")}`);const Fn=a.DEFAULT_DTYPE_SUFFIX_MAPPING[cn],sr=`${be.subfolder??""}/${R}${Fn}.onnx`,gr={...be.session_options};gr.executionProviders??=Bt;const Tr=(0,c.getModelFile)(X,sr,!0,be);let rr=[];if(be.use_external_data_format&&(be.use_external_data_format===!0||typeof be.use_external_data_format=="object"&&be.use_external_data_format.hasOwnProperty(R)&&be.use_external_data_format[R]===!0)){if(C.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const Cr=`${R}${Fn}.onnx_data`,Wn=`${be.subfolder??""}/${Cr}`;rr.push(new Promise(async(cr,Wr)=>{const fi=await(0,c.getModelFile)(X,Wn,!0,be);cr({path:Cr,data:fi})}))}else gr.externalData!==void 0&&(rr=gr.externalData.map(async Cr=>{if(typeof Cr.data=="string"){const Wn=await(0,c.getModelFile)(X,Cr.data,!0,be);return{...Cr,data:Wn}}return Cr}));if(rr.length>0&&(gr.externalData=await Promise.all(rr)),Ct==="webgpu"){const Cr=(0,i.getKeyValueShapes)(be.config,{prefix:"present"});if(Object.keys(Cr).length>0&&!(0,o.isONNXProxy)()){const Wn={};for(const cr in Cr)Wn[cr]="gpu-buffer";gr.preferredOutputLocation=Wn}}return{buffer:await Tr,session_options:gr}}async function W(X,R,be){return Object.fromEntries(await Promise.all(Object.keys(R).map(async Ue=>{const{buffer:Ct,session_options:Bt}=await N(X,R[Ue],be),qt=await(0,o.createInferenceSession)(Ct,Bt);return[Ue,qt]})))}function V(X,R){const be=Object.create(null),Ue=[];for(const qt of X.inputNames){const cn=R[qt];if(!(cn instanceof _.Tensor)){Ue.push(qt);continue}be[qt]=(0,o.isONNXProxy)()?cn.clone():cn}if(Ue.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Ue.join(", ")}.`);const Ct=Object.keys(R).length,Bt=X.inputNames.length;if(Ct>Bt){let qt=Object.keys(R).filter(cn=>!X.inputNames.includes(cn));console.warn(`WARNING: Too many inputs were provided (${Ct} > ${Bt}). The following inputs will be ignored: "${qt.join(", ")}".`)}return be}async function ce(X,R){const be=V(X,R);try{const Ue=Object.fromEntries(Object.entries(be).map(([Bt,qt])=>[Bt,qt.ort_tensor]));let Ct=await X.run(Ue);return Ct=ge(Ct),Ct}catch(Ue){throw console.error(`An error occurred during model execution: "${Ue}".`),console.error("Inputs given to model:",be),Ue}}function ge(X){for(let R in X)(0,o.isONNXTensor)(X[R])?X[R]=new _.Tensor(X[R]):typeof X[R]=="object"&&ge(X[R]);return X}function Re(X){if(X instanceof _.Tensor)return X;if(X.length===0)throw Error("items must be non-empty");if(Array.isArray(X[0])){if(X.some(R=>R.length!==X[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(X.flat().map(R=>BigInt(R))),[X.length,X[0].length])}else return new _.Tensor("int64",BigInt64Array.from(X.map(R=>BigInt(R))),[1,X.length])}function oe(X){return new _.Tensor("bool",[X],[1])}async function Se(X,R){let{encoder_outputs:be,input_ids:Ue,decoder_input_ids:Ct,...Bt}=R;if(!be){const cn=(0,d.pick)(R,X.sessions.model.inputNames);be=(await G(X,cn)).last_hidden_state}return Bt.input_ids=Ct,Bt.encoder_hidden_states=be,X.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Bt.encoder_attention_mask=R.attention_mask),await Ce(X,Bt,!0)}async function G(X,R){const be=X.sessions.model,Ue=(0,d.pick)(R,be.inputNames);if(be.inputNames.includes("inputs_embeds")&&!Ue.inputs_embeds){if(!R.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Ue.inputs_embeds=await X.encode_text({input_ids:R.input_ids})}return be.inputNames.includes("token_type_ids")&&!Ue.token_type_ids&&(Ue.token_type_ids=new _.Tensor("int64",new BigInt64Array(Ue.input_ids.data.length),Ue.input_ids.dims)),await ce(be,Ue)}async function Ce(X,R,be=!1){const Ue=X.sessions[be?"decoder_model_merged":"model"],{past_key_values:Ct,...Bt}=R;Ue.inputNames.includes("use_cache_branch")&&(Bt.use_cache_branch=oe(!!Ct)),Ue.inputNames.includes("position_ids")&&Bt.attention_mask&&!Bt.position_ids&&(Bt.position_ids=Te(Bt,Ct)),X.addPastKeyValues(Bt,Ct);const qt=(0,d.pick)(Bt,Ue.inputNames);return await ce(Ue,qt)}async function pt(X,{input_ids:R=null,attention_mask:be=null,pixel_values:Ue=null,position_ids:Ct=null,inputs_embeds:Bt=null,past_key_values:qt=null,generation_config:cn=null,logits_processor:Fn=null,...sr}){if(!Bt){if(Bt=await X.encode_text({input_ids:R}),Ue&&R.dims[1]!==1){const Tr=await X.encode_image({pixel_values:Ue});({inputs_embeds:Bt,attention_mask:be}=X._merge_input_ids_with_image_features({image_features:Tr,inputs_embeds:Bt,input_ids:R,attention_mask:be}))}else if(qt&&Ue&&R.dims[1]===1){const Tr=R.dims[1],rr=Object.values(qt)[0].dims.at(-2);be=(0,_.cat)([(0,_.ones)([R.dims[0],rr]),be.slice(null,[be.dims[1]-Tr,be.dims[1]])],1)}}return await Ce(X,{inputs_embeds:Bt,past_key_values:qt,attention_mask:be,position_ids:Ct,generation_config:cn,logits_processor:Fn},!0)}function Te(X,R=null){const{input_ids:be,inputs_embeds:Ue,attention_mask:Ct}=X,[Bt,qt]=Ct.dims,cn=new BigInt64Array(Ct.data.length);for(let sr=0;srBt.dims[1])){if(Ctcn==X.config.image_token_index)){const cn=X.config.num_image_tokens;if(!cn)throw new Error("`num_image_tokens` is missing in the model configuration.");const Fn=Bt.dims[1]-(Ct-cn);be.input_ids=Bt.slice(null,[-Fn,null]),be.attention_mask=(0,_.ones)([1,Ct+Fn])}}}return be}function fe(X,R,be,Ue){return be.past_key_values&&(R=R.map(Ct=>[Ct.at(-1)])),{...be,decoder_input_ids:Re(R)}}function Pe(X,...R){return X.config.is_encoder_decoder?fe(X,...R):te(X,...R)}class ne extends l.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(R,be){super(),this.config=R,this.sessions=be;const Ue=L.get(this.constructor),Ct=P.get(Ue);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ct){case S.DecoderOnly:this.can_generate=!0,this._forward=Ce,this._prepare_inputs_for_generation=te;break;case S.Seq2Seq:case S.Vision2Seq:case S.Musicgen:this.can_generate=!0,this._forward=Se,this._prepare_inputs_for_generation=fe;break;case S.EncoderDecoder:this._forward=Se;break;case S.ImageTextToText:this.can_generate=!0,this._forward=pt,this._prepare_inputs_for_generation=Pe;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(){const R=[];for(const be of Object.values(this.sessions))be?.handler?.dispose&&R.push(be.handler.dispose());return await Promise.all(R)}static async from_pretrained(R,{progress_callback:be=null,config:Ue=null,cache_dir:Ct=null,local_files_only:Bt=!1,revision:qt="main",model_file_name:cn=null,subfolder:Fn="onnx",device:sr=null,dtype:gr=null,use_external_data_format:Tr=null,session_options:rr={}}={}){let zn={progress_callback:be,config:Ue,cache_dir:Ct,local_files_only:Bt,revision:qt,model_file_name:cn,subfolder:Fn,device:sr,dtype:gr,use_external_data_format:Tr,session_options:rr};const Cr=L.get(this),Wn=P.get(Cr);Ue=zn.config=await i.AutoConfig.from_pretrained(R,zn);let cr;if(Wn===S.DecoderOnly)cr=await Promise.all([W(R,{model:zn.model_file_name??"model"},zn),(0,c.getModelJSON)(R,"generation_config.json",!1,zn)]);else if(Wn===S.Seq2Seq||Wn===S.Vision2Seq)cr=await Promise.all([W(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},zn),(0,c.getModelJSON)(R,"generation_config.json",!1,zn)]);else if(Wn===S.MaskGeneration)cr=await Promise.all([W(R,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},zn)]);else if(Wn===S.EncoderDecoder)cr=await Promise.all([W(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},zn)]);else if(Wn===S.ImageTextToText){const Wr={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ue.is_encoder_decoder&&(Wr.model="encoder_model"),cr=await Promise.all([W(R,Wr,zn),(0,c.getModelJSON)(R,"generation_config.json",!1,zn)])}else Wn===S.Musicgen?cr=await Promise.all([W(R,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},zn),(0,c.getModelJSON)(R,"generation_config.json",!1,zn)]):(Wn!==S.EncoderOnly&&console.warn(`Model type for '${Cr??Ue?.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),cr=await Promise.all([W(R,{model:zn.model_file_name??"model"},zn)]));return new this(Ue,...cr)}async _call(R){return await this.forward(R)}async forward(R){return await this._forward(this,R)}_get_logits_warper(R){const be=new h.LogitsProcessorList;return R.temperature!==null&&R.temperature!==1&&be.push(new h.TemperatureLogitsWarper(R.temperature)),R.top_k!==null&&R.top_k!==0&&be.push(new h.TopKLogitsWarper(R.top_k)),R.top_p!==null&&R.top_p<1&&be.push(new h.TopPLogitsWarper(R.top_p)),be}_get_logits_processor(R,be,Ue=null){const Ct=new h.LogitsProcessorList;if(R.repetition_penalty!==null&&R.repetition_penalty!==1&&Ct.push(new h.RepetitionPenaltyLogitsProcessor(R.repetition_penalty)),R.no_repeat_ngram_size!==null&&R.no_repeat_ngram_size>0&&Ct.push(new h.NoRepeatNGramLogitsProcessor(R.no_repeat_ngram_size)),R.bad_words_ids!==null&&Ct.push(new h.NoBadWordsLogitsProcessor(R.bad_words_ids,R.eos_token_id)),R.min_length!==null&&R.eos_token_id!==null&&R.min_length>0&&Ct.push(new h.MinLengthLogitsProcessor(R.min_length,R.eos_token_id)),R.min_new_tokens!==null&&R.eos_token_id!==null&&R.min_new_tokens>0&&Ct.push(new h.MinNewTokensLengthLogitsProcessor(be,R.min_new_tokens,R.eos_token_id)),R.forced_bos_token_id!==null&&Ct.push(new h.ForcedBOSTokenLogitsProcessor(R.forced_bos_token_id)),R.forced_eos_token_id!==null&&Ct.push(new h.ForcedEOSTokenLogitsProcessor(R.max_length,R.forced_eos_token_id)),R.begin_suppress_tokens!==null){const Bt=be>1||R.forced_bos_token_id===null?be:be+1;Ct.push(new h.SuppressTokensAtBeginLogitsProcessor(R.begin_suppress_tokens,Bt))}return R.guidance_scale!==null&&R.guidance_scale>1&&Ct.push(new h.ClassifierFreeGuidanceLogitsProcessor(R.guidance_scale)),Ue!==null&&Ct.extend(Ue),Ct}_prepare_generation_config(R,be,Ue=w.GenerationConfig){const Ct={...this.config};for(const qt of["decoder","generator","text_config"])qt in Ct&&Object.assign(Ct,Ct[qt]);const Bt=new Ue(Ct);return"generation_config"in this&&Object.assign(Bt,this.generation_config),R&&Object.assign(Bt,R),be&&Object.assign(Bt,(0,d.pick)(be,Object.getOwnPropertyNames(Bt))),Bt}_get_stopping_criteria(R,be=null){const Ue=new T.StoppingCriteriaList;return R.max_length!==null&&Ue.push(new T.MaxLengthCriteria(R.max_length,this.config.max_position_embeddings??null)),R.eos_token_id!==null&&Ue.push(new T.EosTokenCriteria(R.eos_token_id)),be&&Ue.extend(be),Ue}_validate_model_class(){if(!this.can_generate){const R=[wf,_c,gc,mc],be=L.get(this.constructor),Ue=new Set,Ct=this.config.model_type;for(const qt of R){const cn=qt.get(Ct);cn&&Ue.add(cn[0])}let Bt=`The current model class (${be}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ue.size>0&&(Bt+=` Please use the following class instead: ${[...Ue].join(", ")}`),Error(Bt)}}prepare_inputs_for_generation(...R){return this._prepare_inputs_for_generation(this,...R)}_update_model_kwargs_for_generation({generated_input_ids:R,outputs:be,model_inputs:Ue,is_encoder_decoder:Ct}){return Ue.past_key_values=this.getPastKeyValues(be,Ue.past_key_values),Ue.input_ids=new _.Tensor("int64",R.flat(),[R.length,1]),Ct||(Ue.attention_mask=(0,_.cat)([Ue.attention_mask,(0,_.ones)([Ue.attention_mask.dims[0],1])],1)),Ue.position_ids=null,Ue}_prepare_model_inputs({inputs:R,bos_token_id:be,model_kwargs:Ue}){const Ct=(0,d.pick)(Ue,this.forward_params),Bt=this.main_input_name;if(Bt in Ct){if(R)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Ct[Bt]=R;return{inputs_tensor:Ct[Bt],model_inputs:Ct,model_input_name:Bt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:R,model_inputs:be,model_input_name:Ue,generation_config:Ct}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!be.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:qt,pixel_values:cn,attention_mask:Fn,...sr}=be,gr=await this._prepare_inputs_embeds(be);be={...sr,...(0,d.pick)(gr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Bt}=await G(this,be);if(Ct.guidance_scale!==null&&Ct.guidance_scale>1)Bt=(0,_.cat)([Bt,(0,_.full_like)(Bt,0)],0),"attention_mask"in be&&(be.attention_mask=(0,_.cat)([be.attention_mask,(0,_.zeros_like)(be.attention_mask)],0));else if(be.decoder_input_ids){const qt=Re(be.decoder_input_ids).dims[0];if(qt!==Bt.dims[0]){if(Bt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Bt.dims[0]}) than the decoder inputs (${qt}).`);Bt=(0,_.cat)(Array.from({length:qt},()=>Bt),0)}}return be.encoder_outputs=Bt,be}_prepare_decoder_input_ids_for_generation({batch_size:R,model_input_name:be,model_kwargs:Ue,decoder_start_token_id:Ct,bos_token_id:Bt,generation_config:qt}){let{decoder_input_ids:cn,...Fn}=Ue;if(cn)Array.isArray(cn[0])||(cn=Array.from({length:R},()=>cn));else if(Ct??=Bt,this.config.model_type==="musicgen")cn=Array.from({length:R*this.config.decoder.num_codebooks},()=>[Ct]);else if(Array.isArray(Ct)){if(Ct.length!==R)throw new Error(`\`decoder_start_token_id\` expcted to have length ${R} but got ${Ct.length}`);cn=Ct}else cn=Array.from({length:R},()=>[Ct]);return cn=Re(cn),Ue.decoder_attention_mask=(0,_.ones_like)(cn),{input_ids:cn,model_inputs:Fn}}async generate({inputs:R=null,generation_config:be=null,logits_processor:Ue=null,stopping_criteria:Ct=null,streamer:Bt=null,...qt}){this._validate_model_class(),be=this._prepare_generation_config(be,qt);let{inputs_tensor:cn,model_inputs:Fn,model_input_name:sr}=this._prepare_model_inputs({inputs:R,model_kwargs:qt});const gr=this.config.is_encoder_decoder;gr&&("encoder_outputs"in Fn||(Fn=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:cn,model_inputs:Fn,model_input_name:sr,generation_config:be})));let Tr;gr?{input_ids:Tr,model_inputs:Fn}=this._prepare_decoder_input_ids_for_generation({batch_size:Fn[sr].dims.at(0),model_input_name:sr,model_kwargs:Fn,decoder_start_token_id:be.decoder_start_token_id,bos_token_id:be.bos_token_id,generation_config:be}):Tr=Fn[sr];let rr=Tr.dims.at(-1);be.max_new_tokens!==null&&(be.max_length=rr+be.max_new_tokens);const zn=this._get_logits_processor(be,rr,Ue),Cr=this._get_stopping_criteria(be,Ct),Wn=Fn[sr].dims.at(0),cr=F.LogitsSampler.getSampler(be),Wr=new Array(Wn).fill(0),fi=Tr.tolist();Bt&&Bt.put(fi);let bo=null,ps={};for(;;){Fn=this.prepare_inputs_for_generation(fi,Fn,be);const Hr=await this.forward(Fn);if(be.output_attentions&&be.return_dict_in_generate){const Os=this.getAttentions(Hr);for(const Ma in Os)Ma in ps||(ps[Ma]=[]),ps[Ma].push(Os[Ma])}const Yi=Hr.logits.slice(null,-1,null),eu=zn(fi,Yi),tu=[];for(let Os=0;OsOs)){be.return_dict_in_generate&&(bo=this.getPastKeyValues(Hr,Fn.past_key_values,!1));break}Fn=this._update_model_kwargs_for_generation({generated_input_ids:tu,outputs:Hr,model_inputs:Fn,is_encoder_decoder:gr})}Bt&&Bt.end();const Qi=new _.Tensor("int64",fi.flat(),[fi.length,fi[0].length]);return be.return_dict_in_generate?{sequences:Qi,past_key_values:bo,...ps}:Qi}getPastKeyValues(R,be,Ue=!0){const Ct=Object.create(null);for(const Bt in R)if(Bt.startsWith("present")){const qt=Bt.replace("present","past_key_values");if(be&&Bt.includes("encoder"))Ct[qt]=be[qt];else{if(Ue&&be){const cn=be[qt];cn.location==="gpu-buffer"&&cn.dispose()}Ct[qt]=R[Bt]}}return Ct}getAttentions(R){const be={};for(const Ue of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Ct in R)Ct.startsWith(Ue)&&(Ue in be||(be[Ue]=[]),be[Ue].push(R[Ct]));return be}addPastKeyValues(R,be){if(be)Object.assign(R,be);else{const Ue=this.custom_config.kv_cache_dtype??"float32",Ct=Ue==="float16"?new Uint16Array:[],Bt=(0,i.getKeyValueShapes)(this.config);for(const qt in Bt)R[qt]=new _.Tensor(Ue,Ct,Bt[qt])}}async encode_image({pixel_values:R}){const be=(await ce(this.sessions.vision_encoder,{pixel_values:R})).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 (${be.dims[1]}).`),this.config.num_image_tokens=be.dims[1]),be}async encode_text({input_ids:R}){return(await ce(this.sessions.embed_tokens,{input_ids:R})).inputs_embeds}}class xe{}class ht extends xe{constructor({last_hidden_state:R,hidden_states:be=null,attentions:Ue=null}){super(),this.last_hidden_state=R,this.hidden_states=be,this.attentions=Ue}}class Qe extends ne{}class Ze extends Qe{}class ut extends Qe{async _call(R){return new _i(await super._call(R))}}class Mt extends Qe{async _call(R){return new Yn(await super._call(R))}}class Ft extends Qe{async _call(R){return new di(await super._call(R))}}class Ve extends Qe{async _call(R){return new Fi(await super._call(R))}}class ke extends ne{}class lt extends ke{}class dt extends ne{}class bt extends dt{}class z extends dt{async _call(R){return new _i(await super._call(R))}}class Fe extends dt{async _call(R){return new Yn(await super._call(R))}}class Oe extends dt{async _call(R){return new di(await super._call(R))}}class he extends dt{async _call(R){return new Fi(await super._call(R))}}class de extends ne{}class Ee extends de{}class H extends de{async _call(R){return new _i(await super._call(R))}}class se extends de{async _call(R){return new Yn(await super._call(R))}}class K extends de{async _call(R){return new di(await super._call(R))}}class _e extends de{async _call(R){return new Fi(await super._call(R))}}class pe extends ne{}class Ie extends pe{}class Xe extends pe{async _call(R){return new _i(await super._call(R))}}class St extends pe{async _call(R){return new Yn(await super._call(R))}}class ft extends pe{async _call(R){return new di(await super._call(R))}}class Dt extends pe{async _call(R){return new Fi(await super._call(R))}}class Jt extends ne{}class kt extends Jt{}class ve extends Jt{async _call(R){return new _i(await super._call(R))}}class Ne extends Jt{async _call(R){return new Yn(await super._call(R))}}class rt extends Jt{async _call(R){return new di(await super._call(R))}}class Ye extends Jt{async _call(R){return new Fi(await super._call(R))}}class mt extends ne{}class At extends mt{}class jt extends mt{async _call(R){return new _i(await super._call(R))}}class it extends mt{async _call(R){return new Yn(await super._call(R))}}class en extends mt{async _call(R){return new di(await super._call(R))}}class Vt extends mt{async _call(R){return new Fi(await super._call(R))}}class xt extends ne{}class hn extends xt{}class fn extends xt{async _call(R){return new _i(await super._call(R))}}class Tn extends xt{async _call(R){return new Yn(await super._call(R))}}class bn extends xt{async _call(R){return new di(await super._call(R))}}class mn extends xt{async _call(R){return new Fi(await super._call(R))}}class Sn extends ne{}class An extends Sn{}class In extends Sn{async _call(R){return new Yn(await super._call(R))}}class Mn extends Sn{async _call(R){return new di(await super._call(R))}}class Et extends Sn{async _call(R){return new Fi(await super._call(R))}}class Ht extends Sn{async _call(R){return new _i(await super._call(R))}}class un extends ne{}class zr extends un{}class os extends un{async _call(R){return new _i(await super._call(R))}}class ao extends un{async _call(R){return new Yn(await super._call(R))}}class vr extends un{async _call(R){return new di(await super._call(R))}}class Qr extends ne{}class br extends Qr{}class as extends Qr{async _call(R){return new _i(await super._call(R))}}class kr extends Qr{async _call(R){return new Yn(await super._call(R))}}class mi extends Qr{async _call(R){return new Fi(await super._call(R))}}class ls extends ne{}class us extends ls{}class lo extends ls{async _call(R){return new _i(await super._call(R))}}class Ws extends ls{async _call(R){return new Yn(await super._call(R))}}class Ar extends ls{async _call(R){return new di(await super._call(R))}}class Gi extends ls{async _call(R){return new Fi(await super._call(R))}}class li extends ne{}class $o extends li{}class qi extends li{async _call(R){return new _i(await super._call(R))}}class Si extends li{async _call(R){return new Yn(await super._call(R))}}class cs extends li{async _call(R){return new Fi(await super._call(R))}}class Hi extends ne{}class ki extends Hi{}class Gs extends Hi{async _call(R){return new Yn(await super._call(R))}}class vs extends Hi{async _call(R){return new Fi(await super._call(R))}}class En extends Hi{async _call(R){return new _i(await super._call(R))}}class Xn extends ne{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class uo extends Xn{}class co extends Xn{}class qs extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class mr extends qs{}class ws extends qs{}class ds extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class fs extends ds{}class xr extends ds{}class wi extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class nt extends wi{}class q extends wi{}class ye extends wi{async _call(R){return new Yn(await super._call(R))}}class Le extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class De extends Le{}class ct extends Le{}class Pt extends Le{async _call(R){return new Yn(await super._call(R))}}class tn extends Le{}class zt extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class nn extends zt{}class Qt extends zt{}class nr extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class Cn extends nr{}class qn extends nr{}class kn extends ne{}class Qn extends kn{}class Ei extends kn{async _call(R){return new _i(await super._call(R))}}class Mr extends kn{async _call(R){return new Yn(await super._call(R))}}class yt extends kn{async _call(R){return new di(await super._call(R))}}class Yr extends kn{async _call(R){return new Fi(await super._call(R))}}class er extends ne{}class Dr extends er{}class ui extends er{async _call(R){return new _i(await super._call(R))}}class xn extends er{async _call(R){return new Yn(await super._call(R))}}class Ci extends er{async _call(R){return new di(await super._call(R))}}class $r extends er{async _call(R){return new Fi(await super._call(R))}}class or extends ne{}class ar extends or{}class sn extends or{async _call(R){return new _i(await super._call(R))}}class tr extends or{async _call(R){return new Yn(await super._call(R))}}class pr extends or{async _call(R){return new di(await super._call(R))}}class Ir extends or{async _call(R){return new Fi(await super._call(R))}}class Pi extends ne{}class pn extends Pi{}class la extends Pi{}class Lt extends ne{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class vn extends Lt{}class fo extends Lt{_prepare_generation_config(R,be){return super._prepare_generation_config(R,be,E.WhisperGenerationConfig)}_retrieve_init_tokens(R){const be=[R.decoder_start_token_id];let Ue=R.language;const Ct=R.task;if(R.is_multilingual){Ue||(console.warn("No language specified - defaulting to English (en)."),Ue="en");const qt=`<|${(0,x.whisper_language_to_code)(Ue)}|>`;be.push(R.lang_to_id[qt]),be.push(R.task_to_id[Ct??"transcribe"])}else if(Ue||Ct)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!R.return_timestamps&&R.no_timestamps_token_id&&be.at(-1)!==R.no_timestamps_token_id?be.push(R.no_timestamps_token_id):R.return_timestamps&&be.at(-1)===R.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),be.pop()),be.filter(Bt=>Bt!=null)}async generate({inputs:R=null,generation_config:be=null,logits_processor:Ue=null,stopping_criteria:Ct=null,...Bt}){be=this._prepare_generation_config(be,Bt);const qt=Bt.decoder_input_ids??this._retrieve_init_tokens(be);if(be.return_timestamps&&(Ue??=new h.LogitsProcessorList,Ue.push(new h.WhisperTimeStampLogitsProcessor(be,qt))),be.begin_suppress_tokens&&(Ue??=new h.LogitsProcessorList,Ue.push(new h.SuppressTokensAtBeginLogitsProcessor(be.begin_suppress_tokens,qt.length))),be.return_token_timestamps){if(!be.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.");be.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),be.output_attentions=!0,be.return_dict_in_generate=!0}const cn=await super.generate({inputs:R,generation_config:be,logits_processor:Ue,decoder_input_ids:qt,...Bt});return be.return_token_timestamps&&(cn.token_timestamps=this._extract_token_timestamps(cn,be.alignment_heads,be.num_frames)),cn}_extract_token_timestamps(R,be,Ue=null,Ct=.02){if(!R.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`.");Ue==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 Bt=this.config.median_filter_width;Bt===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Bt=7);const qt=R.cross_attentions,cn=Array.from({length:this.config.decoder_layers},(Wn,cr)=>(0,_.cat)(qt.map(Wr=>Wr[cr]),2)),Fn=(0,_.stack)(be.map(([Wn,cr])=>{if(Wn>=cn.length)throw new Error(`Layer index ${Wn} is out of bounds for cross attentions (length ${cn.length}).`);return Ue?cn[Wn].slice(null,cr,null,[0,Ue]):cn[Wn].slice(null,cr)})).transpose(1,0,2,3),[sr,gr]=(0,_.std_mean)(Fn,-2,0,!0),Tr=Fn.clone();for(let Wn=0;WnWr[Yi+1]-Wr[Yi]),ps=(0,d.mergeArrays)([1],bo).map(Hr=>!!Hr),Qi=[];for(let Hr=0;Hrrr.findIndex(zn=>zn==Bt)),Fn=cn.every(rr=>rr===-1),sr=cn.every(rr=>rr!==-1);if(!Fn&&!sr)throw new Error("Every input should contain either 0 or 1 image token.");if(Fn)return{inputs_embeds:R,attention_mask:Ct};const gr=[],Tr=[];for(let rr=0;rrBt*qt,1);R.input_labels=new _.Tensor("int64",new BigInt64Array(Ct).fill(1n),Ue)}const be={image_embeddings:R.image_embeddings,image_positional_embeddings:R.image_positional_embeddings};return R.input_points&&(be.input_points=R.input_points),R.input_labels&&(be.input_labels=R.input_labels),R.input_boxes&&(be.input_boxes=R.input_boxes),await ce(this.sessions.prompt_encoder_mask_decoder,be)}async _call(R){return new Ld(await super._call(R))}}class Ld extends xe{constructor({iou_scores:R,pred_masks:be}){super(),this.iou_scores=R,this.pred_masks=be}}class Uu extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class sp extends Uu{}class vo extends Uu{}class Ks extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class wo extends Ks{}class Wu extends Ks{}class Bi extends ne{}class xi extends Bi{}class Gu extends Bi{async _call(R){return new Ko(await super._call(R))}}class Ul extends Bi{async _call(R){return new Yn(await super._call(R))}}class qu extends Bi{async _call(R){return new di(await super._call(R))}}class Hu extends ne{}class Bd extends Hu{}class Nd extends Hu{async _call(R){return new di(await super._call(R))}}class Wl extends ne{}class Ku extends Wl{}class Gl extends ne{}class ql extends Gl{}class jd extends Gl{async _call(R){return new Ko(await super._call(R))}}class Xu extends Gl{async _call(R){return new Yn(await super._call(R))}}class Ho extends ne{}class Vd extends Ho{}class Ud extends Ho{async _call(R){return new Ko(await super._call(R))}}class op extends Ho{async _call(R){return new Yn(await super._call(R))}}class Wd extends Ho{async _call(R){return new di(await super._call(R))}}class tl extends ne{}class nl extends tl{}class Gd extends tl{async _call(R){return new Ko(await super._call(R))}}class Qu extends tl{async _call(R){return new Yn(await super._call(R))}}class ap extends ne{}class qd extends Bi{}class Hd extends Bi{async _call(R){return new Ko(await super._call(R))}}class lp extends Bi{async _call(R){return new Yn(await super._call(R))}}class ba extends ne{}class Kd extends ba{}class up extends ba{async _call(R){return new Ko(await super._call(R))}}class Yu extends ba{async _call(R){return new Yn(await super._call(R))}}class Xd extends ba{async _call(R){return new Nf(await super._call(R))}}class Qd extends ba{async _call(R){return new di(await super._call(R))}}class Hl extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class Zu extends Hl{}class Kl extends Hl{}class Yd extends Hl{async generate_speech(R,be,{threshold:Ue=.5,minlenratio:Ct=0,maxlenratio:Bt=20,vocoder:qt=null}={}){const cn={input_ids:R},{encoder_outputs:Fn,encoder_attention_mask:sr}=await G(this,cn),gr=Fn.dims[1]/this.config.reduction_factor,Tr=Math.floor(gr*Bt),rr=Math.floor(gr*Ct),zn=this.config.num_mel_bins;let Cr=[],Wn=null,cr=null,Wr=0;for(;;){++Wr;const ps=oe(!!cr);let Qi;cr?Qi=cr.output_sequence_out:Qi=new _.Tensor("float32",new Float32Array(zn),[1,1,zn]);let Hr={use_cache_branch:ps,output_sequence:Qi,encoder_attention_mask:sr,speaker_embeddings:be,encoder_hidden_states:Fn};this.addPastKeyValues(Hr,Wn),cr=await ce(this.sessions.decoder_model_merged,Hr),Wn=this.getPastKeyValues(cr,Wn);const{prob:Yi,spectrum:eu}=cr;if(Cr.push(eu),Wr>=rr&&(Array.from(Yi.data).filter(tu=>tu>=Ue).length>0||Wr>=Tr))break}const fi=(0,_.cat)(Cr),{waveform:bo}=await ce(qt.sessions.model,{spectrogram:fi});return{spectrogram:fi,waveform:bo}}}class Xl extends ne{main_input_name="spectrogram"}class Ju extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class ec extends Ju{}class tc extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class Zd extends tc{}class nc extends tc{}class rc extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class Jd extends rc{}class ef extends rc{}class tf extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class nf extends tf{}class ic extends tf{}class sc extends ne{}class rf extends sc{}class sf extends sc{static async from_pretrained(R,be={}){return be.model_file_name??="text_model",super.from_pretrained(R,be)}}class of extends sc{static async from_pretrained(R,be={}){return be.model_file_name??="audio_model",super.from_pretrained(R,be)}}class oc extends ne{}class ac extends oc{async _call(R){return new Vf(await super._call(R))}}class Ql extends ne{}class cp extends Ql{}class af extends Ql{}class lf extends Ql{}class lc extends ne{constructor(R,be,Ue){super(R,be),this.generation_config=Ue}}class dp extends lc{}class uf extends lc{}class uc extends ne{}class cf extends uc{}class fp extends uc{async _call(R){return new Yn(await super._call(R))}}class cc extends ne{}class hp extends cc{}class pp extends cc{}class dc extends ne{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];constructor(R,be,Ue){super(R,be),this.generation_config=Ue}_apply_and_filter_by_delay_pattern_mask(R){const[be,Ue]=R.dims,Ct=this.config.decoder.num_codebooks,Bt=Ue-Ct;let qt=0;for(let sr=0;sr0&&rr<=Bt&&(R.data[qt++]=R.data[sr])}const cn=Math.floor(be/Ct),Fn=qt/(cn*Ct);return new _.Tensor(R.type,R.data.slice(0,qt),[cn,Ct,Fn])}prepare_inputs_for_generation(R,be,Ue){let Ct=structuredClone(R);for(let qt=0;qt=cn&&(Ct[qt][cn]=BigInt(this.config.decoder.pad_token_id));return Ue.guidance_scale!==null&&Ue.guidance_scale>1&&(Ct=Ct.concat(Ct)),super.prepare_inputs_for_generation(Ct,be,Ue)}async generate(R){const be=await super.generate(R),Ue=this._apply_and_filter_by_delay_pattern_mask(be).unsqueeze_(0),{audio_values:Ct}=await ce(this.sessions.encodec_decode,{audio_codes:Ue});return Ct}}class fc extends ne{}class mp extends fc{}class Yl extends fc{async _call(R){return new Yn(await super._call(R))}}class xa extends ne{}class hc extends xa{}class df extends xa{async _call(R){return new Yn(await super._call(R))}}class pc extends ne{}class ff extends pc{}class hf extends pc{async _call(R){return new Yn(await super._call(R))}}class Zl extends ne{}class pf extends Zl{}class mf extends Zl{async _call(R){return new Yn(await super._call(R))}}class Er{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(R,{progress_callback:be=null,config:Ue=null,cache_dir:Ct=null,local_files_only:Bt=!1,revision:qt="main",model_file_name:cn=null,subfolder:Fn="onnx",device:sr=null,dtype:gr=null,use_external_data_format:Tr=null,session_options:rr={}}={}){let zn={progress_callback:be,config:Ue,cache_dir:Ct,local_files_only:Bt,revision:qt,model_file_name:cn,subfolder:Fn,device:sr,dtype:gr,use_external_data_format:Tr,session_options:rr};if(zn.config=await i.AutoConfig.from_pretrained(R,zn),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let Cr of this.MODEL_CLASS_MAPPINGS){const Wn=Cr.get(zn.config.model_type);if(Wn)return await Wn[1].from_pretrained(R,zn)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${zn.config.model_type}", attempting to construct from base class.`),await ne.from_pretrained(R,zn);throw Error(`Unsupported model type: ${zn.config.model_type}`)}}const Zg=new Map([["bert",["BertModel",Ze]],["nomic_bert",["NomicBertModel",lt]],["roformer",["RoFormerModel",bt]],["electra",["ElectraModel",Ie]],["esm",["EsmModel",zr]],["convbert",["ConvBertModel",Ee]],["camembert",["CamembertModel",kt]],["deberta",["DebertaModel",At]],["deberta-v2",["DebertaV2Model",hn]],["mpnet",["MPNetModel",us]],["albert",["AlbertModel",ki]],["distilbert",["DistilBertModel",An]],["roberta",["RobertaModel",Qn]],["xlm",["XLMModel",Dr]],["xlm-roberta",["XLMRobertaModel",ar]],["clap",["ClapModel",rf]],["clip",["CLIPModel",Oo]],["clipseg",["CLIPSegModel",ci]],["chinese_clip",["ChineseCLIPModel",ha]],["siglip",["SiglipModel",mo]],["mobilebert",["MobileBertModel",br]],["squeezebert",["SqueezeBertModel",$o]],["wav2vec2",["Wav2Vec2Model",xi]],["wav2vec2-bert",["Wav2Vec2BertModel",nl]],["unispeech",["UniSpeechModel",ql]],["unispeech-sat",["UniSpeechSatModel",Vd]],["hubert",["HubertModel",qd]],["wavlm",["WavLMModel",Kd]],["audio-spectrogram-transformer",["ASTModel",pn]],["vits",["VitsModel",ac]],["pyannote",["PyAnnoteModel",Bd]],["wespeaker-resnet",["WeSpeakerResNetModel",Ku]],["detr",["DetrModel",ii]],["rt_detr",["RTDetrModel",ud]],["table-transformer",["TableTransformerModel",fd]],["vit",["ViTModel",st]],["fastvit",["FastViTModel",He]],["mobilevit",["MobileViTModel",vt]],["mobilevitv2",["MobileViTV2Model",Gt]],["owlvit",["OwlViTModel",rn]],["owlv2",["Owlv2Model",Bn]],["beit",["BeitModel",Kn]],["deit",["DeiTModel",md]],["convnext",["ConvNextModel",Cd]],["convnextv2",["ConvNextV2Model",Ad]],["dinov2",["Dinov2Model",Id]],["resnet",["ResNetModel",_d]],["swin",["SwinModel",vd]],["swin2sr",["Swin2SRModel",Ou]],["donut-swin",["DonutSwinModel",Ms]],["yolos",["YolosModel",ip]],["dpt",["DPTModel",wd]],["glpn",["GLPNModel",rp]],["hifigan",["SpeechT5HifiGan",Xl]],["efficientnet",["EfficientNetModel",cf]],["mobilenet_v1",["MobileNetV1Model",mp]],["mobilenet_v2",["MobileNetV2Model",hc]],["mobilenet_v3",["MobileNetV3Model",ff]],["mobilenet_v4",["MobileNetV4Model",pf]]]),gp=new Map([["t5",["T5Model",uo]],["longt5",["LongT5Model",mr]],["mt5",["MT5Model",fs]],["bart",["BartModel",nt]],["mbart",["MBartModel",De]],["marian",["MarianModel",sp]],["whisper",["WhisperModel",vn]],["m2m_100",["M2M100Model",wo]],["blenderbot",["BlenderbotModel",nn]],["blenderbot-small",["BlenderbotSmallModel",Cn]]]),gf=new Map([["bloom",["BloomModel",v]],["jais",["JAISModel",Ga]],["gpt2",["GPT2Model",Wa]],["gptj",["GPTJModel",Rl]],["gpt_bigcode",["GPTBigCodeModel",Ll]],["gpt_neo",["GPTNeoModel",$s]],["gpt_neox",["GPTNeoXModel",Vo]],["codegen",["CodeGenModel",Ki]],["llama",["LlamaModel",Xa]],["cohere",["CohereModel",Za]],["gemma",["GemmaModel",Ja]],["gemma2",["Gemma2Model",Nl]],["openelm",["OpenELMModel",Rr]],["qwen2",["Qwen2Model",jl]],["phi",["PhiModel",Is]],["phi3",["Phi3Model",xs]],["mpt",["MptModel",Y]],["opt",["OPTModel",ze]],["mistral",["MistralModel",Zd]],["starcoder2",["Starcoder2Model",Jd]],["falcon",["FalconModel",nf]],["stablelm",["StableLmModel",dp]]]),mc=new Map([["speecht5",["SpeechT5ForSpeechToText",Kl]],["whisper",["WhisperForConditionalGeneration",fo]]]),_f=new Map([["speecht5",["SpeechT5ForTextToSpeech",Yd]]]),yf=new Map([["vits",["VitsModel",ac]],["musicgen",["MusicgenForConditionalGeneration",dc]]]),_p=new Map([["bert",["BertForSequenceClassification",Mt]],["roformer",["RoFormerForSequenceClassification",Fe]],["electra",["ElectraForSequenceClassification",St]],["esm",["EsmForSequenceClassification",ao]],["convbert",["ConvBertForSequenceClassification",se]],["camembert",["CamembertForSequenceClassification",Ne]],["deberta",["DebertaForSequenceClassification",it]],["deberta-v2",["DebertaV2ForSequenceClassification",Tn]],["mpnet",["MPNetForSequenceClassification",Ws]],["albert",["AlbertForSequenceClassification",Gs]],["distilbert",["DistilBertForSequenceClassification",In]],["roberta",["RobertaForSequenceClassification",Mr]],["xlm",["XLMForSequenceClassification",xn]],["xlm-roberta",["XLMRobertaForSequenceClassification",tr]],["bart",["BartForSequenceClassification",ye]],["mbart",["MBartForSequenceClassification",Pt]],["mobilebert",["MobileBertForSequenceClassification",kr]],["squeezebert",["SqueezeBertForSequenceClassification",Si]]]),vf=new Map([["bert",["BertForTokenClassification",Ft]],["roformer",["RoFormerForTokenClassification",Oe]],["electra",["ElectraForTokenClassification",ft]],["esm",["EsmForTokenClassification",vr]],["convbert",["ConvBertForTokenClassification",K]],["camembert",["CamembertForTokenClassification",rt]],["deberta",["DebertaForTokenClassification",en]],["deberta-v2",["DebertaV2ForTokenClassification",bn]],["mpnet",["MPNetForTokenClassification",Ar]],["distilbert",["DistilBertForTokenClassification",Mn]],["roberta",["RobertaForTokenClassification",yt]],["xlm",["XLMForTokenClassification",Ci]],["xlm-roberta",["XLMRobertaForTokenClassification",pr]]]),gc=new Map([["t5",["T5ForConditionalGeneration",co]],["longt5",["LongT5ForConditionalGeneration",ws]],["mt5",["MT5ForConditionalGeneration",xr]],["bart",["BartForConditionalGeneration",q]],["mbart",["MBartForConditionalGeneration",ct]],["marian",["MarianMTModel",vo]],["m2m_100",["M2M100ForConditionalGeneration",Wu]],["blenderbot",["BlenderbotForConditionalGeneration",Qt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",qn]]]),wf=new Map([["bloom",["BloomForCausalLM",$]],["gpt2",["GPT2LMHeadModel",Lo]],["jais",["JAISLMHeadModel",Bo]],["gptj",["GPTJForCausalLM",qa]],["gpt_bigcode",["GPTBigCodeForCausalLM",_o]],["gpt_neo",["GPTNeoForCausalLM",pa]],["gpt_neox",["GPTNeoXForCausalLM",ma]],["codegen",["CodeGenForCausalLM",Ha]],["llama",["LlamaForCausalLM",Qa]],["cohere",["CohereForCausalLM",_a]],["gemma",["GemmaForCausalLM",Bl]],["gemma2",["Gemma2ForCausalLM",Uo]],["openelm",["OpenELMForCausalLM",Wo]],["qwen2",["Qwen2ForCausalLM",va]],["phi",["PhiForCausalLM",Go]],["phi3",["Phi3ForCausalLM",el]],["mpt",["MptForCausalLM",le]],["opt",["OPTForCausalLM",Ke]],["mbart",["MBartForCausalLM",tn]],["mistral",["MistralForCausalLM",nc]],["starcoder2",["Starcoder2ForCausalLM",ef]],["falcon",["FalconForCausalLM",ic]],["trocr",["TrOCRForCausalLM",ec]],["stablelm",["StableLmForCausalLM",uf]]]),bf=new Map([["bert",["BertForMaskedLM",ut]],["roformer",["RoFormerForMaskedLM",z]],["electra",["ElectraForMaskedLM",Xe]],["esm",["EsmForMaskedLM",os]],["convbert",["ConvBertForMaskedLM",H]],["camembert",["CamembertForMaskedLM",ve]],["deberta",["DebertaForMaskedLM",jt]],["deberta-v2",["DebertaV2ForMaskedLM",fn]],["mpnet",["MPNetForMaskedLM",lo]],["albert",["AlbertForMaskedLM",En]],["distilbert",["DistilBertForMaskedLM",Ht]],["roberta",["RobertaForMaskedLM",Ei]],["xlm",["XLMWithLMHeadModel",ui]],["xlm-roberta",["XLMRobertaForMaskedLM",sn]],["mobilebert",["MobileBertForMaskedLM",as]],["squeezebert",["SqueezeBertForMaskedLM",qi]]]),xf=new Map([["bert",["BertForQuestionAnswering",Ve]],["roformer",["RoFormerForQuestionAnswering",he]],["electra",["ElectraForQuestionAnswering",Dt]],["convbert",["ConvBertForQuestionAnswering",_e]],["camembert",["CamembertForQuestionAnswering",Ye]],["deberta",["DebertaForQuestionAnswering",Vt]],["deberta-v2",["DebertaV2ForQuestionAnswering",mn]],["mpnet",["MPNetForQuestionAnswering",Gi]],["albert",["AlbertForQuestionAnswering",vs]],["distilbert",["DistilBertForQuestionAnswering",Et]],["roberta",["RobertaForQuestionAnswering",Yr]],["xlm",["XLMForQuestionAnswering",$r]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ir]],["mobilebert",["MobileBertForQuestionAnswering",mi]],["squeezebert",["SqueezeBertForQuestionAnswering",cs]]]),_c=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Io]]]),yp=new Map([["llava",["LlavaForConditionalGeneration",ho]],["moondream1",["Moondream1ForConditionalGeneration",Ln]],["florence2",["Florence2ForConditionalGeneration",Fo]]]),Jg=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Io]]]),Mf=new Map([["vit",["ViTForImageClassification",We]],["fastvit",["FastViTForImageClassification",tt]],["mobilevit",["MobileViTForImageClassification",wt]],["mobilevitv2",["MobileViTV2ForImageClassification",on]],["beit",["BeitForImageClassification",Li]],["deit",["DeiTForImageClassification",gd]],["convnext",["ConvNextForImageClassification",Pd]],["convnextv2",["ConvNextV2ForImageClassification",$d]],["dinov2",["Dinov2ForImageClassification",Fd]],["resnet",["ResNetForImageClassification",yd]],["swin",["SwinForImageClassification",Iu]],["segformer",["SegformerForImageClassification",af]],["efficientnet",["EfficientNetForImageClassification",fp]],["mobilenet_v1",["MobileNetV1ForImageClassification",Yl]],["mobilenet_v2",["MobileNetV2ForImageClassification",df]],["mobilenet_v3",["MobileNetV3ForImageClassification",hf]],["mobilenet_v4",["MobileNetV4ForImageClassification",mf]]]),Tf=new Map([["detr",["DetrForObjectDetection",si]],["rt_detr",["RTDetrForObjectDetection",cd]],["table-transformer",["TableTransformerForObjectDetection",hd]],["yolos",["YolosForObjectDetection",Od]]]),Sf=new Map([["owlvit",["OwlViTForObjectDetection",an]],["owlv2",["Owlv2ForObjectDetection",jn]]]),kf=new Map([["detr",["DetrForSegmentation",Fs]],["clipseg",["CLIPSegForImageSegmentation",go]]]),vp=new Map([["segformer",["SegformerForSemanticSegmentation",lf]],["sapiens",["SapiensForSemanticSegmentation",Ru]]]),Ef=new Map([["sam",["SamModel",Rd]]]),Cf=new Map([["wav2vec2",["Wav2Vec2ForCTC",Gu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Gd]],["unispeech",["UniSpeechForCTC",jd]],["unispeech-sat",["UniSpeechSatForCTC",Ud]],["wavlm",["WavLMForCTC",up]],["hubert",["HubertForCTC",Hd]]]),Pf=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Ul]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Qu]],["unispeech",["UniSpeechForSequenceClassification",Xu]],["unispeech-sat",["UniSpeechSatForSequenceClassification",op]],["wavlm",["WavLMForSequenceClassification",Yu]],["hubert",["HubertForSequenceClassification",lp]],["audio-spectrogram-transformer",["ASTForAudioClassification",la]]]),Af=new Map([["wavlm",["WavLMForXVector",Xd]]]),wp=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Wd]],["wavlm",["WavLMForAudioFrameClassification",Qd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",qu]],["pyannote",["PyAnnoteForAudioFrameClassification",Nd]]]),$f=new Map([["vitmatte",["VitMatteForImageMatting",Je]]]),If=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Du]]]),Ff=new Map([["dpt",["DPTForDepthEstimation",bd]],["depth_anything",["DepthAnythingForDepthEstimation",Md]],["glpn",["GLPNForDepthEstimation",kd]],["sapiens",["SapiensForDepthEstimation",Td]]]),Of=new Map([["sapiens",["SapiensForNormalEstimation",Sd]]]),bp=new Map([["clip",["CLIPVisionModelWithProjection",Do]],["siglip",["SiglipVisionModel",da]]]),Ii=[[Zg,S.EncoderOnly],[gp,S.EncoderDecoder],[gf,S.DecoderOnly],[_p,S.EncoderOnly],[vf,S.EncoderOnly],[gc,S.Seq2Seq],[mc,S.Seq2Seq],[wf,S.DecoderOnly],[bf,S.EncoderOnly],[xf,S.EncoderOnly],[_c,S.Vision2Seq],[yp,S.ImageTextToText],[Mf,S.EncoderOnly],[kf,S.EncoderOnly],[vp,S.EncoderOnly],[$f,S.EncoderOnly],[If,S.EncoderOnly],[Ff,S.EncoderOnly],[Of,S.EncoderOnly],[Tf,S.EncoderOnly],[Sf,S.EncoderOnly],[Ef,S.MaskGeneration],[Cf,S.EncoderOnly],[Pf,S.EncoderOnly],[_f,S.Seq2Seq],[yf,S.EncoderOnly],[Af,S.EncoderOnly],[wp,S.EncoderOnly],[bp,S.EncoderOnly]];for(const[X,R]of Ii)for(const[be,Ue]of X.values())P.set(be,R),L.set(Ue,be),j.set(be,Ue);const xp=[["MusicgenForConditionalGeneration",dc,S.Musicgen],["CLIPTextModelWithProjection",Ai,S.EncoderOnly],["SiglipTextModel",zo,S.EncoderOnly],["ClapTextModelWithProjection",sf,S.EncoderOnly],["ClapAudioModelWithProjection",of,S.EncoderOnly]];for(const[X,R,be]of xp)P.set(X,be),L.set(R,X),j.set(X,R);class Mp extends Er{static MODEL_CLASS_MAPPINGS=Ii.map(R=>R[0]);static BASE_IF_FAIL=!0}class Df extends Er{static MODEL_CLASS_MAPPINGS=[_p]}class Tp extends Er{static MODEL_CLASS_MAPPINGS=[vf]}class Jl extends Er{static MODEL_CLASS_MAPPINGS=[gc]}class Sp extends Er{static MODEL_CLASS_MAPPINGS=[mc]}class kp extends Er{static MODEL_CLASS_MAPPINGS=[_f]}class zf extends Er{static MODEL_CLASS_MAPPINGS=[yf]}class Ep extends Er{static MODEL_CLASS_MAPPINGS=[wf]}class Cp extends Er{static MODEL_CLASS_MAPPINGS=[bf]}class Rf extends Er{static MODEL_CLASS_MAPPINGS=[xf]}class Pp extends Er{static MODEL_CLASS_MAPPINGS=[_c]}class Ap extends Er{static MODEL_CLASS_MAPPINGS=[Mf]}class $p extends Er{static MODEL_CLASS_MAPPINGS=[kf]}class Lf extends Er{static MODEL_CLASS_MAPPINGS=[vp]}class Ip extends Er{static MODEL_CLASS_MAPPINGS=[Tf]}class Fp extends Er{static MODEL_CLASS_MAPPINGS=[Sf]}class Bf extends Er{static MODEL_CLASS_MAPPINGS=[Ef]}class Op extends Er{static MODEL_CLASS_MAPPINGS=[Cf]}class e_ extends Er{static MODEL_CLASS_MAPPINGS=[Pf]}class Dp extends Er{static MODEL_CLASS_MAPPINGS=[Af]}class zp extends Er{static MODEL_CLASS_MAPPINGS=[wp]}class Rp extends Er{static MODEL_CLASS_MAPPINGS=[Jg]}class Lp extends Er{static MODEL_CLASS_MAPPINGS=[$f]}class t_ extends Er{static MODEL_CLASS_MAPPINGS=[If]}class Bp extends Er{static MODEL_CLASS_MAPPINGS=[Ff]}class Np extends Er{static MODEL_CLASS_MAPPINGS=[Of]}class jp extends Er{static MODEL_CLASS_MAPPINGS=[bp]}class n_ extends xe{constructor({logits:R,past_key_values:be,encoder_outputs:Ue,decoder_attentions:Ct=null,cross_attentions:Bt=null}){super(),this.logits=R,this.past_key_values=be,this.encoder_outputs=Ue,this.decoder_attentions=Ct,this.cross_attentions=Bt}}class Yn extends xe{constructor({logits:R}){super(),this.logits=R}}class Nf extends xe{constructor({logits:R,embeddings:be}){super(),this.logits=R,this.embeddings=be}}class di extends xe{constructor({logits:R}){super(),this.logits=R}}class _i extends xe{constructor({logits:R}){super(),this.logits=R}}class Fi extends xe{constructor({start_logits:R,end_logits:be}){super(),this.start_logits=R,this.end_logits=be}}class Ko extends xe{constructor({logits:R}){super(),this.logits=R}}class Vp extends xe{constructor({logits:R,past_key_values:be}){super(),this.logits=R,this.past_key_values=be}}class jf extends xe{constructor({alphas:R}){super(),this.alphas=R}}class Vf extends xe{constructor({waveform:R,spectrogram:be}){super(),this.waveform=R,this.spectrogram=be}}},"./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 w=d.length===2?o.keys():o.values();throw new Error(`Language "${d}" is not supported. Must be one of: ${JSON.stringify(w)}`)}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{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}},"./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,h)=>{const w=await(0,i.createInferenceSession)(new Uint8Array(d),c);return async _=>{const M=Object.fromEntries(Object.entries(_).map(([F,C])=>[F,C.ort_tensor])),T=await w.run(M);return Array.isArray(h)?h.map(F=>new o.Tensor(T[F])):new o.Tensor(T[h])}};class l{static session_options={};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}}},"./src/pipelines.js":(e,t,n)=>{n.r(t),n.d(t,{AudioClassificationPipeline:()=>oe,AutomaticSpeechRecognitionPipeline:()=>G,DepthEstimationPipeline:()=>Qe,DocumentQuestionAnsweringPipeline:()=>ne,FeatureExtractionPipeline:()=>ge,FillMaskPipeline:()=>P,ImageClassificationPipeline:()=>pt,ImageFeatureExtractionPipeline:()=>Re,ImageSegmentationPipeline:()=>Te,ImageToImagePipeline:()=>ht,ImageToTextPipeline:()=>Ce,ObjectDetectionPipeline:()=>fe,Pipeline:()=>C,QuestionAnsweringPipeline:()=>S,SummarizationPipeline:()=>L,Text2TextGenerationPipeline:()=>j,TextClassificationPipeline:()=>E,TextGenerationPipeline:()=>V,TextToAudioPipeline:()=>xe,TokenClassificationPipeline:()=>x,TranslationPipeline:()=>N,ZeroShotAudioClassificationPipeline:()=>Se,ZeroShotClassificationPipeline:()=>ce,ZeroShotImageClassificationPipeline:()=>te,ZeroShotObjectDetectionPipeline:()=>Pe,pipeline:()=>Mt});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"),h=n("./src/utils/audio.js"),w=n("./src/utils/tensor.js"),_=n("./src/utils/image.js");async function M(Ve){return Array.isArray(Ve)||(Ve=[Ve]),await Promise.all(Ve.map(ke=>_.RawImage.read(ke)))}async function T(Ve,ke){return Array.isArray(Ve)||(Ve=[Ve]),await Promise.all(Ve.map(lt=>typeof lt=="string"||lt instanceof URL?(0,h.read_audio)(lt,ke):lt instanceof Float64Array?new Float32Array(lt):lt))}function F(Ve,ke){ke&&(Ve=Ve.map(Fe=>Fe|0));const[lt,dt,bt,z]=Ve;return{xmin:lt,ymin:dt,xmax:bt,ymax:z}}class C extends l.Callable{constructor({task:ke,model:lt,tokenizer:dt=null,processor:bt=null}){super(),this.task=ke,this.model=lt,this.tokenizer=dt,this.processor=bt}async dispose(){await this.model.dispose()}}class E extends C{constructor(ke){super(ke)}async _call(ke,{top_k:lt=1}={}){const dt=this.tokenizer(ke,{padding:!0,truncation:!0}),bt=await this.model(dt),z=this.model.config.problem_type==="multi_label_classification"?he=>he.sigmoid():he=>new w.Tensor("float32",(0,c.softmax)(he.data),he.dims),Fe=this.model.config.id2label,Oe=[];for(const he of bt.logits){const de=z(he),Ee=await(0,w.topk)(de,lt),H=Ee[0].tolist(),K=Ee[1].tolist().map((_e,pe)=>({label:Fe?Fe[_e]:`LABEL_${_e}`,score:H[pe]}));lt===1?Oe.push(...K):Oe.push(K)}return Array.isArray(ke)||lt===1?Oe:Oe[0]}}class x extends C{constructor(ke){super(ke)}async _call(ke,{ignore_labels:lt=["O"]}={}){const dt=Array.isArray(ke),bt=this.tokenizer(dt?ke:[ke],{padding:!0,truncation:!0}),Fe=(await this.model(bt)).logits,Oe=this.model.config.id2label,he=[];for(let de=0;deft==this.tokenizer.sep_token_id);he[H].map((ft,Dt)=>ft==1&&(Dt===0||Dt>K&&de.findIndex(Jt=>Jt==se[Dt])===-1));const _e=z[H].tolist(),pe=Fe[H].tolist();for(let ft=1;ft<_e.length;++ft)(he[H]==0||ft<=K||de.findIndex(Dt=>Dt==se[ft])!==-1)&&(_e[ft]=-1/0,pe[ft]=-1/0);const Ie=(0,c.softmax)(_e).map((ft,Dt)=>[ft,Dt]),Xe=(0,c.softmax)(pe).map((ft,Dt)=>[ft,Dt]);Ie[0][0]=0,Xe[0][0]=0;const St=(0,d.product)(Ie,Xe).filter(ft=>ft[0][1]<=ft[1][1]).map(ft=>[ft[0][1],ft[1][1],ft[0][0]*ft[1][0]]).sort((ft,Dt)=>Dt[2]-ft[2]);for(let ft=0;ft_e==this.tokenizer.mask_token_id);if(de===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ee=bt[Oe][de],H=await(0,w.topk)(new w.Tensor("float32",(0,c.softmax)(Ee.data),Ee.dims),lt),se=H[0].tolist(),K=H[1].tolist();z.push(K.map((_e,pe)=>{const Ie=he.slice();return Ie[de]=_e,{score:se[pe],token:Number(_e),token_str:this.tokenizer.model.vocab[_e],sequence:this.tokenizer.decode(Ie,{skip_special_tokens:!0})}}))}return Array.isArray(ke)?z:z[0]}}class j extends C{_key="generated_text";constructor(ke){super(ke)}async _call(ke,lt={}){Array.isArray(ke)||(ke=[ke]),this.model.config.prefix&&(ke=ke.map(he=>this.model.config.prefix+he));const dt=this.model.config.task_specific_params;dt&&dt[this.task]&&dt[this.task].prefix&&(ke=ke.map(he=>dt[this.task].prefix+he));const bt=this.tokenizer,z={padding:!0,truncation:!0};let Fe;this instanceof N&&"_build_translation_inputs"in bt?Fe=bt._build_translation_inputs(ke,z,lt):Fe=bt(ke,z);const Oe=await this.model.generate({...Fe,...lt});return bt.batch_decode(Oe,{skip_special_tokens:!0}).map(he=>({[this._key]:he}))}}class L extends j{_key="summary_text";constructor(ke){super(ke)}}class N extends j{_key="translation_text";constructor(ke){super(ke)}}function W(Ve){return Array.isArray(Ve)&&Ve.every(ke=>"role"in ke&&"content"in ke)}class V extends C{constructor(ke){super(ke)}async _call(ke,lt={}){let dt=!1,bt=!1,z;if(typeof ke=="string")z=ke=[ke];else if(Array.isArray(ke)&&ke.every(K=>typeof K=="string"))dt=!0,z=ke;else{if(W(ke))ke=[ke];else if(Array.isArray(ke)&&ke.every(W))dt=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");bt=!0,z=ke.map(K=>this.tokenizer.apply_chat_template(K,{tokenize:!1,add_generation_prompt:!0}))}const Fe=lt.add_special_tokens??!1,Oe=bt?!1:lt.return_full_text??!0;this.tokenizer.padding_side="left";const he=this.tokenizer(z,{add_special_tokens:Fe,padding:!0,truncation:!0}),de=await this.model.generate({...he,...lt}),Ee=this.tokenizer.batch_decode(de,{skip_special_tokens:!0});let H;!Oe&&he.input_ids.dims.at(-1)>0&&(H=this.tokenizer.batch_decode(he.input_ids,{skip_special_tokens:!0}).map(K=>K.length));const se=Array.from({length:ke.length},K=>[]);for(let K=0;K[lt.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(ke,lt,{hypothesis_template:dt="This example is {}.",multi_label:bt=!1}={}){const z=Array.isArray(ke);z||(ke=[ke]),Array.isArray(lt)||(lt=[lt]);const Fe=lt.map(de=>dt.replace("{}",de)),Oe=bt||lt.length===1,he=[];for(const de of ke){const Ee=[];for(const K of Fe){const _e=this.tokenizer(de,{text_pair:K,padding:!0,truncation:!0}),pe=await this.model(_e);Oe?Ee.push([pe.logits.data[this.contradiction_id],pe.logits.data[this.entailment_id]]):Ee.push(pe.logits.data[this.entailment_id])}const se=(Oe?Ee.map(K=>(0,c.softmax)(K)[1]):(0,c.softmax)(Ee)).map((K,_e)=>[K,_e]).sort((K,_e)=>_e[0]-K[0]);he.push({sequence:de,labels:se.map(K=>lt[K[1]]),scores:se.map(K=>K[0])})}return z?he:he[0]}}class ge extends C{constructor(ke){super(ke)}async _call(ke,{pooling:lt="none",normalize:dt=!1,quantize:bt=!1,precision:z="binary"}={}){const Fe=this.tokenizer(ke,{padding:!0,truncation:!0}),Oe=await this.model(Fe);let he=Oe.last_hidden_state??Oe.logits??Oe.token_embeddings;if(lt!=="none")if(lt==="mean")he=(0,w.mean_pooling)(he,Fe.attention_mask);else if(lt==="cls")he=he.slice(null,0);else throw Error(`Pooling method '${lt}' not supported.`);return dt&&(he=he.normalize(2,-1)),bt&&(he=(0,w.quantize_embeddings)(he,z)),he}}class Re extends C{constructor(ke){super(ke)}async _call(ke,{pool:lt=null}={}){const dt=await M(ke),{pixel_values:bt}=await this.processor(dt),z=await this.model({pixel_values:bt});let Fe;if(lt){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(ke){super(ke)}async _call(ke,{top_k:lt=5}={}){const dt=this.processor.feature_extractor.config.sampling_rate,bt=await T(ke,dt),z=this.model.config.id2label,Fe=[];for(const Oe of bt){const he=await this.processor(Oe),Ee=(await this.model(he)).logits[0],H=await(0,w.topk)(new w.Tensor("float32",(0,c.softmax)(Ee.data),Ee.dims),lt),se=H[0].tolist(),_e=H[1].tolist().map((pe,Ie)=>({label:z?z[pe]:`LABEL_${pe}`,score:se[Ie]}));Fe.push(_e)}return Array.isArray(ke)?Fe:Fe[0]}}class Se extends C{constructor(ke){super(ke)}async _call(ke,lt,{hypothesis_template:dt="This is a sound of {}."}={}){const bt=!Array.isArray(ke);bt&&(ke=[ke]);const z=lt.map(Ee=>dt.replace("{}",Ee)),Fe=this.tokenizer(z,{padding:!0,truncation:!0}),Oe=this.processor.feature_extractor.config.sampling_rate,he=await T(ke,Oe),de=[];for(const Ee of he){const H=await this.processor(Ee),se=await this.model({...Fe,...H}),K=(0,c.softmax)(se.logits_per_audio.data);de.push([...K].map((_e,pe)=>({score:_e,label:lt[pe]})))}return bt?de[0]:de}}class G extends C{constructor(ke){super(ke)}async _call(ke,lt={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ke,lt);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ke,lt);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ke,lt){lt.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),lt.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const dt=!Array.isArray(ke);dt&&(ke=[ke]);const bt=this.processor.feature_extractor.config.sampling_rate,z=await T(ke,bt),Fe=[];for(const Oe of z){const he=await this.processor(Oe),Ee=(await this.model(he)).logits[0],H=[];for(const K of Ee)H.push((0,c.max)(K.data)[1]);const se=this.tokenizer.decode(H);Fe.push({text:se})}return dt?Fe[0]:Fe}async _call_whisper(ke,lt){const dt=lt.return_timestamps??!1,bt=lt.chunk_length_s??0,z=lt.force_full_sequences??!1;let Fe=lt.stride_length_s??null;const Oe={...lt};dt==="word"&&(Oe.return_token_timestamps=!0,Oe.return_timestamps=!1);const he=!Array.isArray(ke);he&&(ke=[ke]);const de=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ee=this.processor.feature_extractor.config.hop_length,H=this.processor.feature_extractor.config.sampling_rate,se=await T(ke,H),K=[];for(const _e of se){let pe=[];if(bt>0){if(Fe===null)Fe=bt/6;else if(bt<=Fe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const St=H*bt,ft=H*Fe,Dt=St-2*ft;let Jt=0;for(;;){const kt=Jt+St,ve=_e.subarray(Jt,kt),Ne=await this.processor(ve),rt=Jt===0,Ye=kt>=_e.length;if(pe.push({stride:[ve.length,rt?0:ft,Ye?0:ft],input_features:Ne.input_features,is_last:Ye}),Ye)break;Jt+=Dt}}else pe=[{stride:[_e.length,0,0],input_features:(await this.processor(_e)).input_features,is_last:!0}];for(const St of pe){Oe.num_frames=Math.floor(St.stride[0]/Ee);const ft=await this.model.generate({inputs:St.input_features,...Oe});dt==="word"?(St.tokens=ft.sequences.tolist()[0],St.token_timestamps=ft.token_timestamps.tolist()[0].map(Dt=>(0,c.round)(Dt,2))):St.tokens=ft[0].tolist(),St.stride=St.stride.map(Dt=>Dt/H)}const[Ie,Xe]=this.tokenizer._decode_asr(pe,{time_precision:de,return_timestamps:dt,force_full_sequences:z});K.push({text:Ie,...Xe})}return he?K[0]:K}}class Ce extends C{constructor(ke){super(ke)}async _call(ke,lt={}){const dt=Array.isArray(ke),bt=await M(ke),{pixel_values:z}=await this.processor(bt),Fe=[];for(const Oe of z){Oe.dims=[1,...Oe.dims];const he=await this.model.generate({inputs:Oe,...lt}),de=this.tokenizer.batch_decode(he,{skip_special_tokens:!0}).map(Ee=>({generated_text:Ee.trim()}));Fe.push(de)}return dt?Fe:Fe[0]}}class pt extends C{constructor(ke){super(ke)}async _call(ke,{top_k:lt=5}={}){const dt=await M(ke),{pixel_values:bt}=await this.processor(dt),z=await this.model({pixel_values:bt}),Fe=this.model.config.id2label,Oe=[];for(const he of z.logits){const de=await(0,w.topk)(new w.Tensor("float32",(0,c.softmax)(he.data),he.dims),lt),Ee=de[0].tolist(),se=de[1].tolist().map((K,_e)=>({label:Fe?Fe[K]:`LABEL_${K}`,score:Ee[_e]}));Oe.push(se)}return Array.isArray(ke)?Oe:Oe[0]}}class Te extends C{constructor(ke){super(ke),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ke,{threshold:lt=.5,mask_threshold:dt=.5,overlap_mask_area_threshold:bt=.8,label_ids_to_fuse:z=null,target_sizes:Fe=null,subtask:Oe=null}={}){if(Array.isArray(ke)&&ke.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const de=await M(ke),Ee=de.map(Xe=>[Xe.height,Xe.width]),{pixel_values:H,pixel_mask:se}=await this.processor(de),K=await this.model({pixel_values:H,pixel_mask:se});let _e=null;if(Oe!==null)_e=this.subtasks_mapping[Oe];else for(let[Xe,St]of Object.entries(this.subtasks_mapping))if(St in this.processor.feature_extractor){_e=this.processor.feature_extractor[St].bind(this.processor.feature_extractor),Oe=Xe;break}const pe=this.model.config.id2label,Ie=[];if(Oe==="panoptic"||Oe==="instance"){const Xe=_e(K,lt,dt,bt,z,Fe??Ee)[0],St=Xe.segmentation;for(const ft of Xe.segments_info){const Dt=new Uint8ClampedArray(St.data.length);for(let kt=0;ktdt.replace("{}",se)),Oe=this.tokenizer(Fe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:he}=await this.processor(z),de=await this.model({...Oe,pixel_values:he}),Ee=this.model.config.model_type==="siglip"?se=>se.sigmoid().data:se=>(0,c.softmax)(se.data),H=[];for(const se of de.logits_per_image){const _e=[...Ee(se)].map((pe,Ie)=>({score:pe,label:lt[Ie]}));_e.sort((pe,Ie)=>Ie.score-pe.score),H.push(_e)}return bt?H:H[0]}}class fe extends C{constructor(ke){super(ke)}async _call(ke,{threshold:lt=.9,percentage:dt=!1}={}){const bt=Array.isArray(ke);if(bt&&ke.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const z=await M(ke),Fe=dt?null:z.map(K=>[K.height,K.width]),{pixel_values:Oe,pixel_mask:he}=await this.processor(z),de=await this.model({pixel_values:Oe,pixel_mask:he}),Ee=this.processor.feature_extractor.post_process_object_detection(de,lt,Fe),H=this.model.config.id2label,se=Ee.map(K=>K.boxes.map((_e,pe)=>({score:K.scores[pe],label:H[K.classes[pe]],box:F(_e,!dt)})));return bt?se:se[0]}}class Pe extends C{constructor(ke){super(ke)}async _call(ke,lt,{threshold:dt=.1,top_k:bt=null,percentage:z=!1}={}){const Fe=Array.isArray(ke),Oe=await M(ke),he=this.tokenizer(lt,{padding:!0,truncation:!0}),de=await this.processor(Oe),Ee=[];for(let H=0;H({score:Ie.scores[ft],label:lt[Ie.classes[ft]],box:F(St,!z)})).sort((St,ft)=>ft.score-St.score);bt!==null&&(Xe=Xe.slice(0,bt)),Ee.push(Xe)}return Fe?Ee:Ee[0]}}class ne extends C{constructor(ke){super(ke)}async _call(ke,lt,dt={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class xe extends C{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(ke){super(ke),this.vocoder=ke.vocoder??null}async _call(ke,{speaker_embeddings:lt=null}={}){return this.processor?this._call_text_to_spectrogram(ke,{speaker_embeddings:lt}):this._call_text_to_waveform(ke)}async _call_text_to_waveform(ke){const lt=this.tokenizer(ke,{padding:!0,truncation:!0}),{waveform:dt}=await this.model(lt),bt=this.model.config.sampling_rate;return{audio:dt.data,sampling_rate:bt}}async _call_text_to_spectrogram(ke,{speaker_embeddings:lt}){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 lt=="string"||lt instanceof URL)&&(lt=new Float32Array(await(await fetch(lt)).arrayBuffer())),lt instanceof Float32Array)lt=new w.Tensor("float32",lt,[1,lt.length]);else if(!(lt instanceof w.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:dt}=this.tokenizer(ke,{padding:!0,truncation:!0}),{waveform:bt}=await this.model.generate_speech(dt,lt,{vocoder:this.vocoder}),z=this.processor.feature_extractor.config.sampling_rate;return{audio:bt.data,sampling_rate:z}}}class ht extends C{constructor(ke){super(ke)}async _call(ke){const lt=await M(ke),dt=await this.processor(lt),bt=await this.model(dt),z=[];for(const Fe of bt.reconstruction){const Oe=Fe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");z.push(_.RawImage.fromTensor(Oe))}return z.length>1?z:z[0]}}class Qe extends C{constructor(ke){super(ke)}async _call(ke){const lt=await M(ke),dt=await this.processor(lt),{predicted_depth:bt}=await this.model(dt),z=[];for(let Fe=0;Fe1?z:z[0]}}const Ze=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:S,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:i.AutoTokenizer,pipeline:P,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:i.AutoTokenizer,pipeline:L,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:i.AutoTokenizer,pipeline:N,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:i.AutoTokenizer,pipeline:j,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:i.AutoTokenizer,pipeline:V,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:i.AutoTokenizer,pipeline:ce,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:pt,model:o.AutoModelForImageClassification,processor:a.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Te,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:Pe,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:ht,model:o.AutoModelForImageToImage,processor:a.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Qe,model:o.AutoModelForDepthEstimation,processor:a.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:i.AutoTokenizer,pipeline:ge,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:a.AutoProcessor,pipeline:Re,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ut=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Mt(Ve,ke=null,{progress_callback:lt=null,config:dt=null,cache_dir:bt=null,local_files_only:z=!1,revision:Fe="main",device:Oe=null,dtype:he=null,model_file_name:de=null,session_options:Ee={}}={}){Ve=ut[Ve]??Ve;const H=Ze[Ve.split("_",1)[0]];if(!H)throw Error(`Unsupported pipeline: ${Ve}. Must be one of [${Object.keys(Ze)}]`);ke||(ke=H.default.model,console.log(`No model specified. Using default model: "${ke}".`));const se={progress_callback:lt,config:dt,cache_dir:bt,local_files_only:z,revision:Fe,device:Oe,dtype:he,model_file_name:de,session_options:Ee},K=new Map([["tokenizer",H.tokenizer],["model",H.model],["processor",H.processor]]),_e=await Ft(K,ke,se);_e.task=Ve,(0,d.dispatchCallback)(lt,{status:"ready",task:Ve,model:ke});const pe=H.pipeline;return new pe(_e)}async function Ft(Ve,ke,lt){const dt=Object.create(null),bt=[];for(let[z,Fe]of Ve.entries()){if(!Fe)continue;let Oe;Array.isArray(Fe)?Oe=new Promise(async(he,de)=>{let Ee;for(let H of Fe){if(H===null){he(null);return}try{he(await H.from_pretrained(ke,lt));return}catch(se){if(se.message?.includes("Unsupported model type"))Ee=se;else if(se.message?.includes("Could not locate file"))Ee=se;else{de(se);return}}}de(Ee)}):Oe=Fe.from_pretrained(ke,lt),dt[z]=Oe,bt.push(Oe)}await Promise.all(bt);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:()=>ut,BitImageProcessor:()=>L,CLIPFeatureExtractor:()=>W,CLIPImageProcessor:()=>V,ChineseCLIPFeatureExtractor:()=>ce,ClapFeatureExtractor:()=>de,ConvNextFeatureExtractor:()=>Re,ConvNextImageProcessor:()=>oe,DPTFeatureExtractor:()=>P,DPTImageProcessor:()=>j,DeiTFeatureExtractor:()=>Ze,DetrFeatureExtractor:()=>Ve,DonutFeatureExtractor:()=>Mt,EfficientNetImageProcessor:()=>Ce,FeatureExtractor:()=>C,Florence2Processor:()=>Dt,GLPNFeatureExtractor:()=>N,ImageFeatureExtractor:()=>E,MobileNetV1FeatureExtractor:()=>pt,MobileNetV2FeatureExtractor:()=>Te,MobileNetV3FeatureExtractor:()=>te,MobileNetV4FeatureExtractor:()=>fe,MobileViTFeatureExtractor:()=>Pe,MobileViTImageProcessor:()=>ne,NougatImageProcessor:()=>Ft,OwlViTFeatureExtractor:()=>xe,OwlViTProcessor:()=>ft,Owlv2ImageProcessor:()=>ht,Processor:()=>K,PyAnnoteFeatureExtractor:()=>Ee,PyAnnoteProcessor:()=>Xe,RTDetrImageProcessor:()=>Qe,SamImageProcessor:()=>lt,SamProcessor:()=>_e,SapiensFeatureExtractor:()=>x,SeamlessM4TFeatureExtractor:()=>Oe,SegformerFeatureExtractor:()=>S,SiglipImageProcessor:()=>ge,SpeechT5FeatureExtractor:()=>se,SpeechT5Processor:()=>St,Swin2SRImageProcessor:()=>dt,ViTFeatureExtractor:()=>Se,ViTImageProcessor:()=>G,VitMatteImageProcessor:()=>bt,Wav2Vec2FeatureExtractor:()=>Fe,Wav2Vec2ProcessorWithLM:()=>Ie,WeSpeakerFeatureExtractor:()=>H,WhisperFeatureExtractor:()=>z,WhisperProcessor:()=>pe,YolosFeatureExtractor:()=>ke});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 h([kt,ve,Ne,rt]){return[kt-Ne/2,ve-rt/2,kt+Ne/2,ve+rt/2]}function w(kt,ve=.5,Ne=null,rt=!1){const Ye=kt.logits,mt=kt.pred_boxes,[At,jt,it]=Ye.dims;if(Ne!==null&&Ne.length!==At)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let en=[];for(let Vt=0;Vtve&&Sn.push(In)}else{let In=(0,l.max)(mn.data)[1];if(In===it-1||(An=(0,l.softmax)(mn.data),An[In]Et*xt[(Ht+1)%2])),hn.boxes.push(Mn),hn.classes.push(In),hn.scores.push(An[In])}}en.push(hn)}return en}function _(kt,ve=null){const Ne=kt.logits,rt=Ne.dims[0];if(ve!==null&&ve.length!==rt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Ye=[];for(let mt=0;mtxt[An]&&(xt[An]=Sn[An],hn[An]=mn)}const fn=new Array(jt.dims[0]),Tn=Vt.data;for(let mn=0;mnmn!==void 0);Ye.push({segmentation:Vt,labels:bn})}return Ye}function M(kt,ve){if(!(kt instanceof Float32Array||kt instanceof Float64Array))throw new Error(`${ve} expects input to be a Float32Array or a Float64Array, but got ${kt?.constructor?.name??typeof kt} 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 T(kt,ve,Ne=0,rt=null){const Ye=kt/ve;let mt=(0,l.bankers_round)(Ye)*ve;return rt!==null&&mt>rt&&(mt=Math.floor(Ye)*ve),mtmt?en=Math.floor(mt*it/Ye):mt>Ye&&(it=Math.floor(Ye*en/mt)),await ve.resize(en,it,{resample:rt}))}async crop_margin(ve,Ne=200){const rt=ve.clone().grayscale(),Ye=(0,l.min)(rt.data)[0],At=(0,l.max)(rt.data)[0]-Ye;if(At===0)return ve;const jt=Ne/255;let it=rt.width,en=rt.height,Vt=0,xt=0;const hn=rt.data;for(let fn=0;fnthis.preprocess(mt)));return{pixel_values:(0,d.stack)(rt.map(mt=>mt.pixel_values),0),original_sizes:rt.map(mt=>mt.original_size),reshaped_input_sizes:rt.map(mt=>mt.reshaped_input_size)}}}class x extends E{post_process_semantic_segmentation(...ve){return _(...ve)}}class S extends E{post_process_semantic_segmentation(...ve){return _(...ve)}}class P extends E{}class j extends P{}class L extends E{}class N extends E{}class W extends E{}class V extends W{}class ce extends E{}class ge extends E{}class Re extends E{constructor(ve){super(ve),this.crop_pct=this.config.crop_pct??224/256}async resize(ve){const Ne=this.size?.shortest_edge;if(Ne===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(Ne<384){const rt=Math.floor(Ne/this.crop_pct),[Ye,mt]=this.get_resize_output_image_size(ve,{shortest_edge:rt});ve=await ve.resize(Ye,mt,{resample:this.resample}),ve=await ve.center_crop(Ne,Ne)}else ve=await ve.resize(Ne,Ne,{resample:this.resample});return ve}}class oe extends Re{}class Se extends E{}class G extends E{}class Ce extends E{constructor(ve){super(ve),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(Ne=>Ne*Ne))}}class pt extends E{}class Te extends E{}class te extends E{}class fe extends E{}class Pe extends E{}class ne extends Pe{}class xe extends E{post_process_object_detection(...ve){return w(...ve)}}class ht extends xe{}class Qe extends E{post_process_object_detection(...ve){return w(...ve)}}class Ze extends E{}class ut extends E{}class Mt extends E{pad_image(ve,Ne,rt,Ye={}){const[mt,At,jt]=Ne;let it=this.image_mean;Array.isArray(this.image_mean)||(it=new Array(jt).fill(it));let en=this.image_std;Array.isArray(en)||(en=new Array(jt).fill(it));const Vt=it.map((xt,hn)=>-xt/en[hn]);return super.pad_image(ve,Ne,rt,{center:!0,constant_values:Vt,...Ye})}}class Ft extends Mt{}class Ve extends E{async _call(ve){const Ne=await super._call(ve),rt=[Ne.pixel_values.dims[0],64,64],Ye=new d.Tensor("int64",new BigInt64Array(rt.reduce((mt,At)=>mt*At)).fill(1n),rt);return{...Ne,pixel_mask:Ye}}post_process_object_detection(...ve){return w(...ve)}remove_low_and_no_objects(ve,Ne,rt,Ye){let mt=[],At=[],jt=[];for(let it=0;itrt&&(mt.push(Vt),At.push(fn),jt.push(xt))}return[mt,At,jt]}check_segment_validity(ve,Ne,rt,Ye=.5,mt=.8){let At=[],jt=0,it=0;const en=Ne[rt].data;for(let xt=0;xt=Ye&&++it;let Vt=jt>0&&it>0;return Vt&&(Vt=jt/it>mt),[Vt,At]}compute_segments(ve,Ne,rt,Ye,mt,At=null,jt=null){let[it,en]=jt??ve[0].dims,Vt=new d.Tensor("int32",new Int32Array(it*en),[it,en]),xt=[];if(jt!==null)for(let mn=0;mnfn[In]&&(hn[In]=mn,fn[In]=An[In])}let Tn=0;const bn=Vt.data;for(let mn=0;mnYe!==Ne.dims[mt]))throw Error(`The first ${rt.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new d.Tensor("int64",ve.flat(1/0).map(BigInt),rt)}async _call(ve,{input_points:Ne=null,input_labels:rt=null,input_boxes:Ye=null}={}){const mt=await super._call(ve);if(Ne&&(mt.input_points=this.reshape_input_points(Ne,mt.original_sizes,mt.reshaped_input_sizes)),rt){if(!mt.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");mt.input_labels=this.add_input_labels(rt,mt.input_points)}return Ye&&(mt.input_boxes=this.reshape_input_points(Ye,mt.original_sizes,mt.reshaped_input_sizes,!0)),mt}async post_process_masks(ve,Ne,rt,{mask_threshold:Ye=0,binarize:mt=!0,pad_size:At=null}={}){const jt=[];At=At??this.pad_size;const it=[At.height,At.width];for(let en=0;enYe&&(Tn[bn]=1);hn=new d.Tensor("bool",Tn,hn.dims)}jt.push(hn)}return jt}generate_crop_boxes(ve,Ne,{crop_n_layers:rt=0,overlap_ratio:Ye=512/1500,points_per_crop:mt=32,crop_n_points_downscale_factor:At=1}={}){}}class dt extends E{pad_image(ve,Ne,rt,Ye={}){const[mt,At,jt]=Ne;return super.pad_image(ve,Ne,{width:At+(rt-At%rt)%rt,height:mt+(rt-mt%rt)%rt},{mode:"symmetric",center:!1,constant_values:-1,...Ye})}}class bt extends E{async _call(ve,Ne){Array.isArray(ve)||(ve=[ve]),Array.isArray(Ne)||(Ne=[Ne]);const rt=await Promise.all(ve.map(At=>this.preprocess(At))),Ye=await Promise.all(Ne.map(At=>this.preprocess(At,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,d.stack)(rt.map((At,jt)=>(0,d.cat)([At.pixel_values,Ye[jt].pixel_values],0)),0),original_sizes:rt.map(At=>At.original_size),reshaped_input_sizes:rt.map(At=>At.reshaped_input_size)}}}class z extends C{constructor(ve){super(ve),this.config.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(ve){const Ne=await(0,c.spectrogram)(ve,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}),rt=Ne.data,Ye=(0,l.max)(rt)[0];for(let mt=0;mtthis.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`."),Ne=ve.slice(0,this.config.n_samples)):(Ne=new Float32Array(this.config.n_samples),Ne.set(ve)),{input_features:(await this._extract_fbank_features(Ne)).unsqueeze_(0)}}}class Fe extends C{_zero_mean_unit_var_norm(ve){const rt=ve.reduce((mt,At)=>mt+At,0)/ve.length,Ye=ve.reduce((mt,At)=>mt+(At-rt)**2,0)/ve.length;return ve.map(mt=>(mt-rt)/Math.sqrt(Ye+1e-7))}async _call(ve){M(ve,"Wav2Vec2FeatureExtractor"),ve instanceof Float64Array&&(ve=new Float32Array(ve));let Ne=ve;this.config.do_normalize&&(Ne=this._zero_mean_unit_var_norm(Ne));const rt=[1,Ne.length];return{input_values:new d.Tensor("float32",Ne,rt),attention_mask:new d.Tensor("int64",new BigInt64Array(Ne.length).fill(1n),rt)}}}class Oe extends C{constructor(ve){super(ve);const Ne=this.config.sampling_rate,rt=(0,c.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(Ne/2),Ne,null,"kaldi",!0);for(let Ye=0;Yert*32768),(0,c.spectrogram)(ve,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:Ne,transpose:!0})}async _call(ve,{padding:Ne=!0,pad_to_multiple_of:rt=2,do_normalize_per_mel_bins:Ye=!0,return_attention_mask:mt=!0}={}){M(ve,"SeamlessM4TFeatureExtractor");let At=await this._extract_fbank_features(ve,this.config.max_length);if(Ye){const[Tn,bn]=At.dims,mn=At.data;for(let Sn=0;Sn0){const An=new Float32Array(bn*(Tn+Sn));An.set(mn),An.fill(this.config.padding_value,mn.length);const In=Tn+Sn;At=new d.Tensor(At.type,An,[In,bn]),mt&&(jt=new d.Tensor("int64",new BigInt64Array(In),[1,In]),jt.data.fill(1n,0,Tn))}}const[it,en]=At.dims,Vt=this.config.stride;if(it%Vt!==0)throw new Error(`The number of frames (${it}) must be a multiple of the stride (${Vt}).`);const hn=At.view(1,Math.floor(it/Vt),en*Vt),fn={input_features:hn};if(mt){const Tn=hn.dims[1],bn=new BigInt64Array(Tn);if(jt){const mn=jt.data;for(let Sn=1,An=0;Sn0)if(rt==="rand_trunc"){const jt=Math.floor(Math.random()*(At+1));ve=ve.subarray(jt,jt+Ne),mt=await this._extract_fbank_features(ve,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${rt}" not implemented`);else{if(At<0){let jt=new Float64Array(Ne);if(jt.set(ve),Ye==="repeat")for(let it=ve.length;it({id:it,start:en*rt,end:Vt*rt,confidence:xt/(Vt-en)})))}return Ye}}class H extends C{constructor(ve){super(ve);const Ne=this.config.sampling_rate,rt=(0,c.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(Ne/2),Ne,null,"kaldi",!0);for(let Ye=0;YeNe*32768),(0,c.spectrogram)(ve,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(ve){M(ve,"WeSpeakerFeatureExtractor");const Ne=(await this._extract_fbank_features(ve)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const rt=Ne.mean(1).data,Ye=Ne.data,[mt,At,jt]=Ne.dims;for(let it=0;it/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(ve){typeof ve=="string"&&(ve=[ve]);const Ne=[];for(const rt of ve)if(this.task_prompts_without_inputs.has(rt))Ne.push(this.task_prompts_without_inputs.get(rt));else{for(const[Ye,mt]of this.task_prompts_with_input)if(rt.includes(Ye)){Ne.push(mt.replaceAll("{input}",rt).replaceAll(Ye,""));break}Ne.length!==ve.length&&Ne.push(rt)}return Ne}post_process_generation(ve,Ne,rt){const Ye=this.tasks_answer_post_processing_type.get(Ne)??"pure_text";ve=ve.replaceAll("","").replaceAll("","");let mt;switch(Ye){case"pure_text":mt=ve;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const At=Ye==="ocr"?"quad_boxes":"bboxes",jt=ve.matchAll(this.regexes[At]),it=[],en=[];for(const[Vt,xt,...hn]of jt)it.push(xt?xt.trim():it.at(-1)??""),en.push(hn.map((fn,Tn)=>(Number(fn)+.5)/this.size_per_bin*rt[Tn%2]));mt={labels:it,[At]:en};break;default:throw new Error(`Task "${Ne}" (of type "${Ye}") not yet implemented.`)}return{[Ne]:mt}}}class Jt{static FEATURE_EXTRACTOR_CLASS_MAPPING={ImageFeatureExtractor:E,WhisperFeatureExtractor:z,ViTFeatureExtractor:Se,MobileViTFeatureExtractor:Pe,MobileViTImageProcessor:ne,MobileNetV1FeatureExtractor:pt,MobileNetV2FeatureExtractor:Te,MobileNetV3FeatureExtractor:te,MobileNetV4FeatureExtractor:fe,OwlViTFeatureExtractor:xe,Owlv2ImageProcessor:ht,CLIPFeatureExtractor:W,CLIPImageProcessor:V,Florence2Processor:Dt,ChineseCLIPFeatureExtractor:ce,SiglipImageProcessor:ge,ConvNextFeatureExtractor:Re,ConvNextImageProcessor:oe,SegformerFeatureExtractor:S,SapiensFeatureExtractor:x,BitImageProcessor:L,DPTImageProcessor:j,DPTFeatureExtractor:P,GLPNFeatureExtractor:N,BeitFeatureExtractor:ut,DeiTFeatureExtractor:Ze,DetrFeatureExtractor:Ve,RTDetrImageProcessor:Qe,YolosFeatureExtractor:ke,DonutFeatureExtractor:Mt,NougatImageProcessor:Ft,EfficientNetImageProcessor:Ce,ViTImageProcessor:G,VitMatteImageProcessor:bt,SamImageProcessor:lt,Swin2SRImageProcessor:dt,Wav2Vec2FeatureExtractor:Fe,SeamlessM4TFeatureExtractor:Oe,SpeechT5FeatureExtractor:se,ASTFeatureExtractor:he,ClapFeatureExtractor:de,PyAnnoteFeatureExtractor:Ee,WeSpeakerFeatureExtractor:H};static PROCESSOR_CLASS_MAPPING={WhisperProcessor:pe,Wav2Vec2ProcessorWithLM:Ie,PyAnnoteProcessor:Xe,SamProcessor:_e,SpeechT5Processor:St,OwlViTProcessor:ft,Florence2Processor:Dt};static async from_pretrained(ve,{progress_callback:Ne=null,config:rt=null,cache_dir:Ye=null,local_files_only:mt=!1,revision:At="main"}={}){let jt=rt??await(0,a.getModelJSON)(ve,"preprocessor_config.json",!0,{progress_callback:Ne,config:rt,cache_dir:Ye,local_files_only:mt,revision:At}),it=jt.feature_extractor_type??jt.image_processor_type,en=this.FEATURE_EXTRACTOR_CLASS_MAPPING[it];if(!en)if(jt.size!==void 0)console.warn(`Feature extractor type "${it}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),en=E;else throw new Error(`Unknown Feature Extractor type: ${it}`);let Vt=this.PROCESSOR_CLASS_MAPPING[jt.processor_class]??K,xt=new en(jt);return new Vt(xt)}}},"./src/tokenizers.js":(e,t,n)=>{n.r(t),n.d(t,{AlbertTokenizer:()=>fn,AutoTokenizer:()=>wi,BartTokenizer:()=>vr,BertTokenizer:()=>hn,BlenderbotSmallTokenizer:()=>mr,BlenderbotTokenizer:()=>qs,BloomTokenizer:()=>kr,CLIPTokenizer:()=>En,CamembertTokenizer:()=>Ht,CodeGenTokenizer:()=>vs,CodeLlamaTokenizer:()=>us,CohereTokenizer:()=>xr,ConvBertTokenizer:()=>In,DebertaTokenizer:()=>mn,DebertaV2Tokenizer:()=>Sn,DistilBertTokenizer:()=>Et,ElectraTokenizer:()=>zr,EsmTokenizer:()=>li,FalconTokenizer:()=>Ar,GPT2Tokenizer:()=>ao,GPTNeoXTokenizer:()=>Gi,GemmaTokenizer:()=>qi,Grok1Tokenizer:()=>Si,HerbertTokenizer:()=>An,LlamaTokenizer:()=>ls,M2M100Tokenizer:()=>ki,MBart50Tokenizer:()=>br,MBartTokenizer:()=>Qr,MPNetTokenizer:()=>Ws,MarianTokenizer:()=>uo,MobileBertTokenizer:()=>Tn,NllbTokenizer:()=>Hi,NougatTokenizer:()=>ds,PreTrainedTokenizer:()=>xt,Qwen2Tokenizer:()=>$o,RoFormerTokenizer:()=>Mn,RobertaTokenizer:()=>as,SiglipTokenizer:()=>Xn,SpeechT5Tokenizer:()=>ws,SqueezeBertTokenizer:()=>bn,T5Tokenizer:()=>os,TokenizerModel:()=>Re,VitsTokenizer:()=>fs,Wav2Vec2CTCTokenizer:()=>co,WhisperTokenizer:()=>Gs,XLMRobertaTokenizer:()=>lo,XLMTokenizer:()=>un,is_chinese_char:()=>j});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"),h=n("./node_modules/@huggingface/jinja/dist/index.js"),w=n("./src/models/whisper/common_whisper.js"),_=n("./src/utils/constants.js");async function M(nt,q){const ye=await Promise.all([(0,a.getModelJSON)(nt,"tokenizer.json",!0,q),(0,a.getModelJSON)(nt,"tokenizer_config.json",!0,q)]);return q.legacy!==null&&(ye[1].legacy=q.legacy),ye}function T(nt,q){const ye=[];let Le=0;for(const De of nt.matchAll(q)){const ct=De[0];Le0&&ye.push(ct),Le=De.index+ct.length}return Le=19968&&nt<=40959||nt>=13312&&nt<=19903||nt>=131072&&nt<=173791||nt>=173824&&nt<=177983||nt>=177984&&nt<=178207||nt>=178208&&nt<=183983||nt>=63744&&nt<=64255||nt>=194560&&nt<=195103}function L(nt,q,ye){const Le=[];let De=0;for(;Dethis.tokens_to_ids.get(ye)??this.unk_token_id)}convert_ids_to_tokens(q){return q.map(ye=>this.vocab[ye]??this.unk_token)}}class oe extends Re{constructor(q){super(q),this.tokens_to_ids=C(q.vocab),this.unk_token_id=this.tokens_to_ids.get(q.unk_token),this.unk_token=q.unk_token,this.max_input_chars_per_word=q.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[ye,Le]of this.tokens_to_ids)this.vocab[Le]=ye}encode(q){const ye=[];for(const Le of q){const De=[...Le];if(De.length>this.max_input_chars_per_word){ye.push(this.unk_token);continue}let ct=!1,Pt=0;const tn=[];for(;Pt0&&(Qt=this.config.continuing_subword_prefix+Qt),this.tokens_to_ids.has(Qt)){nn=Qt;break}--zt}if(nn===null){ct=!0;break}tn.push(nn),Pt=zt}ct?ye.push(this.unk_token):ye.push(...tn)}return ye}}class Se extends Re{constructor(q,ye){super(q);const Le=q.vocab.length;this.vocab=new Array(Le),this.scores=new Array(Le);for(let De=0;De[De,ct])),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(q){const ye=q.sentence,Le=ye.length;let De=0;for(;De{const nt=[...Array.from({length:94},(De,ct)=>ct+33),...Array.from({length:12},(De,ct)=>ct+161),...Array.from({length:82},(De,ct)=>ct+174)],q=nt.slice();let ye=0;for(let De=0;De<256;++De)nt.includes(De)||(nt.push(De),q.push(256+ye),ye+=1);const Le=q.map(De=>String.fromCharCode(De));return Object.fromEntries(nt.map((De,ct)=>[De,Le[ct]]))})(),Ce=(0,o.reverseDictionary)(G);class pt extends Re{constructor(q){super(q),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=C(q.vocab),this.unk_token_id=this.tokens_to_ids.get(q.unk_token),this.unk_token=q.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ye,Le]of this.tokens_to_ids)this.vocab[Le]=ye;this.bpe_ranks=new Map(q.merges.map((ye,Le)=>[ye,Le])),this.merges=q.merges.map(ye=>ye.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=q.end_of_word_suffix,this.continuing_subword_suffix=q.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(q){if(q.length===0)return[];const ye=this.cache.get(q);if(ye!==void 0)return ye;const Le=Array.from(q);this.end_of_word_suffix&&(Le[Le.length-1]+=this.end_of_word_suffix);let De=[];if(Le.length>1){const ct=new c.PriorityQueue((zt,nn)=>zt.score`<0x${Pt.toString(16).toUpperCase().padStart(2,"0")}>`)):ye.push(this.unk_token)}return ye}}class Te extends Re{constructor(q,ye){super(q),this.tokens_to_ids=C(ye.target_lang?q.vocab[ye.target_lang]:q.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[Le,De]of this.tokens_to_ids)this.vocab[De]=Le}encode(q){return q}}class te extends i.Callable{constructor(q){super(),this.config=q}static fromConfig(q){if(q===null)return null;switch(q.type){case"BertNormalizer":return new Ft(q);case"Precompiled":return new rt(q);case"Sequence":return new Mt(q);case"Replace":return new fe(q);case"NFC":return new Pe(q);case"NFKC":return new ne(q);case"NFKD":return new xe(q);case"Strip":return new ht(q);case"StripAccents":return new Qe(q);case"Lowercase":return new Ze(q);case"Prepend":return new ut(q);default:throw new Error(`Unknown Normalizer type: ${q.type}`)}}normalize(q){throw Error("normalize should be implemented in subclass.")}_call(q){return this.normalize(q)}}class fe extends te{normalize(q){const ye=F(this.config.pattern);return ye===null?q:q.replaceAll(ye,this.config.content)}}class Pe extends te{normalize(q){return q=q.normalize("NFC"),q}}class ne extends te{normalize(q){return q=q.normalize("NFKC"),q}}class xe extends te{normalize(q){return q=q.normalize("NFKD"),q}}class ht extends te{normalize(q){return this.config.strip_left&&this.config.strip_right?q=q.trim():(this.config.strip_left&&(q=q.trimStart()),this.config.strip_right&&(q=q.trimEnd())),q}}class Qe extends te{normalize(q){return q=S(q),q}}class Ze extends te{normalize(q){return q=q.toLowerCase(),q}}class ut extends te{normalize(q){return q=this.config.prepend+q,q}}class Mt extends te{constructor(q){super(q),this.normalizers=q.normalizers.map(ye=>te.fromConfig(ye))}normalize(q){return this.normalizers.reduce((ye,Le)=>Le.normalize(ye),q)}}class Ft extends te{_tokenize_chinese_chars(q){const ye=[];for(let Le=0;Lethis.pre_tokenize_text(Le,ye)):this.pre_tokenize_text(q,ye)).flat()}_call(q,ye){return this.pre_tokenize(q,ye)}}class ke extends Ve{constructor(q){super(),this.pattern=new RegExp(`[^\\s${W}]+|[${W}]`,"gu")}pre_tokenize_text(q,ye){return q.trim().match(this.pattern)||[]}}class lt extends Ve{constructor(q){super(),this.config=q,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=/'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(q,ye){return this.add_prefix_space&&!q.startsWith(" ")&&(q=" "+q),(this.use_regex?q.match(this.pattern)||[]:[q]).map(De=>Array.from(this.text_encoder.encode(De),ct=>this.byte_encoder[ct]).join(""))}}class dt extends Ve{constructor(q){super(),this.config=q,this.pattern=F(this.config.pattern,this.config.invert)}pre_tokenize_text(q,ye){return this.pattern===null?[]:this.config.invert?q.match(this.pattern)||[]:T(q,this.pattern)}}class bt extends Ve{constructor(q){super(),this.config=q,this.pattern=new RegExp(`[^${W}]+|[${W}]+`,"gu")}pre_tokenize_text(q,ye){return q.match(this.pattern)||[]}}class z extends Ve{constructor(q){super(),this.config=q;const ye=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(ye,"gu")}pre_tokenize_text(q,ye){return q.match(this.pattern)||[]}}class Fe extends i.Callable{constructor(q){super(),this.config=q}static fromConfig(q){if(q===null)return null;switch(q.type){case"TemplateProcessing":return new de(q);case"ByteLevel":return new Ee(q);case"RobertaProcessing":return new he(q);case"BertProcessing":return new Oe(q);case"Sequence":return new H(q);default:throw new Error(`Unknown PostProcessor type: ${q.type}`)}}post_process(q,...ye){throw Error("post_process should be implemented in subclass.")}_call(q,...ye){return this.post_process(q,...ye)}}class Oe extends Fe{constructor(q){super(q),this.cls=q.cls[0],this.sep=q.sep[0]}post_process(q,ye=null,{add_special_tokens:Le=!0}={}){Le&&(q=(0,o.mergeArrays)([this.cls],q,[this.sep]));let De=new Array(q.length).fill(0);if(ye!==null){const ct=Le&&this instanceof he?[this.sep]:[],Pt=Le?[this.sep]:[];q=(0,o.mergeArrays)(q,ct,ye,Pt),De=(0,o.mergeArrays)(De,new Array(ye.length+ct.length+Pt.length).fill(1))}return{tokens:q,token_type_ids:De}}}class he extends Oe{}class de extends Fe{constructor(q){super(q),this.single=q.single,this.pair=q.pair}post_process(q,ye=null,{add_special_tokens:Le=!0}={}){const De=ye===null?this.single:this.pair;let ct=[],Pt=[];for(const tn of De)"SpecialToken"in tn?Le&&(ct.push(tn.SpecialToken.id),Pt.push(tn.SpecialToken.type_id)):"Sequence"in tn&&(tn.Sequence.id==="A"?(ct=(0,o.mergeArrays)(ct,q),Pt=(0,o.mergeArrays)(Pt,new Array(q.length).fill(tn.Sequence.type_id))):tn.Sequence.id==="B"&&(ct=(0,o.mergeArrays)(ct,ye),Pt=(0,o.mergeArrays)(Pt,new Array(ye.length).fill(tn.Sequence.type_id))));return{tokens:ct,token_type_ids:Pt}}}class Ee extends Fe{post_process(q,ye=null){return ye&&(q=(0,o.mergeArrays)(q,ye)),{tokens:q}}}class H extends Fe{constructor(q){super(q),this.processors=q.processors.map(ye=>Fe.fromConfig(ye))}post_process(q,ye=null,Le={}){let De;for(const ct of this.processors)if(ct instanceof Ee)q=ct.post_process(q).tokens,ye&&(ye=ct.post_process(ye).tokens);else{const Pt=ct.post_process(q,ye,Le);q=Pt.tokens,De=Pt.token_type_ids}return{tokens:q,token_type_ids:De}}}class se extends i.Callable{constructor(q){super(),this.config=q,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=q.trim_offsets}static fromConfig(q){if(q===null)return null;switch(q.type){case"WordPiece":return new Xe(q);case"Metaspace":return new Ne(q);case"ByteLevel":return new St(q);case"Replace":return new K(q);case"ByteFallback":return new _e(q);case"Fuse":return new pe(q);case"Strip":return new Ie(q);case"Sequence":return new Dt(q);case"CTC":return new ft(q);case"BPEDecoder":return new Jt(q);default:throw new Error(`Unknown Decoder type: ${q.type}`)}}_call(q){return this.decode(q)}decode(q){return this.decode_chain(q).join("")}decode_chain(q){throw Error("`decode_chain` should be implemented in subclass.")}}class K extends se{decode_chain(q){const ye=F(this.config.pattern);return ye===null?q:q.map(Le=>Le.replaceAll(ye,this.config.content))}}class _e extends se{constructor(q){super(q),this.text_decoder=new TextDecoder}decode_chain(q){const ye=[];let Le=[];for(const De of q){let ct=null;if(De.length===6&&De.startsWith("<0x")&&De.endsWith(">")){const Pt=parseInt(De.slice(3,5),16);isNaN(Pt)||(ct=Pt)}if(ct!==null)Le.push(ct);else{if(Le.length>0){const Pt=this.text_decoder.decode(Uint8Array.from(Le));ye.push(Pt),Le=[]}ye.push(De)}}if(Le.length>0){const De=this.text_decoder.decode(Uint8Array.from(Le));ye.push(De),Le=[]}return ye}}class pe extends se{decode_chain(q){return[q.join("")]}}class Ie extends se{constructor(q){super(q),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(q){return q.map(ye=>{let Le=0;for(let ct=0;ct(Le!==0&&(ye.startsWith(this.config.prefix)?ye=ye.replace(this.config.prefix,""):ye=" "+ye),this.cleanup&&(ye=x(ye)),ye))}}class St extends se{constructor(q){super(q),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(q){const ye=q.join(""),Le=new Uint8Array([...ye].map(ct=>this.byte_decoder[ct]));return this.text_decoder.decode(Le)}decode_chain(q){const ye=[];let Le=[];for(const De of q)this.added_tokens.find(ct=>ct.content===De)!==void 0?(Le.length>0&&(ye.push(this.convert_tokens_to_string(Le)),Le=[]),ye.push(De)):Le.push(De);return Le.length>0&&ye.push(this.convert_tokens_to_string(Le)),ye}}class ft extends se{constructor(q){super(q),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(q){if(q.length===0)return"";const ye=[q[0]];for(let ct=1;ctct!==this.pad_token).join("");return this.cleanup&&(De=x(De).replaceAll(this.word_delimiter_token," ").trim()),De}decode_chain(q){return[this.convert_tokens_to_string(q)]}}class Dt extends se{constructor(q){super(q),this.decoders=q.decoders.map(ye=>se.fromConfig(ye))}decode_chain(q){return this.decoders.reduce((ye,Le)=>Le.decode_chain(ye),q)}}class Jt extends se{constructor(q){super(q),this.suffix=this.config.suffix}decode_chain(q){return q.map((ye,Le)=>ye.replaceAll(this.suffix,Le===q.length-1?"":" "))}}class kt extends se{decode_chain(q){let ye="";for(let Le=1;LeLe.normalize("NFKC")).join("~"):q=q.normalize("NFKC"),q}}class Ye extends Ve{constructor(q){super(),this.tokenizers=q.pretokenizers.map(ye=>Ve.fromConfig(ye))}pre_tokenize_text(q,ye){return this.tokenizers.reduce((Le,De)=>De.pre_tokenize(Le,ye),[q])}}class mt extends Ve{constructor(q){super()}pre_tokenize_text(q,ye){return q.match(/\w+|[^\w\s]+/g)||[]}}class At extends Ve{constructor(q){super()}pre_tokenize_text(q,ye){return N(q)}}class jt extends Ve{constructor(q){super(),this.config=q,this.pattern=F(this.config.pattern),this.content=this.config.content}pre_tokenize_text(q,ye){return this.pattern===null?[q]:[q.replaceAll(this.pattern,this.config.content)]}}const it=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function en(nt,q,ye,Le){for(const De of Object.keys(nt)){const ct=q-nt[De].length,Pt=ye(De),tn=new Array(ct).fill(Pt);nt[De]=Le==="right"?(0,o.mergeArrays)(nt[De],tn):(0,o.mergeArrays)(tn,nt[De])}}function Vt(nt,q){for(const ye of Object.keys(nt))nt[ye].length=q}class xt extends i.Callable{return_token_type_ids=!1;padding_side="right";constructor(q,ye){super(),this._tokenizer_config=ye,this.normalizer=te.fromConfig(q.normalizer),this.pre_tokenizer=Ve.fromConfig(q.pre_tokenizer),this.model=Re.fromConfig(q.model,ye),this.post_processor=Fe.fromConfig(q.post_processor),this.decoder=se.fromConfig(q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Le of q.added_tokens){const De=new ge(Le);this.added_tokens.push(De),this.model.tokens_to_ids.set(De.content,De.id),this.model.vocab[De.id]=De.content,De.special&&(this.special_tokens.push(De.content),this.all_special_ids.push(De.id))}if(this.additional_special_tokens=ye.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((Le,De)=>De.content.length-Le.content.length).map(Le=>`${Le.lstrip?"\\s*":""}(${(0,o.escapeRegExp)(Le.content)})${Le.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=ye.model_max_length,this.remove_space=ye.remove_space,this.clean_up_tokenization_spaces=ye.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ye.do_lowercase_and_remove_accent??!1,ye.padding_side&&(this.padding_side=ye.padding_side),this.legacy=!1,this.chat_template=ye.chat_template??null,Array.isArray(this.chat_template)){const Le=Object.create(null);for(const{name:De,template:ct}of this.chat_template){if(typeof De!="string"||typeof ct!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Le[De]=ct}this.chat_template=Le}this._compiled_template_cache=new Map}getToken(...q){for(const ye of q){const Le=this._tokenizer_config[ye];if(Le)if(typeof Le=="object"){if(Le.__type==="AddedToken")return Le.content;throw Error(`Unknown token: ${Le}`)}else return Le}return null}static async from_pretrained(q,{progress_callback:ye=null,config:Le=null,cache_dir:De=null,local_files_only:ct=!1,revision:Pt="main",legacy:tn=null}={}){const zt=await M(q,{progress_callback:ye,config:Le,cache_dir:De,local_files_only:ct,revision:Pt,legacy:tn});return new this(...zt)}_call(q,{text_pair:ye=null,add_special_tokens:Le=!0,padding:De=!1,truncation:ct=null,max_length:Pt=null,return_tensor:tn=!0,return_token_type_ids:zt=null}={}){const nn=Array.isArray(q);let Qt;if(nn){if(q.length===0)throw Error("text array must be non-empty");if(ye!==null){if(Array.isArray(ye)){if(q.length!==ye.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Qt=q.map((Cn,qn)=>this._encode_plus(Cn,{text_pair:ye[qn],add_special_tokens:Le,return_token_type_ids:zt}))}else Qt=q.map(Cn=>this._encode_plus(Cn,{add_special_tokens:Le,return_token_type_ids:zt}))}else{if(q==null)throw Error("text may not be null or undefined");if(Array.isArray(ye))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Qt=[this._encode_plus(q,{text_pair:ye,add_special_tokens:Le,return_token_type_ids:zt})]}if(Pt===null?De==="max_length"?Pt=this.model_max_length:Pt=(0,l.max)(Qt.map(Cn=>Cn.input_ids.length))[0]:ct||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."),Pt=Math.min(Pt,this.model_max_length??1/0),De||ct)for(let Cn=0;CnPt?ct&&Vt(Qt[Cn],Pt):De&&en(Qt[Cn],Pt,qn=>qn==="input_ids"?this.pad_token_id:0,this.padding_side));const nr={};if(tn){if(!(De&&ct)&&Qt.some(qn=>{for(const kn of Object.keys(qn))if(qn[kn].length!==Qt[0][kn]?.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 Cn=[Qt.length,Qt[0].input_ids.length];for(const qn of Object.keys(Qt[0]))nr[qn]=new d.Tensor("int64",BigInt64Array.from(Qt.flatMap(kn=>kn[qn]).map(BigInt)),Cn)}else{for(const Cn of Object.keys(Qt[0]))nr[Cn]=Qt.map(qn=>qn[Cn]);if(!nn)for(const Cn of Object.keys(nr))nr[Cn]=nr[Cn][0]}return nr}_encode_text(q){return q===null?null:(this.added_tokens_regex?q.split(this.added_tokens_regex).filter(De=>De):[q]).map((De,ct)=>{if(this.added_tokens.find(tn=>tn.content===De)!==void 0)return De;{if(this.remove_space===!0&&(De=De.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(De=P(De)),this.normalizer!==null&&(De=this.normalizer(De)),De.length===0)return[];const tn=this.pre_tokenizer!==null?this.pre_tokenizer(De,{section_index:ct}):[De];return this.model(tn)}}).flat()}_encode_plus(q,{text_pair:ye=null,add_special_tokens:Le=!0,return_token_type_ids:De=null}={}){const{tokens:ct,token_type_ids:Pt}=this._tokenize_helper(q,{pair:ye,add_special_tokens:Le}),tn=this.model.convert_tokens_to_ids(ct),zt={input_ids:tn,attention_mask:new Array(tn.length).fill(1)};return(De??this.return_token_type_ids)&&Pt&&(zt.token_type_ids=Pt),zt}_tokenize_helper(q,{pair:ye=null,add_special_tokens:Le=!1}={}){const De=this._encode_text(q),ct=this._encode_text(ye);return this.post_processor?this.post_processor(De,ct,{add_special_tokens:Le}):{tokens:(0,o.mergeArrays)(De??[],ct??[])}}tokenize(q,{pair:ye=null,add_special_tokens:Le=!1}={}){return this._tokenize_helper(q,{pair:ye,add_special_tokens:Le}).tokens}encode(q,{text_pair:ye=null,add_special_tokens:Le=!0,return_token_type_ids:De=null}={}){return this._encode_plus(q,{text_pair:ye,add_special_tokens:Le,return_token_type_ids:De}).input_ids}batch_decode(q,ye={}){return q instanceof d.Tensor&&(q=q.tolist()),q.map(Le=>this.decode(Le,ye))}decode(q,ye={}){if(q instanceof d.Tensor&&(q=E(q)),!Array.isArray(q)||q.length===0||!(0,o.isIntegralNumber)(q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(q,ye)}decode_single(q,{skip_special_tokens:ye=!1,clean_up_tokenization_spaces:Le=null}){let De=this.model.convert_ids_to_tokens(q);ye&&(De=De.filter(Pt=>!this.special_tokens.includes(Pt)));let ct=this.decoder?this.decoder(De):De.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(ct=ct.replaceAll(this.decoder.end_of_word_suffix," "),ye&&(ct=ct.trim())),(Le??this.clean_up_tokenization_spaces)&&(ct=x(ct)),ct}apply_chat_template(q,{tools:ye=null,documents:Le=null,chat_template:De=null,add_generation_prompt:ct=!1,tokenize:Pt=!0,padding:tn=!1,truncation:zt=!1,max_length:nn=null,return_tensor:Qt=!0,return_dict:nr=!1,tokenizer_kwargs:Cn={},...qn}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const Mr=this.chat_template;if(De!==null&&Object.hasOwn(Mr,De))De=Mr[De];else if(De===null&&"default"in Mr)De=Mr.default;else if(De===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(Mr).sort()}.`)}else if(this.chat_template)De=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 De!="string")throw Error(`chat_template must be a string, but got ${typeof De}`);let kn=this._compiled_template_cache.get(De);kn===void 0&&(kn=new h.Template(De),this._compiled_template_cache.set(De,kn));const Qn=Object.create(null);for(const Mr of it){const yt=this.getToken(Mr);yt&&(Qn[Mr]=yt)}const Ei=kn.render({messages:q,add_generation_prompt:ct,tools:ye,documents:Le,...Qn,...qn});if(Pt){const Mr=this._call(Ei,{add_special_tokens:!1,padding:tn,truncation:zt,max_length:nn,return_tensor:Qt,...Cn});return nr?Mr:Mr.input_ids}return Ei}}class hn extends xt{return_token_type_ids=!0}class fn extends xt{return_token_type_ids=!0}class Tn extends xt{return_token_type_ids=!0}class bn extends xt{return_token_type_ids=!0}class mn extends xt{return_token_type_ids=!0}class Sn extends xt{return_token_type_ids=!0}class An extends xt{return_token_type_ids=!0}class In extends xt{return_token_type_ids=!0}class Mn extends xt{return_token_type_ids=!0}class Et extends xt{}class Ht extends xt{}class un extends xt{return_token_type_ids=!0;constructor(q,ye){super(q,ye),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class zr extends xt{return_token_type_ids=!0}class os extends xt{}class ao extends xt{}class vr extends xt{}class Qr extends xt{constructor(q,ye){super(q,ye),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Le=>this.languageRegex.test(Le)),this.lang_to_token=Le=>Le}_build_translation_inputs(q,ye,Le){return cs(this,q,ye,Le)}}class br extends Qr{}class as extends xt{}class kr extends xt{constructor(q,ye){const Le=".,!?…。,、।۔،",De=q.pre_tokenizer?.pretokenizers[0]?.pattern;De&&De.Regex===` ?[^(\\s|[${Le}])]+`&&(De.Regex=` ?[^\\s${Le}]+`),super(q,ye)}}const mi="▁";class ls extends xt{padding_side="left";constructor(q,ye){super(q,ye),this.legacy=ye.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new ve({replacement:mi,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(q){if(q===null)return null;if(this.legacy||q.length===0)return super._encode_text(q);let ye=super._encode_text(mi+q.replaceAll(mi," "));return ye.length>1&&ye[0]===mi&&this.special_tokens.includes(ye[1])&&(ye=ye.slice(1)),ye}}class us extends xt{}class lo extends xt{}class Ws extends xt{}class Ar extends xt{}class Gi extends xt{}class li extends xt{}class $o extends xt{}class qi extends xt{}class Si extends xt{}function cs(nt,q,ye,Le){if(!("language_codes"in nt)||!Array.isArray(nt.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in nt)||!(nt.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in nt)||typeof nt.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const De=Le.src_lang,ct=Le.tgt_lang;if(!nt.language_codes.includes(ct))throw new Error(`Target language code "${ct}" is not valid. Must be one of: {${nt.language_codes.join(", ")}}`);if(De!==void 0){if(!nt.language_codes.includes(De))throw new Error(`Source language code "${De}" is not valid. Must be one of: {${nt.language_codes.join(", ")}}`);for(const Pt of nt.post_processor.config.single)if("SpecialToken"in Pt&&nt.languageRegex.test(Pt.SpecialToken.id)){Pt.SpecialToken.id=nt.lang_to_token(De);break}}return Le.forced_bos_token_id=nt.model.convert_tokens_to_ids([nt.lang_to_token(ct)])[0],nt._call(q,ye)}class Hi extends xt{constructor(q,ye){super(q,ye),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Le=>this.languageRegex.test(Le)),this.lang_to_token=Le=>Le}_build_translation_inputs(q,ye,Le){return cs(this,q,ye,Le)}}class ki extends xt{constructor(q,ye){super(q,ye),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Le=>this.languageRegex.test(Le)).map(Le=>Le.slice(2,-2)),this.lang_to_token=Le=>`__${Le}__`}_build_translation_inputs(q,ye,Le){return cs(this,q,ye,Le)}}class Gs extends xt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(q,{return_timestamps:ye=!1,return_language:Le=!1,time_precision:De=null,force_full_sequences:ct=!0}={}){if(De===null)throw Error("Must specify time_precision");let Pt=null;const tn=ye==="word";function zt(){return{language:Pt,timestamp:[null,null],text:""}}const nn=[];let Qt=zt(),nr=0;const Cn=this.timestamp_begin;let qn=[],kn=[],Qn=!1,Ei=null;const Mr=new Set(this.all_special_ids);for(const er of q){const Dr=er.tokens,ui=tn?er.token_timestamps:null;let xn=null,Ci=Cn;if("stride"in er){const[ar,sn,tr]=er.stride;if(nr-=sn,Ei=ar-tr,sn&&(Ci=sn/De+Cn),tr)for(let pr=Dr.length-1;pr>=0;--pr){const Ir=Number(Dr[pr]);if(Ir>=Cn){if(xn!==null&&(Ir-Cn)*De=Cn){const tr=(sn-Cn)*De+nr,pr=(0,l.round)(tr,2);if(xn!==null&&sn>=xn)Qn=!0;else if(Qn||qn.length>0&&sn0?(qn.push($r),tn&&kn.push(or)):qn.every(ar=>ar.length===0)&&(Qt=zt(),qn=[],$r=[],kn=[],or=[])}if(qn.length>0){if(ct&&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[er,Dr]=this.findLongestCommonSequence(qn,kn),ui=this.decode(er);Qt.text=ui,tn&&(Qt.words=this.collateWordTimestamps(er,Dr,Pt)),nn.push(Qt)}let yt=Object.create(null);const Yr=nn.map(er=>er.text).join("");if(ye||Le){for(let er=0;er0;let tn=Pt?[]:null,zt=Pt?ye[0]:null;for(let nn=1;nnpr===or[Ir]&&zt[Dr+Ir]<=ye[nn][Ci+Ir]).length:ar=xn.filter((pr,Ir)=>pr===or[Ir]).length;const sn=er/1e4,tr=ar/er+sn;ar>1&&tr>nr&&(nr=tr,Cn=[Dr,ui,Ci,$r])}const[kn,Qn,Ei,Mr]=Cn,yt=Math.floor((Qn+kn)/2),Yr=Math.floor((Mr+Ei)/2);ct.push(...Le.slice(0,yt)),Le=Qt.slice(Yr),De=Le.length,Pt&&(tn.push(...zt.slice(0,yt)),zt=ye[nn].slice(Yr))}return ct.push(...Le),Pt?(tn.push(...zt),[ct,tn]):[ct,[]]}collateWordTimestamps(q,ye,Le){const[De,ct,Pt]=this.combineTokensIntoWords(q,Le),tn=[];for(let zt=0;zt=De){const tn=((Pt-De)*Le).toFixed(2);ct.push(`<|${tn}|>`),ct.push([])}else ct[ct.length-1].push(Pt);return ct=ct.map(Pt=>typeof Pt=="string"?Pt:super.decode(Pt,ye)),ct.join("")}splitTokensOnUnicode(q){const ye=this.decode(q,{decode_with_timestamps:!0}),Le="�",De=[],ct=[],Pt=[];let tn=[],zt=[],nn=0;for(let Qt=0;Qt=this.model.tokens_to_ids.get("<|endoftext|>"),kn=Qt.startsWith(" "),Qn=Qt.trim(),Ei=zt.test(Qn);if(qn||kn||Ei||ct.length===0)ct.push(Qt),Pt.push(nr),tn.push(Cn);else{const Mr=ct.length-1;ct[Mr]+=Qt,Pt[Mr].push(...nr),tn[Mr].push(...Cn)}}return[ct,Pt,tn]}mergePunctuations(q,ye,Le,De,ct){const Pt=structuredClone(q),tn=structuredClone(ye),zt=structuredClone(Le);let nn=Pt.length-2,Qt=Pt.length-1;for(;nn>=0;)Pt[nn].startsWith(" ")&&De.includes(Pt[nn].trim())?(Pt[Qt]=Pt[nn]+Pt[Qt],tn[Qt]=(0,o.mergeArrays)(tn[nn],tn[Qt]),zt[Qt]=(0,o.mergeArrays)(zt[nn],zt[Qt]),Pt[nn]="",tn[nn]=[],zt[nn]=[]):Qt=nn,--nn;for(nn=0,Qt=1;Qtnr),tn.filter(nr=>nr.length>0),zt.filter(nr=>nr.length>0)]}get_decoder_prompt_ids({language:q=null,task:ye=null,no_timestamps:Le=!0}={}){const De=[];if(q){const ct=(0,w.whisper_language_to_code)(q),Pt=this.model.tokens_to_ids.get(`<|${ct}|>`);if(Pt===void 0)throw new Error(`Unable to find language "${ct}" in model vocabulary. Please report this issue at ${_.GITHUB_ISSUE_URL}.`);De.push(Pt)}else De.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 ct=this.model.tokens_to_ids.get(`<|${ye}|>`);if(ct===void 0)throw new Error(`Unable to find task "${ye}" in model vocabulary. Please report this issue at ${_.GITHUB_ISSUE_URL}.`);De.push(ct)}else De.push(null);if(Le){const ct=this.model.tokens_to_ids.get("<|notimestamps|>");if(ct===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${_.GITHUB_ISSUE_URL}.`);De.push(ct)}return De.map((ct,Pt)=>[Pt+1,ct]).filter(ct=>ct[1]!==null)}}class vs extends xt{}class En extends xt{}class Xn extends xt{}class uo extends xt{constructor(q,ye){super(q,ye),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Le=>this.languageRegex.test(Le)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(q){if(q===null)return null;const[ye,...Le]=q.trim().split(this.languageRegex);if(Le.length===0)return super._encode_text(ye);if(Le.length===2){const[De,ct]=Le;return this.supported_language_codes.includes(De)||console.warn(`Unsupported language code "${De}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([De],super._encode_text(ct))}}}class co extends xt{}class qs extends xt{}class mr extends xt{}class ws extends xt{}class ds extends xt{}class fs extends xt{constructor(q,ye){super(q,ye),this.decoder=new kt({})}}class xr extends xt{}class wi{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:os,DistilBertTokenizer:Et,CamembertTokenizer:Ht,DebertaTokenizer:mn,DebertaV2Tokenizer:Sn,BertTokenizer:hn,HerbertTokenizer:An,ConvBertTokenizer:In,RoFormerTokenizer:Mn,XLMTokenizer:un,ElectraTokenizer:zr,MobileBertTokenizer:Tn,SqueezeBertTokenizer:bn,AlbertTokenizer:fn,GPT2Tokenizer:ao,BartTokenizer:vr,MBartTokenizer:Qr,MBart50Tokenizer:br,RobertaTokenizer:as,WhisperTokenizer:Gs,CodeGenTokenizer:vs,CLIPTokenizer:En,SiglipTokenizer:Xn,MarianTokenizer:uo,BloomTokenizer:kr,NllbTokenizer:Hi,M2M100Tokenizer:ki,LlamaTokenizer:ls,CodeLlamaTokenizer:us,XLMRobertaTokenizer:lo,MPNetTokenizer:Ws,FalconTokenizer:Ar,GPTNeoXTokenizer:Gi,EsmTokenizer:li,Wav2Vec2CTCTokenizer:co,BlenderbotTokenizer:qs,BlenderbotSmallTokenizer:mr,SpeechT5Tokenizer:ws,NougatTokenizer:ds,VitsTokenizer:fs,Qwen2Tokenizer:$o,GemmaTokenizer:qi,Grok1Tokenizer:Si,CohereTokenizer:xr,PreTrainedTokenizer:xt};static async from_pretrained(q,{progress_callback:ye=null,config:Le=null,cache_dir:De=null,local_files_only:ct=!1,revision:Pt="main",legacy:tn=null}={}){const[zt,nn]=await M(q,{progress_callback:ye,config:Le,cache_dir:De,local_files_only:ct,revision:Pt,legacy:tn}),Qt=nn.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let nr=this.TOKENIZER_CLASS_MAPPING[Qt];return nr||(console.warn(`Unknown tokenizer class "${Qt}", attempting to construct from base class.`),nr=xt),new nr(zt,nn)}}},"./src/utils/audio.js":(e,t,n)=>{n.r(t),n.d(t,{hamming:()=>w,hanning:()=>h,mel_filter_bank:()=>x,read_audio:()=>d,spectrogram:()=>N,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(V,ce){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 ge=await(await(0,i.getFile)(V)).arrayBuffer(),Re=new AudioContext({sampleRate:ce});typeof ce>"u"&&console.warn(`No sampling rate provided, using default of ${Re.sampleRate}Hz.`);const oe=await Re.decodeAudioData(ge);let Se;if(oe.numberOfChannels===2){const G=Math.sqrt(2),Ce=oe.getChannelData(0),pt=oe.getChannelData(1);Se=new Float32Array(Ce.length);for(let Te=0;Te2595*Math.log10(1+V/700),kaldi:V=>1127*Math.log(1+V/700),slaney:(V,ce=1e3,ge=15,Re=27/Math.log(6.4))=>V>=ce?ge+Math.log(V/ce)*Re:3*V/200};function M(V,ce="htk"){const ge=_[ce];if(!ge)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof V=="number"?ge(V):V.map(Re=>ge(Re))}const T={htk:V=>700*(10**(V/2595)-1),kaldi:V=>700*(Math.exp(V/1127)-1),slaney:(V,ce=1e3,ge=15,Re=Math.log(6.4)/27)=>V>=ge?ce*Math.exp(Re*(V-ge)):200*V/3};function F(V,ce="htk"){const ge=T[ce];if(!ge)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof V=="number"?ge(V):V.map(Re=>ge(Re))}function C(V,ce){const ge=Float64Array.from({length:ce.length-1},(G,Ce)=>ce[Ce+1]-ce[Ce]),Re=Array.from({length:V.length},()=>new Array(ce.length));for(let G=0;Gnew Array(V.length));for(let G=0;GV+Re*Se)}function x(V,ce,ge,Re,oe,Se=null,G="htk",Ce=!1){if(Se!==null&&Se!=="slaney")throw new Error('norm must be one of null or "slaney"');const pt=M(ge,G),Te=M(Re,G),te=E(pt,Te,ce+2);let fe=F(te,G),Pe;if(Ce){const xe=oe/(V*2);Pe=M(Float64Array.from({length:V},(ht,Qe)=>Qe*xe),G),fe=te}else Pe=E(0,Math.floor(oe/2),V);const ne=C(Pe,fe);if(Se!==null&&Se==="slaney")for(let xe=0;xeoe)throw Error(`frame_length (${ge}) may not be larger than fft_length (${oe})`);if(Ve!==ge)throw new Error(`Length of the window (${Ve}) must equal frame_length (${ge})`);if(Re<=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 se=Math.floor((oe-1)/2)+1;V=S(V,se,se)}let ke=Math.floor(1+Math.floor((V.length-ge)/Re));Ze!==null&&keke?Mt&&(bt=ut):bt=dt=ut);const z=new o.FFT(oe),Fe=new Float64Array(oe),Oe=new Float64Array(z.outputBufferSize),he=new Float32Array(lt*bt);for(let se=0;se=1;--pe)Fe[pe]-=Te*Fe[pe-1];Fe[0]*=1-Te}for(let pe=0;peMath.pow(Ce,.85));break;default:throw new Error(`Unknown window type ${ce}.`)}if(ge&&(G=G.subarray(0,V)),Re===null)return G;if(V>Re)throw new Error(`Length of the window (${V}) may not be larger than frame_length (${Re})`);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:()=>M,dispatchCallback:()=>i,escapeRegExp:()=>a,isIntegralNumber:()=>d,isTypedArray:()=>l,mergeArrays:()=>w,pick:()=>T,pop:()=>h,product:()=>_,reverseDictionary:()=>o});function i(F,C){F&&F(C)}function o(F){return Object.fromEntries(Object.entries(F).map(([C,E])=>[E,C]))}function a(F){return F.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function l(F){return F?.prototype?.__proto__?.constructor?.name==="TypedArray"}function d(F){return Number.isInteger(F)||typeof F=="bigint"}function c(F){const C=[];let E=F;for(;Array.isArray(E);)C.push(E.length),E=E[0];return C}function h(F,C,E=void 0){const x=F[C];if(x!==void 0)return delete F[C],x;if(E===void 0)throw Error(`Key ${C} does not exist in object.`);return E}function w(...F){return Array.prototype.concat.apply([],F)}function _(...F){return F.reduce((C,E)=>C.flatMap(x=>E.map(S=>[x,S])))}function M(F,C){return Math.abs((F+C)%(2*C)-C)}function T(F,C){return Object.assign({},...C.map(E=>{if(F[E]!==void 0)return{[E]:F[E]}}))}},"./src/utils/data-structures.js":(e,t,n)=>{n.r(t),n.d(t,{CharTrie:()=>o,PriorityQueue:()=>i,TokenLattice:()=>l});class i{constructor(h=(_,M)=>_>M,w=1/0){this._heap=[],this._comparator=h,this._maxSize=w}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...h){return this.extend(h)}extend(h){for(const w of h)if(this.size0&&this._swap(0,w),this._heap.pop(),this._siftDown(),h}replace(h){const w=this.peek();return this._heap[0]=h,this._siftDown(),w}_parent(h){return(h+1>>>1)-1}_left(h){return(h<<1)+1}_right(h){return h+1<<1}_greater(h,w){return this._comparator(this._heap[h],this._heap[w])}_swap(h,w){const _=this._heap[h];this._heap[h]=this._heap[w],this._heap[w]=_}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(h){for(;h>0&&this._greater(h,this._parent(h));)this._swap(h,this._parent(h)),h=this._parent(h)}_siftDown(){let h=0;for(;this._left(h)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const M=new d(this.bosTokenId,0,0,0,0),T=new d(this.eosTokenId,1,this.len,0,0);this.nodes.push(M.clone()),this.nodes.push(T.clone()),this.beginNodes[this.len].push(T),this.endNodes[0].push(M)}insert(h,w,_,M){const T=this.nodes.length,F=new d(M,T,h,w,_);this.beginNodes[h].push(F),this.endNodes[h+w].push(F),this.nodes.push(F)}viterbi(){const h=this.len;let w=0;for(;w<=h;){if(this.beginNodes[w].length==0)return[];for(let C of this.beginNodes[w]){C.prev=null;let E=0,x=null;for(let S of this.endNodes[w]){const P=S.backtraceScore+C.score;(x===null||P>E)&&(x=S.clone(),E=P)}if(x!==null)C.prev=x,C.backtraceScore=E;else return[]}++w}const _=[],T=this.beginNodes[h][0].prev;if(T===null)return[];let F=T.clone();for(;F.prev!==null;)_.push(F.clone()),F=F.clone().prev.clone();return _.reverse(),_}piece(h){return this.sentence.slice(h.pos,h.pos+h.length)}tokens(){return this.viterbi().map(w=>this.piece(w))}tokenIds(){return this.viterbi().map(w=>w.tokenId)}}class d{constructor(h,w,_,M,T){this.tokenId=h,this.nodeId=w,this.pos=_,this.length=M,this.score=T,this.prev=null,this.backtraceScore=0}clone(){const h=new d(this.tokenId,this.nodeId,this.pos,this.length,this.score);return h.prev=this.prev,h.backtraceScore=this.backtraceScore,h}}},"./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 h;return async function(){if(h===void 0)if(!i.apis.IS_WEBGPU_AVAILABLE)h=!1;else try{h=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{h=!1}return h}}(),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:()=>w,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(j){if(this.filePath=j,this.headers=new Headers,this.exists=i.existsSync(j),this.exists){this.status=200,this.statusText="OK";let L=i.statSync(j);this.headers.set("content-length",L.size.toString()),this.updateContentType();let N=this;this.body=new ReadableStream({start(W){N.arrayBuffer().then(V=>{W.enqueue(new Uint8Array(V)),W.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const j=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",d[j]??"application/octet-stream")}clone(){let j=new c(this.filePath);return j.exists=this.exists,j.status=this.status,j.statusText=this.statusText,j.headers=new Headers(this.headers),j}async arrayBuffer(){return(await i.promises.readFile(this.filePath)).buffer}async blob(){const j=await i.promises.readFile(this.filePath);return new Blob([j],{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 h(P,j=null,L=null){let N;try{N=new URL(P)}catch{return!1}return!(j&&!j.includes(N.protocol)||L&&!L.includes(N.hostname))}async function w(P){if(a.env.useFS&&!h(P,["http:","https:","blob:"]))return new c(P);if(typeof process<"u"&&process?.release?.name==="node"){const j=!!hy?.TESTING_REMOTELY,L=a.env.version,N=new Headers;if(N.set("User-Agent",`transformers.js/${L}; is_ci/${j};`),h(P,["http:","https:"],["huggingface.co","hf.co"])){const V=hy?.HF_TOKEN??hy?.HF_ACCESS_TOKEN;V&&N.set("Authorization",`Bearer ${V}`)}return fetch(P,{headers:N})}else return fetch(P)}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 M(P,j,L){if(!L)return null;const N=_[P]??`Error (${P}) occurred while trying to load file`;throw Error(`${N}: "${j}".`)}class T{constructor(j){this.path=j}async match(j){let L=o.join(this.path,j),N=new c(L);if(N.exists)return N}async put(j,L){const N=Buffer.from(await L.arrayBuffer());let W=o.join(this.path,j);try{await i.promises.mkdir(o.dirname(W),{recursive:!0}),await i.promises.writeFile(W,N)}catch(V){console.warn("An error occurred while writing the file to cache:",V)}}}async function F(P,...j){for(let L of j)try{let N=await P.match(L);if(N)return N}catch{continue}}async function C(P,j,L=!0,N={}){if(!a.env.allowLocalModels){if(N.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)(N.progress_callback,{status:"initiate",name:P,file:j});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(Pe){console.warn("An error occurred while opening the browser cache:",Pe)}}if(!W&&a.env.useFSCache&&(W=new T(N.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 V=N.revision??"main";let ce=S(P,j),ge=S(a.env.localModelPath,ce),Re=S(a.env.remoteHost,a.env.remotePathTemplate.replaceAll("{model}",P).replaceAll("{revision}",encodeURIComponent(V)),j),oe=V==="main"?ce:S(P,V,j),Se,G=W instanceof T?oe:Re,Ce=!1,pt;W&&(pt=await F(W,ge,G));const Te=pt!==void 0;if(pt===void 0){if(a.env.allowLocalModels)if(h(ce,["http:","https:"])){if(N.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ce}.`);if(!a.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ce}.`)}else try{pt=await w(ge),Se=ge}catch(ne){console.warn(`Unable to load from local path "${ge}": "${ne}"`)}if(pt===void 0||pt.status===404){if(N.local_files_only||!a.env.allowRemoteModels){if(L)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ge}".`);return null}if(pt=await w(Re),pt.status!==200)return M(pt.status,Re,L);Se=G}Ce=W&&typeof Response<"u"&&pt instanceof Response&&pt.status===200}(0,l.dispatchCallback)(N.progress_callback,{status:"download",name:P,file:j});const te={status:"progress",name:P,file:j};let fe;return N.progress_callback?Te&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(fe=new Uint8Array(await pt.arrayBuffer()),(0,l.dispatchCallback)(N.progress_callback,{...te,progress:100,loaded:fe.length,total:fe.length})):fe=await x(pt,Pe=>{(0,l.dispatchCallback)(N.progress_callback,{...te,...Pe})}):fe=new Uint8Array(await pt.arrayBuffer()),Ce&&Se&&await W.match(Se)===void 0&&await W.put(Se,new Response(fe,{headers:pt.headers})).catch(Pe=>{console.warn(`Unable to add response to browser cache: ${Pe}.`)}),(0,l.dispatchCallback)(N.progress_callback,{status:"done",name:P,file:j}),fe}async function E(P,j,L=!0,N={}){let W=await C(P,j,L,N);if(W===null)return{};let ce=new TextDecoder("utf-8").decode(W);return JSON.parse(ce)}async function x(P,j){const L=P.headers.get("Content-Length");L===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let N=parseInt(L??"0"),W=new Uint8Array(N),V=0;const ce=P.body.getReader();async function ge(){const{done:Re,value:oe}=await ce.read();if(Re)return;let Se=V+oe.length;if(Se>N){N=Se;let Ce=new Uint8Array(N);Ce.set(W),W=Ce}W.set(oe,V),V=Se;const G=V/N*100;return j({progress:G,loaded:V,total:N}),ge()}return await ge(),W}function S(...P){return P=P.map((j,L)=>(L&&(j=j.replace(new RegExp("^/"),"")),L!==P.length-1&&(j=j.replace(new RegExp("/$"),"")),j)),P.join("/")}},"./src/utils/image.js":(e,t,n)=>{n.r(t),n.d(t,{RawImage:()=>F});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 h,w,_;if(d)h=(C,E)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(C,E)},_=self.createImageBitmap,w=self.ImageData;else if(l)_=async C=>{const x=(await C.metadata()).channels,{data:S,info:P}=await C.rotate().raw().toBuffer({resolveWithObject:!0}),j=new F(new Uint8ClampedArray(S),P.width,P.height,P.channels);return x!==void 0&&x!==P.channels&&j.convert(x),j};else throw new Error("Unable to load image processing library.");const M={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},T=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class F{constructor(E,x,S,P){this.data=E,this.width=x,this.height=S,this.channels=P}get size(){return[this.width,this.height]}static async read(E){if(E instanceof F)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 S=E.getContext("2d").getImageData(0,0,E.width,E.height).data;return new F(S,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 S=await x.blob();return this.fromBlob(S)}static async fromBlob(E){if(d){const x=await _(E),S=h(x.width,x.height).getContext("2d");return S.drawImage(x,0,0),new this(S.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 F(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,S=0;x=0?W=S:ce=-S,P>=0?V=P:ge=-P,N.drawImage(L,W,V,E,x,ce,ge,E,x),new F(N.getImageData(0,0,E,x).data,E,x,4).convert(j)}else{let j=this.toSharp();if(S>=0&&P>=0)j=j.extract({left:Math.floor(S),top:Math.floor(P),width:E,height:x});else if(S<=0&&P<=0){const L=Math.floor(-P),N=Math.floor(-S);j=j.extend({top:L,left:N,right:E-this.width-N,bottom:x-this.height-L})}else{let L=[0,0],N=0;P<0?(L[0]=Math.floor(-P),L[1]=x-this.height-L[0]):N=Math.floor(P);let W=[0,0],V=0;S<0?(W[0]=Math.floor(-S),W[1]=E-this.width-W[0]):V=Math.floor(S),j=j.extend({top:L[0],bottom:L[1],left:W[0],right:W[1]}).extract({left:V,top:N,width:E,height:x})}return await _(j)}}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=h(E.width,E.height),S=new w(E.data,E.width,E.height);return x.getContext("2d").putImageData(S,0,0),x}_update(E,x,S,P=null){return this.data=E,this.width=x,this.height=S,P!==null&&(this.channels=P),this}clone(){return new F(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(),S=T.get(x)??"image/png",P=await this.toBlob(S),j=URL.createObjectURL(P),L=document.createElement("a");L.href=j,L.download=E,L.click(),L.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:()=>S,cos_sim:()=>c,dot:()=>d,dynamic_time_warping:()=>P,interpolate_data:()=>i,log_softmax:()=>l,magnitude:()=>h,max:()=>_,medianFilter:()=>E,min:()=>w,permute_data:()=>o,round:()=>x,softmax:()=>a});function i(j,[L,N,W],[V,ce],ge="bilinear",Re=!1){const oe=ce/W,Se=V/N,G=new j.constructor(V*ce*L),Ce=N*W,pt=V*ce;for(let Te=0;Te=0;--Re)V[Re]=oe,W[Re]=L[N[Re]],oe*=W[Re];const ce=N.map((Re,oe)=>V[N.indexOf(oe)]),ge=new j.constructor(j.length);for(let Re=0;Re=0;--Se)oe+=G%L[Se]*ce[Se],G=Math.floor(G/L[Se]);ge[oe]=j[Re]}return[ge,W]}function a(j){const L=_(j)[0],N=j.map(ce=>Math.exp(ce-L)),W=N.reduce((ce,ge)=>ce+ge,0);return N.map(ce=>ce/W)}function l(j){return a(j).map(W=>Math.log(W))}function d(j,L){let N=0;for(let W=0;WL+N*N,0))}function w(j){if(j.length===0)throw Error("Array must not be empty");let L=j[0],N=0;for(let W=1;WL&&(L=j[W],N=W);return[Number(L),N]}function M(j){return j>0&&(j&j-1)===0}class T{constructor(L){if(this.size=L|0,this.size<=1||!M(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=L<<1,this.table=new Float64Array(this.size*2);for(let W=0;WW;W<<=1)++N;this._width=N%2===0?N-1:N,this._bitrev=new Int32Array(1<>>V&3)<>>1);for(let V=0;V>>1]=L[V];return W}toComplexArray(L,N){const W=N||this.createComplexArray();for(let V=0;V>>1],W[V+1]=0;return W}transform(L,N){if(L===N)throw new Error("Input and output buffers must be different");this._transform4(L,N,1)}realTransform(L,N){if(L===N)throw new Error("Input and output buffers must be different");this._realTransform4(L,N,1)}inverseTransform(L,N){if(L===N)throw new Error("Input and output buffers must be different");this._transform4(L,N,-1);for(let W=0;W>=2;ge>=2;ge>>=2){Re=V/ge<<1;const pt=Re>>>2;for(oe=0;oe>>1,ge>>>1)}else for(oe=0,Se=0;oe>>1,ge>>>1,W)}const Ce=this.table;for(ge>>=2;ge>=2;ge>>=2){Re=V/ge<<1;const Te=Re>>>1,te=Te>>>1,fe=te>>>1;for(oe=0;oe>>1;for(let Te=2;Te>1;++G){const Ce=(G+1-L)**2/2,pt=Math.sqrt(oe**2+Se**2)**Ce,Te=Ce*Math.atan2(Se,oe),te=2*G;ce[te]=pt*Math.cos(Te),ce[te+1]=pt*Math.sin(Te),ge[te]=ce[te],ge[te+1]=-ce[te+1]}this._slicedChirpBuffer=ce.subarray(N,W),this._f=new T(V>>1),this._f.transform(this._chirpBuffer,ge)}_transform(L,N,W){const V=this._buffer1,ce=this._buffer2,ge=this._outBuffer1,Re=this._outBuffer2,oe=this._chirpBuffer,Se=this._slicedChirpBuffer,G=this._a;if(W)for(let Ce=0;Ce>1,te=N[Te];V[Ce]=te*Se[Ce],V[pt]=te*Se[pt]}else for(let Ce=0;Ce=j.length&&(oe=2*(j.length-1)-oe),W[ge++]=j[oe]}W.sort(),N[ce]=W[V]}return N}function x(j,L){const N=Math.pow(10,L);return Math.round(j*N)/N}function S(j){const L=Math.round(j);return Math.abs(j)%1===.5?L%2===0?L:L-1:L}function P(j){const L=j.length,N=j[0].length,W=[L+1,N+1],V=Array.from({length:W[0]},()=>Array(W[1]).fill(1/0));V[0][0]=0;const ce=Array.from({length:W[0]},()=>Array(W[1]).fill(-1));for(let G=1;G0||Re>0;)switch(oe.push(ge-1),Se.push(Re-1),ce[ge][Re]){case 0:--ge,--Re;break;case 1:--ge;break;case 2:--Re;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ge}, ${Re}]. 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:()=>j,full:()=>ge,full_like:()=>Re,interpolate:()=>w,interpolate_4d:()=>_,layer_norm:()=>E,matmul:()=>M,mean:()=>W,mean_pooling:()=>C,ones:()=>oe,ones_like:()=>Se,permute:()=>h,quantize_embeddings:()=>pt,rfft:()=>T,stack:()=>L,std_mean:()=>N,topk:()=>F,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{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}ort_tensor;constructor(...te){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,Pe)=>{if(typeof Pe=="string"){let ne=Number(Pe);if(Number.isInteger(ne))return fe._getitem(ne)}return fe[Pe]},set:(fe,Pe,ne)=>fe[Pe]=ne})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[te,...fe]=this.dims;if(fe.length>0){const Pe=fe.reduce((ne,xe)=>ne*xe);for(let ne=0;ne0){const ne=Pe.reduce((xe,ht)=>xe*ht);return this._subarray(te,ne,Pe)}else return new d(this.type,[this.data[te]],Pe)}indexOf(te){const fe=this.data;for(let Pe=0;PeVe)throw new Error(`Invalid slice: ${Mt}`);const ke=[Math.max(Ft,0),Math.min(Ve,this.dims[ut])];Pe.push(ke),fe.push(ke[1]-ke[0])}else throw new Error(`Invalid slice: ${Mt}`)}const ne=Pe.map(([ut,Mt])=>Mt-ut),xe=ne.reduce((ut,Mt)=>ut*Mt),ht=this.data,Qe=new ht.constructor(xe),Ze=this.stride();for(let ut=0;ut=0;--Ft){const ke=ne[Ft];Mt+=(Ve%ke+Pe[Ft][0])*Ze[Ft],Ve=Math.floor(Ve/ke)}Qe[ut]=ht[Mt]}return new d(this.type,Qe,fe)}permute(...te){return h(this,te)}transpose(...te){return this.permute(...te)}sum(te=null,fe=!1){return this.norm(1,te,fe)}norm(te="fro",fe=null,Pe=!1){if(te==="fro")te=2;else if(typeof te=="string")throw Error(`Unsupported norm: ${te}`);const ne=this.data;if(fe===null){let Qe=ne.reduce((Ze,ut)=>Ze+ut**te,0)**(1/te);return new d(this.type,[Qe],[])}fe=P(fe,this.dims.length);const xe=this.dims.slice();xe[fe]=1;const ht=new ne.constructor(ne.length/this.dims[fe]);for(let Qe=0;Qe=0;--ut){const Ve=this.dims[ut];if(ut!==fe){const ke=Mt%Ve;Ze+=ke*Ft,Ft*=xe[ut]}Mt=Math.floor(Mt/Ve)}ht[Ze]+=ne[Qe]**te}if(te!==1)for(let Qe=0;Qe=0;--Ze){const Ft=this.dims[Ze];if(Ze!==fe){const Ve=ut%Ft;Qe+=Ve*Mt,Mt*=this.dims[Ze]}ut=Math.floor(ut/Ft)}ne[ht]/=xe[Qe]}return this}normalize(te=2,fe=1){return this.clone().normalize_(te,fe)}stride(){return V(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,S(this.dims,te))}unsqueeze_(te=null){return this.dims=S(this.dims,te),this}flatten_(te=0,fe=-1){fe=(fe+this.dims.length)%this.dims.length;let Pe=this.dims.slice(0,te),ne=this.dims.slice(te,fe+1),xe=this.dims.slice(fe+1);return this.dims=[...Pe,ne.reduce((ht,Qe)=>ht*Qe,1),...xe],this}flatten(te=0,fe=-1){return this.clone().flatten_(te,fe)}view(...te){let fe=-1;for(let ne=0;neQe!==fe?xe*ht:xe,1);te[fe]=Pe.length/ne}return new d(this.type,Pe,te)}neg_(){const te=this.data;for(let fe=0;fexe*ht);if(fe!==Pe)throw Error(`cannot reshape array of size ${fe} into shape (${te})`);let ne=Te;for(let xe=te.length-1;xe>=0;xe--)ne=ne.reduce((ht,Qe)=>{let Ze=ht[ht.length-1];return Ze.lengthfe!==1):typeof te=="number"?Te[te]===1&&Te.splice(te,1):Array.isArray(te)&&(Te=Te.filter((fe,Pe)=>fe!==1||!te.includes(Pe))),Te}function S(Te,te){return te=P(te,Te.length+1),Te=Te.slice(),Te.splice(te,0,1),Te}function P(Te,te,fe=null,Pe=!0){if(Pe&&(Te<-te||Te>=te))throw new Error(`IndexError: index ${Te} is out of bounds for dimension${fe===null?"":" "+fe} with size ${te}`);return Te<0&&(Te=(Te%te+te)%te),Te}function j(Te,te=0){te=P(te,Te[0].dims.length);const fe=Te[0].dims.slice();fe[te]=Te.reduce((ht,Qe)=>ht+Qe.dims[te],0);const Pe=fe.reduce((ht,Qe)=>ht*Qe,1),ne=new Te[0].data.constructor(Pe),xe=Te[0].type;if(te===0){let ht=0;for(const Qe of Te){const Ze=Qe.data;ne.set(Ze,ht),ht+=Ze.length}}else{let ht=0;for(let Qe=0;Qe=0;--Ve){const dt=ut[Ve];let bt=ke%dt;Ve===te&&(bt+=ht),Ft+=bt*lt,lt*=fe[Ve],ke=Math.floor(ke/dt)}ne[Ft]=Ze[Mt]}ht+=ut[te]}}return new d(xe,ne,fe)}function L(Te,te=0){return j(Te.map(fe=>fe.unsqueeze(te)),te)}function N(Te,te=null,fe=1,Pe=!1){const ne=Te.data,xe=Te.dims;if(te===null){const Ve=ne.reduce((bt,z)=>bt+z,0)/ne.length,ke=Math.sqrt(ne.reduce((bt,z)=>bt+(z-Ve)**2,0)/(ne.length-fe)),lt=new d(Te.type,[Ve],[]);return[new d(Te.type,[ke],[]),lt]}te=P(te,xe.length);const ht=W(Te,te,Pe),Qe=ht.data,Ze=xe.slice();Ze[te]=1;const ut=new ne.constructor(ne.length/xe[te]);for(let Ft=0;Ft=0;--ke){const bt=xe[ke];if(ke!==te){const z=lt%bt;Ve+=z*dt,dt*=Ze[ke]}lt=Math.floor(lt/bt)}ut[Ve]+=(ne[Ft]-Qe[Ve])**2}for(let Ft=0;FtZe+ut,0);return new d(Te.type,[Qe/Pe.length],[])}const ne=Te.dims;te=P(te,ne.length);const xe=ne.slice();xe[te]=1;const ht=new Pe.constructor(Pe.length/ne[te]);for(let Qe=0;Qe=0;--ut){const Ve=ne[ut];if(ut!==te){const ke=Mt%Ve;Ze+=ke*Ft,Ft*=xe[ut]}Mt=Math.floor(Mt/Ve)}ht[Ze]+=Pe[Qe]}if(ne[te]!==1)for(let Qe=0;Qe=0;--fe)te[fe]=Pe,Pe*=Te[fe];return te}function ce(Te,te,fe,Pe){const ne=Te.reduce((xe,ht)=>xe*ht,1);return new d(fe,new Pe(ne).fill(te),Te)}function ge(Te,te){let fe,Pe;if(typeof te=="number")fe="float32",Pe=Float32Array;else if(typeof te=="bigint")fe="int64",Pe=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof te}`);return ce(Te,te,fe,Pe)}function Re(Te,te){return ge(Te.dims,te)}function oe(Te){return ce(Te,1n,"int64",BigInt64Array)}function Se(Te){return oe(Te.dims)}function G(Te){return ce(Te,0n,"int64",BigInt64Array)}function Ce(Te){return G(Te.dims)}function pt(Te,te){if(Te.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(Te.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",Pe=fe?"int8":"uint8",ne=fe?Int8Array:Uint8Array,xe=Te.data,ht=new ne(xe.length/8);for(let Qe=0;Qe0?1:0,ut=Math.floor(Qe/8),Mt=Qe%8;ht[ut]|=Ze<<7-Mt,fe&&Mt===0&&(ht[ut]-=128)}return new d(Pe,ht,[Te.dims[0],Te.dims[1]/8])}}},p2={};function Ur(e){var t=p2[e];if(t!==void 0)return t.exports;var n=p2[e]={exports:{}};return ok[e](n,n.exports,Ur),n.exports}Ur.m=ok;(()=>{var e=Object.getPrototypeOf?n=>Object.getPrototypeOf(n):n=>n.__proto__,t;Ur.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);Ur.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,Ur.d(o,a),o}})();Ur.d=(e,t)=>{for(var n in t)Ur.o(t,n)&&!Ur.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})};Ur.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);Ur.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(/\/[^\/]+$/,"/"),Ur.p=e})();Ur.b=new URL("./",import.meta.url);var D={};/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/Ur.r(D);Ur.d(D,{ASTFeatureExtractor:()=>Dn.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:()=>Vn.AlbertTokenizer,AudioClassificationPipeline:()=>jr.AudioClassificationPipeline,AutoConfig:()=>py.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:()=>Dn.AutoProcessor,AutoTokenizer:()=>Vn.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>jr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>ee.BartForConditionalGeneration,BartForSequenceClassification:()=>ee.BartForSequenceClassification,BartModel:()=>ee.BartModel,BartPretrainedModel:()=>ee.BartPretrainedModel,BartTokenizer:()=>Vn.BartTokenizer,BaseModelOutput:()=>ee.BaseModelOutput,BaseStreamer:()=>my.BaseStreamer,BeitFeatureExtractor:()=>Dn.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:()=>Vn.BertTokenizer,BitImageProcessor:()=>Dn.BitImageProcessor,BlenderbotForConditionalGeneration:()=>ee.BlenderbotForConditionalGeneration,BlenderbotModel:()=>ee.BlenderbotModel,BlenderbotPreTrainedModel:()=>ee.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>ee.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>ee.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>ee.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>Vn.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>Vn.BlenderbotTokenizer,BloomForCausalLM:()=>ee.BloomForCausalLM,BloomModel:()=>ee.BloomModel,BloomPreTrainedModel:()=>ee.BloomPreTrainedModel,BloomTokenizer:()=>Vn.BloomTokenizer,CLIPFeatureExtractor:()=>Dn.CLIPFeatureExtractor,CLIPImageProcessor:()=>Dn.CLIPImageProcessor,CLIPModel:()=>ee.CLIPModel,CLIPPreTrainedModel:()=>ee.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>ee.CLIPSegForImageSegmentation,CLIPSegModel:()=>ee.CLIPSegModel,CLIPSegPreTrainedModel:()=>ee.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>ee.CLIPTextModelWithProjection,CLIPTokenizer:()=>Vn.CLIPTokenizer,CLIPVisionModelWithProjection:()=>ee.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>ee.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>ee.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>ee.CamembertForSequenceClassification,CamembertForTokenClassification:()=>ee.CamembertForTokenClassification,CamembertModel:()=>ee.CamembertModel,CamembertPreTrainedModel:()=>ee.CamembertPreTrainedModel,CamembertTokenizer:()=>Vn.CamembertTokenizer,CausalLMOutput:()=>ee.CausalLMOutput,CausalLMOutputWithPast:()=>ee.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Dn.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>ee.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>ee.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>ee.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Dn.ClapFeatureExtractor,ClapModel:()=>ee.ClapModel,ClapPreTrainedModel:()=>ee.ClapPreTrainedModel,ClapTextModelWithProjection:()=>ee.ClapTextModelWithProjection,CodeGenForCausalLM:()=>ee.CodeGenForCausalLM,CodeGenModel:()=>ee.CodeGenModel,CodeGenPreTrainedModel:()=>ee.CodeGenPreTrainedModel,CodeGenTokenizer:()=>Vn.CodeGenTokenizer,CodeLlamaTokenizer:()=>Vn.CodeLlamaTokenizer,CohereForCausalLM:()=>ee.CohereForCausalLM,CohereModel:()=>ee.CohereModel,CoherePreTrainedModel:()=>ee.CoherePreTrainedModel,CohereTokenizer:()=>Vn.CohereTokenizer,ConvBertForMaskedLM:()=>ee.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>ee.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>ee.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>ee.ConvBertForTokenClassification,ConvBertModel:()=>ee.ConvBertModel,ConvBertPreTrainedModel:()=>ee.ConvBertPreTrainedModel,ConvBertTokenizer:()=>Vn.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Dn.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>ee.ConvNextForImageClassification,ConvNextImageProcessor:()=>Dn.ConvNextImageProcessor,ConvNextModel:()=>ee.ConvNextModel,ConvNextPreTrainedModel:()=>ee.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>ee.ConvNextV2ForImageClassification,ConvNextV2Model:()=>ee.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>ee.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Dn.DPTFeatureExtractor,DPTForDepthEstimation:()=>ee.DPTForDepthEstimation,DPTImageProcessor:()=>Dn.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:()=>Vn.DebertaTokenizer,DebertaV2ForMaskedLM:()=>ee.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>ee.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>ee.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>ee.DebertaV2ForTokenClassification,DebertaV2Model:()=>ee.DebertaV2Model,DebertaV2PreTrainedModel:()=>ee.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>Vn.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>Dn.DeiTFeatureExtractor,DeiTForImageClassification:()=>ee.DeiTForImageClassification,DeiTModel:()=>ee.DeiTModel,DeiTPreTrainedModel:()=>ee.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>ee.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>ee.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>jr.DepthEstimationPipeline,DetrFeatureExtractor:()=>Dn.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:()=>Vn.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>jr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Dn.DonutFeatureExtractor,DonutSwinModel:()=>ee.DonutSwinModel,DonutSwinPreTrainedModel:()=>ee.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>ee.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Dn.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:()=>Vn.ElectraTokenizer,EosTokenCriteria:()=>nh.EosTokenCriteria,EsmForMaskedLM:()=>ee.EsmForMaskedLM,EsmForSequenceClassification:()=>ee.EsmForSequenceClassification,EsmForTokenClassification:()=>ee.EsmForTokenClassification,EsmModel:()=>ee.EsmModel,EsmPreTrainedModel:()=>ee.EsmPreTrainedModel,EsmTokenizer:()=>Vn.EsmTokenizer,FFT:()=>Ss.FFT,FalconForCausalLM:()=>ee.FalconForCausalLM,FalconModel:()=>ee.FalconModel,FalconPreTrainedModel:()=>ee.FalconPreTrainedModel,FalconTokenizer:()=>Vn.FalconTokenizer,FastViTForImageClassification:()=>ee.FastViTForImageClassification,FastViTModel:()=>ee.FastViTModel,FastViTPreTrainedModel:()=>ee.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>jr.FeatureExtractionPipeline,FeatureExtractor:()=>Dn.FeatureExtractor,FillMaskPipeline:()=>jr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>ee.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>ee.Florence2PreTrainedModel,Florence2Processor:()=>Dn.Florence2Processor,GLPNFeatureExtractor:()=>Dn.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>ee.GLPNForDepthEstimation,GLPNModel:()=>ee.GLPNModel,GLPNPreTrainedModel:()=>ee.GLPNPreTrainedModel,GPT2LMHeadModel:()=>ee.GPT2LMHeadModel,GPT2Model:()=>ee.GPT2Model,GPT2PreTrainedModel:()=>ee.GPT2PreTrainedModel,GPT2Tokenizer:()=>Vn.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:()=>Vn.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>ee.Gemma2ForCausalLM,Gemma2Model:()=>ee.Gemma2Model,Gemma2PreTrainedModel:()=>ee.Gemma2PreTrainedModel,GemmaForCausalLM:()=>ee.GemmaForCausalLM,GemmaModel:()=>ee.GemmaModel,GemmaPreTrainedModel:()=>ee.GemmaPreTrainedModel,GemmaTokenizer:()=>Vn.GemmaTokenizer,Grok1Tokenizer:()=>Vn.Grok1Tokenizer,HerbertTokenizer:()=>Vn.HerbertTokenizer,HubertForCTC:()=>ee.HubertForCTC,HubertForSequenceClassification:()=>ee.HubertForSequenceClassification,HubertModel:()=>ee.HubertModel,HubertPreTrainedModel:()=>ee.HubertPreTrainedModel,ImageClassificationPipeline:()=>jr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>jr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Dn.ImageFeatureExtractor,ImageMattingOutput:()=>ee.ImageMattingOutput,ImageSegmentationPipeline:()=>jr.ImageSegmentationPipeline,ImageToImagePipeline:()=>jr.ImageToImagePipeline,ImageToTextPipeline:()=>jr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>nh.InterruptableStoppingCriteria,JAISLMHeadModel:()=>ee.JAISLMHeadModel,JAISModel:()=>ee.JAISModel,JAISPreTrainedModel:()=>ee.JAISPreTrainedModel,LlamaForCausalLM:()=>ee.LlamaForCausalLM,LlamaModel:()=>ee.LlamaModel,LlamaPreTrainedModel:()=>ee.LlamaPreTrainedModel,LlamaTokenizer:()=>Vn.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:()=>Vn.M2M100Tokenizer,MBart50Tokenizer:()=>Vn.MBart50Tokenizer,MBartForCausalLM:()=>ee.MBartForCausalLM,MBartForConditionalGeneration:()=>ee.MBartForConditionalGeneration,MBartForSequenceClassification:()=>ee.MBartForSequenceClassification,MBartModel:()=>ee.MBartModel,MBartPreTrainedModel:()=>ee.MBartPreTrainedModel,MBartTokenizer:()=>Vn.MBartTokenizer,MPNetForMaskedLM:()=>ee.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>ee.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>ee.MPNetForSequenceClassification,MPNetForTokenClassification:()=>ee.MPNetForTokenClassification,MPNetModel:()=>ee.MPNetModel,MPNetPreTrainedModel:()=>ee.MPNetPreTrainedModel,MPNetTokenizer:()=>Vn.MPNetTokenizer,MT5ForConditionalGeneration:()=>ee.MT5ForConditionalGeneration,MT5Model:()=>ee.MT5Model,MT5PreTrainedModel:()=>ee.MT5PreTrainedModel,MarianMTModel:()=>ee.MarianMTModel,MarianModel:()=>ee.MarianModel,MarianPreTrainedModel:()=>ee.MarianPreTrainedModel,MarianTokenizer:()=>Vn.MarianTokenizer,MaskedLMOutput:()=>ee.MaskedLMOutput,MaxLengthCriteria:()=>nh.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:()=>Vn.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>Dn.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>ee.MobileNetV1ForImageClassification,MobileNetV1Model:()=>ee.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>ee.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Dn.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>ee.MobileNetV2ForImageClassification,MobileNetV2Model:()=>ee.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>ee.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Dn.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>ee.MobileNetV3ForImageClassification,MobileNetV3Model:()=>ee.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>ee.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Dn.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>ee.MobileNetV4ForImageClassification,MobileNetV4Model:()=>ee.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>ee.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Dn.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>ee.MobileViTForImageClassification,MobileViTImageProcessor:()=>Dn.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:()=>Vn.NllbTokenizer,NomicBertModel:()=>ee.NomicBertModel,NomicBertPreTrainedModel:()=>ee.NomicBertPreTrainedModel,NougatImageProcessor:()=>Dn.NougatImageProcessor,NougatTokenizer:()=>Vn.NougatTokenizer,OPTForCausalLM:()=>ee.OPTForCausalLM,OPTModel:()=>ee.OPTModel,OPTPreTrainedModel:()=>ee.OPTPreTrainedModel,ObjectDetectionPipeline:()=>jr.ObjectDetectionPipeline,OpenELMForCausalLM:()=>ee.OpenELMForCausalLM,OpenELMModel:()=>ee.OpenELMModel,OpenELMPreTrainedModel:()=>ee.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Dn.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>ee.OwlViTForObjectDetection,OwlViTModel:()=>ee.OwlViTModel,OwlViTPreTrainedModel:()=>ee.OwlViTPreTrainedModel,OwlViTProcessor:()=>Dn.OwlViTProcessor,Owlv2ForObjectDetection:()=>ee.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Dn.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:()=>jr.Pipeline,PreTrainedModel:()=>ee.PreTrainedModel,PreTrainedTokenizer:()=>Vn.PreTrainedTokenizer,PretrainedConfig:()=>py.PretrainedConfig,PretrainedMixin:()=>ee.PretrainedMixin,Processor:()=>Dn.Processor,PyAnnoteFeatureExtractor:()=>Dn.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>ee.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>ee.PyAnnoteModel,PyAnnotePreTrainedModel:()=>ee.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Dn.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>ee.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>jr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>ee.Qwen2ForCausalLM,Qwen2Model:()=>ee.Qwen2Model,Qwen2PreTrainedModel:()=>ee.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>Vn.Qwen2Tokenizer,RTDetrForObjectDetection:()=>ee.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Dn.RTDetrImageProcessor,RTDetrModel:()=>ee.RTDetrModel,RTDetrObjectDetectionOutput:()=>ee.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>ee.RTDetrPreTrainedModel,RawImage:()=>e3.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:()=>Vn.RoFormerTokenizer,RobertaForMaskedLM:()=>ee.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>ee.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>ee.RobertaForSequenceClassification,RobertaForTokenClassification:()=>ee.RobertaForTokenClassification,RobertaModel:()=>ee.RobertaModel,RobertaPreTrainedModel:()=>ee.RobertaPreTrainedModel,RobertaTokenizer:()=>Vn.RobertaTokenizer,SamImageProcessor:()=>Dn.SamImageProcessor,SamImageSegmentationOutput:()=>ee.SamImageSegmentationOutput,SamModel:()=>ee.SamModel,SamPreTrainedModel:()=>ee.SamPreTrainedModel,SamProcessor:()=>Dn.SamProcessor,SapiensFeatureExtractor:()=>Dn.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>ee.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>ee.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>ee.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>ee.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Dn.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Dn.SegformerFeatureExtractor,SegformerForImageClassification:()=>ee.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>ee.SegformerForSemanticSegmentation,SegformerModel:()=>ee.SegformerModel,SegformerPreTrainedModel:()=>ee.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>ee.Seq2SeqLMOutput,SequenceClassifierOutput:()=>ee.SequenceClassifierOutput,SiglipImageProcessor:()=>Dn.SiglipImageProcessor,SiglipModel:()=>ee.SiglipModel,SiglipPreTrainedModel:()=>ee.SiglipPreTrainedModel,SiglipTextModel:()=>ee.SiglipTextModel,SiglipTokenizer:()=>Vn.SiglipTokenizer,SiglipVisionModel:()=>ee.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Dn.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>ee.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>ee.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>ee.SpeechT5HifiGan,SpeechT5Model:()=>ee.SpeechT5Model,SpeechT5PreTrainedModel:()=>ee.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Dn.SpeechT5Processor,SpeechT5Tokenizer:()=>Vn.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>ee.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>ee.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>ee.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>ee.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>ee.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>Vn.SqueezeBertTokenizer,StableLmForCausalLM:()=>ee.StableLmForCausalLM,StableLmModel:()=>ee.StableLmModel,StableLmPreTrainedModel:()=>ee.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>ee.Starcoder2ForCausalLM,Starcoder2Model:()=>ee.Starcoder2Model,Starcoder2PreTrainedModel:()=>ee.Starcoder2PreTrainedModel,StoppingCriteria:()=>nh.StoppingCriteria,StoppingCriteriaList:()=>nh.StoppingCriteriaList,SummarizationPipeline:()=>jr.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>ee.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Dn.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:()=>Vn.T5Tokenizer,TableTransformerForObjectDetection:()=>ee.TableTransformerForObjectDetection,TableTransformerModel:()=>ee.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>ee.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>ee.TableTransformerPreTrainedModel,Tensor:()=>yi.Tensor,Text2TextGenerationPipeline:()=>jr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>jr.TextClassificationPipeline,TextGenerationPipeline:()=>jr.TextGenerationPipeline,TextStreamer:()=>my.TextStreamer,TextToAudioPipeline:()=>jr.TextToAudioPipeline,TokenClassificationPipeline:()=>jr.TokenClassificationPipeline,TokenClassifierOutput:()=>ee.TokenClassifierOutput,TokenizerModel:()=>Vn.TokenizerModel,TrOCRForCausalLM:()=>ee.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>ee.TrOCRPreTrainedModel,TranslationPipeline:()=>jr.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:()=>Dn.ViTFeatureExtractor,ViTForImageClassification:()=>ee.ViTForImageClassification,ViTImageProcessor:()=>Dn.ViTImageProcessor,ViTModel:()=>ee.ViTModel,ViTPreTrainedModel:()=>ee.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>ee.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>ee.VitMatteForImageMatting,VitMatteImageProcessor:()=>Dn.VitMatteImageProcessor,VitMattePreTrainedModel:()=>ee.VitMattePreTrainedModel,VitsModel:()=>ee.VitsModel,VitsModelOutput:()=>ee.VitsModelOutput,VitsPreTrainedModel:()=>ee.VitsPreTrainedModel,VitsTokenizer:()=>Vn.VitsTokenizer,Wav2Vec2BertForCTC:()=>ee.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>ee.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>ee.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>ee.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>Vn.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Dn.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>ee.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>ee.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>ee.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>ee.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>ee.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Dn.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>ee.WavLMForAudioFrameClassification,WavLMForCTC:()=>ee.WavLMForCTC,WavLMForSequenceClassification:()=>ee.WavLMForSequenceClassification,WavLMForXVector:()=>ee.WavLMForXVector,WavLMModel:()=>ee.WavLMModel,WavLMPreTrainedModel:()=>ee.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Dn.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>ee.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>ee.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Dn.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>ee.WhisperForConditionalGeneration,WhisperModel:()=>ee.WhisperModel,WhisperPreTrainedModel:()=>ee.WhisperPreTrainedModel,WhisperProcessor:()=>Dn.WhisperProcessor,WhisperTextStreamer:()=>my.WhisperTextStreamer,WhisperTokenizer:()=>Vn.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:()=>Vn.XLMRobertaTokenizer,XLMTokenizer:()=>Vn.XLMTokenizer,XLMWithLMHeadModel:()=>ee.XLMWithLMHeadModel,XVectorOutput:()=>ee.XVectorOutput,YolosFeatureExtractor:()=>Dn.YolosFeatureExtractor,YolosForObjectDetection:()=>ee.YolosForObjectDetection,YolosModel:()=>ee.YolosModel,YolosObjectDetectionOutput:()=>ee.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>ee.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>jr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>jr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>jr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>jr.ZeroShotObjectDetectionPipeline,bankers_round:()=>Ss.bankers_round,cat:()=>yi.cat,cos_sim:()=>Ss.cos_sim,dot:()=>Ss.dot,dynamic_time_warping:()=>Ss.dynamic_time_warping,env:()=>JI.env,full:()=>yi.full,full_like:()=>yi.full_like,getKeyValueShapes:()=>py.getKeyValueShapes,hamming:()=>Tc.hamming,hanning:()=>Tc.hanning,interpolate:()=>yi.interpolate,interpolate_4d:()=>yi.interpolate_4d,interpolate_data:()=>Ss.interpolate_data,is_chinese_char:()=>Vn.is_chinese_char,layer_norm:()=>yi.layer_norm,log_softmax:()=>Ss.log_softmax,magnitude:()=>Ss.magnitude,matmul:()=>yi.matmul,max:()=>Ss.max,mean:()=>yi.mean,mean_pooling:()=>yi.mean_pooling,medianFilter:()=>Ss.medianFilter,mel_filter_bank:()=>Tc.mel_filter_bank,min:()=>Ss.min,ones:()=>yi.ones,ones_like:()=>yi.ones_like,permute:()=>yi.permute,permute_data:()=>Ss.permute_data,pipeline:()=>jr.pipeline,quantize_embeddings:()=>yi.quantize_embeddings,read_audio:()=>Tc.read_audio,rfft:()=>yi.rfft,round:()=>Ss.round,softmax:()=>Ss.softmax,spectrogram:()=>Tc.spectrogram,stack:()=>yi.stack,std_mean:()=>yi.std_mean,topk:()=>yi.topk,window_function:()=>Tc.window_function,zeros:()=>yi.zeros,zeros_like:()=>yi.zeros_like});var JI=Ur("./src/env.js"),jr=Ur("./src/pipelines.js"),ee=Ur("./src/models.js"),Vn=Ur("./src/tokenizers.js"),Dn=Ur("./src/processors.js"),py=Ur("./src/configs.js"),Tc=Ur("./src/utils/audio.js"),e3=Ur("./src/utils/image.js"),yi=Ur("./src/utils/tensor.js"),Ss=Ur("./src/utils/maths.js"),my=Ur("./src/generation/streamers.js"),nh=Ur("./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 ck=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 dk=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 m2=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 k0=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 Sm(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 fk={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(h,w){if(!o[h]){if(!i[h]){var _=typeof Sm=="function"&&Sm;if(!w&&_)return _(h,!0);if(d)return d(h,!0);var M=new Error("Cannot find module '"+h+"'");throw M.code="MODULE_NOT_FOUND",M}var T=o[h]={exports:{}};i[h][0].call(T.exports,function(F){var C=i[h][1][F];return l(C||F)},T,T.exports,n,i,o,a)}return o[h].exports}for(var d=typeof Sm=="function"&&Sm,c=0;c>2,T=(3&h)<<4|w>>4,F=1>6:64,C=2>4,w=(15&M)<<4|(T=d.indexOf(c.charAt(C++)))>>2,_=(3&T)<<6|(F=d.indexOf(c.charAt(C++))),S[E++]=h,T!==64&&(S[E++]=w),F!==64&&(S[E++]=_);return S}},{"./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 h(w,_,M,T,F){this.compressedSize=w,this.uncompressedSize=_,this.crc32=M,this.compression=T,this.compressedContent=F}h.prototype={getContentWorker:function(){var w=new l(a.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),_=this;return w.on("end",function(){if(this.streamInfo.data_length!==_.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),w},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)}},h.createWorkerFrom=function(w,_,M){return w.pipe(new d).pipe(new c("uncompressedSize")).pipe(_.compressWorker(M)).pipe(new c("compressedSize")).withStreamInfo("compression",_)},i.exports=h},{"./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=[],h=0;h<256;h++){d=h;for(var w=0;w<8;w++)d=1&d?3988292384^d>>>1:d>>>1;c[h]=d}return c}();i.exports=function(d,c){return d!==void 0&&d.length?a.getTypeOf(d)!=="string"?function(h,w,_,M){var T=l,F=M+_;h^=-1;for(var C=M;C>>8^T[255&(h^w[C])];return-1^h}(0|c,d,d.length,0):function(h,w,_,M){var T=l,F=M+_;h^=-1;for(var C=M;C>>8^T[255&(h^w.charCodeAt(C))];return-1^h}(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"),h=a?"uint8array":"array";function w(_,M){c.call(this,"FlateWorker/"+_),this._pako=null,this._pakoAction=_,this._pakoOptions=M,this.meta={}}o.magic="\b\0",d.inherits(w,c),w.prototype.processChunk=function(_){this.meta=_.meta,this._pako===null&&this._createPako(),this._pako.push(d.transformTo(h,_.data),!1)},w.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},w.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},w.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var _=this;this._pako.onData=function(M){_.push({data:M,meta:_.meta})}},o.compressWorker=function(_){return new w("Deflate",_)},o.uncompressWorker=function(){return new w("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,i,o){function a(T,F){var C,E="";for(C=0;C>>=8;return E}function l(T,F,C,E,x,S){var P,j,L=T.file,N=T.compression,W=S!==h.utf8encode,V=d.transformTo("string",S(L.name)),ce=d.transformTo("string",h.utf8encode(L.name)),ge=L.comment,Re=d.transformTo("string",S(ge)),oe=d.transformTo("string",h.utf8encode(ge)),Se=ce.length!==L.name.length,G=oe.length!==ge.length,Ce="",pt="",Te="",te=L.dir,fe=L.date,Pe={crc32:0,compressedSize:0,uncompressedSize:0};F&&!C||(Pe.crc32=T.crc32,Pe.compressedSize=T.compressedSize,Pe.uncompressedSize=T.uncompressedSize);var ne=0;F&&(ne|=8),W||!Se&&!G||(ne|=2048);var xe=0,ht=0;te&&(xe|=16),x==="UNIX"?(ht=798,xe|=function(Ze,ut){var Mt=Ze;return Ze||(Mt=ut?16893:33204),(65535&Mt)<<16}(L.unixPermissions,te)):(ht=20,xe|=function(Ze){return 63&(Ze||0)}(L.dosPermissions)),P=fe.getUTCHours(),P<<=6,P|=fe.getUTCMinutes(),P<<=5,P|=fe.getUTCSeconds()/2,j=fe.getUTCFullYear()-1980,j<<=4,j|=fe.getUTCMonth()+1,j<<=5,j|=fe.getUTCDate(),Se&&(pt=a(1,1)+a(w(V),4)+ce,Ce+="up"+a(pt.length,2)+pt),G&&(Te=a(1,1)+a(w(Re),4)+oe,Ce+="uc"+a(Te.length,2)+Te);var Qe="";return Qe+=` \0`,Qe+=a(ne,2),Qe+=N.magic,Qe+=a(P,2),Qe+=a(j,2),Qe+=a(Pe.crc32,4),Qe+=a(Pe.compressedSize,4),Qe+=a(Pe.uncompressedSize,4),Qe+=a(V.length,2),Qe+=a(Ce.length,2),{fileRecord:_.LOCAL_FILE_HEADER+Qe+V+Ce,dirRecord:_.CENTRAL_FILE_HEADER+a(ht,2)+Qe+a(Re.length,2)+"\0\0\0\0"+a(xe,4)+a(E,4)+V+Ce+Re}}var d=n("../utils"),c=n("../stream/GenericWorker"),h=n("../utf8"),w=n("../crc32"),_=n("../signature");function M(T,F,C,E){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=F,this.zipPlatform=C,this.encodeFileName=E,this.streamFiles=T,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}d.inherits(M,c),M.prototype.push=function(T){var F=T.meta.percent||0,C=this.entriesCount,E=this._sources.length;this.accumulate?this.contentBuffer.push(T):(this.bytesWritten+=T.data.length,c.prototype.push.call(this,{data:T.data,meta:{currentFile:this.currentFile,percent:C?(F+100*(C-E-1))/C:100}}))},M.prototype.openedSource=function(T){this.currentSourceOffset=this.bytesWritten,this.currentFile=T.file.name;var F=this.streamFiles&&!T.file.dir;if(F){var C=l(T,F,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:C.fileRecord,meta:{percent:0}})}else this.accumulate=!0},M.prototype.closedSource=function(T){this.accumulate=!1;var F=this.streamFiles&&!T.file.dir,C=l(T,F,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(C.dirRecord),F)this.push({data:function(E){return _.DATA_DESCRIPTOR+a(E.crc32,4)+a(E.compressedSize,4)+a(E.uncompressedSize,4)}(T),meta:{percent:100}});else for(this.push({data:C.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},M.prototype.flush=function(){for(var T=this.bytesWritten,F=0;F=this.index;c--)h=(h<<8)+this.byteAt(c);return this.index+=d,h},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"),h=n("./NodeBufferReader"),w=n("./Uint8ArrayReader");i.exports=function(_){var M=a.getTypeOf(_);return a.checkSupport(M),M!=="string"||l.uint8array?M==="nodebuffer"?new h(_):l.uint8array?new w(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 h=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=h+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 h=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(w){h.dataIsReady=!0,h.data=w,h.max=w&&w.length||0,h.type=a.getTypeOf(w),h.isPaused||h._tickAndRepeat()},function(w){h.error(w)})}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,h=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,h);break;case"uint8array":c=this.data.subarray(this.index,h);break;case"array":case"nodebuffer":c=this.data.slice(this.index,h)}return this.index=h,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"),h=n("../support"),w=n("../external"),_=null;if(h.nodestream)try{_=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function M(F,C){return new w.Promise(function(E,x){var S=[],P=F._internalType,j=F._outputType,L=F._mimeType;F.on("data",function(N,W){S.push(N),C&&C(W)}).on("error",function(N){S=[],x(N)}).on("end",function(){try{var N=function(W,V,ce){switch(W){case"blob":return a.newBlob(a.transformTo("arraybuffer",V),ce);case"base64":return c.encode(V);default:return a.transformTo(W,V)}}(j,function(W,V){var ce,ge=0,Re=null,oe=0;for(ce=0;ce"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"),h=new Array(256),w=0;w<256;w++)h[w]=252<=w?6:248<=w?5:240<=w?4:224<=w?3:192<=w?2:1;h[254]=h[254]=1;function _(){c.call(this,"utf-8 decode"),this.leftOver=null}function M(){c.call(this,"utf-8 encode")}o.utf8encode=function(T){return l.nodebuffer?d.newBufferFrom(T,"utf-8"):function(F){var C,E,x,S,P,j=F.length,L=0;for(S=0;S>>6:(E<65536?C[P++]=224|E>>>12:(C[P++]=240|E>>>18,C[P++]=128|E>>>12&63),C[P++]=128|E>>>6&63),C[P++]=128|63&E);return C}(T)},o.utf8decode=function(T){return l.nodebuffer?a.transformTo("nodebuffer",T).toString("utf-8"):function(F){var C,E,x,S,P=F.length,j=new Array(2*P);for(C=E=0;C>10&1023,j[E++]=56320|1023&x)}return j.length!==E&&(j.subarray?j=j.subarray(0,E):j.length=E),a.applyFromCharCode(j)}(T=a.transformTo(l.uint8array?"uint8array":"array",T))},a.inherits(_,c),_.prototype.processChunk=function(T){var F=a.transformTo(l.uint8array?"uint8array":"array",T.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var C=F;(F=new Uint8Array(C.length+this.leftOver.length)).set(this.leftOver,0),F.set(C,this.leftOver.length)}else F=this.leftOver.concat(F);this.leftOver=null}var E=function(S,P){var j;for((P=P||S.length)>S.length&&(P=S.length),j=P-1;0<=j&&(192&S[j])==128;)j--;return j<0||j===0?P:j+h[S[j]]>P?j:P}(F),x=F;E!==F.length&&(l.uint8array?(x=F.subarray(0,E),this.leftOver=F.subarray(E,F.length)):(x=F.slice(0,E),this.leftOver=F.slice(E,F.length))),this.push({data:o.utf8decode(x),meta:T.meta})},_.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:o.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},o.Utf8DecodeWorker=_,a.inherits(M,c),M.prototype.processChunk=function(T){this.push({data:o.utf8encode(T.data),meta:T.meta})},o.Utf8EncodeWorker=M},{"./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 h(C){return C}function w(C,E){for(var x=0;x>8;this.dir=!!(16&this.externalFileAttributes),T==0&&(this.dosPermissions=63&this.externalFileAttributes),T==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var T=a(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=T.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=T.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=T.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=T.readInt(4))}},readExtraFields:function(T){var F,C,E,x=T.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});T.index+4>>6:(T<65536?M[E++]=224|T>>>12:(M[E++]=240|T>>>18,M[E++]=128|T>>>12&63),M[E++]=128|T>>>6&63),M[E++]=128|63&T);return M},o.buf2binstring=function(_){return w(_,_.length)},o.binstring2buf=function(_){for(var M=new a.Buf8(_.length),T=0,F=M.length;T>10&1023,S[F++]=56320|1023&C)}return w(S,F)},o.utf8border=function(_,M){var T;for((M=M||_.length)>_.length&&(M=_.length),T=M-1;0<=T&&(192&_[T])==128;)T--;return T<0||T===0?M:T+c[_[T]]>M?T:M}},{"./common":41}],43:[function(n,i,o){i.exports=function(a,l,d,c){for(var h=65535&a|0,w=a>>>16&65535|0,_=0;d!==0;){for(d-=_=2e3>>1:l>>>1;d[c]=l}return d}();i.exports=function(l,d,c,h){var w=a,_=h+c;l^=-1;for(var M=h;M<_;M++)l=l>>>8^w[255&(l^d[M])];return-1^l}},{}],46:[function(n,i,o){var a,l=n("../utils/common"),d=n("./trees"),c=n("./adler32"),h=n("./crc32"),w=n("./messages"),_=0,M=4,T=0,F=-2,C=-1,E=4,x=2,S=8,P=9,j=286,L=30,N=19,W=2*j+1,V=15,ce=3,ge=258,Re=ge+ce+1,oe=42,Se=113,G=1,Ce=2,pt=3,Te=4;function te(z,Fe){return z.msg=w[Fe],Fe}function fe(z){return(z<<1)-(4z.avail_out&&(Oe=z.avail_out),Oe!==0&&(l.arraySet(z.output,Fe.pending_buf,Fe.pending_out,Oe,z.next_out),z.next_out+=Oe,Fe.pending_out+=Oe,z.total_out+=Oe,z.avail_out-=Oe,Fe.pending-=Oe,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 ht(z,Fe){z.pending_buf[z.pending++]=Fe}function Qe(z,Fe){z.pending_buf[z.pending++]=Fe>>>8&255,z.pending_buf[z.pending++]=255&Fe}function Ze(z,Fe){var Oe,he,de=z.max_chain_length,Ee=z.strstart,H=z.prev_length,se=z.nice_match,K=z.strstart>z.w_size-Re?z.strstart-(z.w_size-Re):0,_e=z.window,pe=z.w_mask,Ie=z.prev,Xe=z.strstart+ge,St=_e[Ee+H-1],ft=_e[Ee+H];z.prev_length>=z.good_match&&(de>>=2),se>z.lookahead&&(se=z.lookahead);do if(_e[(Oe=Fe)+H]===ft&&_e[Oe+H-1]===St&&_e[Oe]===_e[Ee]&&_e[++Oe]===_e[Ee+1]){Ee+=2,Oe++;do;while(_e[++Ee]===_e[++Oe]&&_e[++Ee]===_e[++Oe]&&_e[++Ee]===_e[++Oe]&&_e[++Ee]===_e[++Oe]&&_e[++Ee]===_e[++Oe]&&_e[++Ee]===_e[++Oe]&&_e[++Ee]===_e[++Oe]&&_e[++Ee]===_e[++Oe]&&EeK&&--de!=0);return H<=z.lookahead?H:z.lookahead}function ut(z){var Fe,Oe,he,de,Ee,H,se,K,_e,pe,Ie=z.w_size;do{if(de=z.window_size-z.lookahead-z.strstart,z.strstart>=Ie+(Ie-Re)){for(l.arraySet(z.window,z.window,Ie,Ie,0),z.match_start-=Ie,z.strstart-=Ie,z.block_start-=Ie,Fe=Oe=z.hash_size;he=z.head[--Fe],z.head[Fe]=Ie<=he?he-Ie:0,--Oe;);for(Fe=Oe=Ie;he=z.prev[--Fe],z.prev[Fe]=Ie<=he?he-Ie:0,--Oe;);de+=Ie}if(z.strm.avail_in===0)break;if(H=z.strm,se=z.window,K=z.strstart+z.lookahead,_e=de,pe=void 0,pe=H.avail_in,_e=ce)for(Ee=z.strstart-z.insert,z.ins_h=z.window[Ee],z.ins_h=(z.ins_h<=ce&&(z.ins_h=(z.ins_h<=ce)if(he=d._tr_tally(z,z.strstart-z.match_start,z.match_length-ce),z.lookahead-=z.match_length,z.match_length<=z.max_lazy_match&&z.lookahead>=ce){for(z.match_length--;z.strstart++,z.ins_h=(z.ins_h<=ce&&(z.ins_h=(z.ins_h<=ce&&z.match_length<=z.prev_length){for(de=z.strstart+z.lookahead-ce,he=d._tr_tally(z,z.strstart-1-z.prev_match,z.prev_length-ce),z.lookahead-=z.prev_length-1,z.prev_length-=2;++z.strstart<=de&&(z.ins_h=(z.ins_h<z.pending_buf_size-5&&(Oe=z.pending_buf_size-5);;){if(z.lookahead<=1){if(ut(z),z.lookahead===0&&Fe===_)return G;if(z.lookahead===0)break}z.strstart+=z.lookahead,z.lookahead=0;var he=z.block_start+Oe;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-Re&&(xe(z,!1),z.strm.avail_out===0))return G}return z.insert=0,Fe===M?(xe(z,!0),z.strm.avail_out===0?pt:Te):(z.strstart>z.block_start&&(xe(z,!1),z.strm.avail_out),G)}),new Ve(4,4,8,4,Mt),new Ve(4,5,16,8,Mt),new Ve(4,6,32,32,Mt),new Ve(4,4,16,16,Ft),new Ve(8,16,32,32,Ft),new Ve(8,16,128,128,Ft),new Ve(8,32,128,256,Ft),new Ve(32,128,258,1024,Ft),new Ve(32,258,258,4096,Ft)],o.deflateInit=function(z,Fe){return bt(z,Fe,S,15,8,0)},o.deflateInit2=bt,o.deflateReset=dt,o.deflateResetKeep=lt,o.deflateSetHeader=function(z,Fe){return z&&z.state?z.state.wrap!==2?F:(z.state.gzhead=Fe,T):F},o.deflate=function(z,Fe){var Oe,he,de,Ee;if(!z||!z.state||5>8&255),ht(he,he.gzhead.time>>16&255),ht(he,he.gzhead.time>>24&255),ht(he,he.level===9?2:2<=he.strategy||he.level<2?4:0),ht(he,255&he.gzhead.os),he.gzhead.extra&&he.gzhead.extra.length&&(ht(he,255&he.gzhead.extra.length),ht(he,he.gzhead.extra.length>>8&255)),he.gzhead.hcrc&&(z.adler=h(z.adler,he.pending_buf,he.pending,0)),he.gzindex=0,he.status=69):(ht(he,0),ht(he,0),ht(he,0),ht(he,0),ht(he,0),ht(he,he.level===9?2:2<=he.strategy||he.level<2?4:0),ht(he,3),he.status=Se);else{var H=S+(he.w_bits-8<<4)<<8;H|=(2<=he.strategy||he.level<2?0:he.level<6?1:he.level===6?2:3)<<6,he.strstart!==0&&(H|=32),H+=31-H%31,he.status=Se,Qe(he,H),he.strstart!==0&&(Qe(he,z.adler>>>16),Qe(he,65535&z.adler)),z.adler=1}if(he.status===69)if(he.gzhead.extra){for(de=he.pending;he.gzindex<(65535&he.gzhead.extra.length)&&(he.pending!==he.pending_buf_size||(he.gzhead.hcrc&&he.pending>de&&(z.adler=h(z.adler,he.pending_buf,he.pending-de,de)),ne(z),de=he.pending,he.pending!==he.pending_buf_size));)ht(he,255&he.gzhead.extra[he.gzindex]),he.gzindex++;he.gzhead.hcrc&&he.pending>de&&(z.adler=h(z.adler,he.pending_buf,he.pending-de,de)),he.gzindex===he.gzhead.extra.length&&(he.gzindex=0,he.status=73)}else he.status=73;if(he.status===73)if(he.gzhead.name){de=he.pending;do{if(he.pending===he.pending_buf_size&&(he.gzhead.hcrc&&he.pending>de&&(z.adler=h(z.adler,he.pending_buf,he.pending-de,de)),ne(z),de=he.pending,he.pending===he.pending_buf_size)){Ee=1;break}Ee=he.gzindexde&&(z.adler=h(z.adler,he.pending_buf,he.pending-de,de)),Ee===0&&(he.gzindex=0,he.status=91)}else he.status=91;if(he.status===91)if(he.gzhead.comment){de=he.pending;do{if(he.pending===he.pending_buf_size&&(he.gzhead.hcrc&&he.pending>de&&(z.adler=h(z.adler,he.pending_buf,he.pending-de,de)),ne(z),de=he.pending,he.pending===he.pending_buf_size)){Ee=1;break}Ee=he.gzindexde&&(z.adler=h(z.adler,he.pending_buf,he.pending-de,de)),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&&(ht(he,255&z.adler),ht(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,T}else if(z.avail_in===0&&fe(Fe)<=fe(Oe)&&Fe!==M)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 se=he.strategy===2?function(K,_e){for(var pe;;){if(K.lookahead===0&&(ut(K),K.lookahead===0)){if(_e===_)return G;break}if(K.match_length=0,pe=d._tr_tally(K,0,K.window[K.strstart]),K.lookahead--,K.strstart++,pe&&(xe(K,!1),K.strm.avail_out===0))return G}return K.insert=0,_e===M?(xe(K,!0),K.strm.avail_out===0?pt:Te):K.last_lit&&(xe(K,!1),K.strm.avail_out===0)?G:Ce}(he,Fe):he.strategy===3?function(K,_e){for(var pe,Ie,Xe,St,ft=K.window;;){if(K.lookahead<=ge){if(ut(K),K.lookahead<=ge&&_e===_)return G;if(K.lookahead===0)break}if(K.match_length=0,K.lookahead>=ce&&0K.lookahead&&(K.match_length=K.lookahead)}if(K.match_length>=ce?(pe=d._tr_tally(K,1,K.match_length-ce),K.lookahead-=K.match_length,K.strstart+=K.match_length,K.match_length=0):(pe=d._tr_tally(K,0,K.window[K.strstart]),K.lookahead--,K.strstart++),pe&&(xe(K,!1),K.strm.avail_out===0))return G}return K.insert=0,_e===M?(xe(K,!0),K.strm.avail_out===0?pt:Te):K.last_lit&&(xe(K,!1),K.strm.avail_out===0)?G:Ce}(he,Fe):a[he.level].func(he,Fe);if(se!==pt&&se!==Te||(he.status=666),se===G||se===pt)return z.avail_out===0&&(he.last_flush=-1),T;if(se===Ce&&(Fe===1?d._tr_align(he):Fe!==5&&(d._tr_stored_block(he,0,0,!1),Fe===3&&(Pe(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,T}return Fe!==M?T:he.wrap<=0?1:(he.wrap===2?(ht(he,255&z.adler),ht(he,z.adler>>8&255),ht(he,z.adler>>16&255),ht(he,z.adler>>24&255),ht(he,255&z.total_in),ht(he,z.total_in>>8&255),ht(he,z.total_in>>16&255),ht(he,z.total_in>>24&255)):(Qe(he,z.adler>>>16),Qe(he,65535&z.adler)),ne(z),0=Oe.w_size&&(Ee===0&&(Pe(Oe.head),Oe.strstart=0,Oe.block_start=0,Oe.insert=0),_e=new l.Buf8(Oe.w_size),l.arraySet(_e,Fe,pe-Oe.w_size,Oe.w_size,0),Fe=_e,pe=Oe.w_size),H=z.avail_in,se=z.next_in,K=z.input,z.avail_in=pe,z.next_in=0,z.input=Fe,ut(Oe);Oe.lookahead>=ce;){for(he=Oe.strstart,de=Oe.lookahead-(ce-1);Oe.ins_h=(Oe.ins_h<>>=ce=V>>>24,P-=ce,(ce=V>>>16&255)===0)Ce[w++]=65535&V;else{if(!(16&ce)){if(!(64&ce)){V=j[(65535&V)+(S&(1<>>=ce,P-=ce),P<15&&(S+=G[c++]<>>=ce=V>>>24,P-=ce,!(16&(ce=V>>>16&255))){if(!(64&ce)){V=L[(65535&V)+(S&(1<>>=ce,P-=ce,(ce=w-_)>3,S&=(1<<(P-=ge<<3))-1,a.next_in=c,a.next_out=w,a.avail_in=c>>24&255)+(oe>>>8&65280)+((65280&oe)<<8)+((255&oe)<<24)}function S(){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 P(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=F,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,M):T}function j(oe){var Se;return oe&&oe.state?((Se=oe.state).wsize=0,Se.whave=0,Se.wnext=0,P(oe)):T}function L(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=Te.wsize?(a.arraySet(Te.window,Se,G-Te.wsize,Te.wsize,0),Te.wnext=0,Te.whave=Te.wsize):(Ce<(pt=Te.wsize-Te.wnext)&&(pt=Ce),a.arraySet(Te.window,Se,G-Ce,pt,Te.wnext),(Ce-=pt)?(a.arraySet(Te.window,Se,G-Ce,Ce,0),Te.wnext=Ce,Te.whave=Te.wsize):(Te.wnext+=pt,Te.wnext===Te.wsize&&(Te.wnext=0),Te.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[Te++]<>>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[Te++]<>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[Te++]<>>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<(Ze=G.length)&&(Ze=fe),Ze&&(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,Te,Ze,z)),512&G.flags&&(G.check=d(G.check,Ce,Ze,Te)),fe-=Ze,Te+=Ze,G.length-=Ze),G.length))break e;G.length=0,G.mode=7;case 7:if(2048&G.flags){if(fe===0)break e;for(Ze=0;z=Ce[Te+Ze++],G.head&&z&&G.length<65536&&(G.head.name+=String.fromCharCode(z)),z&&Ze>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[Te++]<>>=7&xe,xe-=7&xe,G.mode=27;break}for(;xe<3;){if(fe===0)break e;fe--,ne+=Ce[Te++]<>>=1)){case 0:G.mode=14;break;case 1:if(ge(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[Te++]<>>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(Ze=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[H[G.have++]]=0;if(G.lencode=G.lendyn,G.lenbits=7,Oe={bits:G.lenbits},Fe=h(0,G.lens,0,19,G.lencode,0,G.work,Oe),G.lenbits=Oe.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,ke=65535&de,!((Ft=de>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Te++]<>>=Ft,xe-=Ft,G.lens[G.have++]=ke;else{if(ke===16){for(he=Ft+2;xe>>=Ft,xe-=Ft,G.have===0){oe.msg="invalid bit length repeat",G.mode=30;break}z=G.lens[G.have-1],Ze=3+(3&ne),ne>>>=2,xe-=2}else if(ke===17){for(he=Ft+3;xe>>=Ft)),ne>>>=3,xe-=3}else{for(he=Ft+7;xe>>=Ft)),ne>>>=7,xe-=7}if(G.have+Ze>G.nlen+G.ndist){oe.msg="invalid bit length repeat",G.mode=30;break}for(;Ze--;)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,Oe={bits:G.lenbits},Fe=h(w,G.lens,0,G.nlen,G.lencode,0,G.work,Oe),G.lenbits=Oe.bits,Fe){oe.msg="invalid literal/lengths set",G.mode=30;break}if(G.distbits=6,G.distcode=G.distdyn,Oe={bits:G.distbits},Fe=h(_,G.lens,G.nlen,G.ndist,G.distcode,0,G.work,Oe),G.distbits=Oe.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<=Pe){oe.next_out=te,oe.avail_out=Pe,oe.next_in=Te,oe.avail_in=fe,G.hold=ne,G.bits=xe,c(oe,Qe),te=oe.next_out,pt=oe.output,Pe=oe.avail_out,Te=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;Ve=(de=G.lencode[ne&(1<>>16&255,ke=65535&de,!((Ft=de>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Te++]<>lt)])>>>16&255,ke=65535&de,!(lt+(Ft=de>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Te++]<>>=lt,xe-=lt,G.back+=lt}if(ne>>>=Ft,xe-=Ft,G.back+=Ft,G.length=ke,Ve===0){G.mode=26;break}if(32&Ve){G.back=-1,G.mode=12;break}if(64&Ve){oe.msg="invalid literal/length code",G.mode=30;break}G.extra=15&Ve,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(;Ve=(de=G.distcode[ne&(1<>>16&255,ke=65535&de,!((Ft=de>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Te++]<>lt)])>>>16&255,ke=65535&de,!(lt+(Ft=de>>>24)<=xe);){if(fe===0)break e;fe--,ne+=Ce[Te++]<>>=lt,xe-=lt,G.back+=lt}if(ne>>>=Ft,xe-=Ft,G.back+=Ft,64&Ve){oe.msg="invalid distance code",G.mode=30;break}G.offset=ke,G.extra=15&Ve,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(Pe===0)break e;if(Ze=Qe-Pe,G.offset>Ze){if((Ze=G.offset-Ze)>G.whave&&G.sane){oe.msg="invalid distance too far back",G.mode=30;break}ut=Ze>G.wnext?(Ze-=G.wnext,G.wsize-Ze):G.wnext-Ze,Ze>G.length&&(Ze=G.length),Mt=G.window}else Mt=pt,ut=te-G.offset,Ze=G.length;for(PeW?(ce=ut[Mt+E[Se]],xe[ht+E[Se]]):(ce=96,0),S=1<>te)+(P-=S)]=V<<24|ce<<16|ge|0,P!==0;);for(S=1<>=1;if(S!==0?(ne&=S-1,ne+=S):ne=0,Se++,--Qe[oe]==0){if(oe===Ce)break;oe=_[M+E[Se]]}if(pt>>7)]}function ht(de,Ee){de.pending_buf[de.pending++]=255&Ee,de.pending_buf[de.pending++]=Ee>>>8&255}function Qe(de,Ee,H){de.bi_valid>x-H?(de.bi_buf|=Ee<>x-de.bi_valid,de.bi_valid+=H-x):(de.bi_buf|=Ee<>>=1,H<<=1,0<--Ee;);return H>>>1}function Mt(de,Ee,H){var se,K,_e=new Array(E+1),pe=0;for(se=1;se<=E;se++)_e[se]=pe=pe+H[se-1]<<1;for(K=0;K<=Ee;K++){var Ie=de[2*K+1];Ie!==0&&(de[2*K]=ut(_e[Ie]++,Ie))}}function Ft(de){var Ee;for(Ee=0;Ee>1;1<=H;H--)lt(de,_e,H);for(K=Xe;H=de.heap[1],de.heap[1]=de.heap[de.heap_len--],lt(de,_e,1),se=de.heap[1],de.heap[--de.heap_max]=H,de.heap[--de.heap_max]=se,_e[2*K]=_e[2*H]+_e[2*se],de.depth[K]=(de.depth[H]>=de.depth[se]?de.depth[H]:de.depth[se])+1,_e[2*H+1]=_e[2*se+1]=K,de.heap[1]=K++,lt(de,_e,1),2<=de.heap_len;);de.heap[--de.heap_max]=de.heap[1],function(ft,Dt){var Jt,kt,ve,Ne,rt,Ye,mt=Dt.dyn_tree,At=Dt.max_code,jt=Dt.stat_desc.static_tree,it=Dt.stat_desc.has_stree,en=Dt.stat_desc.extra_bits,Vt=Dt.stat_desc.extra_base,xt=Dt.stat_desc.max_length,hn=0;for(Ne=0;Ne<=E;Ne++)ft.bl_count[Ne]=0;for(mt[2*ft.heap[ft.heap_max]+1]=0,Jt=ft.heap_max+1;Jt>=7;K>>=1)if(1&St&&Ie.dyn_ltree[2*Xe]!==0)return l;if(Ie.dyn_ltree[18]!==0||Ie.dyn_ltree[20]!==0||Ie.dyn_ltree[26]!==0)return d;for(Xe=32;Xe<_;Xe++)if(Ie.dyn_ltree[2*Xe]!==0)return d;return l}(de)),bt(de,de.l_desc),bt(de,de.d_desc),pe=function(Ie){var Xe;for(z(Ie,Ie.dyn_ltree,Ie.l_desc.max_code),z(Ie,Ie.dyn_dtree,Ie.d_desc.max_code),bt(Ie,Ie.bl_desc),Xe=F-1;3<=Xe&&Ie.bl_tree[2*ge[Xe]+1]===0;Xe--);return Ie.opt_len+=3*(Xe+1)+5+5+4,Xe}(de),K=de.opt_len+3+7>>>3,(_e=de.static_len+3+7>>>3)<=K&&(K=_e)):K=_e=H+5,H+4<=K&&Ee!==-1?he(de,Ee,H,se):de.strategy===4||_e===K?(Qe(de,2+(se?1:0),3),dt(de,Re,oe)):(Qe(de,4+(se?1:0),3),function(Ie,Xe,St,ft){var Dt;for(Qe(Ie,Xe-257,5),Qe(Ie,St-1,5),Qe(Ie,ft-4,4),Dt=0;Dt>>8&255,de.pending_buf[de.d_buf+2*de.last_lit+1]=255&Ee,de.pending_buf[de.l_buf+de.last_lit]=255&H,de.last_lit++,Ee===0?de.dyn_ltree[2*H]++:(de.matches++,Ee--,de.dyn_ltree[2*(G[H]+_+1)]++,de.dyn_dtree[2*xe(Ee)]++),de.last_lit===de.lit_bufsize-1},o._tr_align=function(de){Qe(de,2,3),Ze(de,P,Re),function(Ee){Ee.bi_valid===16?(ht(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)}(de)}},{"../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,h,w,_,M=1,T={},F=!1,C=l.document,E=Object.getPrototypeOf&&Object.getPrototypeOf(l);E=E&&E.setTimeout?E:l,c={}.toString.call(l.process)==="[object process]"?function(j){process.nextTick(function(){S(j)})}:function(){if(l.postMessage&&!l.importScripts){var j=!0,L=l.onmessage;return l.onmessage=function(){j=!1},l.postMessage("","*"),l.onmessage=L,j}}()?(_="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",P,!1):l.attachEvent("onmessage",P),function(j){l.postMessage(_+j,"*")}):l.MessageChannel?((w=new MessageChannel).port1.onmessage=function(j){S(j.data)},function(j){w.port2.postMessage(j)}):C&&"onreadystatechange"in C.createElement("script")?(h=C.documentElement,function(j){var L=C.createElement("script");L.onreadystatechange=function(){S(j),L.onreadystatechange=null,h.removeChild(L),L=null},h.appendChild(L)}):function(j){setTimeout(S,0,j)},E.setImmediate=function(j){typeof j!="function"&&(j=new Function(""+j));for(var L=new Array(arguments.length-1),N=0;N"u"?a===void 0?this:a:self)}).call(this,typeof Eo<"u"?Eo:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(fk);var t3=fk.exports;const hk=Eg(t3);var pk={exports:{}};(function(e,t){(function(n,i){i()})(Eo,function(){function n(h,w){return typeof w>"u"?w={autoBom:!1}:typeof w!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),w={autoBom:!w}),w.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(h.type)?new Blob(["\uFEFF",h],{type:h.type}):h}function i(h,w,_){var M=new XMLHttpRequest;M.open("GET",h),M.responseType="blob",M.onload=function(){c(M.response,w,_)},M.onerror=function(){console.error("could not download file")},M.send()}function o(h){var w=new XMLHttpRequest;w.open("HEAD",h,!1);try{w.send()}catch{}return 200<=w.status&&299>=w.status}function a(h){try{h.dispatchEvent(new MouseEvent("click"))}catch{var w=document.createEvent("MouseEvents");w.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),h.dispatchEvent(w)}}var l=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof Eo=="object"&&Eo.global===Eo?Eo: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(h,w,_){var M=l.URL||l.webkitURL,T=document.createElement("a");w=w||h.name||"download",T.download=w,T.rel="noopener",typeof h=="string"?(T.href=h,T.origin===location.origin?a(T):o(T.href)?i(h,w,_):a(T,T.target="_blank")):(T.href=M.createObjectURL(h),setTimeout(function(){M.revokeObjectURL(T.href)},4e4),setTimeout(function(){a(T)},0))}:"msSaveOrOpenBlob"in navigator?function(h,w,_){if(w=w||h.name||"download",typeof h!="string")navigator.msSaveOrOpenBlob(n(h,_),w);else if(o(h))i(h,w,_);else{var M=document.createElement("a");M.href=h,M.target="_blank",setTimeout(function(){a(M)})}}:function(h,w,_,M){if(M=M||open("","_blank"),M&&(M.document.title=M.document.body.innerText="downloading..."),typeof h=="string")return i(h,w,_);var T=h.type==="application/octet-stream",F=/constructor/i.test(l.HTMLElement)||l.safari,C=/CriOS\/[\d]+/.test(navigator.userAgent);if((C||T&&F||d)&&typeof FileReader<"u"){var E=new FileReader;E.onloadend=function(){var P=E.result;P=C?P:P.replace(/^data:[^;]*;/,"data:attachment/file;"),M?M.location.href=P:location=P,M=null},E.readAsDataURL(h)}else{var x=l.URL||l.webkitURL,S=x.createObjectURL(h);M?M.location=S:location.href=S,M=null,setTimeout(function(){x.revokeObjectURL(S)},4e4)}});l.saveAs=c.saveAs=c,e.exports=c})})(pk);var mk=pk.exports,gk={exports:{}};(function(e,t){(function(n,i){e.exports=i()})(Eo,function(){var n=function(f,v){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function($,U){$.__proto__=U}||function($,U){for(var Y in U)Object.prototype.hasOwnProperty.call(U,Y)&&($[Y]=U[Y])})(f,v)},i=function(){return(i=Object.assign||function(f){for(var v,$=1,U=arguments.length;$"u"||a.Promise||(a.Promise=Promise);var h=Object.getPrototypeOf,w={}.hasOwnProperty;function _(f,v){return w.call(f,v)}function M(f,v){typeof v=="function"&&(v=v(h(f))),(typeof Reflect>"u"?l:Reflect.ownKeys)(v).forEach(function($){F(f,$,v[$])})}var T=Object.defineProperty;function F(f,v,$,U){T(f,v,c($&&_($,"get")&&typeof $.get=="function"?{get:$.get,set:$.set,configurable:!0}:{value:$,configurable:!0,writable:!0},U))}function C(f){return{from:function(v){return f.prototype=Object.create(v.prototype),F(f.prototype,"constructor",f),{extend:M.bind(null,f.prototype)}}}}var E=Object.getOwnPropertyDescriptor,x=[].slice;function S(f,v,$){return x.call(f,v,$)}function P(f,v){return v(f)}function j(f){if(!f)throw new Error("Assertion Failed")}function L(f){a.setImmediate?setImmediate(f):setTimeout(f,0)}function N(f,v){if(typeof v=="string"&&_(f,v))return f[v];if(!v)return f;if(typeof v!="string"){for(var $=[],U=0,Y=v.length;U"u"?[]:function(){var f=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[f,h(f),f];var v=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[v,h(v),f]}(),Ie=De[0],bi=De[1],De=De[2],bi=bi&&bi.then,Xe=Ie&&Ie.constructor,St=!!De,ft=function(f,v){mt.push([f,v]),Jt&&(queueMicrotask(bn),Jt=!1)},Dt=!0,Jt=!0,kt=[],ve=[],Ne=bt,rt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:dt,pgp:!1,env:{},finalize:dt},Ye=rt,mt=[],At=0,jt=[];function it(f){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var v=this._PSD=Ye;if(typeof f!="function"){if(f!==_e)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&xt(this,this._value))}this._state=null,this._value=null,++v.ref,function $(U,Y){try{Y(function(le){if(U._state===null){if(le===U)throw new TypeError("A promise cannot be resolved with itself.");var Me=U._lib&&mn();le&&typeof le.then=="function"?$(U,function(ze,Ke){le instanceof it?le._then(ze,Ke):le.then(ze,Ke)}):(U._state=!0,U._value=le,hn(U)),Me&&Sn()}},xt.bind(null,U))}catch(le){xt(U,le)}}(this,f)}var en={get:function(){var f=Ye,v=os;function $(U,Y){var le=this,Me=!f.global&&(f!==Ye||v!==os),ze=Me&&!br(),Ke=new it(function(Ge,st){fn(le,new Vt(lo(U,f,Me,ze),lo(Y,f,Me,ze),Ge,st,f))});return this._consoleTask&&(Ke._consoleTask=this._consoleTask),Ke}return $.prototype=_e,$},set:function(f){F(this,"then",f&&f.prototype===_e?en:{get:function(){return f},set:en.set})}};function Vt(f,v,$,U,Y){this.onFulfilled=typeof f=="function"?f:null,this.onRejected=typeof v=="function"?v:null,this.resolve=$,this.reject=U,this.psd=Y}function xt(f,v){var $,U;ve.push(v),f._state===null&&($=f._lib&&mn(),v=Ne(v),f._state=!1,f._value=v,U=f,kt.some(function(Y){return Y._value===U._value})||kt.push(U),hn(f),$&&Sn())}function hn(f){var v=f._listeners;f._listeners=[];for(var $=0,U=v.length;$.",$o="String expected.",qi=[],Si="__dbnames",cs="readonly",Hi="readwrite";function ki(f,v){return f?v?function(){return f.apply(this,arguments)&&v.apply(this,arguments)}:f:v}var Gs={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function vs(f){return typeof f!="string"||/\./.test(f)?function(v){return v}:function(v){return v[f]===void 0&&f in v&&delete(v=Se(v))[f],v}}function En(){throw Ve.Type()}function Xn(f,v){try{var $=uo(f),U=uo(v);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 vwt+_t&>(wt+ot)})})}var vt=fs($)&&$.limit===1/0&&(typeof f!="function"||f===nn)&&{index:$.index,range:$.range};return gt(0).then(function(){if(0=ot})).length!==0?(st.forEach(function(gt){at.push(function(){var vt=Je,wt=gt._cfg.dbschema;Do(We,vt,tt),Do(We,wt,tt),Je=We._dbSchema=wt;var _t=ua(vt,wt);_t.add.forEach(function(an){Fo(tt,an[0],an[1].primKey,an[1].indexes)}),_t.change.forEach(function(an){if(an.recreate)throw new Ve.Upgrade("Not yet support for changing primary key");var Ut=tt.objectStore(an.name);an.add.forEach(function(Bn){return Oo(Ut,Bn)}),an.change.forEach(function(Bn){Ut.deleteIndex(Bn.name),Oo(Ut,Bn)}),an.del.forEach(function(Bn){return Ut.deleteIndex(Bn)})});var Gt=gt._cfg.contentUpgrade;if(Gt&>._cfg.version>ot){vn(We,tt),He._memoizedTables={};var on=V(wt);_t.del.forEach(function(an){on[an]=vt[an]}),Io(We,[We.Transaction.prototype]),fo(We,[We.Transaction.prototype],l(on),on),He.schema=on;var Wt,rn=ne(Gt);return rn&&Qr(),_t=it.follow(function(){var an;(Wt=Gt(He))&&rn&&(an=br.bind(null,null),Wt.then(an,an))}),Wt&&typeof Wt.then=="function"?it.resolve(Wt):_t.then(function(){return Wt})}}),at.push(function(vt){var wt,_t,Gt=gt._cfg.dbschema;wt=Gt,_t=vt,[].slice.call(_t.db.objectStoreNames).forEach(function(on){return wt[on]==null&&_t.db.deleteObjectStore(on)}),Io(We,[We.Transaction.prototype]),fo(We,[We.Transaction.prototype],We._storeNames,We._dbSchema),He.schema=We._dbSchema}),at.push(function(vt){We.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(We.idbdb.version/10)===gt._cfg.version?(We.idbdb.deleteObjectStore("$meta"),delete We._dbSchema.$meta,We._storeNames=We._storeNames.filter(function(wt){return wt!=="$meta"})):vt.objectStore("$meta").put(gt._cfg.version,"version"))})}),function gt(){return at.length?it.resolve(at.shift()(He.idbtrans)).then(gt):it.resolve()}().then(function(){po(Je,tt)})):it.resolve();var We,ot,He,tt,at,Je}).catch(Me)):(l(Y).forEach(function(st){Fo($,st,Y[st].primKey,Y[st].indexes)}),vn(f,$),void it.follow(function(){return f.on.populate.fire(le)}).catch(Me));var Ke,Ge})}function Ln(f,v){po(f._dbSchema,v),v.db.version%10!=0||v.objectStoreNames.contains("$meta")||v.db.createObjectStore("$meta").add(Math.ceil(v.db.version/10-1),"version");var $=Ai(0,f.idbdb,v);Do(f,f._dbSchema,v);for(var U=0,Y=ua($,f._dbSchema).change;UMath.pow(2,62)?0:Je.oldVersion,We=Je<1,f.idbdb=at.result,le&&Ln(f,st),ho(f,Je/10,st,He))},He),at.onsuccess=Mn(function(){st=null;var Je,gt,vt,wt,_t,Gt=f.idbdb=at.result,on=S(Gt.objectStoreNames);if(0"u"?it.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(ot){function He(){return indexedDB.databases().finally(ot)}Ke=setInterval(He,100),He()}).finally(function(){return clearInterval(Ke)}):Promise.resolve()).then(ze)]).then(function(){return Me(),v.onReadyBeingFired=[],it.resolve(ha(function(){return f.on.ready.fire(f.vip)})).then(function ot(){if(0v.limit?ot.length=v.limit:f.length===v.limit&&ot.length=gt.limit&&(!gt.values||Gt.req.values)&&Bl(Gt.req.query.range,gt.query.range)}),!1,vt,wt];case"count":return _t=wt.find(function(Gt){return Ja(Gt.req.query.range,gt.query.range)}),[_t,!!_t,vt,wt]}}(v,$,"query",le),st=Ge[0],We=Ge[1],ot=Ge[2],He=Ge[3];return st&&We?st.obsSet=le.obsSet:(We=U.query(le).then(function(tt){var at=tt.result;if(st&&(st.res=at),Me){for(var Je=0,gt=at.length;Je=0)&&Object.prototype.propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}function l3(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 vg(){return vg=Object.assign?Object.assign.bind():function(e){for(var t=1;tRs.createElement(t.tag,wg({key:n},t.attr),yk(t.child)))}function aa(e){return t=>Rs.createElement(f3,vg({attr:wg({},e.attr)},t),yk(e.child))}function f3(e){var t=n=>{var{attr:i,size:o,title:a}=e,l=a3(e,o3),d=o||n.size||"1em",c;return n.className&&(c=n.className),e.className&&(c=(c?c+" ":"")+e.className),Rs.createElement("svg",vg({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,i,l,{className:c,style:wg(wg({color:e.color||n.color},n.style),e.style),height:d,width:d,xmlns:"http://www.w3.org/2000/svg"}),a&&Rs.createElement("title",null,a),e.children)};return _2!==void 0?Rs.createElement(_2.Consumer,null,n=>t(n)):t(_k)}function h3(e){return aa({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 p3(e){return aa({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 vk(e){return aa({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 wk(e){return aa({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 m3(e){return aa({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 g3(e){return aa({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 _3(e){return aa({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 y3(e){return aa({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 v3(e){return aa({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 w3(e){return aa({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 b3(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 Vh(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}const C0=e=>Array.isArray(e);function bk(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 Lv(e,t,n,i){if(typeof t=="function"){const[o,a]=v2(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]=v2(i);t=t(n!==void 0?n:e.custom,o,a)}return t}function Wg(e,t,n){const i=e.getProps();return Lv(i,t,n!==void 0?n:i.custom,e)}const Bv=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Nv=["initial",...Bv],Jh=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ol=new Set(Jh),Fa=e=>e*1e3,Oa=e=>e/1e3,x3={type:"spring",stiffness:500,damping:25,restSpeed:10},M3=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),T3={type:"keyframes",duration:.8},S3={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},k3=(e,{keyframes:t})=>t.length>2?T3:Ol.has(e)?e.startsWith("scale")?M3(t[1]):x3:S3;function E3({when:e,delay:t,delayChildren:n,staggerChildren:i,staggerDirection:o,repeat:a,repeatType:l,repeatDelay:d,from:c,elapsed:h,...w}){return!!Object.keys(w).length}function jv(e,t){return e[t]||e.default||e}const C3={skipAnimations:!1,useManualTiming:!1},P3=e=>e!==null;function Gg(e,{repeat:t,repeatType:n="loop"},i){const o=e.filter(P3),a=t&&n!=="loop"&&t%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const is=e=>e;function A3(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(h){a.has(h)&&(c.schedule(h),e()),h(l)}const c={schedule:(h,w=!1,_=!1)=>{const T=_&&i?t:n;return w&&a.add(h),T.has(h)||T.add(h),h},cancel:h=>{n.delete(h),a.delete(h)},process:h=>{if(l=h,i){o=!0;return}i=!0,[t,n]=[n,t],n.clear(),t.forEach(d),i=!1,o&&(o=!1,c.process(h))}};return c}const km=["read","resolveKeyframes","update","preRender","render","postRender"],$3=40;function xk(e,t){let n=!1,i=!0;const o={delta:0,timestamp:0,isProcessing:!1},a=()=>n=!0,l=km.reduce((x,S)=>(x[S]=A3(a),x),{}),{read:d,resolveKeyframes:c,update:h,preRender:w,render:_,postRender:M}=l,T=()=>{const x=performance.now();n=!1,o.delta=i?1e3/60:Math.max(Math.min(x-o.timestamp,$3),1),o.timestamp=x,o.isProcessing=!0,d.process(o),c.process(o),h.process(o),w.process(o),_.process(o),M.process(o),o.isProcessing=!1,n&&t&&(i=!1,e(T))},F=()=>{n=!0,i=!0,o.isProcessing||e(T)};return{schedule:km.reduce((x,S)=>{const P=l[S];return x[S]=(j,L=!1,N=!1)=>(n||F(),P.schedule(j,L,N)),x},{}),cancel:x=>{for(let S=0;S/^0[^.\s]+$/u.test(e);function I3(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||Mk(e):!0}let P0=is;const Tk=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),Sk=e=>t=>typeof t=="string"&&t.startsWith(e),kk=Sk("--"),F3=Sk("var(--"),Vv=e=>F3(e)?O3.test(e.split("/*")[0].trim()):!1,O3=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,D3=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function z3(e){const t=D3.exec(e);if(!t)return[,];const[,n,i,o]=t;return[`--${n??i}`,o]}function Ek(e,t,n=1){const[i,o]=z3(e);if(!i)return;const a=window.getComputedStyle(t).getPropertyValue(i);if(a){const l=a.trim();return Tk(l)?parseFloat(l):l}return Vv(o)?Ek(o,t,n+1):o}const Pl=(e,t,n)=>n>t?t:ntypeof e=="number",parse:parseFloat,transform:e=>e},wh={...ld,transform:e=>Pl(0,1,e)},Em={...ld,default:1},bh=e=>Math.round(e*1e5)/1e5,Uv=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu,R3=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu,L3=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu;function ep(e){return typeof e=="string"}function B3(e){return e==null}const tp=e=>({test:t=>ep(t)&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),fl=tp("deg"),oa=tp("%"),Rn=tp("px"),N3=tp("vh"),j3=tp("vw"),w2={...oa,parse:e=>oa.parse(e)/100,transform:e=>oa.transform(e*100)},V3=new Set(["width","height","top","left","right","bottom","x","y","translateX","translateY"]),b2=e=>e===ld||e===Rn,x2=(e,t)=>parseFloat(e.split(", ")[t]),M2=(e,t)=>(n,{transform:i})=>{if(i==="none"||!i)return 0;const o=i.match(/^matrix3d\((.+)\)$/u);if(o)return x2(o[1],t);{const a=i.match(/^matrix\((.+)\)$/u);return a?x2(a[1],e):0}},U3=new Set(["x","y","z"]),W3=Jh.filter(e=>!U3.has(e));function G3(e){const t=[];return W3.forEach(n=>{const i=e.getValue(n);i!==void 0&&(t.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),t}const td={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:M2(4,13),y:M2(5,14)};td.translateX=td.x;td.translateY=td.y;const Ck=e=>t=>t.test(e),q3={test:e=>e==="auto",parse:e=>e},Pk=[ld,Rn,oa,fl,j3,N3,q3],T2=e=>Pk.find(Ck(e)),wu=new Set;let A0=!1,$0=!1;function Ak(){if($0){const e=Array.from(wu).filter(i=>i.needsMeasurement),t=new Set(e.map(i=>i.element)),n=new Map;t.forEach(i=>{const o=G3(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)})}$0=!1,A0=!1,wu.forEach(e=>e.complete()),wu.clear()}function $k(){wu.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&($0=!0)})}function H3(){$k(),Ak()}class Wv{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?(wu.add(this),A0||(A0=!0,Fr.read($k),Fr.resolveKeyframes(Ak))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:i,motionValue:o}=this;for(let a=0;an=>!!(ep(n)&&L3.test(n)&&n.startsWith(e)||t&&!B3(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ik=(e,t,n)=>i=>{if(!ep(i))return i;const[o,a,l,d]=i.match(Uv);return{[e]:parseFloat(o),[t]:parseFloat(a),[n]:parseFloat(l),alpha:d!==void 0?parseFloat(d):1}},K3=e=>Pl(0,255,e),_y={...ld,transform:e=>Math.round(K3(e))},_u={test:Gv("rgb","red"),parse:Ik("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:i=1})=>"rgba("+_y.transform(e)+", "+_y.transform(t)+", "+_y.transform(n)+", "+bh(wh.transform(i))+")"};function X3(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 I0={test:Gv("#"),parse:X3,transform:_u.transform},Rc={test:Gv("hsl","hue"),parse:Ik("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:i=1})=>"hsla("+Math.round(e)+", "+oa.transform(bh(t))+", "+oa.transform(bh(n))+", "+bh(wh.transform(i))+")"},ts={test:e=>_u.test(e)||I0.test(e)||Rc.test(e),parse:e=>_u.test(e)?_u.parse(e):Rc.test(e)?Rc.parse(e):I0.parse(e),transform:e=>ep(e)?e:e.hasOwnProperty("red")?_u.transform(e):Rc.transform(e)};function Q3(e){var t,n;return isNaN(e)&&ep(e)&&(((t=e.match(Uv))===null||t===void 0?void 0:t.length)||0)+(((n=e.match(R3))===null||n===void 0?void 0:n.length)||0)>0}const Fk="number",Ok="color",Y3="var",Z3="var(",S2="${}",J3=/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 Wh(e){const t=e.toString(),n=[],i={color:[],number:[],var:[]},o=[];let a=0;const d=t.replace(J3,c=>(ts.test(c)?(i.color.push(a),o.push(Ok),n.push(ts.parse(c))):c.startsWith(Z3)?(i.var.push(a),o.push(Y3),n.push(c)):(i.number.push(a),o.push(Fk),n.push(parseFloat(c))),++a,S2)).split(S2);return{values:n,split:d,indexes:i,types:o}}function Dk(e){return Wh(e).values}function zk(e){const{split:t,types:n}=Wh(e),i=t.length;return o=>{let a="";for(let l=0;ltypeof e=="number"?0:e;function tF(e){const t=Dk(e);return zk(e)(t.map(eF))}const Al={test:Q3,parse:Dk,createTransformer:zk,getAnimatableNone:tF},nF=new Set(["brightness","contrast","saturate","opacity"]);function rF(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[i]=n.match(Uv)||[];if(!i)return e;const o=n.replace(i,"");let a=nF.has(t)?1:0;return i!==n&&(a*=100),t+"("+a+o+")"}const iF=/\b([a-z-]*)\(.*?\)/gu,F0={...Al,getAnimatableNone:e=>{const t=e.match(iF);return t?t.map(rF).join(" "):e}},k2={...ld,transform:Math.round},qv={borderWidth:Rn,borderTopWidth:Rn,borderRightWidth:Rn,borderBottomWidth:Rn,borderLeftWidth:Rn,borderRadius:Rn,radius:Rn,borderTopLeftRadius:Rn,borderTopRightRadius:Rn,borderBottomRightRadius:Rn,borderBottomLeftRadius:Rn,width:Rn,maxWidth:Rn,height:Rn,maxHeight:Rn,size:Rn,top:Rn,right:Rn,bottom:Rn,left:Rn,padding:Rn,paddingTop:Rn,paddingRight:Rn,paddingBottom:Rn,paddingLeft:Rn,margin:Rn,marginTop:Rn,marginRight:Rn,marginBottom:Rn,marginLeft:Rn,rotate:fl,rotateX:fl,rotateY:fl,rotateZ:fl,scale:Em,scaleX:Em,scaleY:Em,scaleZ:Em,skew:fl,skewX:fl,skewY:fl,distance:Rn,translateX:Rn,translateY:Rn,translateZ:Rn,x:Rn,y:Rn,z:Rn,perspective:Rn,transformPerspective:Rn,opacity:wh,originX:w2,originY:w2,originZ:Rn,zIndex:k2,backgroundPositionX:Rn,backgroundPositionY:Rn,fillOpacity:wh,strokeOpacity:wh,numOctaves:k2},sF={...qv,color:ts,backgroundColor:ts,outlineColor:ts,fill:ts,stroke:ts,borderColor:ts,borderTopColor:ts,borderRightColor:ts,borderBottomColor:ts,borderLeftColor:ts,filter:F0,WebkitFilter:F0},Hv=e=>sF[e];function Rk(e,t){let n=Hv(e);return n!==F0&&(n=Al),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const oF=new Set(["auto","none","0"]);function aF(e,t,n){let i=0,o;for(;i{n.getValue(c).set(h)}),this.resolveNoneKeyframes()}}function Bk(e){let t;return()=>(t===void 0&&(t=e()),t)}let Vm;function lF(){Vm=void 0}const Da={now:()=>(Vm===void 0&&Da.set(Vi.isProcessing||C3.useManualTiming?Vi.timestamp:performance.now()),Vm),set:e=>{Vm=e,queueMicrotask(lF)}},E2=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(Al.test(e)||e==="0")&&!e.startsWith("url("));function uF(e){const t=e[0];if(e.length===1)return!0;for(let n=0;ndF?this.resolvedAt:this.createdAt:this.createdAt}get resolved(){return!this._resolved&&!this.hasAttemptedResolve&&H3(),this._resolved}onKeyframesResolved(t,n){this.resolvedAt=Da.now(),this.hasAttemptedResolve=!0;const{name:i,type:o,velocity:a,delay:l,onComplete:d,onUpdate:c,isGenerator:h}=this.options;if(!h&&!cF(t,i,o,a))if(l)this.options.duration=0;else{c?.(Gg(t,this.options,n)),d?.(),this.resolveFinishedPromise();return}const w=this.initPlayback(t,n);w!==!1&&(this._resolved={keyframes:t,finalKeyframe:n,...w},this.onPostResolved())}onPostResolved(){}then(t,n){return this.currentFinishedPromise.then(t,n)}updateFinishedPromise(){this.currentFinishedPromise=new Promise(t=>{this.resolveFinishedPromise=t})}}function jk(e,t){return t?e*(1e3/t):0}const fF=5;function Vk(e,t,n){const i=Math.max(t-fF,0);return jk(n-e(i),t-i)}const yy=.001,hF=.01,pF=10,mF=.05,gF=1;function _F({duration:e=800,bounce:t=.25,velocity:n=0,mass:i=1}){let o,a,l=1-t;l=Pl(mF,gF,l),e=Pl(hF,pF,Oa(e)),l<1?(o=h=>{const w=h*l,_=w*e,M=w-n,T=O0(h,l),F=Math.exp(-_);return yy-M/T*F},a=h=>{const _=h*l*e,M=_*n+n,T=Math.pow(l,2)*Math.pow(h,2)*e,F=Math.exp(-_),C=O0(Math.pow(h,2),l);return(-o(h)+yy>0?-1:1)*((M-T)*F)/C}):(o=h=>{const w=Math.exp(-h*e),_=(h-n)*e+1;return-yy+w*_},a=h=>{const w=Math.exp(-h*e),_=(n-h)*(e*e);return w*_});const d=5/e,c=vF(o,a,d);if(e=Fa(e),isNaN(c))return{stiffness:100,damping:10,duration:e};{const h=Math.pow(c,2)*i;return{stiffness:h,damping:l*2*Math.sqrt(i*h),duration:e}}}const yF=12;function vF(e,t,n){let i=n;for(let o=1;oe[n]!==void 0)}function xF(e){let t={velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1,...e};if(!C2(e,bF)&&C2(e,wF)){const n=_F(e);t={...t,...n,mass:1},t.isResolvedFromDuration=!0}return t}function Uk({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:h,duration:w,velocity:_,isResolvedFromDuration:M}=xF({...i,velocity:-Oa(i.velocity||0)}),T=_||0,F=c/(2*Math.sqrt(d*h)),C=a-o,E=Oa(Math.sqrt(d/h)),x=Math.abs(C)<5;n||(n=x?.01:2),t||(t=x?.005:.5);let S;if(F<1){const P=O0(E,F);S=j=>{const L=Math.exp(-F*E*j);return a-L*((T+F*E*C)/P*Math.sin(P*j)+C*Math.cos(P*j))}}else if(F===1)S=P=>a-Math.exp(-E*P)*(C+(T+E*C)*P);else{const P=E*Math.sqrt(F*F-1);S=j=>{const L=Math.exp(-F*E*j),N=Math.min(P*j,300);return a-L*((T+F*E*C)*Math.sinh(N)+P*C*Math.cosh(N))/P}}return{calculatedDuration:M&&w||null,next:P=>{const j=S(P);if(M)l.done=P>=w;else{let L=0;F<1&&(L=P===0?Fa(T):Vk(S,P,j));const N=Math.abs(L)<=n,W=Math.abs(a-j)<=t;l.done=N&&W}return l.value=l.done?a:j,l}}}function P2({keyframes:e,velocity:t=0,power:n=.8,timeConstant:i=325,bounceDamping:o=10,bounceStiffness:a=500,modifyTarget:l,min:d,max:c,restDelta:h=.5,restSpeed:w}){const _=e[0],M={done:!1,value:_},T=V=>d!==void 0&&Vc,F=V=>d===void 0?c:c===void 0||Math.abs(d-V)-C*Math.exp(-V/i),P=V=>x+S(V),j=V=>{const ce=S(V),ge=P(V);M.done=Math.abs(ce)<=h,M.value=M.done?x:ge};let L,N;const W=V=>{T(M.value)&&(L=V,N=Uk({keyframes:[M.value,F(M.value)],velocity:Vk(P,V,M.value),damping:o,stiffness:a,restDelta:h,restSpeed:w}))};return W(0),{calculatedDuration:null,next:V=>{let ce=!1;return!N&&L===void 0&&(ce=!0,j(V),W(V)),L!==void 0&&V>=L?N.next(V-L):(!ce&&j(V),M)}}}const Wk=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,MF=1e-7,TF=12;function SF(e,t,n,i,o){let a,l,d=0;do l=t+(n-t)/2,a=Wk(l,i,o)-e,a>0?n=l:t=l;while(Math.abs(a)>MF&&++dSF(a,0,1,e,n);return a=>a===0||a===1?a:Wk(o(a),t,i)}const kF=np(.42,0,1,1),EF=np(0,0,.58,1),Gk=np(.42,0,.58,1),CF=e=>Array.isArray(e)&&typeof e[0]!="number",qk=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,Hk=e=>t=>1-e(1-t),Kv=e=>1-Math.sin(Math.acos(e)),Kk=Hk(Kv),PF=qk(Kv),Xk=np(.33,1.53,.69,.99),Xv=Hk(Xk),AF=qk(Xv),$F=e=>(e*=2)<1?.5*Xv(e):.5*(2-Math.pow(2,-10*(e-1))),A2={linear:is,easeIn:kF,easeInOut:Gk,easeOut:EF,circIn:Kv,circInOut:PF,circOut:Kk,backIn:Xv,backInOut:AF,backOut:Xk,anticipate:$F},$2=e=>{if(Array.isArray(e)){P0(e.length===4);const[t,n,i,o]=e;return np(t,n,i,o)}else if(typeof e=="string")return P0(A2[e]!==void 0),A2[e];return e},IF=(e,t)=>n=>t(e(n)),za=(...e)=>e.reduce(IF),Gh=(e,t,n)=>{const i=t-e;return i===0?1:(n-e)/i},ti=(e,t,n)=>e+(t-e)*n;function vy(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 FF({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=vy(c,d,e+1/3),a=vy(c,d,e),l=vy(c,d,e-1/3)}return{red:Math.round(o*255),green:Math.round(a*255),blue:Math.round(l*255),alpha:i}}function bg(e,t){return n=>n>0?t:e}const wy=(e,t,n)=>{const i=e*e,o=n*(t*t-i)+i;return o<0?0:Math.sqrt(o)},OF=[I0,_u,Rc],DF=e=>OF.find(t=>t.test(e));function I2(e){const t=DF(e);if(!t)return!1;let n=t.parse(e);return t===Rc&&(n=FF(n)),n}const F2=(e,t)=>{const n=I2(e),i=I2(t);if(!n||!i)return bg(e,t);const o={...n};return a=>(o.red=wy(n.red,i.red,a),o.green=wy(n.green,i.green,a),o.blue=wy(n.blue,i.blue,a),o.alpha=ti(n.alpha,i.alpha,a),_u.transform(o))},D0=new Set(["none","hidden"]);function zF(e,t){return D0.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function RF(e,t){return n=>ti(e,t,n)}function Qv(e){return typeof e=="number"?RF:typeof e=="string"?Vv(e)?bg:ts.test(e)?F2:NF:Array.isArray(e)?Qk:typeof e=="object"?ts.test(e)?F2:LF:bg}function Qk(e,t){const n=[...e],i=n.length,o=e.map((a,l)=>Qv(a)(a,t[l]));return a=>{for(let l=0;l{for(const a in i)n[a]=i[a](o);return n}}function BF(e,t){var n;const i=[],o={color:0,var:0,number:0};for(let a=0;a{const n=Al.createTransformer(t),i=Wh(e),o=Wh(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?D0.has(e)&&!o.values.length||D0.has(t)&&!i.values.length?zF(e,t):za(Qk(BF(i,o),o.values),n):bg(e,t)};function Yk(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?ti(e,t,n):Qv(e)(e,t)}function jF(e,t,n){const i=[],o=n||Yk,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=jF(t,i,o),d=l.length,c=h=>{let w=0;if(d>1)for(;wc(Pl(e[0],e[a-1],h)):c}function UF(e,t){const n=e[e.length-1];for(let i=1;i<=t;i++){const o=Gh(0,t,i);e.push(ti(n,1,o))}}function WF(e){const t=[0];return UF(t,e.length-1),t}function GF(e,t){return e.map(n=>n*t)}function qF(e,t){return e.map(()=>t||Gk).splice(0,e.length-1)}function xg({duration:e=300,keyframes:t,times:n,ease:i="easeInOut"}){const o=CF(i)?i.map($2):$2(i),a={done:!1,value:t[0]},l=GF(n&&n.length===t.length?n:WF(t),e),d=VF(l,t,{ease:Array.isArray(o)?o:qF(t,o)});return{calculatedDuration:e,next:c=>(a.value=d(c),a.done=c>=e,a)}}const O2=2e4;function HF(e){let t=0;const n=50;let i=e.next(t);for(;!i.done&&t=O2?1/0:t}const KF=e=>{const t=({timestamp:n})=>e(n);return{start:()=>Fr.update(t,!0),stop:()=>Va(t),now:()=>Vi.isProcessing?Vi.timestamp:Da.now()}},XF={decay:P2,inertia:P2,tween:xg,keyframes:xg,spring:Uk},QF=e=>e/100;class Yv extends Nk{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?.KeyframeResolver||Wv,d=(c,h)=>this.onKeyframesResolved(c,h);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=XF[n]||xg;let c,h;d!==xg&&typeof t[0]!="number"&&(c=za(QF,Yk(t[0],t[1])),t=[0,100]);const w=d({...this.options,keyframes:t});a==="mirror"&&(h=d({...this.options,keyframes:[...t].reverse(),velocity:-l})),w.calculatedDuration===null&&(w.calculatedDuration=HF(w));const{calculatedDuration:_}=w,M=_+o,T=M*(i+1)-o;return{generator:w,mirroredGenerator:h,mapPercentToKeyframes:c,calculatedDuration:_,resolvedDuration:M,totalDuration:T}}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:V}=this.options;return{done:!0,value:V[V.length-1]}}const{finalKeyframe:o,generator:a,mirroredGenerator:l,mapPercentToKeyframes:d,keyframes:c,calculatedDuration:h,totalDuration:w,resolvedDuration:_}=i;if(this.startTime===null)return a.next(0);const{delay:M,repeat:T,repeatType:F,repeatDelay:C,onUpdate:E}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-w/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-M*(this.speed>=0?1:-1),S=this.speed>=0?x<0:x>w;this.currentTime=Math.max(x,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=w);let P=this.currentTime,j=a;if(T){const V=Math.min(this.currentTime,w)/_;let ce=Math.floor(V),ge=V%1;!ge&&V>=1&&(ge=1),ge===1&&ce--,ce=Math.min(ce,T+1),!!(ce%2)&&(F==="reverse"?(ge=1-ge,C&&(ge-=C/_)):F==="mirror"&&(j=l)),P=Pl(0,1,ge)*_}const L=S?{done:!1,value:c[0]}:j.next(P);d&&(L.value=d(L.value));let{done:N}=L;!S&&h!==null&&(N=this.speed>=0?this.currentTime>=w:this.currentTime<=0);const W=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return W&&o!==void 0&&(L.value=Gg(c,this.options,o)),E&&E(L.value),W&&this.finish(),L}get duration(){const{resolved:t}=this;return t?Oa(t.calculatedDuration):0}get time(){return Oa(this.currentTime)}set time(t){t=Fa(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=Oa(this.currentTime))}play(){if(this.resolver.isScheduled||this.resolver.resume(),!this._resolved){this.pendingPlayState="running";return}if(this.isStopped)return;const{driver:t=KF,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 Zk=new Set(["opacity","clipPath","filter","transform"]),Jk=e=>Array.isArray(e)&&typeof e[0]=="number";function eE(e){return!!(!e||typeof e=="string"&&e in Zv||Jk(e)||Array.isArray(e)&&e.every(eE))}const uh=([e,t,n,i])=>`cubic-bezier(${e}, ${t}, ${n}, ${i})`,Zv={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:uh([0,.65,.55,1]),circOut:uh([.55,0,1,.45]),backIn:uh([.31,.01,.66,-.59]),backOut:uh([.33,1.53,.69,.99])};function YF(e){return tE(e)||Zv.easeOut}function tE(e){if(e)return Jk(e)?uh(e):Array.isArray(e)?e.map(YF):Zv[e]}function ZF(e,t,n,{delay:i=0,duration:o=300,repeat:a=0,repeatType:l="loop",ease:d,times:c}={}){const h={[t]:n};c&&(h.offset=c);const w=tE(d);return Array.isArray(w)&&(h.easing=w),e.animate(h,{delay:i,duration:o,easing:Array.isArray(w)?"linear":w,fill:"both",iterations:a+1,direction:l==="reverse"?"alternate":"normal"})}const JF=Bk(()=>Object.hasOwnProperty.call(Element.prototype,"animate")),Mg=10,eO=2e4;function tO(e){return e.type==="spring"||!eE(e.ease)}function nO(e,t){const n=new Yv({...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:h,startTime:w}=this.options;if(!(!((i=c.owner)===null||i===void 0)&&i.current))return!1;if(tO(this.options)){const{onComplete:M,onUpdate:T,motionValue:F,element:C,...E}=this.options,x=nO(t,E);t=x.keyframes,t.length===1&&(t[1]=t[0]),o=x.duration,a=x.times,l=x.ease,d="keyframes"}const _=ZF(c.owner.current,h,t,{...this.options,duration:o,times:a,ease:l});return _.startTime=w??this.calcStartTime(),this.pendingTimeline?(_.timeline=this.pendingTimeline,this.pendingTimeline=void 0):_.onfinish=()=>{const{onComplete:M}=this.options;c.set(Gg(t,this.options,n)),M&&M(),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 Oa(n)}get time(){const{resolved:t}=this;if(!t)return 0;const{animation:n}=t;return Oa(n.currentTime||0)}set time(t){const{resolved:n}=this;if(!n)return;const{animation:i}=n;i.currentTime=Fa(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 is;const{animation:i}=n;i.timeline=t,i.onfinish=null}return is}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:h,onUpdate:w,onComplete:_,element:M,...T}=this.options,F=new Yv({...T,keyframes:i,duration:o,type:a,ease:l,times:d,isGenerator:!0}),C=Fa(this.time);h.setWithVelocity(F.sample(C-Mg).value,F.sample(C).value,Mg)}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 JF()&&i&&Zk.has(i)&&n&&n.owner&&n.owner.current instanceof HTMLElement&&!n.owner.getProps().onUpdate&&!o&&a!=="mirror"&&l!==0&&d!=="inertia"}}function rO(e,t){let n;const i=()=>{const{currentTime:o}=t,l=(o===null?0:o.value)/100;n!==l&&e(l),n=l};return Fr.update(i,!0),()=>Va(i)}const iO=Bk(()=>window.ScrollTimeline!==void 0);class sO{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(iO()&&i.attachTimeline)i.attachTimeline(t);else return i.pause(),rO(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 Jv=(e,t,n,i={},o,a,l)=>d=>{const c=jv(i,e)||{},h=c.delay||i.delay||0;let{elapsed:w=0}=i;w=w-Fa(h);let _={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...c,delay:-w,onUpdate:T=>{t.set(T),c.onUpdate&&c.onUpdate(T)},onComplete:()=>{d(),c.onComplete&&c.onComplete(),l&&l()},onStop:l,name:e,motionValue:t,element:a?void 0:o};E3(c)||(_={..._,...k3(e,_)}),_.duration&&(_.duration=Fa(_.duration)),_.repeatDelay&&(_.repeatDelay=Fa(_.repeatDelay)),_.from!==void 0&&(_.keyframes[0]=_.from);let M=!1;if((_.type===!1||_.duration===0&&!_.repeatDelay)&&(_.duration=0,_.delay===0&&(M=!0)),M&&!a&&t.get()!==void 0){const T=Gg(_.keyframes,c);if(T!==void 0)return Fr.update(()=>{_.onUpdate(T),_.onComplete()}),new sO([])}return!a&&D2.supports(_)?new D2(_):new Yv(_)},oO=e=>!!(e&&typeof e=="object"&&e.mix&&e.toValue),aO=e=>C0(e)?e[e.length-1]||0:e;function qg(e,t){e.indexOf(t)===-1&&e.push(t)}function Hg(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}class ew{constructor(){this.subscriptions=[]}add(t){return qg(this.subscriptions,t),()=>Hg(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 nE{constructor(t,n={}){this.version="11.5.4",this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,o=!0)=>{const a=Da.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=Da.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=lO(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 ew);const i=this.events[t].add(n);return t==="change"?()=>{i(),Fr.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=Da.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>z2)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,z2);return jk(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 qh(e,t){return new nE(e,t)}function uO(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,qh(n))}function cO(e,t){const n=Wg(e,t);let{transitionEnd:i={},transition:o={},...a}=n||{};a={...a,...i};for(const l in a){const d=aO(a[l]);uO(e,l,d)}}const Kg=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),dO="framerAppearId",rE="data-"+Kg(dO);function iE(e){return e.props[rE]}function sE(e){if(Ol.has(e))return"transform";if(Zk.has(e))return Kg(e)}class fO extends nE{constructor(){super(...arguments),this.output=[],this.counts=new Map}add(t){const n=sE(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&&(Hg(this.output,n),this.update())}}update(){this.set(this.output.length?this.output.join(", "):"auto")}}const rs=e=>!!(e&&e.getVelocity);function hO(e){return!!(rs(e)&&e.add)}function z0(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 fO("auto"),e.addValue("willChange",i)),hO(i))return i.add(t)}function pO({protectedKeys:e,needsAnimating:t},n){const i=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,i}function oE(e,t,{delay:n=0,transitionOverride:i,type:o}={}){var a;let{transition:l=e.getDefaultTransition(),transitionEnd:d,...c}=t;i&&(l=i);const h=[],w=o&&e.animationState&&e.animationState.getState()[o];for(const _ in c){const M=e.getValue(_,(a=e.latestValues[_])!==null&&a!==void 0?a:null),T=c[_];if(T===void 0||w&&pO(w,_))continue;const F={delay:n,...jv(l||{},_)};let C=!1;if(window.MotionHandoffAnimation){const x=iE(e);if(x){const S=window.MotionHandoffAnimation(x,_,Fr);S!==null&&(F.startTime=S,C=!0)}}M.start(Jv(_,M,T,e.shouldReduceMotion&&Ol.has(_)?{type:!1}:F,e,C,z0(e,_)));const E=M.animation;E&&h.push(E)}return d&&Promise.all(h).then(()=>{Fr.update(()=>{d&&cO(e,d)})}),h}function R0(e,t,n={}){var i;const o=Wg(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(oE(e,o,n)):()=>Promise.resolve(),d=e.variantChildren&&e.variantChildren.size?(h=0)=>{const{delayChildren:w=0,staggerChildren:_,staggerDirection:M}=a;return mO(e,t,w+h,_,M,n)}:()=>Promise.resolve(),{when:c}=a;if(c){const[h,w]=c==="beforeChildren"?[l,d]:[d,l];return h().then(()=>w())}else return Promise.all([l(),d(n.delay)])}function mO(e,t,n=0,i=0,o=1,a){const l=[],d=(e.variantChildren.size-1)*i,c=o===1?(h=0)=>h*i:(h=0)=>d-h*i;return Array.from(e.variantChildren).sort(gO).forEach((h,w)=>{h.notify("AnimationStart",t),l.push(R0(h,t,{...a,delay:n+c(w)}).then(()=>h.notify("AnimationComplete",t)))}),Promise.all(l)}function gO(e,t){return e.sortNodePosition(t)}function _O(e,t,n={}){e.notify("AnimationStart",t);let i;if(Array.isArray(t)){const o=t.map(a=>R0(e,a,n));i=Promise.all(o)}else if(typeof t=="string")i=R0(e,t,n);else{const o=typeof t=="function"?Wg(e,t,n.custom):t;i=Promise.all(oE(e,o,n))}return i.then(()=>{e.notify("AnimationComplete",t)})}const yO=[...Bv].reverse(),vO=Bv.length;function wO(e){return t=>Promise.all(t.map(({animation:n,options:i})=>_O(e,n,i)))}function bO(e){let t=wO(e),n=R2(),i=!0;const o=c=>(h,w)=>{var _;const M=Wg(e,w,c==="exit"?(_=e.presenceContext)===null||_===void 0?void 0:_.custom:void 0);if(M){const{transition:T,transitionEnd:F,...C}=M;h={...h,...C,...F}}return h};function a(c){t=c(e)}function l(c){const h=e.getProps(),w=e.getVariantContext(!0)||{},_=[],M=new Set;let T={},F=1/0;for(let E=0;EF&&j,ce=!1;const ge=Array.isArray(P)?P:[P];let Re=ge.reduce(o(x),{});L===!1&&(Re={});const{prevResolvedValues:oe={}}=S,Se={...oe,...Re},G=Ce=>{V=!0,M.has(Ce)&&(ce=!0,M.delete(Ce)),S.needsAnimating[Ce]=!0;const pt=e.getValue(Ce);pt&&(pt.liveStyle=!1)};for(const Ce in Se){const pt=Re[Ce],Te=oe[Ce];if(T.hasOwnProperty(Ce))continue;let te=!1;C0(pt)&&C0(Te)?te=!bk(pt,Te):te=pt!==Te,te?pt!=null?G(Ce):M.add(Ce):pt!==void 0&&M.has(Ce)?G(Ce):S.protectedKeys[Ce]=!0}S.prevProp=P,S.prevResolvedValues=Re,S.isActive&&(T={...T,...Re}),i&&e.blockInitialAnimation&&(V=!1),V&&(!N||ce)&&_.push(...ge.map(Ce=>({animation:Ce,options:{type:x}})))}if(M.size){const E={};M.forEach(x=>{const S=e.getBaseTarget(x),P=e.getValue(x);P&&(P.liveStyle=!0),E[x]=S??null}),_.push({animation:E})}let C=!!_.length;return i&&(h.initial===!1||h.initial===h.animate)&&!e.manuallyAnimateOnMount&&(C=!1),i=!1,C?t(_):Promise.resolve()}function d(c,h){var w;if(n[c].isActive===h)return Promise.resolve();(w=e.variantChildren)===null||w===void 0||w.forEach(M=>{var T;return(T=M.animationState)===null||T===void 0?void 0:T.setActive(c,h)}),n[c].isActive=h;const _=l(c);for(const M in n)n[M].protectedKeys={};return _}return{animateChanges:l,setActive:d,setAnimateFunction:a,getState:()=>n,reset:()=>{n=R2(),i=!0}}}function xO(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!bk(t,e):!1}function lu(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function R2(){return{animate:lu(!0),whileInView:lu(),whileHover:lu(),whileTap:lu(),whileDrag:lu(),whileFocus:lu(),exit:lu()}}class Dl{constructor(t){this.isMounted=!1,this.node=t}update(){}}class MO extends Dl{constructor(t){super(t),t.animationState||(t.animationState=bO(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();Vh(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 TO=0;class SO extends Dl{constructor(){super(...arguments),this.id=TO++}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 kO={animation:{Feature:MO},exit:{Feature:SO}},aE=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1;function Xg(e,t="page"){return{point:{x:e[`${t}X`],y:e[`${t}Y`]}}}const EO=e=>t=>aE(t)&&e(t,Xg(t));function Aa(e,t,n,i={passive:!0}){return e.addEventListener(t,n,i),()=>e.removeEventListener(t,n)}function Ra(e,t,n,i){return Aa(e,t,EO(n),i)}const L2=(e,t)=>Math.abs(e-t);function CO(e,t){const n=L2(e.x,t.x),i=L2(e.y,t.y);return Math.sqrt(n**2+i**2)}class lE{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 _=xy(this.lastMoveEventInfo,this.history),M=this.startEvent!==null,T=CO(_.offset,{x:0,y:0})>=3;if(!M&&!T)return;const{point:F}=_,{timestamp:C}=Vi;this.history.push({...F,timestamp:C});const{onStart:E,onMove:x}=this.handlers;M||(E&&E(this.lastMoveEvent,_),this.startEvent=this.lastMoveEvent),x&&x(this.lastMoveEvent,_)},this.handlePointerMove=(_,M)=>{this.lastMoveEvent=_,this.lastMoveEventInfo=by(M,this.transformPagePoint),Fr.update(this.updatePoint,!0)},this.handlePointerUp=(_,M)=>{this.end();const{onEnd:T,onSessionEnd:F,resumeAnimation:C}=this.handlers;if(this.dragSnapToOrigin&&C&&C(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const E=xy(_.type==="pointercancel"?this.lastMoveEventInfo:by(M,this.transformPagePoint),this.history);this.startEvent&&T&&T(_,E),F&&F(_,E)},!aE(t))return;this.dragSnapToOrigin=a,this.handlers=n,this.transformPagePoint=i,this.contextWindow=o||window;const l=Xg(t),d=by(l,this.transformPagePoint),{point:c}=d,{timestamp:h}=Vi;this.history=[{...c,timestamp:h}];const{onSessionStart:w}=n;w&&w(t,xy(d,this.history)),this.removeListeners=za(Ra(this.contextWindow,"pointermove",this.handlePointerMove),Ra(this.contextWindow,"pointerup",this.handlePointerUp),Ra(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),Va(this.updatePoint)}}function by(e,t){return t?{point:t(e.point)}:e}function B2(e,t){return{x:e.x-t.x,y:e.y-t.y}}function xy({point:e},t){return{point:e,delta:B2(e,uE(t)),offset:B2(e,PO(t)),velocity:AO(t,.1)}}function PO(e){return e[0]}function uE(e){return e[e.length-1]}function AO(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,i=null;const o=uE(e);for(;n>=0&&(i=e[n],!(o.timestamp-i.timestamp>Fa(t)));)n--;if(!i)return{x:0,y:0};const a=Oa(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 cE(e){let t=null;return()=>{const n=()=>{t=null};return t===null?(t=e,n):!1}}const N2=cE("dragHorizontal"),j2=cE("dragVertical");function dE(e){let t=!1;if(e==="y")t=j2();else if(e==="x")t=N2();else{const n=N2(),i=j2();n&&i?t=()=>{n(),i()}:(n&&n(),i&&i())}return t}function fE(){const e=dE(!0);return e?(e(),!1):!0}function Lc(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}const hE=1e-4,$O=1-hE,IO=1+hE,pE=.01,FO=0-pE,OO=0+pE;function js(e){return e.max-e.min}function DO(e,t,n){return Math.abs(e-t)<=n}function V2(e,t,n,i=.5){e.origin=i,e.originPoint=ti(t.min,t.max,e.origin),e.scale=js(n)/js(t),e.translate=ti(n.min,n.max,e.origin)-e.originPoint,(e.scale>=$O&&e.scale<=IO||isNaN(e.scale))&&(e.scale=1),(e.translate>=FO&&e.translate<=OO||isNaN(e.translate))&&(e.translate=0)}function xh(e,t,n,i){V2(e.x,t.x,n.x,i?i.originX:void 0),V2(e.y,t.y,n.y,i?i.originY:void 0)}function U2(e,t,n){e.min=n.min+t.min,e.max=e.min+js(t)}function zO(e,t,n){U2(e.x,t.x,n.x),U2(e.y,t.y,n.y)}function W2(e,t,n){e.min=t.min-n.min,e.max=e.min+js(t)}function Mh(e,t,n){W2(e.x,t.x,n.x),W2(e.y,t.y,n.y)}function RO(e,{min:t,max:n},i){return t!==void 0&&en&&(e=i?ti(n,e,i.max):Math.min(e,n)),e}function G2(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 LO(e,{top:t,left:n,bottom:i,right:o}){return{x:G2(e.x,n,o),y:G2(e.y,t,i)}}function q2(e,t){let n=t.min-e.min,i=t.max-e.max;return t.max-t.mini?n=Gh(t.min,t.max-i,e.min):i>o&&(n=Gh(e.min,e.max-o,t.min)),Pl(0,1,n)}function jO(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 L0=.35;function VO(e=L0){return e===!1?e=0:e===!0&&(e=L0),{x:H2(e,"left","right"),y:H2(e,"top","bottom")}}function H2(e,t,n){return{min:K2(e,t),max:K2(e,n)}}function K2(e,t){return typeof e=="number"?e:e[t]||0}const X2=()=>({translate:0,scale:1,origin:0,originPoint:0}),Bc=()=>({x:X2(),y:X2()}),Q2=()=>({min:0,max:0}),hi=()=>({x:Q2(),y:Q2()});function eo(e){return[e("x"),e("y")]}function mE({top:e,left:t,right:n,bottom:i}){return{x:{min:t,max:n},y:{min:e,max:i}}}function UO({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function WO(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 My(e){return e===void 0||e===1}function B0({scale:e,scaleX:t,scaleY:n}){return!My(e)||!My(t)||!My(n)}function du(e){return B0(e)||gE(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function gE(e){return Y2(e.x)||Y2(e.y)}function Y2(e){return e&&e!=="0%"}function Tg(e,t,n){const i=e-n,o=t*i;return n+o}function Z2(e,t,n,i,o){return o!==void 0&&(e=Tg(e,o,i)),Tg(e,n,i)+t}function N0(e,t=0,n=1,i,o){e.min=Z2(e.min,t,n,i,o),e.max=Z2(e.max,t,n,i,o)}function _E(e,{x:t,y:n}){N0(e.x,t.translate,t.scale,t.originPoint),N0(e.y,n.translate,n.scale,n.originPoint)}const J2=.999999999999,eM=1.0000000000001;function GO(e,t,n,i=!1){const o=n.length;if(!o)return;t.x=t.y=1;let a,l;for(let d=0;dJ2&&(t.x=1),t.yJ2&&(t.y=1)}function Nc(e,t){e.min=e.min+t,e.max=e.max+t}function tM(e,t,n,i,o=.5){const a=ti(e.min,e.max,o);N0(e,t,n,a,i)}function jc(e,t){tM(e.x,t.x,t.scaleX,t.scale,t.originX),tM(e.y,t.y,t.scaleY,t.scale,t.originY)}function yE(e,t){return mE(WO(e.getBoundingClientRect(),t))}function qO(e,t,n){const i=yE(e,n),{scroll:o}=t;return o&&(Nc(i.x,o.offset.x),Nc(i.y,o.offset.y)),i}const vE=({current:e})=>e?e.ownerDocument.defaultView:null,HO=new WeakMap;class KO{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=hi(),this.visualElement=t}start(t,{snapToCursor:n=!1}={}){const{presenceContext:i}=this.visualElement;if(i&&i.isPresent===!1)return;const o=w=>{const{dragSnapToOrigin:_}=this.getProps();_?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Xg(w,"page").point)},a=(w,_)=>{var M;const{drag:T,dragPropagation:F,onDragStart:C}=this.getProps();if(T&&!F&&(this.openGlobalLock&&this.openGlobalLock(),this.openGlobalLock=dE(T),!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),eo(x=>{let S=this.getAxisMotionValue(x).get()||0;if(oa.test(S)){const{projection:P}=this.visualElement;if(P&&P.layout){const j=P.layout.layoutBox[x];j&&(S=js(j)*(parseFloat(S)/100))}}this.originPoint[x]=S}),C&&Fr.postRender(()=>C(w,_)),(M=this.removeWillChange)===null||M===void 0||M.call(this),this.removeWillChange=z0(this.visualElement,"transform");const{animationState:E}=this.visualElement;E&&E.setActive("whileDrag",!0)},l=(w,_)=>{const{dragPropagation:M,dragDirectionLock:T,onDirectionLock:F,onDrag:C}=this.getProps();if(!M&&!this.openGlobalLock)return;const{offset:E}=_;if(T&&this.currentDirection===null){this.currentDirection=XO(E),this.currentDirection!==null&&F&&F(this.currentDirection);return}this.updateAxis("x",_.point,E),this.updateAxis("y",_.point,E),this.visualElement.render(),C&&C(w,_)},d=(w,_)=>this.stop(w,_),c=()=>eo(w=>{var _;return this.getAnimationState(w)==="paused"&&((_=this.getAxisMotionValue(w).animation)===null||_===void 0?void 0:_.play())}),{dragSnapToOrigin:h}=this.getProps();this.panSession=new lE(t,{onSessionStart:o,onStart:a,onMove:l,onSessionEnd:d,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:h,contextWindow:vE(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&&Fr.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||!Cm(t,o,this.currentDirection))return;const a=this.getAxisMotionValue(t);let l=this.originPoint[t]+i[t];this.constraints&&this.constraints[t]&&(l=RO(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&&Lc(n)?this.constraints||(this.constraints=this.resolveRefConstraints()):n&&o?this.constraints=LO(o.layoutBox,n):this.constraints=!1,this.elastic=VO(i),a!==this.constraints&&o&&this.constraints&&!this.hasMutatedConstraints&&eo(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=jO(o.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!Lc(t))return!1;const i=t.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;const a=qO(i,o.root,this.visualElement.getTransformPagePoint());let l=BO(o.layout.layoutBox,a);if(n){const d=n(UO(l));this.hasMutatedConstraints=!!d,d&&(l=mE(d))}return l}startAnimation(t){const{drag:n,dragMomentum:i,dragElastic:o,dragTransition:a,dragSnapToOrigin:l,onDragTransitionEnd:d}=this.getProps(),c=this.constraints||{},h=eo(w=>{if(!Cm(w,n,this.currentDirection))return;let _=c&&c[w]||{};l&&(_={min:0,max:0});const M=o?200:1e6,T=o?40:1e7,F={type:"inertia",velocity:i?t[w]:0,bounceStiffness:M,bounceDamping:T,timeConstant:750,restDelta:1,restSpeed:10,...a,..._};return this.startAxisValueAnimation(w,F)});return Promise.all(h).then(d)}startAxisValueAnimation(t,n){const i=this.getAxisMotionValue(t);return i.start(Jv(t,i,0,n,this.visualElement,!1,z0(this.visualElement,t)))}stopAnimation(){eo(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){eo(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){eo(n=>{const{drag:i}=this.getProps();if(!Cm(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]-ti(l,d,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!Lc(n)||!i||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};eo(l=>{const d=this.getAxisMotionValue(l);if(d&&this.constraints!==!1){const c=d.get();o[l]=NO({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(),eo(l=>{if(!Cm(l,t,null))return;const d=this.getAxisMotionValue(l),{min:c,max:h}=this.constraints[l];d.set(ti(c,h,o[l]))})}addListeners(){if(!this.visualElement.current)return;HO.set(this.visualElement,this);const t=this.visualElement.current,n=Ra(t,"pointerdown",c=>{const{drag:h,dragListener:w=!0}=this.getProps();h&&w&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();Lc(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()),Fr.read(i);const l=Aa(window,"resize",()=>this.scalePositionWithinConstraints()),d=o.addEventListener("didUpdate",({delta:c,hasLayoutChanged:h})=>{this.isDragging&&h&&(eo(w=>{const _=this.getAxisMotionValue(w);_&&(this.originPoint[w]+=c[w].translate,_.set(_.get()+c[w].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=L0,dragMomentum:d=!0}=t;return{...t,drag:n,dragDirectionLock:i,dragPropagation:o,dragConstraints:a,dragElastic:l,dragMomentum:d}}}function Cm(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function XO(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class QO extends Dl{constructor(t){super(t),this.removeGroupControls=is,this.removeListeners=is,this.controls=new KO(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||is}unmount(){this.removeGroupControls(),this.removeListeners()}}const nM=e=>(t,n)=>{e&&Fr.postRender(()=>e(t,n))};class YO extends Dl{constructor(){super(...arguments),this.removePointerDownListener=is}onPointerDown(t){this.session=new lE(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:vE(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:i,onPanEnd:o}=this.node.getProps();return{onSessionStart:nM(t),onStart:nM(n),onMove:i,onEnd:(a,l)=>{delete this.session,o&&Fr.postRender(()=>o(a,l))}}}mount(){this.removePointerDownListener=Ra(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 tw=Yt.createContext(null);function ZO(){const e=Yt.useContext(tw);if(e===null)return[!0,null];const{isPresent:t,onExitComplete:n,register:i}=e,o=Yt.useId();Yt.useEffect(()=>i(o),[]);const a=Yt.useCallback(()=>n&&n(o),[o,n]);return!t&&n?[!1,a]:[!0]}const wE=Yt.createContext({}),bE=Yt.createContext({}),Um={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function rM(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const rh={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(Rn.test(e))e=parseFloat(e);else return e;const n=rM(e,t.target.x),i=rM(e,t.target.y);return`${n}% ${i}%`}},JO={correct:(e,{treeScale:t,projectionDelta:n})=>{const i=e,o=Al.parse(e);if(o.length>5)return i;const a=Al.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 h=ti(d,c,.5);return typeof o[2+l]=="number"&&(o[2+l]/=h),typeof o[3+l]=="number"&&(o[3+l]/=h),a(o)}},Sg={};function eD(e){Object.assign(Sg,e)}const{schedule:nw,cancel:lR}=xk(queueMicrotask,!1);class tD extends Yt.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:i,layoutId:o}=this.props,{projection:a}=t;eD(nD),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()})),Um.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()||Fr.postRender(()=>{const d=l.getStack();(!d||!d.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),nw.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 xE(e){const[t,n]=ZO(),i=Yt.useContext(wE);return Xt.jsx(tD,{...e,layoutGroup:i,switchLayoutGroup:Yt.useContext(bE),isPresent:t,safeToRemove:n})}const nD={borderRadius:{...rh,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:rh,borderTopRightRadius:rh,borderBottomLeftRadius:rh,borderBottomRightRadius:rh,boxShadow:JO},ME=["TopLeft","TopRight","BottomLeft","BottomRight"],rD=ME.length,iM=e=>typeof e=="string"?parseFloat(e):e,sM=e=>typeof e=="number"||Rn.test(e);function iD(e,t,n,i,o,a){o?(e.opacity=ti(0,n.opacity!==void 0?n.opacity:1,sD(i)),e.opacityExit=ti(t.opacity!==void 0?t.opacity:1,0,oD(i))):a&&(e.opacity=ti(t.opacity!==void 0?t.opacity:1,n.opacity!==void 0?n.opacity:1,i));for(let l=0;lit?1:n(Gh(e,t,i))}function aM(e,t){e.min=t.min,e.max=t.max}function Js(e,t){aM(e.x,t.x),aM(e.y,t.y)}function lM(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function uM(e,t,n,i,o){return e-=t,e=Tg(e,1/n,i),o!==void 0&&(e=Tg(e,1/o,i)),e}function aD(e,t=0,n=1,i=.5,o,a=e,l=e){if(oa.test(t)&&(t=parseFloat(t),t=ti(l.min,l.max,t/100)-l.min),typeof t!="number")return;let d=ti(a.min,a.max,i);e===a&&(d-=t),e.min=uM(e.min,t,n,d,o),e.max=uM(e.max,t,n,d,o)}function cM(e,t,[n,i,o],a,l){aD(e,t[n],t[i],t[o],t.scale,a,l)}const lD=["x","scaleX","originX"],uD=["y","scaleY","originY"];function dM(e,t,n,i){cM(e.x,t,lD,n?n.x:void 0,i?i.x:void 0),cM(e.y,t,uD,n?n.y:void 0,i?i.y:void 0)}function fM(e){return e.translate===0&&e.scale===1}function SE(e){return fM(e.x)&&fM(e.y)}function hM(e,t){return e.min===t.min&&e.max===t.max}function cD(e,t){return hM(e.x,t.x)&&hM(e.y,t.y)}function pM(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function kE(e,t){return pM(e.x,t.x)&&pM(e.y,t.y)}function mM(e){return js(e.x)/js(e.y)}function gM(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class dD{constructor(){this.members=[]}add(t){qg(this.members,t),t.scheduleRender()}remove(t){if(Hg(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 fD(e,t,n){let i="";const o=e.x.translate/t.x,a=e.y.translate/t.y,l=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:h,rotate:w,rotateX:_,rotateY:M,skewX:T,skewY:F}=n;h&&(i=`perspective(${h}px) ${i}`),w&&(i+=`rotate(${w}deg) `),_&&(i+=`rotateX(${_}deg) `),M&&(i+=`rotateY(${M}deg) `),T&&(i+=`skewX(${T}deg) `),F&&(i+=`skewY(${F}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 hD=(e,t)=>e.depth-t.depth;class pD{constructor(){this.children=[],this.isDirty=!1}add(t){qg(this.children,t),this.isDirty=!0}remove(t){Hg(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(hD),this.isDirty=!1,this.children.forEach(t)}}function Wm(e){const t=rs(e)?e.get():e;return oO(t)?t.toValue():t}function mD(e,t){const n=Da.now(),i=({timestamp:o})=>{const a=o-n;a>=t&&(Va(i),e(a-t))};return Fr.read(i,!0),()=>Va(i)}function gD(e){return e instanceof SVGElement&&e.tagName!=="svg"}function _D(e,t,n){const i=rs(e)?e:qh(e);return i.start(Jv("",i,t,n)),i.animation}const fu={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0},ch=typeof window<"u"&&window.MotionDebug!==void 0,Ty=["","X","Y","Z"],yD={visibility:"hidden"},_M=1e3;let vD=0;function Sy(e,t,n,i){const{latestValues:o}=t;o[e]&&(n[e]=o[e],t.setStaticValue(e,0),i&&(i[e]=0))}function EE(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=iE(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:o,layoutId:a}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",Fr,!(o||a))}const{parent:i}=e;i&&!i.hasCheckedOptimisedAppear&&EE(i)}function CE({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:i,resetTransform:o}){return class{constructor(l={},d=t?.()){this.id=vD++,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,ch&&(fu.totalNodes=fu.resolvedTargetDeltas=fu.recalculatedProjection=0),this.nodes.forEach(xD),this.nodes.forEach(ED),this.nodes.forEach(CD),this.nodes.forEach(MD),ch&&window.MotionDebug.record(fu)},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,_&&_(),_=mD(M,250),Um.hasAnimatedSinceResize&&(Um.hasAnimatedSinceResize=!1,this.nodes.forEach(vM))})}c&&this.root.registerSharedNode(c,this),this.options.animate!==!1&&w&&(c||h)&&this.addEventListener("didUpdate",({delta:_,hasLayoutChanged:M,hasRelativeTargetChanged:T,layout:F})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const C=this.options.transition||w.getDefaultTransition()||FD,{onLayoutAnimationStart:E,onLayoutAnimationComplete:x}=w.getProps(),S=!this.targetLayout||!kE(this.targetLayout,F)||T,P=!M&&T;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||P||M&&(S||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(_,P);const j={...jv(C,"layout"),onPlay:E,onComplete:x};(w.shouldReduceMotion||this.options.layoutRoot)&&(j.delay=0,j.type=!1),this.startAnimation(j)}else M||vM(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=F})}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,Va(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(PD),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&&EE(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let w=0;w{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 L=j/1e3;wM(_.x,l.x,L),wM(_.y,l.y,L),this.setTargetDelta(_),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Mh(M,this.layout.layoutBox,this.relativeParent.layout.layoutBox),$D(this.relativeTarget,this.relativeTargetOrigin,M,L),P&&cD(this.relativeTarget,P)&&(this.isProjectionDirty=!1),P||(P=hi()),Js(P,this.relativeTarget)),C&&(this.animationValues=w,iD(w,h,this.latestValues,L,S,x)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=L},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&&(Va(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Fr.update(()=>{Um.hasAnimatedSinceResize=!0,this.currentAnimation=_D(0,_M,{...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(_M),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:d,target:c,layout:h,latestValues:w}=l;if(!(!d||!c||!h)){if(this!==l&&this.layout&&h&&PE(this.options.animationType,this.layout.layoutBox,h.layoutBox)){c=this.target||hi();const _=js(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+_;const M=js(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+M}Js(d,c),jc(d,w),xh(this.projectionDeltaWithTransform,this.layoutCorrected,d,w)}}registerSharedNode(l,d){this.sharedNodes.has(l)||this.sharedNodes.set(l,new dD),this.sharedNodes.get(l).add(d);const h=d.options.initialPromotionConfig;d.promote({transition:h?h.transition:void 0,preserveFollowOpacity:h&&h.shouldPreserveFollowOpacity?h.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 h=this.getStack();h&&h.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 h={};c.z&&Sy("z",l,h,this.animationValues);for(let w=0;w{var d;return(d=l.currentAnimation)===null||d===void 0?void 0:d.stop()}),this.root.nodes.forEach(yM),this.root.sharedNodes.clear()}}}function wD(e){e.updateLayout()}function bD(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"?eo(_=>{const M=l?n.measuredBox[_]:n.layoutBox[_],T=js(M);M.min=i[_].min,M.max=M.min+T}):PE(a,n.layoutBox,i)&&eo(_=>{const M=l?n.measuredBox[_]:n.layoutBox[_],T=js(i[_]);M.max=M.min+T,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[_].max=e.relativeTarget[_].min+T)});const d=Bc();xh(d,i,n.layoutBox);const c=Bc();l?xh(c,e.applyTransform(o,!0),n.measuredBox):xh(c,i,n.layoutBox);const h=!SE(d);let w=!1;if(!e.resumeFrom){const _=e.getClosestProjectingParent();if(_&&!_.resumeFrom){const{snapshot:M,layout:T}=_;if(M&&T){const F=hi();Mh(F,n.layoutBox,M.layoutBox);const C=hi();Mh(C,i,T.layoutBox),kE(F,C)||(w=!0),_.options.layoutRoot&&(e.relativeTarget=C,e.relativeTargetOrigin=F,e.relativeParent=_)}}}e.notifyListeners("didUpdate",{layout:i,snapshot:n,delta:c,layoutDelta:d,hasLayoutChanged:h,hasRelativeTargetChanged:w})}else if(e.isLead()){const{onExitComplete:i}=e.options;i&&i()}e.options.transition=void 0}function xD(e){ch&&fu.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 MD(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function TD(e){e.clearSnapshot()}function yM(e){e.clearMeasurements()}function SD(e){e.isLayoutDirty=!1}function kD(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function vM(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function ED(e){e.resolveTargetDelta()}function CD(e){e.calcProjection()}function PD(e){e.resetSkewAndRotation()}function AD(e){e.removeLeadSnapshot()}function wM(e,t,n){e.translate=ti(t.translate,0,n),e.scale=ti(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function bM(e,t,n,i){e.min=ti(t.min,n.min,i),e.max=ti(t.max,n.max,i)}function $D(e,t,n,i){bM(e.x,t.x,n.x,i),bM(e.y,t.y,n.y,i)}function ID(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const FD={duration:.45,ease:[.4,0,.1,1]},xM=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),MM=xM("applewebkit/")&&!xM("chrome/")?Math.round:is;function TM(e){e.min=MM(e.min),e.max=MM(e.max)}function OD(e){TM(e.x),TM(e.y)}function PE(e,t,n){return e==="position"||e==="preserve-aspect"&&!DO(mM(t),mM(n),.2)}function DD(e){var t;return e!==e.root&&((t=e.scroll)===null||t===void 0?void 0:t.wasRoot)}const zD=CE({attachResizeListener:(e,t)=>Aa(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ky={current:void 0},AE=CE({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!ky.current){const e=new zD({});e.mount(window),e.setOptions({layoutScroll:!0}),ky.current=e}return ky.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),RD={pan:{Feature:YO},drag:{Feature:QO,ProjectionNode:AE,MeasureLayout:xE}};function SM(e,t){const n=t?"pointerenter":"pointerleave",i=t?"onHoverStart":"onHoverEnd",o=(a,l)=>{if(a.pointerType==="touch"||fE())return;const d=e.getProps();e.animationState&&d.whileHover&&e.animationState.setActive("whileHover",t);const c=d[i];c&&Fr.postRender(()=>c(a,l))};return Ra(e.current,n,o,{passive:!e.getProps()[i]})}class LD extends Dl{mount(){this.unmount=za(SM(this.node,!0),SM(this.node,!1))}unmount(){}}class BD extends Dl{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=za(Aa(this.node.current,"focus",()=>this.onFocus()),Aa(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}const $E=(e,t)=>t?e===t?!0:$E(e,t.parentElement):!1;function Ey(e,t){if(!t)return;const n=new PointerEvent("pointer"+e);t(n,Xg(n))}class ND extends Dl{constructor(){super(...arguments),this.removeStartListeners=is,this.removeEndListeners=is,this.removeAccessibleListeners=is,this.startPointerPress=(t,n)=>{if(this.isPressing)return;this.removeEndListeners();const i=this.node.getProps(),a=Ra(window,"pointerup",(d,c)=>{if(!this.checkPressEnd())return;const{onTap:h,onTapCancel:w,globalTapTarget:_}=this.node.getProps(),M=!_&&!$E(this.node.current,d.target)?w:h;M&&Fr.update(()=>M(d,c))},{passive:!(i.onTap||i.onPointerUp)}),l=Ra(window,"pointercancel",(d,c)=>this.cancelPress(d,c),{passive:!(i.onTapCancel||i.onPointerCancel)});this.removeEndListeners=za(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()||Ey("up",(c,h)=>{const{onTap:w}=this.node.getProps();w&&Fr.postRender(()=>w(c,h))})};this.removeEndListeners(),this.removeEndListeners=Aa(this.node.current,"keyup",l),Ey("down",(d,c)=>{this.startPress(d,c)})},n=Aa(this.node.current,"keydown",t),i=()=>{this.isPressing&&Ey("cancel",(a,l)=>this.cancelPress(a,l))},o=Aa(this.node.current,"blur",i);this.removeAccessibleListeners=za(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&&Fr.postRender(()=>i(t,n))}checkPressEnd(){return this.removeEndListeners(),this.isPressing=!1,this.node.getProps().whileTap&&this.node.animationState&&this.node.animationState.setActive("whileTap",!1),!fE()}cancelPress(t,n){if(!this.checkPressEnd())return;const{onTapCancel:i}=this.node.getProps();i&&Fr.postRender(()=>i(t,n))}mount(){const t=this.node.getProps(),n=Ra(t.globalTapTarget?window:this.node.current,"pointerdown",this.startPointerPress,{passive:!(t.onTapStart||t.onPointerStart)}),i=Aa(this.node.current,"focus",this.startAccessiblePress);this.removeStartListeners=za(n,i)}unmount(){this.removeStartListeners(),this.removeEndListeners(),this.removeAccessibleListeners()}}const j0=new WeakMap,Cy=new WeakMap,jD=e=>{const t=j0.get(e.target);t&&t(e)},VD=e=>{e.forEach(jD)};function UD({root:e,...t}){const n=e||document;Cy.has(n)||Cy.set(n,{});const i=Cy.get(n),o=JSON.stringify(t);return i[o]||(i[o]=new IntersectionObserver(VD,{root:e,...t})),i[o]}function WD(e,t,n){const i=UD(t);return j0.set(e,n),i.observe(e),()=>{j0.delete(e),i.unobserve(e)}}const GD={some:0,all:1};class qD extends Dl{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:GD[o]},d=c=>{const{isIntersecting:h}=c;if(this.isInView===h||(this.isInView=h,a&&!h&&this.hasEnteredView))return;h&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",h);const{onViewportEnter:w,onViewportLeave:_}=this.node.getProps(),M=h?w:_;M&&M(c)};return WD(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(HD(t,n))&&this.startObserver()}unmount(){}}function HD({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const KD={inView:{Feature:qD},tap:{Feature:ND},focus:{Feature:BD},hover:{Feature:LD}},XD={layout:{ProjectionNode:AE,MeasureLayout:xE}},IE=Yt.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"}),Qg=Yt.createContext({}),rw=typeof window<"u",QD=rw?Yt.useLayoutEffect:Yt.useEffect,FE=Yt.createContext({strict:!1});let kM=!1;function YD(e,t,n,i,o){var a;const{visualElement:l}=Yt.useContext(Qg),d=Yt.useContext(FE),c=Yt.useContext(tw),h=Yt.useContext(IE).reducedMotion,w=Yt.useRef();i=i||d.renderer,!w.current&&i&&(w.current=i(e,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:h}));const _=w.current,M=Yt.useContext(bE);_&&!_.projection&&o&&(_.type==="html"||_.type==="svg")&&JD(w.current,n,o,M),Yt.useInsertionEffect(()=>{_&&_.update(n,c)});const T=n[rE],F=Yt.useRef(!!T&&!window.MotionHandoffIsComplete&&((a=window.MotionHasOptimisedAnimation)===null||a===void 0?void 0:a.call(window,T)));return QD(()=>{_&&(_.updateFeatures(),nw.render(_.render),F.current&&_.animationState&&_.animationState.animateChanges())}),Yt.useEffect(()=>{_&&(!F.current&&_.animationState&&_.animationState.animateChanges(),F.current=!1,kM||(kM=!0,queueMicrotask(ZD)))}),_}function ZD(){window.MotionHandoffIsComplete=!0}function JD(e,t,n,i){const{layoutId:o,layout:a,drag:l,dragConstraints:d,layoutScroll:c,layoutRoot:h}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:OE(e.parent)),e.projection.setOptions({layoutId:o,layout:a,alwaysMeasureLayout:!!l||d&&Lc(d),visualElement:e,animationType:typeof a=="string"?a:"both",initialPromotionConfig:i,layoutScroll:c,layoutRoot:h})}function OE(e){if(e)return e.options.allowProjection!==!1?e.projection:OE(e.parent)}function ez(e,t,n){return Yt.useCallback(i=>{i&&e.mount&&e.mount(i),t&&(i?t.mount(i):t.unmount()),n&&(typeof n=="function"?n(i):Lc(n)&&(n.current=i))},[t])}function Yg(e){return Vh(e.animate)||Nv.some(t=>Uh(e[t]))}function DE(e){return!!(Yg(e)||e.variants)}function tz(e,t){if(Yg(e)){const{initial:n,animate:i}=e;return{initial:n===!1||Uh(n)?n:void 0,animate:Uh(i)?i:void 0}}return e.inherit!==!1?t:{}}function nz(e){const{initial:t,animate:n}=tz(e,Yt.useContext(Qg));return Yt.useMemo(()=>({initial:t,animate:n}),[EM(t),EM(n)])}function EM(e){return Array.isArray(e)?e.join(" "):e}const CM={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"]},nd={};for(const e in CM)nd[e]={isEnabled:t=>CM[e].some(n=>!!t[n])};function rz(e){for(const t in e)nd[t]={...nd[t],...e[t]}}const iz=Symbol.for("motionComponentSymbol");function sz({preloadedFeatures:e,createVisualElement:t,useRender:n,useVisualState:i,Component:o}){e&&rz(e);function a(d,c){let h;const w={...Yt.useContext(IE),...d,layoutId:oz(d)},{isStatic:_}=w,M=nz(d),T=i(d,_);if(!_&&rw){az();const F=lz(w);h=F.MeasureLayout,M.visualElement=YD(o,T,w,t,F.ProjectionNode)}return Xt.jsxs(Qg.Provider,{value:M,children:[h&&M.visualElement?Xt.jsx(h,{visualElement:M.visualElement,...w}):null,n(o,d,ez(T,M.visualElement,c),T,_,M.visualElement)]})}const l=Yt.forwardRef(a);return l[iz]=o,l}function oz({layoutId:e}){const t=Yt.useContext(wE).id;return t&&e!==void 0?t+"-"+e:e}function az(e,t){Yt.useContext(FE).strict}function lz(e){const{drag:t,layout:n}=nd;if(!t&&!n)return{};const i={...t,...n};return{MeasureLayout:t?.isEnabled(e)||n?.isEnabled(e)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}const uz=["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 iw(e){return typeof e!="string"||e.includes("-")?!1:!!(uz.indexOf(e)>-1||/[A-Z]/u.test(e))}function zE(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 RE=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 LE(e,t,n,i){zE(e,t,void 0,i);for(const o in t.attrs)e.setAttribute(RE.has(o)?o:Kg(o),t.attrs[o])}function BE(e,{layout:t,layoutId:n}){return Ol.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Sg[e]||e==="opacity")}function sw(e,t,n){var i;const{style:o}=e,a={};for(const l in o)(rs(o[l])||t.style&&rs(t.style[l])||BE(l,e)||((i=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 NE(e,t,n){const i=sw(e,t,n);for(const o in e)if(rs(e[o])||rs(t[o])){const a=Jh.indexOf(o)!==-1?"attr"+o.charAt(0).toUpperCase()+o.substring(1):o;i[a]=e[o]}return i}function cz(e){const t=Yt.useRef(null);return t.current===null&&(t.current=e()),t.current}function dz({applyWillChange:e=!1,scrapeMotionValuesFromProps:t,createRenderState:n,onMount:i},o,a,l,d){const c={latestValues:hz(o,a,l,d?!1:e,t),renderState:n()};return i&&(c.mount=h=>i(o,h,c)),c}const jE=e=>(t,n)=>{const i=Yt.useContext(Qg),o=Yt.useContext(tw),a=()=>dz(e,t,i,o,n);return n?a():cz(a)};function fz(e,t){const n=sE(t);n&&qg(e,n)}function PM(e,t,n){const i=Array.isArray(t)?t:[t];for(let o=0;o{for(const S in E){let P=E[S];if(Array.isArray(P)){const j=F?P.length-1:0;P=P[j]}P!==null&&(l[S]=P)}for(const S in x)l[S]=x[S]}),c&&(_&&w!==!1&&!Vh(_)&&PM(e,_,E=>{for(const x in E)fz(d,x)}),d.length&&(l.willChange=d.join(","))),l}const ow=()=>({style:{},transform:{},transformOrigin:{},vars:{}}),VE=()=>({...ow(),attrs:{}}),UE=(e,t)=>t&&typeof e=="number"?t.transform(e):e,pz={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},mz=Jh.length;function gz(e,t,n){let i="",o=!0;for(let a=0;atypeof e=="string"&&e.toLowerCase()==="svg",bz={useVisualState:jE({scrapeMotionValuesFromProps:NE,createRenderState:VE,onMount:(e,t,{renderState:n,latestValues:i})=>{Fr.read(()=>{try{n.dimensions=typeof t.getBBox=="function"?t.getBBox():t.getBoundingClientRect()}catch{n.dimensions={x:0,y:0,width:0,height:0}}}),Fr.render(()=>{lw(n,i,uw(t.tagName),e.transformTemplate),LE(t,n)})}})},xz={useVisualState:jE({applyWillChange:!0,scrapeMotionValuesFromProps:sw,createRenderState:ow})};function WE(e,t,n){for(const i in t)!rs(t[i])&&!BE(i,n)&&(e[i]=t[i])}function Mz({transformTemplate:e},t){return Yt.useMemo(()=>{const n=ow();return aw(n,t,e),Object.assign({},n.vars,n.style)},[t])}function Tz(e,t){const n=e.style||{},i={};return WE(i,n,e),Object.assign(i,Mz(e,t)),i}function Sz(e,t){const n={},i=Tz(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 kz=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 kg(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||kz.has(e)}let GE=e=>!kg(e);function Ez(e){e&&(GE=t=>t.startsWith("on")?!kg(t):e(t))}try{Ez(require("@emotion/is-prop-valid").default)}catch{}function Cz(e,t,n){const i={};for(const o in e)o==="values"&&typeof e.values=="object"||(GE(o)||n===!0&&kg(o)||!t&&!kg(o)||e.draggable&&o.startsWith("onDrag"))&&(i[o]=e[o]);return i}function Pz(e,t,n,i){const o=Yt.useMemo(()=>{const a=VE();return lw(a,t,uw(i),e.transformTemplate),{...a.attrs,style:{...a.style}}},[t]);if(e.style){const a={};WE(a,e.style,e),o.style={...a,...o.style}}return o}function Az(e=!1){return(n,i,o,{latestValues:a},l)=>{const c=(iw(n)?Pz:Sz)(i,a,l,n),h=Cz(i,typeof n=="string",e),w=n!==Yt.Fragment?{...h,...c,ref:o}:{},{children:_}=i,M=Yt.useMemo(()=>rs(_)?_.get():_,[_]);return Yt.createElement(n,{...w,children:M})}}function $z(e,t){return function(i,{forwardMotionProps:o}={forwardMotionProps:!1}){const l={...iw(i)?bz:xz,preloadedFeatures:e,useRender:Az(o),createVisualElement:t,Component:i};return sz(l)}}const V0={current:null},qE={current:!1};function Iz(){if(qE.current=!0,!!rw)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>V0.current=e.matches;e.addListener(t),t()}else V0.current=!1}function Fz(e,t,n){for(const i in t){const o=t[i],a=n[i];if(rs(o))e.addValue(i,o);else if(rs(a))e.addValue(i,qh(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,qh(l!==void 0?l:o,{owner:e}))}}for(const i in n)t[i]===void 0&&e.removeValue(i);return t}const $M=new WeakMap,Oz=[...Pk,ts,Al],Dz=e=>Oz.find(Ck(e)),IM=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"],zz=Nv.length;class Rz{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=Wv,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,Fr.render(this.render,!1,!0))};const{latestValues:c,renderState:h}=l;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=h,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=Yg(n),this.isVariantNode=DE(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:w,..._}=this.scrapeMotionValuesFromProps(n,{},this);for(const M in _){const T=_[M];c[M]!==void 0&&rs(T)&&T.set(c[M],!1)}}mount(t){this.current=t,$M.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)),qE.current||Iz(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:V0.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){$M.delete(this.current),this.projection&&this.projection.unmount(),Va(this.notifyUpdate),Va(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=Ol.has(t),o=n.on("change",d=>{this.latestValues[t]=d,this.props.onUpdate&&Fr.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 nd){const n=nd[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):hi()}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=qh(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"&&(Tk(o)||Mk(o))?o=parseFloat(o):!Dz(o)&&Al.test(n)&&(o=Rk(t,n)),this.setBaseTarget(t,rs(o)?o.get():o)),rs(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=Lv(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&&!rs(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 ew),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}}class HE extends Rz{constructor(){super(...arguments),this.KeyframeResolver=Lk}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 Lz(e){return window.getComputedStyle(e)}class Bz extends HE{constructor(){super(...arguments),this.type="html",this.applyWillChange=!0,this.renderInstance=zE}readValueFromInstance(t,n){if(Ol.has(n)){const i=Hv(n);return i&&i.default||0}else{const i=Lz(t),o=(kk(n)?i.getPropertyValue(n):i[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return yE(t,n)}build(t,n,i){aw(t,n,i.transformTemplate)}scrapeMotionValuesFromProps(t,n,i){return sw(t,n,i)}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;rs(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Nz extends HE{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=hi}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Ol.has(n)){const i=Hv(n);return i&&i.default||0}return n=RE.has(n)?n:Kg(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,i){return NE(t,n,i)}build(t,n,i){lw(t,n,this.isSVGTag,i.transformTemplate)}renderInstance(t,n,i,o){LE(t,n,i,o)}mount(t){this.isSVGTag=uw(t.tagName),super.mount(t)}}const jz=(e,t)=>iw(e)?new Nz(t):new Bz(t,{allowProjection:e!==Yt.Fragment}),Vz=$z({...kO,...KD,...RD,...XD},jz),ta=b3(Vz);function Uz(){const e=s3(()=>Ia.images.reverse().toArray()),[t,n]=Yt.useState(null),[i,o]=Yt.useState([]),[a,l]=Yt.useState(!1),[d,c]=Yt.useState(null),[h,w]=Yt.useState(!1),_=Yt.useMemo(()=>e?.filter(P=>P.processedFile instanceof File).length||0,[e]),M=()=>{i.length===e?.length?o([]):o(e?.map(P=>P.id).filter(P=>P!==void 0)||[])},T=async()=>{await Ia.images.bulkDelete(i),o([])},F=async()=>{const P=await Ia.images.where("id").anyOf(i).toArray(),j=new hk;for(const N of P)N.processedFile instanceof File&&j.file(N.processedFile.name,N.processedFile);const L=await j.generateAsync({type:"blob"});mk.saveAs(L,"selected_processed_images.zip")},C=()=>{w(!h),h||o([])},E=P=>{if(!h)return;l(!0),c(P);const j=e?.[P].id;j!==void 0&&o(L=>L.includes(j)?L.filter(N=>N!==j):[...L,j])},x=()=>{l(!1),c(null)},S=P=>{if(h&&a&&d!==null&&e){const j=e[P].id;j!==void 0&&o(L=>L.includes(e[d].id??-1)?Array.from(new Set([...L,j])):L.filter(W=>W!==j))}};return Yt.useEffect(()=>{const P=()=>{l(!1),c(null)};return window.addEventListener("mouseup",P),()=>{window.removeEventListener("mouseup",P)}},[]),Xt.jsxs("div",{className:"bg-white dark:bg-gray-800 p-4 sm:p-6 rounded-lg shadow-lg",children:[Xt.jsxs("div",{className:"flex justify-between items-center mb-4",children:[Xt.jsxs("h2",{className:"text-xl sm:text-2xl font-bold text-gray-800 dark:text-white",children:["Images: ",e?.length," (Processed: ",_,", Selected: ",i.length,")"]}),Xt.jsxs("div",{className:"flex gap-2 items-center",children:[Xt.jsxs("button",{onClick:C,className:`text-white px-3 py-1 rounded-full text-sm transition-colors ${h?"bg-blue-500 hover:bg-blue-600":"bg-gray-500 hover:bg-gray-600"}`,children:[h?Xt.jsx(v3,{className:"inline mr-2"}):Xt.jsx(y3,{className:"inline mr-2"}),h?"Disable Selection":"Enable Selection"]}),h&&Xt.jsxs(Xt.Fragment,{children:[Xt.jsx("button",{onClick:M,className:"bg-blue-500 text-white px-3 py-1 rounded-full text-sm hover:bg-blue-600 transition-colors",children:i.length===e?.length?"Deselect All":"Select All"}),Xt.jsxs("button",{onClick:T,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,")"]}),Xt.jsxs("button",{onClick:F,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,")"]})]})]})]}),Xt.jsx(ta.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?.map((P,j)=>P.file.type.includes("video")?Xt.jsx(Wz,{video:P},P.id):Xt.jsx(Gz,{image:P,onPreview:()=>n(P),isSelected:i.includes(P.id??-1),onToggleSelect:()=>{h&&o(L=>L.includes(P.id??-1)?L.filter(N=>N!==P.id):[...L,P.id??-1])},onMouseDown:()=>E(j),onMouseEnter:()=>S(j),onMouseUp:x,selectionEnabled:h},P.id))}),t&&Xt.jsx(qz,{image:t,onClose:()=>n(null)})]})}function Wz({video:e}){const t=URL.createObjectURL(e.file);return Xt.jsx("div",{className:"aspect-square rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow duration-300",children:Xt.jsx("video",{className:"w-full h-full object-cover",loop:!0,muted:!0,autoPlay:!0,playsInline:!0,src:t})})}function Gz({image:e,onPreview:t,isSelected:n,onToggleSelect:i,onMouseDown:o,onMouseEnter:a,onMouseUp:l,selectionEnabled:d}){const[c,h]=Yt.useState(!1),w=Yt.useRef(null),_=e.processedFile instanceof File,M=URL.createObjectURL(e.file),T=_?URL.createObjectURL(e.processedFile):"",F=async C=>{if(C.stopPropagation(),_)try{const E=await fetch(T).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 Xt.jsxs(ta.div,{ref:w,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:()=>{h(!0),a()},onMouseLeave:()=>h(!1),onMouseUp:l,whileHover:{scale:1.05},transition:{type:"spring",stiffness:300,damping:10},children:[Xt.jsx(ta.img,{className:"w-full h-full object-cover",src:M,alt:e.file.name,initial:{opacity:0},animate:{opacity:1},transition:{duration:.3}}),!_&&Xt.jsxs(ta.div,{className:"absolute inset-0 overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.5},children:[Xt.jsx("div",{className:"absolute inset-0 bg-black bg-opacity-50 dark:bg-opacity-70"}),Xt.jsx(ta.div,{className:"absolute inset-0 matrix-scan",initial:{y:"-100%"},animate:{y:"100%"},transition:{repeat:1/0,duration:2,ease:"linear"}}),Xt.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:Xt.jsx("div",{className:"text-green-400 dark:text-green-300 font-mono text-lg",children:"Processing..."})})]}),_&&Xt.jsx(ta.img,{className:"absolute inset-0 w-full h-full object-cover bg-checkered",src:T,alt:"Processed",initial:{opacity:0},animate:{opacity:c?0:1},transition:{duration:.3}}),c&&_&&Xt.jsx(ta.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:Xt.jsx("div",{className:"bg-black bg-opacity-50 text-white px-2 py-1 rounded-full text-sm",children:"Hover to see original"})}),Xt.jsxs(ta.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:[Xt.jsx("button",{onClick:C=>{C.stopPropagation(),Ia.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:Xt.jsx(w3,{})}),_&&Xt.jsxs(Xt.Fragment,{children:[Xt.jsx("button",{onClick:F,className:"bg-blue-500 text-white p-2 rounded-full text-xs sm:text-sm hover:bg-blue-600 transition-colors button-hover",children:Xt.jsx(vk,{})}),Xt.jsx("a",{href:T,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:Xt.jsx(wk,{})})]})]}),d&&Xt.jsx(ta.div,{className:"absolute top-2 left-2 z-10",initial:{scale:0},animate:{scale:1},transition:{type:"spring",stiffness:300,damping:20},children:Xt.jsx(ta.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&&Xt.jsx(h3,{className:"text-white"})})})]})}function qz({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 Xt.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4",onClick:t,children:Xt.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:[Xt.jsxs("div",{className:"flex justify-between items-center mb-4",children:[Xt.jsx("h3",{className:"text-xl sm:text-2xl font-bold text-gray-800 dark:text-white",children:e.file.name}),Xt.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:Xt.jsx(_3,{})})]}),Xt.jsxs("div",{className:"grid gap-4 sm:gap-6 grid-cols-1 sm:grid-cols-2",children:[Xt.jsxs("div",{children:[Xt.jsx("h4",{className:"text-base sm:text-lg font-semibold mb-2 text-gray-700 dark:text-gray-300",children:"Original"}),Xt.jsx("img",{src:i,alt:"Original",className:"w-full h-auto rounded-lg shadow-md"})]}),Xt.jsxs("div",{children:[Xt.jsx("h4",{className:"text-base sm:text-lg font-semibold mb-2 text-gray-700 dark:text-gray-300",children:"Processed"}),n?Xt.jsx("img",{src:o,alt:"Processed",className:"w-full h-auto bg-checkered rounded-lg shadow-md"}):Xt.jsx("div",{className:"w-full h-0 pb-[100%] bg-gray-200 animate-pulse rounded-lg"})]})]}),Xt.jsx("div",{className:"mt-4 sm:mt-6 flex flex-wrap justify-end gap-2 sm:gap-4",children:n&&Xt.jsxs(Xt.Fragment,{children:[Xt.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:[Xt.jsx(vk,{className:"mr-2"})," Copy to Clipboard"]}),Xt.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:[Xt.jsx(wk,{className:"mr-2"})," Download Processed Image"]})]})})]})})}const KE="Xenova/modnet";k0.backends.onnx.wasm&&(k0.backends.onnx.wasm.proxy=!1);const Hz=await ck.from_pretrained(KE,{device:"webgpu"}),Kz=await dk.from_pretrained(KE);async function Xz(e){const t=await m2.fromURL(URL.createObjectURL(e)),{pixel_values:n}=await Kz(t),{output:i}=await Hz({input:n}),o=(await m2.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 M=0;Ma.toBlob(F=>F?M(F):T(),"image/png")),[h,w]=e.name.split(".");return new File([c],`${h}-bg-blasted.png`,{type:"image/png"})}async function Qz(){console.log("Processing images...");const e=Ia.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 Xz(t.file);await Ia.images.update(t.id,{processedFile:n})}console.log("Processing images done")}function Yz(){Yt.useState([]),Yt.useState([]),Yt.useState(!1),Yt.useState(!1);const[e,t]=Yt.useState(!0),[n,i]=Yt.useState(null),o=Yt.useRef(null),a=Yt.useRef(null),[l,d]=Yt.useState(!1);Yt.useEffect(()=>{(async()=>{try{if(!("gpu"in navigator))throw new Error("WebGPU is not supported in this browser.");const E="Xenova/modnet";k0.backends.onnx.wasm.proxy=!1,o.current??=await ck.from_pretrained(E,{device:"webgpu"}),a.current??=await dk.from_pretrained(E)}catch(E){i(E)}t(!1)})()},[]);const c=Yt.useCallback(async E=>{for(const x of E){const S=await Ia.images.add({file:x,processedFile:"null"});console.log(`Added image with id ${S}`)}await Qz()},[]),{getRootProps:h,getInputProps:w,isDragActive:_,isDragAccept:M,isDragReject:T}=sk({onDrop:c,accept:{"image/*":[".jpeg",".jpg",".png",".mp4"]}}),F=async()=>{const E=await Ia.images.toArray(),x=new hk;for(const P of E)P.processedFile instanceof File&&x.file(P.processedFile.name,P.processedFile);const S=await x.generateAsync({type:"blob"});mk.saveAs(S,"processed_images.zip")},C=()=>{d(!l),document.documentElement.classList.toggle("dark"),localStorage.setItem("darkMode",(!l).toString())};return n?Xt.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:Xt.jsxs("div",{className:"text-center bg-white p-8 rounded-lg shadow-2xl",children:[Xt.jsx("h2",{className:"text-4xl font-bold mb-4",children:"ERROR"}),Xt.jsx("p",{className:"text-xl max-w-[500px]",children:n.message})]})}):e?Xt.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:Xt.jsxs("div",{className:"text-center",children:[Xt.jsx("div",{className:"inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-800 mb-4"}),Xt.jsx("p",{className:"text-xl",children:"Loading background removal model..."})]})}):Xt.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:Xt.jsxs("div",{className:"max-w-6xl mx-auto",children:[Xt.jsx("div",{className:"flex justify-end mb-4",children:Xt.jsx("button",{onClick:C,className:"p-2 rounded-full bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white",children:l?Xt.jsx(g3,{}):Xt.jsx(m3,{})})}),Xt.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"}),Xt.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"," ",Xt.jsx("a",{className:"underline hover:text-blue-600 transition-colors",target:"_blank",href:"https://github.com/xenova/transformers.js",children:"🤗 Transformers.js"})]}),Xt.jsxs("div",{className:"flex flex-wrap justify-center mb-4 sm:mb-8 gap-4 sm:gap-8",children:[Xt.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)"}),Xt.jsx("a",{className:"underline hover:text-blue-600 transition-colors",target:"_blank",href:"https://huggingface.co./Xenova/modnet",children:"Model (MODNet)"}),Xt.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)"})]}),Xt.jsx("div",{className:"flex justify-center mb-4 sm:mb-8",children:Xt.jsxs("button",{onClick:F,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:[Xt.jsx(p3,{className:"mr-2"}),"Download All Processed Images"]})}),Xt.jsxs("div",{...h(),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 ${M?"border-green-500 bg-green-100":""} ${T?"border-red-500 bg-red-100":""} ${_?"border-blue-500 bg-blue-100":"border-gray-300 hover:border-blue-400 hover:bg-blue-50"} `,children:[Xt.jsx("input",{...w(),className:"hidden"}),Xt.jsx("p",{className:"text-lg sm:text-xl mb-2",children:_?"Drop the images here...":"Drag and drop some images here"}),Xt.jsx("p",{className:"text-xs sm:text-sm text-gray-500",children:"or click to select files"})]}),Xt.jsx(Uz,{})]})})}GS(document.getElementById("root")).render(Xt.jsx(Yt.StrictMode,{children:Xt.jsx(Yz,{})}));